Commit 2a974293 authored by Kevin Turner's avatar Kevin Turner

use more CPUs with parallel streams!

parent 3dee6493
......@@ -33,18 +33,21 @@ fun searchGrid3(serial: Int): Coordinate {
fun powerInGrid(serial: Int, x: Int, y: Int, size: Int): Int {
val everyplace = (x until (x+size)).flatMap { ix -> (y until (y + size)).map { iy-> Coordinate(ix, iy)}}
val everyplace = (x until (x+size)).flatMap { ix -> (y until (y + size)).map { iy-> Coordinate(ix, iy)}}.parallelStream()
return everyplace.sumBy { (ix, iy) -> powerAtPoint(serial, ix, iy)}
return everyplace.mapToInt { (ix, iy) -> powerAtPoint(serial, ix, iy)}.sum()
}
fun searchGridAny(serial: Int, size: Int): Pair<Int, Coordinate> {
val everyplace = (1..(GRID_SIZE - size + 1)).flatMap { x -> (1..(GRID_SIZE - size + 1)).map { y-> Coordinate(x, y)}}
val result = everyplace.maxValueBy { (x, y) -> powerInGrid(serial, x, y, size) }!!
println("grid size $size $result")
return result
val powerAtEveryplace = everyplace.parallelStream().map { coord -> powerInGrid(serial, coord.x, coord.y, size) to coord}
val mostPower = powerAtEveryplace.max { a, b -> a.first.compareTo(b.first) }.get()
println("grid size $size $mostPower")
return mostPower
}
......@@ -66,11 +69,6 @@ private fun <E, V: Comparable<V>> List<E>.maxValueBy(f: (E) -> V): Pair<V, E>? {
}
private fun Pair<Int, Coordinate>.compareTo(other: Pair<Int, Coordinate>): Int {
return this.first.compareTo(other.first)
}
fun searchAllSizes(serial: Int): Pair<Int, Coordinate> {
val allSizes = (1 until GRID_SIZE).toList()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment