adamu

adamu

Nobody’s doing Advent of Code this year? :grinning_face_with_smiling_eyes:

I might do the first week or so.

For Day 1, first I solved it using regular expressions and String.replace, which took about 10ms for each part.

Then I rewrote it using binaries and recursion, which got each part under 1ms.

  def filter_digits2(<<>>), do: <<>>
  def filter_digits2(<<x, rest::binary>>) when x in ?1..?9, do: <<x>> <> filter_digits2(rest)
  def filter_digits2(<<"one", rest::binary>>), do: "1" <> filter_digits2("e" <> rest)
  def filter_digits2(<<"two", rest::binary>>), do: "2" <> filter_digits2("o" <> rest)
  def filter_digits2(<<"three", rest::binary>>), do: "3" <> filter_digits2("e" <> rest)
  def filter_digits2(<<"four", rest::binary>>), do: "4" <> filter_digits2("r" <> rest)
  def filter_digits2(<<"five", rest::binary>>), do: "5" <> filter_digits2("e" <> rest)
  def filter_digits2(<<"six", rest::binary>>), do: "6" <> filter_digits2("x" <> rest)
  def filter_digits2(<<"seven", rest::binary>>), do: "7" <> filter_digits2("n" <> rest)
  def filter_digits2(<<"eight", rest::binary>>), do: "8" <> filter_digits2("t" <> rest)
  def filter_digits2(<<"nine", rest::binary>>), do: "9" <> filter_digits2("e" <> rest)
  def filter_digits2(<<_, rest::binary>>), do: filter_digits2(rest)

https://git.adamu.jp/adam/AdventOfCode/src/branch/main/2023/day1.exs

Showing Posts 1 to 10

mexicat

mexicat

stefanluptak

stefanluptak

How did you realize that "oneight" should be transformed to "18"?

kwando

kwando

Binary pattern matching made today’s problem quite straightforward, I got lucky with my input though so the first version which didn’t account for “overlapping” numbers worked, “oneight” for instance is both “one” and “eight”.

mexicat

mexicat

The naive solution didn’t work and while the text didn’t mention these cases specifically (which for day 1 is kind of unexpected…) I noticed the ambiguity in the eightwothree example, so I gave it a try.

stefanluptak

stefanluptak

Exactly. Day 1 used to be just a little warmup to get our environments up and running. :smiley: I was also quite surprised by them using this kind of “catch”. Or maybe I am just being tired and not thinking clearly enough. :smiley: Anyway, thank you for the explanation.

APB9785

APB9785

Creator of ECSx

My first approach didn’t handle overlaps properly in part 2, so I ended up with a somewhat funky pattern match syntax:

defp process_line(["o", "n", "e" | _] = [_h | t], ...),
    do: process_line(t, ...)

There’s probably a cleaner way to do this, but it works!

Full solution here: https://github.com/APB9785/AoC-2023-elixir/blob/master/lib/day_01.ex

mruoss

mruoss

I approached part 2 from both sides :wink:

defmodule Task2 do
  @digits %{
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "four" => 4,
    "five" => 5,
    "six" => 6,
    "seven" => 7,
    "eight" => 8,
    "nine" => 9
  }

  def solve(input) do
    input
    |> String.split("\n", trim: true)
    |> Enum.map(&convert_line/1)
    |> Enum.sum()
  end

  def convert_line(line) do
    10 * first_digit(line) + last_digit(String.reverse(line))
  end

  for digit <- 1..9 do
    string = Integer.to_string(digit)
    defp first_digit(<<unquote(string), _::binary>>), do: unquote(digit)
    defp last_digit(<<unquote(string), _::binary>>), do: unquote(digit)
  end

  for {string, digit} <- @digits do
    reverse_string = String.reverse(string)
    defp first_digit(<<unquote(string), _::binary>>), do: unquote(digit)
    defp last_digit(<<unquote(reverse_string), _::binary>>), do: unquote(digit)
  end

  defp first_digit(<<_::utf8, rest::binary>>), do: first_digit(rest)
  defp last_digit(<<_::utf8, rest::binary>>), do: last_digit(rest)
end
hq1

hq1

Very clean and fast, love it

andre-dasilva

