<turbo-stream action="append" target="posts_list"><template>    <div class="postbit" id="348605" data-post-id="348605">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="newton-peixoto" src="/assets/icons/user-9f439610.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  newton-peixoto
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Livebook. solution using maps<br>
<a href="https://github.com/newton-peixoto/advent-of-code/commit/df97e0fe72c3797e664cf392a51fcf38d982dd65#diff-03ac184df3657c047b4aab1cf312757da95a7cb83163b100662ca7a13ae8dc81R43" class="onebox" target="_blank" rel="noopener nofollow ugc">https://github.com/newton-peixoto/advent-of-code/commit/df97e0fe72c3797e664cf392a51fcf38d982dd65#diff-03ac184df3657c047b4aab1cf312757da95a7cb83163b100662ca7a13ae8dc81R43</a></p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="348605" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/advent-of-code-2024-day-5/67893/22">Post #21</a>
	                </div>
	            </div>
              <div id="likers-container-348605" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="348605"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #21"></div>
  </section>
</div>
    <div class="postbit" id="348607" data-post-id="348607">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="Andrew-Bekhiet" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/Andrew-Bekhiet/120/39712_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  Andrew-Bekhiet
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>My solution is very similar to <a class="mention" href="/u/seeplusplus" rel="nofollow">@seeplusplus</a></p>
<p>Didn’t realize I could use the rules to sort the pages, until I got a bit stuck in part 2 and decided to rethink the whole thing again</p>
<p><a href="https://github.com/Andrew-Bekhiet/advent-of-code-2024/blob/master/Day-5/elixir.ex" class="onebox" target="_blank" rel="noopener nofollow ugc">https://github.com/Andrew-Bekhiet/advent-of-code-2024/blob/master/Day-5/elixir.ex</a></p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="348607" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/advent-of-code-2024-day-5/67893/23">Post #22</a>
	                </div>
	            </div>
              <div id="likers-container-348607" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="348607"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #22"></div>
  </section>
</div>
    <div class="postbit" id="348620" data-post-id="348620">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="bengtson" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/bengtson/120/20947_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  bengtson
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>I used a sort function to Enum.sort based on the rules. This created a list of update entries each with {original_order, sorted_order).  From there it was a simple sort for; part1 == and part 2 !=, then summing the middle value in each list.<br>
Here’s the code for part 1 and part 2:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule Aoc.Day05 do
  def run() do
    IO.puts("Part 1 : result: #{part1()}")
    IO.puts("Part 2 : result: #{part2()}")
  end

  def part1() do
    get_ordered_lists()
    |&gt; Enum.filter(fn {original, ordered} -&gt; original == ordered end)
    |&gt; Enum.map(fn {l, _o} -&gt; Enum.at(l, trunc(Enum.count(l) / 2)) end)
    |&gt; Enum.sum()
  end

  def part2() do
    get_ordered_lists()
    |&gt; Enum.filter(fn {original, ordered} -&gt; original != ordered end)
    |&gt; Enum.map(fn {_l, o} -&gt; Enum.at(o, trunc(Enum.count(o) / 2)) end)
    |&gt; Enum.sum()
  end

  def get_ordered_lists() do
    {rules, updates} = get_input()

    updates
    |&gt; Enum.map(fn page_list -&gt; {page_list, check_page_order(page_list, rules)} end)
  end

  def check_page_order(page_list, rules) do
    page_list
    |&gt; Enum.sort(fn n1, n2 -&gt;
      rule = Map.get(rules, n1, [n1])
      not Enum.member?(rule, n2)
    end)
    |&gt; Enum.reverse()
  end

  # parsed_rules is map of page =&gt; [pages list must be after]
  # parsed_update is list of updates, each update is a list of original order.

  def get_input() do
    [rules, updates] =
      String.split(Atom.to_string(__MODULE__), ".")
      |&gt; List.last()
      |&gt; String.downcase()
      |&gt; then(fn day -&gt; "lib/#{day}/input.txt" end)
      |&gt; File.read!()
      |&gt; String.split("\n\n")

    parsed_rules =
      rules
      |&gt; String.split("\n")
      |&gt; Enum.map(fn rule -&gt; String.split(rule, "|") end)
      |&gt; Enum.map(fn [f, l] -&gt; {String.to_integer(f), String.to_integer(l)} end)
      |&gt; Enum.group_by(fn {b, _a} -&gt; b end)
      |&gt; Enum.map(fn {p, list} -&gt; {p, list |&gt; Enum.map(fn {_p, i} -&gt; i end)} end)
      |&gt; Enum.into(%{})

    parsed_updates =
      updates
      |&gt; String.split("\n")
      |&gt; Enum.map(fn nums -&gt; String.split(nums, ",") end)
      |&gt; Enum.map(fn list -&gt; list |&gt; Enum.map(fn strint -&gt; String.to_integer(strint) end) end)

    {parsed_rules, parsed_updates}
  end
