Skip to content

Commit e4f8cb8

Browse files
committed
Solution 2015-20 (Infinite Elves and Infinite Houses)
1 parent 786cd0e commit e4f8cb8

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package de.ronny_h.aoc.year2015.day20
2+
3+
import de.ronny_h.aoc.AdventOfCode
4+
5+
fun main() = InfiniteElvesAndInfiniteHouses().run(776160, 786240)
6+
7+
class InfiniteElvesAndInfiniteHouses : AdventOfCode<Int>(2015, 20) {
8+
9+
override fun part1(input: List<String>): Int {
10+
val s = input.single().toInt() / 10
11+
var houseNumber = s / 5
12+
var sum = 0
13+
println("Searching for the hous with at least $s presents, starting at $houseNumber")
14+
while (sum < s) {
15+
houseNumber++
16+
sum = numberOfPresentsForHouse(houseNumber)
17+
if (houseNumber % 10000 == 0) {
18+
println("at house number $houseNumber: $sum presents")
19+
}
20+
}
21+
return houseNumber
22+
}
23+
24+
override fun part2(input: List<String>): Int {
25+
val s = input.single().toInt()
26+
var houseNumber = s / 50
27+
var sum = 0
28+
println("Searching for the hous with at least $s presents, starting at $houseNumber")
29+
while (sum < s) {
30+
houseNumber++
31+
sum = numberOfPresentsForHouseWithMax50Visits(houseNumber) * 11
32+
if (houseNumber % 10000 == 0) {
33+
println("at house number $houseNumber: $sum presents")
34+
}
35+
}
36+
return houseNumber
37+
}
38+
}
39+
40+
// this is an implementation of the Divisor function:
41+
// https://en.wikipedia.org/wiki/Divisor_function
42+
fun numberOfPresentsForHouse(number: Int) = (1..number)
43+
.sumOf { if (number % it == 0) it else 0 }
44+
45+
fun numberOfPresentsForHouseWithMax50Visits(number: Int) = (1..number)
46+
.sumOf { if (number % it == 0 && number / it <= 50) it else 0 }
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package de.ronny_h.aoc.year2015.day20
2+
3+
import io.kotest.core.spec.style.StringSpec
4+
import io.kotest.data.forAll
5+
import io.kotest.data.row
6+
import io.kotest.matchers.shouldBe
7+
8+
class InfiniteElvesAndInfiniteHousesTest : StringSpec({
9+
"the divisor function for some small numbers" {
10+
forAll(
11+
row(1, 1),
12+
row(2, 3),
13+
row(3, 4),
14+
row(4, 7),
15+
row(5, 6),
16+
row(6, 12),
17+
row(7, 8),
18+
row(8, 15),
19+
row(9, 13),
20+
) { number, presents ->
21+
numberOfPresentsForHouse(number) shouldBe presents
22+
}
23+
}
24+
25+
"part 1: the lowest house number to get at least 120 presents" {
26+
InfiniteElvesAndInfiniteHouses().part1(listOf("120")) shouldBe 6
27+
}
28+
29+
"part 2: the lowest house number to get at least 120 presents with 11 presents each" {
30+
InfiniteElvesAndInfiniteHouses().part2(listOf("77")) shouldBe 4
31+
}
32+
})

0 commit comments

Comments
 (0)