andre-dasilva

Hi everyone, i am quite new to elixir. So my code looks quite ugly:

defmodule Day1 do
  def part_1(input) do
    File.stream!(input)
    |> Stream.map(&String.trim/1)
    |> Stream.map(fn line ->
      numbers =
        Enum.filter(String.graphemes(line), fn
          char ->
            case(Integer.parse(char)) do
              {_, ""} -> true
              :error -> false
            end
        end)

      [List.first(numbers), List.last(numbers)]
      |> Enum.join("")
      |> String.to_integer()
    end)
    |> Enum.sum()
  end

  defp find_number_in_text(line, keyword, value, numbers) do
    string_keyword = Atom.to_string(keyword)

    case :binary.match(line, string_keyword) do
      {pos, len} ->
        new_text = String.replace(line, string_keyword, String.duplicate("_", len), global: false)

        if new_text == line do
          numbers
        else
          numbers = numbers ++ [{pos, value}]

          find_number_in_text(new_text, keyword, value, numbers)
        end

      :nomatch ->
        numbers
    end
  end

  defp find_all_number(keywords, line) do
    text_numbers =
      Enum.reduce(keywords, [], fn {keyword, value}, acc ->
        find_number_in_text(line, keyword, value, acc)
      end)

    numbers =
      String.graphemes(line)
      |> Enum.with_index()
      |> Enum.flat_map(fn {char, pos} ->
        case(Integer.parse(char)) do
          {_, _} -> [{pos, char}]
          :error -> []
        end
      end)

    (text_numbers ++ numbers)
    |> Enum.sort_by(fn {pos, _} -> pos end)
    |> Enum.map(fn {_, number} -> number end)
  end

  def part_2(input) do
    keywords = [
      one: "1",
      two: "2",
      three: "3",
      four: "4",
      five: "5",
      six: "6",
      seven: "7",
      eight: "8",
      nine: "9"
    ]

    File.stream!(input)
    |> Stream.map(&String.trim/1)
    |> Stream.map(fn line ->
      numbers = find_all_number(keywords, line)
      String.to_integer(List.first(numbers) <> List.last(numbers))
    end)
    |> Enum.sum()
  end
end

But i gotta say there are some beautiful solutions in this thread :smile:

Askath

Askath

Took me way to long, as I misread the question. But was nice trying out elixir with a more difficult prolbem for the first time! really enjoyed it. Although my solution seems bruteforced :smiley:

defmodule Aoc1 do
  @moduledoc """
  Documentation for `Aoc1`.
  """

  @doc """
  Hello world.

  ## Examples

      iex> Aoc1.hello()
      :world

  """
  def first_and_last(string) do
    first = String.first(string)
    last = String.last(string)
    IO.puts("first: #{first}, last: #{last}")

    {first, last}
  end

  def read_file do
    case File.read("input") do
      {:ok, result} ->
        result

      {:error, error} ->
        IO.puts("Error: #{error}")
    end
  end

  def replace_spoken_numbers(list) do
    digits = [
      {"eighthree", 83},
      {"eightwo", 82},
      {"fiveight", 58},
      {"threeight", 38},
      {"sevenine", 79},
      {"oneight", 18},
      {"twone", 21},
      {"one", 1},
      {"two", 2},
      {"three", 3},
      {"four", 4},
      {"five", 5},
      {"six", 6},
      {"seven", 7},
      {"eight", 8},
      {"nine", 9},
      {"zero", 0}
    ]

    Enum.map(list, fn line ->
      Enum.reduce(digits, line, fn {word, digit}, acc ->
        String.replace(acc, word, Integer.to_string(digit))
      end)
    end)
  end

  def parse(file) do
    file |> String.split("\n", trim: true) |> replace_spoken_numbers()
  end

  def hello do
    numbers =
      parse(read_file())
      |> Enum.map(fn line ->
        Regex.replace(~r/[a-z]/, line, "") |> first_and_last()
      end)

    Enum.reduce(numbers, 0, fn {first, last}, acc ->
      num = first <> last
      IO.puts(num)
      acc = acc + String.to_integer(num)
      acc
    end)
    |> IO.inspect()
  end
end

Aoc1.hello()

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
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews