Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- import java.util.function.BiFunction;
- /**
- * @author /u/Philboyd_Studge on 12/22/2015.
- */
- public class Advent22 {
- static List<Instruction> program = new ArrayList<>();
- static int index;
- enum CMD {
- hlf((x, y) -> x / 2),
- tpl((x, y) -> x * 3),
- inc((x, y) -> x + 1),
- jmp(Advent22::jump),
- jie(Advent22::jumpIfEven),
- jio(Advent22::jumpIfOne);
- private final BiFunction<Integer, Integer, Integer> func;
- private CMD(BiFunction<Integer, Integer, Integer> func) {
- this.func = func;
- }
- }
- public static int jump(int offset, int value) {
- return index + offset;
- }
- public static int jumpIfEven(int offset, int value) {
- return isEven(value) ? index + offset : index + 1;
- }
- public static int jumpIfOne(int offset, int value) {
- return value==1 ? index + offset : index + 1;
- }
- public static boolean isEven(int val) {
- return val % 2 == 0;
- }
- static class Instruction {
- CMD command;
- Register register;
- int offset;
- public Instruction(CMD command, Register register, int offset) {
- this.command = command;
- this.register = register;
- this.offset = offset;
- }
- public void execute() {
- if (command.ordinal() < 3) {
- register.value = command.func.apply(register.value, 0);
- index++;
- } else {
- index = command.func.apply(offset, register.value);
- }
- }
- }
- static class Register {
- int value = 0;
- }
- public static void run() {
- while (true) {
- Instruction instr = program.get(index);
- instr.execute();
- if (index >= program.size()) break;
- }
- }
- public static void main(String[] args) {
- List<String[]> input = FileIO.getFileLinesSplit("advent22.txt", "[ ,]+");
- Register a = new Register();
- Register b = new Register();
- for (String[] each : input) {
- program.add(new Instruction(CMD.valueOf(each[0]),
- each[1].equals("a") ? a : each[1].equals("b") ? b : a,
- each.length==2 && (each[1].startsWith("+") || each[1].startsWith("-"))
- ? Integer.parseInt(each[1]) : each.length==3
- ? Integer.parseInt(each[2]) : 0));
- }
- run();
- System.out.println(b.value);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement