Skip to content

Commit 703001a

Browse files
committed
Solution 2018-03 (No Matter How You Slice It)
1 parent 71ba5e3 commit 703001a

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package de.ronny_h.aoc.year2018.day03
2+
3+
import de.ronny_h.aoc.AdventOfCode
4+
import de.ronny_h.aoc.extensions.grids.Coordinates
5+
6+
fun main() = NoMatterHowYouSliceIt().run(107820, 661)
7+
8+
class NoMatterHowYouSliceIt : AdventOfCode<Int>(2018, 3) {
9+
override fun part1(input: List<String>): Int = ClaimedAreas(input).numberOfOverlaps()
10+
override fun part2(input: List<String>): Int = ClaimedAreas(input).findTheOneThatDoesntOverlap().id
11+
}
12+
13+
data class Claim(val id: Int, val x: Int, val y: Int, val width: Int, val height: Int)
14+
15+
private val claimPattern = """#(\d+) @ (\d+),(\d+): (\d+)x(\d+)""".toPattern()
16+
17+
fun List<String>.parseClaims() = map {
18+
val matcher = claimPattern.matcher(it)
19+
matcher.find()
20+
check(matcher.groupCount() == 5)
21+
Claim(
22+
id = matcher.group(1).toInt(),
23+
x = matcher.group(2).toInt(),
24+
y = matcher.group(3).toInt(),
25+
width = matcher.group(4).toInt(),
26+
height = matcher.group(5).toInt(),
27+
)
28+
}
29+
30+
class ClaimedAreas(input: List<String>) {
31+
private val claims = input.parseClaims()
32+
private val claimedAreas = mutableMapOf<Coordinates, Int>().withDefault { 0 }
33+
34+
init {
35+
claims.forEach {
36+
for (x in it.x..<it.x + it.width) {
37+
for (y in it.y..<it.y + it.height) {
38+
claimedAreas[Coordinates(y, x)] = claimedAreas.getValue(Coordinates(y, x)) + 1
39+
}
40+
}
41+
}
42+
}
43+
44+
fun numberOfOverlaps() = claimedAreas.values.count { it > 1 }
45+
46+
fun findTheOneThatDoesntOverlap(): Claim = claims
47+
.filter {
48+
for (x in it.x..<it.x + it.width) {
49+
for (y in it.y..<it.y + it.height) {
50+
if (claimedAreas.getValue(Coordinates(y, x)) > 1) return@filter false
51+
}
52+
}
53+
true
54+
}
55+
.single()
56+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package de.ronny_h.aoc.year2018.day03
2+
3+
import de.ronny_h.aoc.extensions.asList
4+
import io.kotest.core.spec.style.StringSpec
5+
import io.kotest.matchers.shouldBe
6+
7+
class NoMatterHowYouSliceItTest : StringSpec({
8+
9+
val input = """
10+
#1 @ 1,3: 4x4
11+
#2 @ 3,1: 4x4
12+
#3 @ 5,5: 2x2
13+
""".asList()
14+
15+
"input can be parsed" {
16+
input.parseClaims() shouldBe listOf(
17+
Claim(1, 1, 3, 4, 4),
18+
Claim(2, 3, 1, 4, 4),
19+
Claim(3, 5, 5, 2, 2),
20+
)
21+
}
22+
23+
"part 1: the number of square inches of fabric within two or more claims" {
24+
NoMatterHowYouSliceIt().part1(input) shouldBe 4
25+
}
26+
27+
"part 2: the ID of the claim that doesn't overlap" {
28+
NoMatterHowYouSliceIt().part2(input) shouldBe 3
29+
}
30+
})

0 commit comments

Comments
 (0)