bjorng

bjorng

Erlang Core Team

Showing Posts 27 to 18

dimitarvp

dimitarvp

Life sadly kept getting in the way but ultimately:

defmodule Day02 do
  @moduledoc ~S"""
  A solution to https://adventofcode.com/2024/day/2.
  """

  @type level :: pos_integer()
  @type distance :: integer()
  @type report :: [level()]

  @spec all_variants_with_one_element_removed(report()) :: [report()]
  def all_variants_with_one_element_removed(list) do
    for i <- 0..(length(list) - 1), do: list |> List.delete_at(i)
  end

  @spec sign(integer()) :: :zero | :minus | :plus
  def sign(0), do: :zero
  def sign(i) when i > 0, do: :plus
  def sign(i) when i < 0, do: :minus

  @spec distances(report()) :: [distance()]
  def distances([first | rest]) do
    rest
    |> Enum.reduce({first, []}, fn current_level, {previous_level, distances} ->
      {current_level, [current_level - previous_level | distances]}
    end)
    |> then(fn {_last_level, distances} -> Enum.reverse(distances) end)
  end

  @spec same_signs?([distance()]) :: boolean()
  def same_signs?(list) do
    list
    |> Enum.map(&sign/1)
    |> Enum.uniq()
    |> length()
    |> Kernel.==(1)
  end

  @spec safe?(report()) :: boolean()
  def safe?(report) do
    distances = distances(report)
    monotonical? = same_signs?(distances)

    safely_advancing? =
      distances |> Enum.map(&abs/1) |> Enum.all?(fn distance -> distance <= 3 end)

    monotonical? and safely_advancing?
  end

  @spec safe_with_a_dampener?(report()) :: boolean()
  def safe_with_a_dampener?(report) do
    safe?(report) or
      report |> all_variants_with_one_element_removed() |> Enum.any?(&safe?/1)
  end

  @doc ~S"""
  iex> Day02.part_1("7 6 4 2 1\n1 2 7 8 9\n9 7 6 2 1\n1 3 2 4 5\n8 6 4 4 1\n1 3 6 7 9\n")
  nil
  """
  @spec part_1(String.t()) :: non_neg_integer()
  def part_1(input \\ Aoc.input(2)) do
    input
    |> Aoc.parse_lines_of_integers()
    |> Enum.count(&safe?/1)
  end

  @spec part_2(String.t()) :: non_neg_integer()
  def part_2(input \\ Aoc.input(2)) do
    input
    |> Aoc.parse_lines_of_integers()
    |> Enum.count(&safe_with_a_dampener?/1)
  end
end

Did my best to make it readable and intuitive, even benchmarked three competing implementation I had ideas about, and only posted the one that won.

Adzz

Adzz

Okay a little late to this one. My part 1 halts as soon as we see an error.

Part two is a little more complex but it does not use List.delete_at or anything. It stops as soon as there are more errors than is legal to correct. To satisfy the edge cases you have to attempt each starting sequence if any fail before you can rule the report unsafe.
Could probably make it shorter. But you definitely don’t have to try deleting each element in the list in turn you can be a bit more surgical so I think we avoid the combinatorial explosion.

Part 1

  def day_2_1() do
    "./day_2_1_input.txt"
    |> File.read!()
    |> String.split(@new_line, trim: true)
    |> Enum.reduce(0, fn line, count ->
      [one, two | rest] = line |> String.split(" ")
      one = String.to_integer(one)
      two = String.to_integer(two)
      diff = abs(one - two)

      if diff > 0 && diff < 4 do
        sum_safe_reports([two | rest], one < two, count)
      else
        count
      end
    end)
  end

  defp sum_safe_reports([_final], _, count), do: count + 1

  defp sum_safe_reports([current, next | rest], incrementing?, count) do
    next = String.to_integer(next)

    diff = if incrementing?, do: next - current, else: current - next

    if diff > 0 && diff < 4 do
      sum_safe_reports([next | rest], incrementing?, count)
    else
      count
    end
  end

