Skip to content

Feat/2020 day 08 #129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 13 commits into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions 2020/day-08/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// eslint-disable-next-line no-unused-vars
const console = require('../helpers')
require('./solution')
649 changes: 649 additions & 0 deletions 2020/day-08/input.txt

Large diffs are not rendered by default.

150 changes: 150 additions & 0 deletions 2020/day-08/runProgram.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
let log = []
log[0] = [1]
log[1] = [2, 8]
log[2] = [3]
log[3] = [6]
log[4] = [7]
log[6] = [4]
log[7] = [5]

let program = [
'nop +0',
'acc +1',
'jmp +4',
'acc +3',
'jmp -3',
'acc -99',
'acc +1',
'jmp -4',
'acc +6'
]

let accumulator = 0
let position = 1
let breaker = false

/**
* API of commands this language supports
*/
const api = {
nop: (a, b) => {
console.debug(`doing a nop ${b}`)
return a + 1
},
acc: (a, b) => {
console.debug(`adding ${b} to accumulator`)
accumulator += api[b.substr(0, 1)](
0,
Number(b.substr((1)))
)
return a + 1
},
jmp: (a, b) => {
console.debug(`jumping from ${a} ${b} `)
return a + api[b.substr(0, 1)](
0,
Number(b.substr((1)))
)
},
'+': (x, y) => x + y,
'-': (x, y) => x - y
}

const parseCommand = (inst) => {
console.debug('Parsing ', inst)
const [cmd, arg] = inst.split(' ')
return { cmd, arg }
}

const execInstruction = (inst, instKey = 0, evKey = 0) => {
const { cmd, arg } = parseCommand(inst)
// Run the command
// Support jumping by passing back next
position = api[cmd](instKey, arg)
logEvent({ instKey, evKey })
// break out when reaching an infinite loop
if (log[instKey].length > 1) {
breaker = true
console.error(`execuetd an error on ${instKey}`, inst, accumulator)
// step back the accumulator
if (cmd === 'acc') {
if (arg.includes('+')) {
api[cmd](0, arg.replace('+', '-'))
}
if (arg.includes('-')) {
api[cmd](0, arg.replace('+-', '+'))
}
}
}
return position
}

const run = (insts) => {
program = insts
accumulator = 0
position = 0
log = []
let evKey = 0

// eslint-disable-next-line no-unmodified-loop-condition
while (breaker === false) {
evKey++
execInstruction(program[position], position, evKey)
}
}

const formatLogRow = (command, idx, program) => {
let countStr
if (!log[idx]) {
countStr = ''
}
if (log[idx] && log[idx].length === 1) {
countStr = `${log[idx][0]}`
}
if (log[idx] && log[idx].length > 1) {
countStr = `${log[idx].join(', ')}(!)`
}
const row = `${command.padEnd(8, ' ')}| ${countStr}`
console.debug(row)
return row
}

const displayLog = () => {
console.debug(`${program.length} steps in program.`)
console.debug('-----------------------------------')
const formattedLog = program.map(formatLogRow)
.reduce((res, row) => {
res += '\n'
res += row
return res
}, '')

return formattedLog
}

const logEvent = ({ instKey, evKey }) => {
console.debug(`event ${evKey} called instruction ${instKey}`)
if (
log[instKey] &&
typeof log[instKey] === 'object' &&
log[instKey].length > 0
) {
// Record another entry on a command already executed once
log[instKey].push(evKey)
return log[instKey]
} else {
// Record the first entry on a command
log[instKey] = [evKey]
}
return log[instKey]
}

module.exports = {
run,
getAccumulator: () => accumulator,
getPosition: () => position,
execInstruction,
parseCommand,
logEvent,
displayLog
}
102 changes: 102 additions & 0 deletions 2020/day-08/runProgram.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/* eslint-env mocha */
const { expect } = require('chai')
const { run, getPosition, getAccumulator, execInstruction, parseCommand, logEvent, displayLog } = require('./runProgram')

