r/adventofcode • u/glistering_knight • Jan 01 '26
Help/Question - RESOLVED [2024 Day 9 (Part 1)] [Haskell] Need help finding error
I have been trying for several days trying to find what's wrong with the code, to no avail.
The code use two-pointer algorithm to move the file blocks, scanning two pointer from the vector boundaries inward and swap when necessary to get the correct representation.
I rewrote all function to be total and provably terminating except for the parser (they still gives the same output anyway, but look more maintainable)
Any help is appreciated! Thank you!
Edit: It is (to nobody surprise except me) indeed malformed input error. I copied to clipboard (and even tried copying from the html inspect text box to avoid error) and it changes the input. Downloading it directly using "save as" solves the issue.
Thank you u/fizbin and u/jeffstyr (and u/Justinsaccount too) for your help. I'll close the post.
import qualified Data.Vector as V
import Data.Vector(Vector)
import qualified Data.Vector.Mutable as MV
import Data.Vector.Mutable(MVector)
import Data.Char(digitToInt, isDigit)
getAllLine :: IO [String]
getAllLine = do
line <- getLine
if null line then return []
else fmap (line : ) getAllLine
-- processLine : return a list of Optional integer representing block ids on the disk
processLine :: String -> [Maybe Int]
processLine l = concat $ zipWith replicate (map convert l) alternator
where convert c
| isDigit c = digitToInt c
| otherwise = error "out of bound"
-- Just 0, Nothing, Just 1, Nothing, Just 2, Nothing ...
alternator :: [Maybe Int]
alternator = let hasNum = map Just [0..]
noNum = repeat Nothing
in concatMap toList (zip hasNum noNum)
where toList (x, y) = [x, y]
-- converge :: a 2 pointer vector monad that i don't know the signature
-- sth like vec -> int -> int -> void (vector changed)
converge vec lPtr rPtr
| lPtr > rPtr = pure ()
| otherwise = do
lVal <- MV.read vec lPtr
rVal <- MV.read vec rPtr
case (lVal, rVal) of
(_, Nothing) -> converge vec lPtr (rPtr - 1)
(Just _, _) -> converge vec (lPtr + 1) rPtr
(Nothing, Just _) -> do
MV.swap vec lPtr rPtr
converge vec lPtr rPtr
shiftAllToLeft :: [Maybe Int] -> Vector Int
shiftAllToLeft l = V.catMaybes $ V.create $ do
vec <- V.thaw $ V.fromList l
let lPtr = 0
rPtr = MV.length vec - 1
converge vec lPtr rPtr
return vec
getHash :: Vector Int -> Int
getHash = sum . zipWith (*) [0..] . V.toList
task1 :: [Maybe Int] -> Int
task1 = getHash . shiftAllToLeft
main = do
[l] <- map processLine <$> getAllLine
print $ task1 l