Part 2

  def day_2_2() do
    "./day_2_1_input.txt"
    |> File.read!()
    |> String.split(@new_line, trim: true)
    |> Enum.reduce(0, fn line, count ->
      [one, two, three | rest] =
        line |> String.split(" ") |> Enum.map(&String.to_integer/1)

      possible_starting_combos = [
        {one, two, [two, three | rest], 0},
        {one, three, [three | rest], 1},
        {two, three, [three | rest], 1}
      ]

      start_with_pair(possible_starting_combos, count)
    end)
  end

  defp start_with_pair([], count), do: count

  defp start_with_pair([{left, right, rest, errors} | next_iteration], count) do
    new_count =
      if is_safe?(left, right, left < right) do
        sum_safe_reports(rest, left < right, errors, count)
      else
        count
      end

    if count == new_count do
      start_with_pair(next_iteration, count)
    else
      new_count
    end
  end

  defp is_safe?(first, next, incrementing?) do
    diff = if incrementing?, do: next - first, else: first - next
    diff > 0 && diff < 4
  end

  defp sum_safe_reports([_final], _, _, count), do: count + 1

  defp sum_safe_reports([penultimate, final], incrementing?, errors, count) do
    # If we have 0 errors then we can always fix when there are 2 numbers left.
    if errors < 1 || is_safe?(penultimate, final, incrementing?) do
      count + 1
    else
      count
    end
  end

  defp sum_safe_reports([one, two, three | rest], incrementing?, errors, count) do
    if is_safe?(one, two, incrementing?) do
      sum_safe_reports([two, three | rest], incrementing?, errors, count)
    else
      errors = errors + 1

      if is_safe?(one, three, incrementing?) && errors < 2 do
        sum_safe_reports([three | rest], incrementing?, errors, count)
      else
        count
      end
    end
  end
stevensonmt

stevensonmt

I tried something similar that ended up not working. My idea was to find how many inflection points there were in the series. If there were only two direction changes and the length of the middle segment was only one item you just need to know if the item before and the item after satisfy the distance rules.
I had something like

list 
|> Enum.zip(tl(list)) 
|> Enum.chunk_by(fn {a,b} -> a - b > 0 end)

If you have one chunk the list is sorted. If you have two chunks and the second one has a single item dropping the last item in the list would make it sorted. If you have three chunks and the middle chunk has a single pair, dropping the second item in that pair would make the list sorted.

I just couldn’t figure out how to include the max distance criteria.

donaldww

donaldww

#!/usr/bin/env elixir

Mix.install([
  {:ex_cli, "~> 0.1.6"}
])

defmodule Day2 do
  def run(test_file) do
    list = extract_list(test_file)
    IO.puts("Safe Reports: #{safe_reports(list)}")
    IO.puts("Dampened Safe Reports: #{safe_reports_dampened(list)}")
  end

  def safe_reports_dampened(reports_list) do
    Enum.reduce(reports_list, 0, fn list, safe_count ->
      if safe_report?(list) or can_become_safe_by_removing_one?(list),
        do: safe_count + 1,
        else: safe_count
    end)
  end

  def safe_reports(reports_list) do
    Enum.reduce(reports_list, 0, fn list, safe_count ->
      if safe_report?(list),
        do: safe_count + 1,
        else: safe_count
    end)
  end

  defp safe_report?([first, second | _])
       when abs(first - second) < 1 or abs(first - second) > 3,
       do: false

  defp safe_report?([first, second | rest]) do
    direction = if first > second, do: :decreasing, else: :increasing

    Enum.reduce_while(rest, {second, direction}, fn current, {prev, dir} ->
      diff = abs(prev - current)

      cond do
        diff < 1 or diff > 3 ->
          {:halt, :unsafe}

        dir == :increasing and prev < current ->
          {:cont, {current, dir}}

        dir == :decreasing and prev > current ->
          {:cont, {current, dir}}

        true ->
          {:halt, :unsafe}
      end
    end) != :unsafe
  end

  defp can_become_safe_by_removing_one?(list) do
    Enum.any?(Enum.with_index(list), fn {_elem, index} ->
      modified_list = List.delete_at(list, index)
      safe_report?(modified_list)
    end)
  end

  def extract_list(test_file) do
    File.stream!(test_file)
    |> Stream.map(&String.split/1)
    |> Stream.map(fn line ->
      Enum.map(line, &String.to_integer/1)
    end)
    |> Enum.to_list()
  end
end

defmodule Main do
  def main do
    {opts, _, _} = OptionParser.parse(System.argv(), switches: [file: :string])

    case opts do
      [file: test_file] -> Day2.run(test_file)
      _ -> IO.puts("Usage: ./day2.exs --file path/to/test_file.txt")
    end
  end
end

Main.main()
mwilsoncoding

mwilsoncoding

Long time lurker, using the advent as an excuse to say hi. =]

Here are my solutions for today.

Part 1:

