Day 2: Fulminating Farmland

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

  • Deebster@programming.dev
    link
    fedilink
    English
    arrow-up
    2
    ·
    10 hours ago

    nu

    I got a bit into the weeds with how nushell handled a few things, so this wasn’t the fastest option. Still, I’ve learnt something - surely that makes it worthwhile(…?)

    Part 1 uses modulo 6 (treating r as 6), and p2 is just sorting the waypoints (again with r as 6).

    use std/util repeat
    
    def parse [input] {
      $input | split chars | each {
        match $in {
          'r' => 0,
          'o' => 1,
          'y' => 2,
          'g' => 3,
          'b' => 4,
          'v' => 5,
          _ => { error make "bad input" }
        }
      }
    }
    
    def dist [] {
      mut dist = 0;
      mut location = 0;
      for point in (parse $in) {
        let d = ($point - $location) mod 6
        $dist += if $d > 0 { $d } else { 6 }
        $location = $point
      }
      $dist
    }
    
    def sortpoints [] {
      # make a record/dictionary { point => frequency }
      let freq = $in | split chars | histogram | select value count | transpose -rd
      'rvbgyo' | split chars | reduce --fold "" {|point, out| 
        let n = $freq | get -o $point | default 0
        $out ++ ($point | repeat $n | str join)
      }
    }
    

    $in is for values from the pipeline, so I run p2 as

    ❯ "rybryb" | sortpoints | dist
    32