Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Advent of Code 2024 - Day 2

advent_of_code_2024_day_2.livemd

Advent of Code 2024 - Day 2

Test Input

test_input = 
"""
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9
"""

Solution

defmodule Day02 do
  def parse(input_string) do
    input_string
    |> String.split("\n", trim: true)
    |> Enum.map(fn line -> 
      line 
      |> String.split(" ") 
      |> Enum.map(&String.to_integer/1)
    end)
  end

  
  def safe?(list) do
    monotonic?(list) and valid_adjacent_diff?(list)
  end

  def monotonic?(list) do
    cond do
      length(list) <= 1 -> true
      Enum.all?(Enum.zip(list, Enum.drop(list, 1)), fn {a, b} -> a <= b end) -> true
      Enum.all?(Enum.zip(list, Enum.drop(list, 1)), fn {a, b} -> a >= b end) -> true
      true -> false
    end
  end


  def valid_adjacent_diff?(list) do
    list
    |> Enum.chunk_every(2, 1, :discard)
    |> Enum.all?(fn [a, b] -> 
      diff = abs(a - b)
      diff > 0 and diff < 4
    end)
  end

  def task1(input) do
    input
    |> parse()
    |> Enum.map(&amp;safe?/1)
    |> Enum.count(fn x -> x == true end)
  end


  # for task 2

  def remove_one_element(list) do
    for {_element, index} <- Enum.with_index(list) do
      List.delete_at(list, index)
    end
  end

  def weakly_safe?(list) do
    (monotonic?(list) and valid_adjacent_diff?(list))
    or
    Enum.any?(remove_one_element(list), &amp;safe?/1)
  end

  def task2(input) do
    input
    |> parse()
    |> Enum.map(&amp;weakly_safe?/1)
    |> Enum.count(fn x -> x == true end)
  end

end
Day02.monotonic?([1, 2, 3, 4])      
Day02.safe?([1, 2, 3, 4])   
Day02.monotonic?([10, 2, 1, -1])
Day02.safe?([10, 2, 1, -1])
Day02.valid_adjacent_diff?([1, 2, 3]) 
Day02.valid_adjacent_diff?([1, 5, 7])  
Day02.valid_adjacent_diff?([1, 1, 7])  
Day02.valid_adjacent_diff?([10, 2, 1, -1])
Day02.valid_adjacent_diff?([10, 8, 7, 4])
Day02.task1(test_input)
real_input =
  # You should paste your Advent of Code puzzle input here
  # This is only a part of my input
"""
51 54 57 60 61 64 67 64
54 56 57 58 60 60
41 44 45 46 48 50 54
62 64 67 69 72 79
57 58 61 62 63 6
63 65 68 70 71 72 74
52 50 49 47 46
30 31 33 34 36 39 40
53 50 47 44 43 42 41 39
21 18 17 15 14 12 10 9
57 60 62 63 64 66
36 39 41 44 45 46 47 49
74 77 80 81 84 87 90
83 84 87 88 89 91 92 94
73 71 68 67 66 64 61 60
18 20 23 24 26 28 31
89 87 85 82 81 80 77
95 93 91 88 87 85
48 49 52 55 57 58 60 62
"""
Day02.task1(real_input)
Day02.task2(test_input)
Day02.task2(real_input)