end

</code></pre> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="348620" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/advent-of-code-2024-day-5/67893/24">Post #23</a>
	                </div>
	            </div>
              <div id="likers-container-348620" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="348620"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #23"></div>
  </section>
</div>
    <div class="postbit" id="348623" data-post-id="348623">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="antoine-duchenet" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/antoine-duchenet/120/27136_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  antoine-duchenet
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Many problems in AoC are NOT the general case. Given input is built in a specific way to ensure there is a solution. Those “meta” bias can sometimes be used to find shortcuts.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="348623" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/advent-of-code-2024-day-5/67893/25">Post #24</a>
	                </div>
	            </div>
              <div id="likers-container-348623" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="348623"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #24"></div>
  </section>
</div>
    <div class="postbit" id="348625" data-post-id="348625">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="rvnash" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/rvnash/120/34778_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  rvnash
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Interesting, I did not know that. It’s my first time trying AoC.<br>
Another possible condition that would cause confusion is if the rule-set is not transitive.</p>
<blockquote>
<p>1|2<br>
2|3<br>
3|1</p>
<p>1,2,3</p>
</blockquote>
<p>No way to sort that to fit all the rules.</p>
<p>Another one would be if the rules form islands.</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">1|2
3|4

4,3,2,1
</code></pre>
<p>There are many ways to sort that like <code>1,2,3,4</code> and <code>1,3,2,4</code></p>
<p>Speaking of which, if the data has an even number of elements then there is not middle element.</p>
<p>I spent a lot of time fretting over these possibilities. I guess the best way to do this would be to check for them as assumptions before trying to handle them somehow.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="348625" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/advent-of-code-2024-day-5/67893/26">Post #25</a>
	                </div>
	            </div>
              <div id="likers-container-348625" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="348625"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #25"></div>
  </section>
</div>
    <div class="postbit" id="348632" data-post-id="348632">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="Flo0807" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/Flo0807/120/28461_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  Flo0807
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Hey!</p>
<p>First, I have grouped the rules by their second number. For each number of a page, I get the relevant rules from this map. I then check whether the rest of my list has any numbers in common with the list of first numbers of the relevant rules. If so, it means that the page violates a rule.</p>
<p>Source Code:</p>
<p><a href="https://github.com/Flo0807/adventofcode/blob/main/2024/05.livemd" class="onebox" target="_blank" rel="noopener nofollow ugc">https://github.com/Flo0807/adventofcode/blob/main/2024/05.livemd</a></p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="348632" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/advent-of-code-2024-day-5/67893/27">Post #26</a>
	                </div>
	            </div>
              <div id="likers-container-348632" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="348632"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #26"></div>
  </section>
</div>
    <div class="postbit" id="348637" data-post-id="348637">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="lkuty" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/lkuty/120/34879_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  lkuty
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<pre data-code-wrap="elixir"><code class="lang-elixir">$ ./day05.exs
Part1. Sum: 4790
Part 1 + I/O done in 5729 µs
Part2. Sum: 6319
Part 2 done in 1605 µs
</code></pre>
<p>File <code>day05.exs</code>:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">#!/usr/bin/env elixir

# AoC 2024. day 5.

defmodule Part1 do
  @spec order_ok?([integer()], MapSet.t()) :: boolean()
  def order_ok?(numbers, rules)
  def order_ok?([], _set), do: true
  def order_ok?([number | numbers], rules) do
    # If for all the following `numbers` x after `number`, we cannot find a rule x|number
    # Then `number` is at the right position
    Enum.all?(numbers, fn x -&gt; !MapSet.member?(rules, {x, number}) end)
    &amp;&amp; order_ok?(numbers, rules)
  end
end

# part 1. accumulates the data and at the same time solve part 1.
# it could be decoupled
start = System.monotonic_time(:microsecond)
{rules, bad_updates, sum} = File.stream!("../day05.txt")
  |&gt; Enum.reduce({MapSet.new(), [], 0}, fn line, {rules, updates, sum} -&gt;
    case Regex.run(~r/^(?:(\d+)\|(\d+))|\d+(?:,\d+)+/, line) do
      [_, fst, snd] -&gt; # first, accumulate the rules in the MapSet
        {MapSet.put(rules, {String.to_integer(fst), String.to_integer(snd)}), updates, sum}
      nil -&gt; {rules, updates, sum}
      [update] -&gt; # then, check all the updates
        update = update |&gt; String.split(",") |&gt; Enum.map(&amp;String.to_integer/1)
        if Part1.order_ok?(update, rules) do
         # take the middle number and add it to sum
         {rules, updates, sum + :lists.nth(div(length(update), 2) + 1, update)}
        else
         {rules, [update | updates], sum}
        end
    end
  end)
IO.puts("Part1. Sum: #{sum}")
elapsed = System.monotonic_time(:microsecond) - start
IO.puts "Part 1 + I/O done in #{elapsed} µs"

# part 2
start = System.monotonic_time(:microsecond)
Enum.reduce(bad_updates, 0, fn update, sum -&gt;
  update = Enum.sort(update, fn n1, n2 -&gt; MapSet.member?(rules, {n1, n2}) end)
  sum + :lists.nth(div(length(update), 2) + 1, update)
end)
|&gt; IO.inspect(label: "Part2. Sum")
elapsed = System.monotonic_time(:microsecond) - start
IO.puts "Part 2 done in #{elapsed} µs"
</code></pre> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="348637" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/advent-of-code-2024-day-5/67893/28">Post #27</a>
	                </div>
	            </div>
              <div id="likers-container-348637" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="348637"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #27"></div>
  </section>
</div>
    <div class="postbit" id="348648" data-post-id="348648">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="king-11" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/king-11/120/36850_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  king-11
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>I used local topological sort over the local graph formed by pair of nodes in each updated runs under 30ms so seems fair enough</p>
<p><a href="https://github.com/king-11/AdventOfCode/blob/main/lib/advent_of_code/day_05.ex" class="onebox" target="_blank" rel="noopener nofollow ugc">https://github.com/king-11/AdventOfCode/blob/main/lib/advent_of_code/day_05.ex</a></p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="348648" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/advent-of-code-2024-day-5/67893/29">Post #28</a>
	                </div>
	            </div>
              <div id="likers-container-348648" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="348648"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #28"></div>
  </section>
</div>
    <div class="postbit" id="348651" data-post-id="348651">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="ken-kost" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/ken-kost/120/40209_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  ken-kost
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Why not<br>
<code>not is_in_rules</code><br>
<img src="https://forum.elixirforum.com/images/emoji/apple/cowboy_hat_face.png?v=15" title=":cowboy_hat_face:" class="emoji only-emoji" alt=":cowboy_hat_face:" loading="lazy" width="20" height="20"></p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="348651" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/advent-of-code-2024-day-5/67893/30">Post #29</a>
	                </div>
	            </div>
              <div id="likers-container-348651" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="348651"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #29"></div>
  </section>
</div>
    <div class="postbit" id="348656" data-post-id="348656">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="joelheaps" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/joelheaps/120/36851_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  joelheaps
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p><a class="mention" href="/u/king-11" rel="nofollow">@king-11</a> Figured I’d rather bring some discussion here than Reddit.</p>
<p>Looks like it took about 36ms for the swap method in part 2.  (Using Livebook, so bear with my formatting).</p>
<p>Edit: Got it down to around 29ms now.</p>
<h2><a name="p-348656-part-1-1" class="anchor" href="#p-348656-part-1-1" aria-label="Heading link" rel="nofollow"></a>Part 1</h2>
<pre data-code-wrap="elixir"><code class="lang-elixir">[rules, updates] = Kino.FS.file_path("day5_input.txt")
  |&gt; File.read!()
  |&gt; String.trim()
  |&gt; String.split("\n\n")
  |&gt; Enum.map(fn section -&gt;
    String.trim(section)
    |&gt; String.split("\n")
  end)

