Skip to content

Commit 9fa206c

Browse files
committed
2016.19
1 parent 0423093 commit 9fa206c

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

src/main/scala/y2016/Day19.scala

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package y2016
2+
3+
import scala.annotation.tailrec
4+
5+
trait Day19 {
6+
7+
def solve1(n: Int): Int = {
8+
val elves = Array.fill(n)(1)
9+
10+
@tailrec def recurse(): Int = {
11+
val winner = elves.indexOf(n)
12+
if (winner >= 0) winner
13+
else {
14+
var i = 0
15+
while (i < n) {
16+
if (elves(i) != 0) {
17+
val next = elves.indexWhere(_ != 0, i + 1) match {
18+
case -1 => elves.indexWhere(_ != 0, 0)
19+
case n => n
20+
}
21+
elves(i) += elves(next % n)
22+
elves(next % n) = 0
23+
}
24+
i += 1
25+
}
26+
recurse()
27+
}
28+
}
29+
30+
recurse() + 1
31+
}
32+
33+
def solve2(n: Int): Int = {
34+
val fast = true
35+
if (fast) {
36+
@tailrec def recurse(i: Int): Int =
37+
if (i * 3 < n) recurse(i * 3)
38+
else n - i
39+
recurse(1)
40+
} else {
41+
val values = Array.fill(n)(1)
42+
val next = { val nx = Array.range(1, n + 1); nx(nx.length - 1) = 0; nx }
43+
val prev = { val pr = Array.range(-1, n - 1); pr(0) = pr.length - 1; pr }
44+
var count = n
45+
46+
@inline @tailrec def advance(c: Int, n: Int): Int = if (n == 0) c else advance(next(c), n - 1)
47+
@inline def opposite(c: Int): Int = advance(c, count / 2)
48+
var cursor = 0
49+
while (values.indexOf(n) == -1) {
50+
if (count > 0 && (count % 1000) == 0) println(count)
51+
val opp = opposite(cursor)
52+
values(cursor) += values(opp)
53+
values(opp) = 0
54+
next(prev(opp)) = next(opp)
55+
prev(next(opp)) = prev(opp)
56+
next(opp) = -1
57+
prev(opp) = -1
58+
cursor = next(cursor)
59+
count -= 1
60+
}
61+
values.indexOf(n) + 1
62+
}
63+
}
64+
}

src/test/scala/y2016/Day19Spec.scala

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package y2016
2+
3+
import org.scalatest.flatspec.AnyFlatSpec
4+
import org.scalatest.matchers.should._
5+
6+
class Day19Spec extends AnyFlatSpec with Matchers with Day19 {
7+
it should "solve part 1" in {
8+
solve1(3014387) shouldBe 1834471
9+
}
10+
it should "solve part 2" in {
11+
solve2(3014387) shouldBe 1420064
12+
}
13+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy