DEV Community

Discussion on: Advent of Code 2019 Solution Megathread - Day 17: Set and Forget

Collapse
 
rizzu26 profile image
Rizwan

Forgot to post the solution here. I tried to solve the part 2 in code and I couldn't find any way of doing it. As usual got the hint from R website and went ahead on manual way.

Swift solution

func partOne() {
    let computer = Opcode.init(input)
    var result: String = ""
    var outputs: [Int] = []
    while !computer.done {
        outputs.append(computer.run())
    }
    outputs.map { result.append(Character(UnicodeScalar($0)!))}

    let grid = result.split(separator: "\n").map{ $0.map{$0}}
    var sum = 0
    for row in 1 ..< (grid.count - 1) {
        for column in 1 ..< (grid[row].count - 1) {
            if grid[row][column] == "#" {
                if grid[row][column - 1] == "#" &&
                    grid[row][column + 1] == "#" &&
                    grid[row - 1][column] == "#" &&
                    grid[row + 1][column] == "#" {
                    sum += row * column
                }
            }
        }
    }
    print(grid)
    print("Part 1 answer is :\(sum)")
}

func partTwo() {
    var scanLine = ""
    let rules = """
    A,B,B,A,B,C,A,C,B,C
    L,4,L,6,L,8,L,12
    L,8,R,12,L,12
    R,12,L,6,L,6,L,8
    y\n
    """.map { Int($0.asciiValue!) }
    var rulesIndex = -1

    var dustCollected = 0
    input[0] = 2
    let computer = Opcode.init(input)
    while !computer.done {
        rulesIndex += 1
        computer.inputIds.append(rules[rulesIndex])
        let value = computer.run()
        dustCollected = value
    }

    print("Part 2 answer is :\(dustCollected)")
}

partOne()
partTwo()

Opcode and input can be found here