LostKobrakai

LostKobrakai

Advent of Code 2022 - Day 10

This one was really fun contrary to other “implement something CPU like” puzzles in the past. I used a bunch of Stream API and a module for scoping the CRT logic. I really liked the visual component of part 2.

Solution
defmodule Day10 do
  defmodule CRT do
    defstruct pixels: [], index: 0

    def render_pixel(state, x) do
      pixel = if state.index in (x - 1)..(x + 1), do: "#", else: "."

      %__MODULE__{
        pixels: [pixel | state.pixels],
        index: rem(state.index + 1, 40)
      }
    end

    def render(state) do
      state.pixels
      |> Enum.reverse()
      |> Enum.chunk_every(40)
      |> Enum.join("\n")
    end
  end

  def run(text) do
    text
    |> program()
    |> Stream.filter(fn {_, cycle} -> cycle in [20, 60, 100, 140, 180, 220] end)
    |> Stream.map(fn {x, cycle} -> x * cycle end)
    |> Enum.take(6)
    |> Enum.sum()
  end

  def render_to_crt(text) do
    text
    |> program()
    |> Stream.take_while(fn {_, cycle} -> cycle <= 240 end)
    |> Enum.reduce(%CRT{}, fn {x, _}, crt ->
      CRT.render_pixel(crt, x)
    end)
    |> CRT.render()
  end

  defp program(text) do
    text
    |> String.split("\n", trim: true)
    |> Stream.transform(1, fn
      "noop", x -> {[x], x}
      "addx " <> num, x -> {[x, x], x + String.to_integer(num)}
    end)
    |> Stream.with_index(1)
  end
end

Most Liked

deadbeef

deadbeef

Nothing special/similar to others. Reminded me of 2021-13 which also had you print out letters with .'s and #'s. So had some fun and added some IO.ANSI to “pretty” print, e.g.

kwando

kwando

I had a very clunky version that got me the gold stars, but after some coffee I ended up with a super neat version using Stream.transform.

  input
  |> Stream.transform({1, 1}, fn 
    :noop, {cycle, x} ->
      {[{cycle, x}], {cycle + 1, x}}
    {:addx, value}, {cycle, x} ->
      {[{cycle, x}, {cycle + 1, x}], {cycle + 2, x + value}}
  end)

That will give you a stream of {cycle_no, x} tuples that you could use to find the solution to the other parts. input is parsed in to a list of tuples, the small example would look like the [:noop, {:addx, 3}, {:addx, -5}].

Just pipe that stream into this for the second part :slight_smile:

cycle_stream # from above
|> Stream.map(fn 
  {pc, x} when rem(pc-1, 40) in (x-1)..(x+1) -> ?#
  _ -> ?\s
end)
|> Stream.chunk_every(40)
|> Enum.intersperse(?\n)
|> IO.puts

Elixir standard library is so awesomely good.

kwando

kwando

It is probably faster with handrolled recursive functions, but it can be quite dense to read :sweat_smile:

There are a lot of gems hidden in the standard library:)

pistelak

pistelak

You are right, there is something wrong. :sweat_smile: I tried to someone’s else solution and the result is slightly different: Screenshot 2022-12-10 at 18.56.23 2022-12-10 at 7.00.50 PM … Will take a look.

pistelak

pistelak

Error by one :sweat: - cycles are indexed from 1 but CRT starts drawing at 0. So
Enum.member?(i.x-1..i.x+1, rem(i.cycle - 1, 40)) is correct.

Where Next?

Popular in Challenges Top

ehayun
I have 2 arrays: a1 can be any combination of value or nil like that a1 = [1,nil,3] and array 2 the same a2 = [4,2, nil] How do I com...
New
New
shritesh
This was way too easy after the last few days. Simple map, filter and count.
New
Aetherus
Today’s challenge is quite interesting. I ended up using Zipper to solve this problem. Maybe I overengineered quite a bit. The data stru...
New
Aetherus
The second part of today’s puzzle is very misleading. FYI, each of the ghosts has only one possible position that ends with a "Z" on its...
New
bjorng
Note: This topic is to talk about Day 23 of the Advent of Code. For general discussion about the Advent of Code 2018 and links to topics...
New
bjorng
This topic is about Day 2 of the Advent of Code 2021. We have a private leaderboard (shared with users of Erlang Forums): https://adven...
New
stevensonmt
Trying to get more facility with dynamic programming concepts on Leetcode and having an issue I can’t find a way around. It’s a chutes an...
New
bjorng
Note: This topic is to talk about Day 18 of the Advent of Code 2019. There is a private leaderboard for elixirforum members. You can joi...
New
Aetherus
Don’t know why the regex ~r/[\W && [^\.]]/x does not work in Elixir. It works pretty well in Ruby. Anyway, here is my solution:
New

Other popular topics Top

albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement