From 7ca1851f732e2f74339354ecc25ef709754a3ac3 Mon Sep 17 00:00:00 2001 From: Oscar Najera Date: Tue, 6 Dec 2022 17:26:18 +0100 Subject: [AoC2022] 06 Rust & Elixir --- AoC2022/06/makefile | 4 ++-- AoC2022/06/solver.exs | 27 +++++++++++++++++++++++++++ AoC2022/06/solver.rs | 27 +++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 2 deletions(-) create mode 100644 AoC2022/06/solver.exs create mode 100644 AoC2022/06/solver.rs diff --git a/AoC2022/06/makefile b/AoC2022/06/makefile index fce871b..3ddfc1a 100644 --- a/AoC2022/06/makefile +++ b/AoC2022/06/makefile @@ -11,5 +11,5 @@ run: sbcl --load ~/.sbclrc --script solver.lisp emacs -batch -l ert -l solver.el -f ert-run-tests-batch-and-exit - # rustc solver.rs && ./solver - # elixir solver.ex + rustc solver.rs -o /tmp/solver && /tmp/solver + elixir solver.exs diff --git a/AoC2022/06/solver.exs b/AoC2022/06/solver.exs new file mode 100644 index 0000000..3d47677 --- /dev/null +++ b/AoC2022/06/solver.exs @@ -0,0 +1,27 @@ +defmodule Solver.Day6 do + def marker([_h | tail] = line, distinct, counter) do + line + |> Enum.take(distinct) + |> MapSet.new() + |> MapSet.size() + |> Kernel.then(fn amount -> + case amount do + ^distinct -> counter + _ -> marker(tail, distinct, counter + 1) + end + end) + end + + def start(msg, distinct) do + String.graphemes(msg) |> marker(distinct, distinct) |> IO.puts() + end +end + +case File.read("input") do + {:ok, body} -> + Solver.Day6.start(body, 4) + Solver.Day6.start(body, 14) + + {:error, reason} -> + IO.puts(reason) +end diff --git a/AoC2022/06/solver.rs b/AoC2022/06/solver.rs new file mode 100644 index 0000000..0d59479 --- /dev/null +++ b/AoC2022/06/solver.rs @@ -0,0 +1,27 @@ +use std::fs; +use std::io::{self, Read}; + +fn solver(bytes: &Vec, marker_len: u32) -> u32 { + let mut count = marker_len; + for view in bytes.windows(marker_len as usize) { + let mut acc: u32 = 0; + for elt in view { + acc |= 1 << (elt - 96); + } + if u32::count_ones(acc) >= marker_len { + break; + } + count += 1; + } + count +} + +fn main() -> io::Result<()> { + let mut file = fs::File::open("input").unwrap(); + let mut bytes: Vec = Vec::new(); + file.read_to_end(&mut bytes)?; + println!("All test passed. {}", solver(&bytes, 4)); + println!("All test passed. {}", solver(&bytes, 14)); + + Ok(()) +} -- cgit v1.2.3