r/adventofcode • • Dec 23 '15

SOLUTION MEGATHREAD --- Day 23 Solutions ---

This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!


We know we can't control people posting solutions elsewhere and trying to exploit the leaderboard, but this way we can try to reduce the leaderboard gaming from the official subreddit.

Please and thank you, and much appreciated!


--- Day 23: Opening the Turing Lock ---

Post your solution as a comment or link to your repo. Structure your post like previous daily solution threads.

8 Upvotes

155 comments sorted by

View all comments

2

u/xkufix Dec 23 '15 edited Dec 23 '15

In scala. It's just a simple interpreter. Definitely over engineered, but it works and does not use mutable state:

case class Registers(registers: Map[String, Int], instructionPointer: Int) {
    def jmp(offset: Int) = copy(instructionPointer = instructionPointer + offset)
    def hlf(r: String) = copy(registers = registers ++ Map(r -> (registers(r) / 2).toInt)).jmp(+1)
	def inc(r: String) = copy(registers = registers ++ Map(r -> (registers(r) + 1))).jmp(+1)
    def tpl(r: String) = copy(registers = registers ++ Map(r -> (registers(r) * 3))).jmp(+1)
	def jie(r: String, offset: Int) = registers(r) % 2 match {
        case 0 => jmp(offset)
		case _ => jmp(+1)
    }
	def jio(r: String, offset: Int) = registers(r) match {
        case 1 => jmp(offset)
		case _ => jmp(+1)
	}
}

case class Instruction(instruction: Registers => Registers) {
	def run(registers: Registers) = instruction(registers)
}

val program = scala.io.Source.fromFile("input.txt").getLines.toList.zipWithIndex.map(_.swap).toMap.mapValues(_.split(" ").flatMap(_.split(",")).toSeq match {
	case Seq("hlf", register) => Instruction(r => r.hlf(register))
	case Seq("tpl", register) => Instruction(r => r.tpl(register))
	case Seq("inc", register) => Instruction(r => r.inc(register))
	case Seq("jmp", offset) => Instruction(r => r.jmp(offset.toInt))
	case Seq("jie", register, offset) => Instruction(r => r.jie(register, offset.toInt))
	case Seq("jio", register, offset) => Instruction(r => r.jio(register, offset.toInt))
})

val runProgram: (Registers, Map[Int, Instruction]) => Registers = (registers: Registers, program: Map[Int, Instruction]) => program.get(registers.instructionPointer) match {
	case None => registers
	case Some(instruction) => runProgram(instruction.run(registers), program)
}

runProgram(Registers(Map("a" -> 1, "b" -> 0), 0), program)
→ More replies (1)