rules = Enum.map(rules, fn pair -&gt;
  String.split(pair, "|") 
  |&gt; Enum.map(&amp;String.to_integer/1)
  |&gt; List.to_tuple()
end)

updates = Enum.map(updates, fn group -&gt;
  String.split(group, ",")
  |&gt; Enum.map(&amp;String.to_integer/1)
end)
</code></pre>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule UpdateValidator do
  @doc """
  Check if all {x before y} rules pass for the given update.
  """
  def is_valid_update?(update, rules) do
    not Enum.any?(rules, fn {x, y} -&gt; not is_before?(x, y, update) end)
  end

  @doc """
  Check if x occurs before y in the given list
  """
  def is_before?(x, y, list = [first | rest]) do
    if x in list and y in list do
      if y == first, do: false, else: is_before?(x, y, rest)
    else
      true
    end
  end
end

sum_middle_numbers = fn updates -&gt; updates
  |&gt; Enum.map(&amp; {length(&amp;1) |&gt; Integer.floor_div(2), &amp;1})  # Get index of middle num.
  |&gt; Enum.map(fn {middle_index, update} -&gt;
      Enum.at(update, middle_index)
    end)  # Extract value at index
  |&gt; Enum.sum()
end

valid_updates = Enum.filter(updates, fn update -&gt;
  UpdateValidator.is_valid_update?(update, rules)
end)

result = sum_middle_numbers.(valid_updates)
</code></pre>

<pre data-code-wrap="elixir"><code class="lang-elixir">----
</code></pre>
<h2><a name="p-348656-part-2-2" class="anchor" href="#p-348656-part-2-2" aria-label="Heading link" rel="nofollow"></a>Part 2</h2>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule UpdateFixer do
  import UpdateValidator

  @doc """
  Recursively applies fixes until no more
  modifications are made (some fixes break other rules).
  """
  def fix_update(update, rules) do
    recursively_fix_update({true, update}, rules)
  end

  # Simply facilitates recursive calling.
  defp recursively_fix_update({true, update}, rules) do
    result = do_fix_update(update, rules)
    recursively_fix_update(result, rules)
  end
  defp recursively_fix_update({false, update}, _), do: update

  # Applies fixes for all rules by swapping values.
  defp do_fix_update(update, rules, modified? \\ false)
  defp do_fix_update(update, [], modified?), do: {modified?, update}
  defp do_fix_update(update, [{x, y} | rules], modified?) do
    {update_, modified?} = if not is_before?(x, y, update) do
      # Swap values if this rule failed validation.
      update_ = update
        |&gt; Enum.map(&amp; {&amp;1})  # Pack into tuple to make compat. with keyreplace
        |&gt; List.keyreplace(x, 0, {y})
        |&gt; List.keyreplace(y, 0, {x})
        |&gt; Enum.map(fn {val} -&gt; val end)
      {update_, true}
    else
      # Otherwise, pass update as-is.
      {update, modified?}
    end
    # Check next rule.
    do_fix_update(update_, rules, modified?)
  end
end

start = System.monotonic_time(:microsecond)

result = updates -- valid_updates  # Invalid updates
  |&gt; Enum.map(fn update -&gt; UpdateFixer.fix_update(update, rules) end)
  |&gt; sum_middle_numbers.()

IO.puts("Part 2 result: #{result}")

elapsed = System.monotonic_time(:microsecond) - start
IO.puts "Part 2 finished in #{elapsed / 1000}ms"
</code></pre>

<pre data-code-wrap="elixir"><code class="lang-elixir">Part 2 result: ----
Part 2 finished in 29.442ms
</code></pre> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="348656" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/advent-of-code-2024-day-5/67893/31">Post #30</a>
	                </div>
	            </div>
              <div id="likers-container-348656" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="348656"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #30"></div>
  </section>
</div>
</template></turbo-stream><turbo-stream action="replace" target="load-more-container"><template><div id="load-more-container" class="load-more-container">
    <a class="load-more-button" data-turbo-stream="true" href="/topics/67893/load_more?page=4">Load more posts (28 remaining)</a>
</div></template></turbo-stream>