10
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Advent of code 2015 Day 19 Part 1 を Livebook で楽しむ

Last updated at Posted at 2024-12-03

はじめに

Advent of code 2024 の準備として、過去回の Advent of code 2015 を Livebook で楽しみます

本記事では Day 19 の Part 1 を解きます

Part 1 と Part 2 の解き方が全く違ったので分けています

問題文はこちら

実装したノートブックはこちら

セットアップ

Kino AOC をインストールします

Mix.install([
  {:kino_aoc, "~> 0.1"}
])

Kino AOC の使い方はこちらを参照

入力の取得

"Advent of Code Helper" スマートセルを追加し、 Day 19 の入力を取得します

スクリーンショット 2024-12-02 23.25.07.png

私の答え

私の答えです。
折りたたんでおきます。
▶を押して開いてください。

回答

まず入力を読み込み、最初の分子配列と置換配列を取得します

rows = String.split(puzzle_input, "\n")
[molecules | replacements] = Enum.reverse(rows)

replacements =
  replacements
  |> Enum.filter(&(&1 != ""))
  |> Enum.map(fn row ->
    [src, dst] = String.split(row, " => ")
    {src, dst}
  end)

{molecules, replacements}

全ての置換について、1回だけ置換した場合の文字列を生成し、重複を排除して数えます

replacements
|> Enum.map(fn {src, dst} ->
  0..(String.length(molecules) - 1)
  |> Enum.map(fn index ->
    replaced =
      molecules
      |> String.slice(index, String.length(molecules) - index)
      |> String.replace(src, dst, global: false)
    
    String.slice(molecules, 0, index) <> replaced
  end)
  |> Enum.filter(&(&1 != molecules))
  |> Enum.uniq()
end)
|> Enum.concat()
|> Enum.uniq()
|> length()

まとめ

Part 1 は単純でしたが、、、

Part 2 はこちら

10
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?