aboutsummaryrefslogtreecommitdiff
path: root/src/Day02.kt
blob: 401c50883fadd56a904ccbd59f5ced19e491bd4a (plain)
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
/**
 * Given a list of correct command strings, dispatch [action] taking command name and argument on each of them.
 * @param commands list of valid command strings
 * @param action function taking a string (command name) and integer (argument) that gets called for each command
 */
fun dispatchCommands(commands: List<String>, action: (command: String, argument: Int) -> Unit) {
    for (line in commands) {
        val parts = line.split(" ")
        val command = parts[0]
        val argument = parts[1].toInt()

        action(command, argument)
    }
}

fun main() {
    fun part1(input: List<String>): Int {
        var horizontal = 0
        var depth = 0

        dispatchCommands(input) { command, argument ->
            when (command) {
                "forward" -> horizontal += argument
                "down" -> depth += argument
                "up" -> depth -= argument
            }
        }

        return horizontal * depth
    }

    fun part2(input: List<String>): Int {
        var horizontal = 0
        var depth = 0
        var aim = 0

        dispatchCommands(input) { command, argument ->
            when (command) {
                "forward" -> {
                    horizontal += argument
                    depth += aim * argument
                }
                "down" -> aim += argument
                "up" -> aim -= argument
            }
        }

        return horizontal * depth
    }

    val testInput = readInputAsLines("Day02_test")
    check(part1(testInput) == 150)
    check(part2(testInput) == 900)

    val input = readInputAsLines("Day02")
    println(part1(input))
    println(part2(input))
}