-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDay13.kt
72 lines (62 loc) · 2.07 KB
/
Day13.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* Copyright (c) 2019 by Todd Ginsberg
*/
/**
* Advent of Code 2019, Day 13 - Care Package
* Problem Description: http://adventofcode.com/2019/day/13
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2019/day13/
*/
package com.ginsberg.advent2019
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.math.sign
@ExperimentalCoroutinesApi
class Day13(input: String) {
private val program: MutableMap<Long, Long> = input
.split(",")
.withIndex()
.associateTo(mutableMapOf()) { it.index.toLong() to it.value.toLong() }
fun solvePart1(): Int = runBlocking {
var blocks = 0
val computer = IntCodeComputerMk2(program = program, output = Channel(Channel.UNLIMITED))
computer.runProgram()
while (!computer.output.isClosedForReceive) {
computer.output.receive()
computer.output.receive()
if (computer.output.receive().toInt() == block) {
blocks++
}
}
blocks
}
fun solvePart2(): Int = runBlocking {
program[0] = freePlay // We r l33t H4x0rz now.
val computer = IntCodeComputerMk2(program = program, output = Channel(Channel.UNLIMITED))
launch {
computer.runProgram()
}
var paddleX = 0
var score = 0
while (!computer.output.isClosedForReceive) {
val x = computer.output.receive().toInt()
computer.output.receive()
val item = computer.output.receive().toInt()
when {
x == -1 -> score = item
item == paddle -> paddleX = x
item == ball -> {
computer.input.send((x - paddleX).sign.toLong())
}
}
}
score
}
companion object {
private const val block = 2
private const val paddle = 3
private const val ball = 4
private const val freePlay = 2L
}
}