Very cute! I did something similar with converting everything to mod6 (Pos) representation, but didn't figure out the simpler equation for the mod6 counting, so I had
steps :: Pos -> Pos -> Int
steps a b
| a == b = 6
| otherwise = (b - a) `mod` 6
For part2, I used a Bag (multiset) to count the occurrences of each letter, ordered the resulting [(Pos, Int)] list in order of step distance from 0 ('r'), then
furthest :: [(Pos, Int)] -> Int
furthest ps
= foldl' go (0, 0) ps & fst
where
go (n, w) (p, c) = case steps w p of s -> (n + s + (c - 1) * 6, p)
I was thinking about mapping red to 6 instead of 0 (that'd make the sorting in part 2 simpler), but I hadn't had my second coffee yet and the logic was giving me headaches
and indeed, it works without changing the common code:
import Control.Monad
import Data.Bifunctor
import Data.Foldable
import Data.List
main = print
. join bimap
(sum
. (zipWith (\s t -> 6 - (s - t + 6) `mod` 6) <*> drop 1)
. (6:))
. ((,) <*> sortOn negate)
. concatMap (toList . flip lookup (zip "oygbvr" [1..]))
=<< getContents
New to FP and haskell. Let me know when I am missing a concept. The other solutions look so much more dense.
part1 :: String -> Int
part1 = snd . foldl (\(position, total_distance) x -> (x, total_distance + distance position x)) ('r', 0)
distance :: Char -> Char -> Int
distance from to
| from == to = length colors
| otherwise = (idx to - idx from) `mod` length colors
where
-- red (r), orange (o), yellow (y), green (g), blue (b), and violet (v)
colors = "roygbv"
idx c = fromJust (elemIndex c colors)
Your code looks good -- that's almost exactly how I solved it. One thing to note: foldl in Haskell is lazy like foldr, so it can inadvertently build up thunks when folding over large lists. It is usually recommended to use the strict variant foldl' for any fold that isn't explicitly lazy, instead. However in this case (and this is getting a bit esoteric!), the fold is reducing to a tuple (position, total_distance) which is a tuple constructor that is already in what is known as "weak head normal form", so a foldl' wouldn't help, here. What you can do is make the total_distance operand strict with a "bang pattern":
part1 = snd . foldl' (\(position, !total_distance) x -> (x, total_distance + distance position x)) ('r', 0)
That will force evaluation of total_distance every iteration of the fold, preventing a thunk buildup.
3
u/Atijohn 3d ago
probably could easily make the modulus transformation simpler, but eh
2
u/blackhat-hemsworth 3d ago
i was excited about actually using infinite strings here. still learning, tips welcome
Github
2
u/niecore 2d ago
New to FP and haskell. Let me know when I am missing a concept. The other solutions look so much more dense.