-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Solution for 2023-12-12, part 1 (bruteforce)
- Loading branch information
Showing
3 changed files
with
1,188 additions
and
0 deletions.
There are no files selected for viewing
54 changes: 54 additions & 0 deletions
54
src/main/kotlin/biz/koziolek/adventofcode/year2023/day12/day12.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
package biz.koziolek.adventofcode.year2023.day12 | ||
|
||
import biz.koziolek.adventofcode.findInput | ||
|
||
fun main() { | ||
val inputFile = findInput(object {}) | ||
val springs = parseHotSpringsRecords(inputFile.bufferedReader().readLines()) | ||
println("There are ${countPossibleArrangements(springs)} possible arrangements") | ||
} | ||
|
||
const val OPERATIONAL = '.' | ||
const val DAMAGED = '#' | ||
const val UNKNOWN = '?' | ||
|
||
data class HotSpringsRow(val conditions: String, val damagedGroupSizes: List<Int>) { | ||
val isUnknown = UNKNOWN in conditions | ||
} | ||
|
||
fun parseHotSpringsRecords(lines: Iterable<String>): List<HotSpringsRow> = | ||
lines | ||
.map { line -> | ||
val (conditions, sizesStr) = line.split(" ") | ||
val sizes = sizesStr.split(",").map { it.toInt() } | ||
HotSpringsRow(conditions, sizes) | ||
} | ||
|
||
fun springsMatch(conditions: String, damagedGroupSizes: List<Int>): Boolean = | ||
conditions | ||
.trim(OPERATIONAL) | ||
.replace(Regex(Regex.escape(OPERATIONAL.toString()) + "+"), OPERATIONAL.toString()) | ||
.split(OPERATIONAL) | ||
.map { it.length } | ||
.let { it == damagedGroupSizes } | ||
|
||
fun generatePossibleArrangements(hotSpringsRow: HotSpringsRow): Sequence<HotSpringsRow> = | ||
sequence { | ||
if (!hotSpringsRow.isUnknown) { | ||
if (springsMatch(hotSpringsRow.conditions, hotSpringsRow.damagedGroupSizes)) { | ||
yield(hotSpringsRow) | ||
} | ||
} else { | ||
val (first, second) = hotSpringsRow.conditions.split(UNKNOWN, limit = 2) | ||
|
||
yieldAll(generatePossibleArrangements( | ||
HotSpringsRow(first + OPERATIONAL + second, hotSpringsRow.damagedGroupSizes) | ||
)) | ||
yieldAll(generatePossibleArrangements( | ||
HotSpringsRow(first + DAMAGED + second, hotSpringsRow.damagedGroupSizes) | ||
)) | ||
} | ||
} | ||
|
||
fun countPossibleArrangements(hotSpringsRows: List<HotSpringsRow>): Int = | ||
hotSpringsRows.sumOf { generatePossibleArrangements(it).count() } |
Oops, something went wrong.