haskell - Print all possible world configurations -


just starting out haskell! exercise, current problem i'm trying implement follows:

we have n squares, print possible world configurations :

  • (1) each square have "p" (pit) or not (2^n possibilities).
  • (2) there can @ 1 "w" (wumpus) in n squares (n+1 possibilities).

representing 2 squares 2 strings, here output example n=2. have (2^n)·(n+1) = (2^2)·(2+1) = 12 configurations.

[[" w"," "],[" "," w"],[" "," "],  [" w","p"],[" ","pw"],[" ","p"],  ["pw"," "],["p"," w"],["p"," "],  ["pw","p"],["p","pw"],["p","p"]] 

condition (1) implemented. looking around, i've found few ways express :

p 0 = [[]] p n = [x:xs | x <- [" ","p"], xs <- p (n-1)] 

or

p n = mapm (\x -> [" ","p"]) [1..n] 

or

p n = replicatem n [" ","p"] 

i cannot claim understand last 2 yet, here completeness.

question : how can add condition (2)? can done list comprehension? not-so-good-looking novice solution involved these functions:

insertw :: int -> [string] -> [string] insertw n xs      | n < 0     = xs     | n >= lgth = xs     | otherwise = (take (n) xs) ++ [xs!!n++"w"] ++ (drop (n+1) xs)     lgth  = length xs  duplicate :: int -> [string] -> [[string]] duplicate squares      | > lgth   = []     | otherwise  = (insertw squares) : duplicate (i+1) squares     lgth   = length squares  worlds :: int -> [[string]] worlds n = concat . map (duplicate 0) . p $ n 

seems obvious me :). in list comprehensions, later lists can depend on values generated in earlier ones. second function generates set calling first when adds wumpus..

p 0 = [[]] p n = [[x,' ']:xs | x <- [' ','p'], xs <- p (n-1)]  pw 0 = [[]] pw n = [[x,w]:xs | w <- [' ','w'], x <- [' ','p'], xs <- if w == 'w' p (n-1) else pw (n-1)] 

it isn't clean possible, find list comprehensions bring elegance problem :). totally worth it.


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -