Skip to content

Commit 6b21d78

Browse files
committed
Refactoring Day 14 to use entropy to find the least random configuration of points to detect the tree
1 parent 97c8086 commit 6b21d78

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

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

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ import adventofcode.util.occurrences
2424
import adventofcode.util.removeAll
2525
import adventofcode.util.splitsAsInt
2626
import kotlin.math.ln
27-
import kotlin.math.roundToInt
2827

2928

3029
data class Robot(val ray: Ray) {
@@ -79,11 +78,16 @@ fun Set<Point2D>.printGrid(maxX: Int, maxY: Int) {
7978
}
8079

8180
fun List<Point2D>.calculateShannonEntropy(maxX: Int, maxY: Int, gridWidth: Int, gridHeight: Int): Double {
82-
val cellWidth = maxX * 1.0 / gridWidth
83-
val cellHeight = maxY * 1.0 / gridHeight
84-
return groupBy { (x, y) -> Point2D((x / cellWidth).roundToInt(), (y / cellHeight).roundToInt()) }
85-
.values
86-
.map { it.size.toDouble() / size }
81+
val cellWidth = maxX.toDouble() / gridWidth
82+
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+
}
88+
val totalPoints = size.toDouble()
89+
return histogram.values
90+
.map { it / totalPoints }
8791
.sumOf { -it * ln(it) }
8892
}
8993

0 commit comments

Comments
 (0)