defmodule SafeReports do
  @comparators %{
    gt: ">",
    lt: "<"
  }

  def count([_h], _safe?, _comparator), do: 1

  def count([a | [b | _t] = tail], safe?, comparator) do
    if safe? and apply(Kernel, :"#{@comparators[comparator]}", [a, b]) and abs(a - b) < 4 do
      count(tail, true, comparator)
    else
      0
    end
  end

  def solve() do
    File.stream!("02/input.txt")
    |> Enum.reduce(
      0,
      fn line, safe_report_count ->
        safe_report_count +
          (line
           |> String.trim()
           |> String.split(" ")
           |> Enum.map(&String.to_integer/1)
           |> (fn
                 [a | [b | _t]] = report ->
                   cond do
                     a < b ->
                       :lt

                     a > b ->
                       :gt

                     true ->
                       :eq
                   end
                   |> case do
                     :eq -> 0
                     comparator -> count(report, true, comparator)
                   end
               end).())
      end
    )
    |> IO.puts()
  end
end

SafeReports.solve()

Part 2:

defmodule SafeReports do
  @comparators %{
    gt: ">",
    lt: "<"
  }

  defp do_count([_h], _safe?, _comparator), do: 1

  defp do_count([a | [b | _t] = tail], safe?, comparator) do
    if safe? and apply(Kernel, :"#{@comparators[comparator]}", [a, b]) and abs(a - b) < 4 do
      do_count(tail, true, comparator)
    else
      0
    end
  end

  defp count([a | [b | _t]] = report) do
    cond do
      a < b ->
        :lt

      a > b ->
        :gt

      true ->
        :eq
    end
    |> case do
      :eq -> 0
      comparator -> do_count(report, true, comparator)
    end
  end

  defp count_if_safe(report) do
    Stream.unfold(
      {0, report},
      fn {index, report} = previous_state ->
        if index >= (report |> Enum.count()) do
          nil
        else
          {previous_state, {index + 1, report}}
        end
      end
    )
    |> Enum.reduce_while(
      0,
      fn {index, report}, _ ->
        case count(report) do
          0 ->
            case count(report |> List.delete_at(index)) do
              0 -> {:cont, 0}
              1 -> {:halt, 1}
            end
          1 -> {:halt, 1}
        end
      end
    )
  end

  def solve() do
    File.stream!("02/input.txt")
    |> Enum.reduce(
      0,
      fn line, safe_report_count ->
        safe_report_count +
          (line
           |> String.trim()
           |> String.split(" ")
           |> Enum.map(&String.to_integer/1)
           |> count_if_safe())
      end
    )
    |> IO.puts()
  end
end

SafeReports.solve()
dimitarvp

dimitarvp

:003:

Reminds me of one of George Carlin’s tidbits for when politicians are deflecting blame:

When the heat builds up, they say: “The whole thing was taken out of context”. Why is it always the whole thing? Apparently, it never happens that only a part of the thing can get taken out of context.

akin

akin

My solution for day 2:

defmodule AdventOfCode.DayTwo do
  def part_one(input) do
    input
    |> parse_input()
    |> Enum.count(&safe?/1)
  end

  def part_two(input) do
    input
    |> parse_input()
    |> Enum.count(&dampener_analysis/1)
  end

  defp parse_input(input) do
    input
    |> String.split("\n")
    |> Enum.map(fn line ->
      line
      |> String.trim()
      |> String.split()
      |> Enum.map(&String.to_integer/1)
    end)
  end

  defp safe?([l1, l2 | _] = report) do
    trend = if l1 < l2, do: :asc, else: :desc
    safe?(report, trend)
  end

  defp safe?([l1, l2 | _], :asc)
       when l1 > l2,
       do: false

  defp safe?([l1, l2 | _], :desc)
       when l1 < l2,
       do: false

  defp safe?([l1, l2 | _], _)
       when abs(l1 - l2) not in 1..3,
       do: false

  defp safe?([l1, l2], trend) do
    match_trend? =
      if trend == :asc,
        do: l1 < l2,
        else: l1 > l2

    match_trend? and abs(l1 - l2) in 1..3
  end

  defp safe?([_l1, l2 | rest], trend),
    do: safe?([l2 | rest], trend)

  defp dampener_analysis(report) do
    case safe?(report) do
      true ->
        true

      _ ->
        report
        |> Enum.with_index()
        |> Enum.map(fn {_, idx} ->
          safe?(List.delete_at(report, idx))
        end)
        |> Enum.any?()
    end
  end
end

BartOtten

BartOtten

My solution to today’s story.

Possible optimizations:

  • detect misleading direction by a → b immediately. Although with 4 reports in my input data that would be catched sooner, I doubt it would be more performant. It would however catch invalid input early on, so that’s something worth too.
  • there’s a very shitty return type in the code. @dimitarvp ..you have been warned :wink:
  • spot the major hole in the logic. I was surprised my data set passed….