const exampleProgram = [
'nop +0',
'acc +1',
'jmp +4',
'acc +3',
'jmp -3',
'acc -99',
'acc +1',
'jmp -4',
'acc +6'
]
const exampleLog = `
nop +0 | 1
acc +1 | 2, 8(!)
jmp +4 | 3
acc +3 | 6
jmp -3 | 7
acc -99 |
acc +1 | 4
jmp -4 | 5
acc +6 | `

describe('--- Day 8: Handheld Halting ---', () => {
describe('Part 1', () => {
describe('execInstruction()', () => {
it('executes a specified command', () => {
expect(getPosition()).to.equal(1)
expect(execInstruction('acc +3', 300, 600)).to.equal(301)
expect(getAccumulator()).to.equal(3)
expect(getPosition()).to.equal(301)
})
xit('steps to the next sequential command', () => {
// logEvent()
// expect(false).to.equal(true)
})
it('can execute a `nop` command which does nothing', () => {
const acc = getAccumulator()
expect(execInstruction('nop +3', 999, 600)).to.equal(1000)
expect(getPosition()).to.equal(1000)
expect(getAccumulator()).to.equal(acc)
})
it('can execute a `acc` command which increments the accumulator', () => {
const acc = getAccumulator()
expect(execInstruction('acc +100', 1234, 600)).to.equal(1235)
expect(getPosition()).to.equal(1235)
expect(getAccumulator()).to.equal(acc + 100)
})
it('can execute a `jmp` command which jumps to a different command in the instruction set', () => {
const acc = getAccumulator()
expect(execInstruction('jmp -23', 400, 600)).to.equal(377)
expect(getPosition()).to.equal(377)
expect(getAccumulator()).to.equal(acc)
})
})
describe('parseCommand()', () => {
it('parses an instruction string into a structured command object', () => {
const instructions = [
'jmp +4',
'acc +3',
'jmp -3',
'acc -99'
]
instructions.forEach((inst) => {
const { cmd, arg } = parseCommand(inst)
expect(`${cmd} ${arg}`).to.equal(inst)
})
})
})
describe('logEvent()', () => {
it('records the step in the execution log', () => {
const result = logEvent({ instKey: 500, evKey: 17 })
expect(result).to.deep.equal([17])
})
it('tracks the state over multiple logging events', () => {
const result = logEvent({ instKey: 500, evKey: 24 })
expect(result).to.deep.equal([17, 24])
})
})
describe('displayLog()', () => {
it('renders the output of the execution log', () => {
expect(
displayLog()
).to.equal(
exampleLog
)
})
})
describe('run()', () => {
it('executes the steps of a given program', () => {
run(exampleProgram)
// stops at infinite loop
expect(getPosition()).to.equal(2)
expect(getAccumulator()).to.equal(6)
expect(displayLog()).to.equal(exampleLog)
})
})
})
})
38 changes: 38 additions & 0 deletions 2020/day-08/solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const fs = require('fs')
const path = require('path')
const filePath = path.join(__dirname, 'input.txt')
const { linesToArray } = require('../../2018/inputParser')
const { run, getAccumulator, displayLog } = require('./runProgram')

fs.readFile(filePath, { encoding: 'utf8' }, (err, initData) => {
if (err) throw err

initData = linesToArray(initData.trim())

const resetInput = () => {
// Deep copy to ensure we aren't mutating the original data
return JSON.parse(JSON.stringify(initData))
}

const part1 = () => {
const data = resetInput()
console.debug(data)
run(data)
console.info(displayLog())
return getAccumulator()
}

const part2 = () => {
const data = resetInput()
console.debug(data)
return 'No answer yet'
}
const answers = []
answers.push(part1())
answers.push(part2())

answers.forEach((ans, idx) => {
console.info(`-- Part ${idx + 1} --`)
console.info(`Answer: ${ans}`)
})
})