mail-alt git-squared

~/abhirag

Advent of Code (2016) : Day 12

-- Problem --
You can find Part 1 of the problem statement here. Part 2 is unlocked on successful completion of Part 1.

-- Solution in Elixir --

      defmodule Aoc.Day12 do

  def eval(register_map, instruction_pointer, instruction_list) when not instruction_pointer in 0..(length(instruction_list) - 1) do
    register_map
  end

  def eval(register_map, instruction_pointer, instruction_list) do
    case Enum.at(instruction_list, instruction_pointer) do
      [:jnz, num, jump_by] when is_integer(num) and num == 0 -> eval(register_map, instruction_pointer + 1, instruction_list)
      [:jnz, num, jump_by] when is_integer(num) -> eval(register_map, instruction_pointer + jump_by, instruction_list)
      [:jnz, register, jump_by] ->
        case register_map[register] == 0 do
          true -> eval(register_map, instruction_pointer + 1, instruction_list)
          false -> eval(register_map, instruction_pointer + jump_by, instruction_list)
        end
      [:inc, register] -> eval(%{register_map | register => register_map[register] + 1}, instruction_pointer + 1, instruction_list)
      [:dec, register] -> eval(%{register_map | register => register_map[register] - 1}, instruction_pointer + 1, instruction_list)
      [:cpy, num, register] when is_integer(num) -> eval(%{register_map | register => num}, instruction_pointer + 1, instruction_list)
      [:cpy, register_src, register_dst] -> eval(%{register_map | register_dst => register_map[register_src]}, instruction_pointer + 1, instruction_list)
    end
  end

  def parse_input() do
    {:ok, input} = File.read("day12_input.txt")
    String.split(input, "\n")
    |> List.delete_at(-1)
    |> Enum.map(&parse_instruction/1)
  end

  def parse_instruction(instruction_string) do
    String.split(instruction_string)
    |> Enum.map(fn(string) ->
      case Integer.parse(string) do
        :error -> String.to_atom(string)
        {num, _} -> num
      end
    end)
  end

  def output_1() do
    instruction_list = parse_input()
    eval(%{:a => 0, :b => 0, :c => 1, :d => 0}, 0, instruction_list)
  end

end
    

You can find all my Advent of Code (2016) solutions here.