[Haskell-beginners] Spoj BWHEELER problem - input problem

Artur Tadrała artur.tadrala at gmail.com
Sat Jan 14 21:34:53 CET 2012


While learning Haskell I'm trying to solve some simple problems on
spoj.ploccasionally. Currently I'm working on:
http://www.spoj.pl/problems/BWHEELER/. I figured out how to solve it but I
have some problems with reading input (that's my guess)

Here is my solution:

import Data.List
import Data.Array
import qualified Data.ByteString.Lazy.Char8 as BS
import IO

traverse :: Array Int (Char, Int) -> Int -> Int -> String -> String
traverse endings n k acc =
    let (c,i) = endings ! n
    in if k == 0
        then acc
        else traverse endings i (k-1) (c:acc)

solve :: (Int, String) -> String
solve (n,w) =
    let l = length w
        endings = sort $ zip w [0..]
        endingsArray = array (0, l) (zip [0..] endings)
    in reverse $ traverse endingsArray (n-1) l ""

parseCases :: [BS.ByteString] -> [(Int, String)]
parseCases (l:l':ls) =
    let n = readInt l
        w = BS.unpack l'
    in (n,w):parseCases ls
parseCases _ = []

main :: IO ()
main = do
  ls <- BS.lines `fmap` (BS.readFile "input.txt")
  putStr $ unlines $ map solve $ parseCases ls

readInt :: BS.ByteString -> Int
readInt x =
  case BS.readInt x of Just (i,_) -> i
                       Nothing    -> error ("Unparsable Int" ++ (show x))

The input.txt file contains following text:

When I compile and execute this code i get follwing output:

It's different  when compared to this in ghci ( this is what I expect):
 > map solve [(2,"bacab"), (3, "rwlb"), (11,"baaabaaaabbbaba")]

Can you explain me what I'm doing wrong?
I appreciate any tips how to improve this code also.

Thanks for help!
Artur Tadrała
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120114/44382447/attachment.htm>

More information about the Beginners mailing list