adolfont
12/5/2018 - 10:26 PM

My solution to Advent of Code - Day 2: Inventory Management System https://adventofcode.com/2018/day/2

My solution to Advent of Code - Day 2: Inventory Management System https://adventofcode.com/2018/day/2

defmodule Day2 do
  def create_map([], map) do
    map
  end

  def create_map([head | tail], map) do
    create_map(tail, Map.update(map, head, 1, fn x -> x + 1 end))
  end

  def process_string(string) do
    values =
      String.codepoints(string)
      |> Enum.sort()
      |> create_map(Map.new())
      |> Map.values()

    {3 in values, 2 in values}
  end

  def process_stream(n_threes, n_twos, []) do
    {n_threes, n_twos}
  end

  def process_stream(o_threes, o_twos, stream) do
    [string] = Enum.take(stream, 1)
    {threes, twos} = process_string(string)
    n_threes = if threes, do: 1, else: 0
    n_twos = if twos, do: 1, else: 0
    process_stream(n_threes + o_threes, n_twos + o_twos, Enum.drop(stream, 1))
  end

  def process_file(stream) do
    process_stream(0, 0, stream)
  end

  ### PART 2

  def aux_differ(x, y, "", "") do
    {x, y}
  end

  def aux_differ(false, y, s1, s2) do
    if String.at(s1, 0) != String.at(s2, 0) do
      aux_differ(true, y, String.slice(s1, 1..-1), String.slice(s2, 1..-1))
    else
      aux_differ(false, y + 1, String.slice(s1, 1..-1), String.slice(s2, 1..-1))
    end
  end

  def aux_differ(true, y, s1, s2) do
    if String.at(s1, 0) != String.at(s2, 0) do
      {false, -1}
    else
      aux_differ(true, y, String.slice(s1, 1..-1), String.slice(s2, 1..-1))
    end
  end

  def differ_by_exactly_one_character(string1, string2) do
    aux_differ(false, 0, string1, string2)
  end

  def new_string(s1, y) do
    String.slice(s1, 0..(y - 1)) <> String.slice(s1, (y + 1)..-1)
  end

  def process_file_differ(file_as_list) do
    for i <- file_as_list do
      for j <- file_as_list do
        {a, b} = differ_by_exactly_one_character(i, j)

        if a do
          IO.puts(new_string(i, b))
        end
      end
    end
  end
end

# Part 1 
# IO.inspect Day2.process_string("ababab")

{x, y} =
  File.stream!("input", [], :line)
  |> Day2.process_file()
  |> IO.inspect()

IO.puts("Value: #{x * y}")

# Part 2

# IO.inspect Day2.differ_by_exactly_one_character("abc", "abd")
# IO.inspect Day2.differ_by_exactly_one_character("abcd", "abce")
# IO.inspect Day2.differ_by_exactly_one_character("abcdfgh", "abcefgh")
# IO.inspect Day2.differ_by_exactly_one_character("bcdfgh", "bcefgh")
# IO.inspect Day2.differ_by_exactly_one_character("cdfgh", "cefgh")
# IO.inspect Day2.differ_by_exactly_one_character("dfgh", "efgh")
# IO.inspect Day2.differ_by_exactly_one_character("abcc", "abdd")

# x1 = "abcdfgh"
# x2 = "abcefgh"
# {true, y} = Day2.differ_by_exactly_one_character(x1, x2)

# new_string = Day2.new_string(x1,y) 

# IO.puts(new_string)

{:ok, file} = File.read("input")
Day2.process_file_differ(String.split(file, "\n"))