Skip to content

Commit eccd9ce

Browse files
committed
Refactoring Day 14 to use entropy to find the least random configuration of points to detect the tree
1 parent 8196ed3 commit eccd9ce

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

src/main/kotlin/adventofcode/day14/RestroomRedoubt.kt

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -80,11 +80,12 @@ fun Set<Point2D>.printGrid(maxX: Int, maxY: Int) {
8080
fun List<Point2D>.calculateShannonEntropy(maxX: Int, maxY: Int, gridWidth: Int, gridHeight: Int): Double {
8181
val cellWidth = maxX.toDouble() / gridWidth
8282
val cellHeight = maxY.toDouble() / gridHeight
83-
val histogram = mutableMapOf<Point2D, Int>()
84-
forEach { (x, y) ->
85-
val cell = Point2D((x / cellWidth).toInt(), (y / cellHeight).toInt())
86-
histogram[cell] = histogram.getOrDefault(cell, 0) + 1
87-
}
83+
val histogram = this.groupingBy { point ->
84+
val cellX = (point.x / cellWidth).toInt()
85+
val cellY = (point.y / cellHeight).toInt()
86+
cellX to cellY
87+
}.eachCount()
88+
8889
val totalPoints = size.toDouble()
8990
return histogram.values
9091
.map { it / totalPoints }

0 commit comments

Comments
 (0)