import gleam/dict import gleam/int import gleam/list import gleam/pair import gleam/string pub fn solve_a(program: String) -> Int { let waypoints = "roygbv" |> string.to_graphemes |> list.index_map(fn(p, i) { #(p, i) }) let steps = program |> string.to_graphemes let #(answer, _) = walk(waypoints, steps) answer } pub fn solve_b(program: String) -> Int { let waypoints = "roygbv" |> string.to_graphemes |> list.index_map(pair.new) let steps = program |> string.to_graphemes let #(answer, _) = walk(waypoints, sort(steps)) answer } pub fn walk(waypoints: List(#(String, Int)), steps: List(String)) { use #(count, index), step <- list.fold(steps, #(0, 0)) let assert Ok(#(_, next)) = list.find(waypoints, fn(tup) { tup.0 == step }) let distance = case next - index { // 6 = length of "roygbv" x if x < 0 -> x + 6 0 -> 6 y -> y } #(count + distance, next) } pub fn sort(steps: List(String)) { let ranks = "rvbgyo" |> string.to_graphemes |> list.index_map(fn(p, i) { #(p, i) }) |> dict.from_list list.sort(steps, fn(a, b) { let assert Ok(a_rank) = dict.get(ranks, a) let assert Ok(b_rank) = dict.get(ranks, b) int.compare(a_rank, b_rank) }) }