defmodule Aoc2024.Solutions.Y24.Day02 do
  alias AoC.Input

  def parse(input, _part) do
    input
    |> Input.stream!(trim: true)
    |> Enum.map(&parse_line/1)
  end

  defp parse_line(line) do
    line
    |> String.split()
    |> Enum.map(&String.to_integer/1)
  end

  def part_one(problem) do
    Enum.count(problem, &(save?(&1) == true))
  end

  defp save?(levels) do
    [a, b | _] = levels
    direction = a < b && :asc || :desc

    # returns true or index....got fired.
    save?(levels, direction)
  end

  defp save?(_report, _direction, idx \\ 0)

  defp save?([x, y | t], :desc, idx),
    do: (x - y > 0 && (x - y) in 1..3 && save?([y|t], :desc, idx + 1)) || idx

  defp save?([x, y | t], :asc, idx),
    do: (x - y < 0 && (x - y) in -3..-1 && save?([y|t], :asc, idx + 1)) || idx

  defp save?([_], _, _), do: true

  def part_two(problem) do
    Enum.count(problem, &save_as_statistics?/1)
  end

  defp save_as_statistics?(report) do
    case save?(report) do
      true ->
        true

      idx ->
        # politician mode: enabled
        # 1. the idx is at fault.
        # 2. the next idx was at fault.
        # 3. we started on the wrong foot.
        cond do
          List.delete_at(report, idx) |> save?() == true -> true
          List.delete_at(report, idx + 1) |> save?() == true -> true
          List.delete_at(report, 0) |> save?() == true -> true
          true -> false
          false -> true # it does not even trigger warnings.
        end
    end
  end
end

ntalfer

ntalfer

I’ve ended up doing something that stops computation asap instead of brute force all possibilities.

defmodule D2 do
  def p1(file) do
    file
    |> reports()
    |> Stream.filter(&safe_report_p1?/1)
    |> Enum.count()
  end

  defp reports(file) do
    file
    |> File.stream!(:line)
    |> Stream.map(fn line ->
      line |> String.split() |> Enum.map(&String.to_integer/1)
    end)
  end

  def safe_report_p1?(report) do
    safe_report_p1?(report, :asc) or safe_report_p1?(report, :desc)
  end

  def safe_report_p1?([], _) do
    true
  end
  def safe_report_p1?([_], _) do
    true
  end
  def safe_report_p1?([a, b | rest], :asc) when a < b and b - a <= 3 do
    safe_report_p1?([b | rest], :asc)
  end
  def safe_report_p1?([a, b | rest], :desc) when a > b and a - b <= 3 do
    safe_report_p1?([b | rest], :desc)
  end
  def safe_report_p1?(_, _) do
    false
  end

  def p2(file) do
    file
    |> reports()
    |> Stream.filter(&safe_report_p2?/1)
    |> Enum.count()
  end

  def safe_report_p2?(report) do
    safe_report_p2?([], report, :asc) or safe_report_p2?([], report, :desc)
  end

  def safe_report_p2?(_, [], _) do
    true
  end
  def safe_report_p2?(_, [_], _) do
    true
  end
  def safe_report_p2?(scanned, [a, b | rest], :asc) when a < b and b - a <= 3 do
    safe_report_p2?(scanned ++ [a], [b | rest], :asc)
  end
  def safe_report_p2?(scanned, [a, b | rest], :desc) when a > b and a - b <= 3 do
    safe_report_p2?(scanned ++ [a], [b | rest], :desc)
  end
  def safe_report_p2?(scanned, [a, b | rest], asc_or_desc) do
    safe_report_p1?(scanned ++ [a | rest], asc_or_desc) or
      safe_report_p1?(scanned ++ [b | rest], asc_or_desc)
  end
  def safe_report_p2?(_, _, _) do
    false
  end
end
NobbZ

NobbZ

My second day solution took me much longer than necessary.

I managed to get most of it done between getting the kids to the bus and having my first meeting of the day. Though part B was off… And throughout the day, I took some minutes between meetings or during breaks to try to fix this.

Now, 12 hours after I have started the AoC day, I found a working solution, and in hindsight, my previous iterations, either skipped the variant with only the first or the last level, which lead to skewed results :slightly_frowning_face:

https://gitlab.com/NobbZ/aoc_ex/-/blob/main/lib/y2024/d02.ex?ref_type=heads

Where Next? Top

Trending in Challenges Top

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews