solveMaze function explaination v2

solveMaze x = let
  all = concat [ [(row, colum, char) 
                 | (colum, char) <- zip [0..] line ] 
               | (row, line) <- zip [0..] x ]

  (start_r, start_c, _) = head (filter (test 's') all)
  (end_r, end_c, _)     = head (filter (test 'e') all)

  filterFree = [ (row, colum) 
               | (row, colum, char) <- all, char == ' ' || char == 'e' ]

  solve [] _ = []
  solve ((row, colum, price):rest) freeElement = let
    n = [ x | x <- [ (row + 1, colum)
                  , (row - 1, colum)
                  , (row, colum + 1)
                  , (row, colum - 1) ]
          , x `elem` freeElement ]
    in (row, colum, price) : solve (rest ++ [ (row, colum, price+1) | (row, colum) <- n ])
                                  [ x | x <- freeElement, x `notElem` n ]

  solution = solve [(start_r, start_c, 0)] filterFree
  in head [ p | (row, colum, p) <- solution, row == end_r, colum == end_c ]

test :: Eq a => a -> (b, c, a) -> Bool
test x (_, _, char) = char == x

allPositions x = concat [ [(row, colum, char) 
                         | (colum, char) <- zip [0..] line ] 
                        | (row, line) <- zip [0..] x ]

-- (startR,startC, _ )= head $ filter (matchesChar 's') allPositions
-- (endR,endC,_ )= head $ filter (matchesChar 'e') allPositions

findStartEnd maze =
  let allPos = allPositions maze
      (startR, startC, _) = head $ filter (matchesChar 's') allPos
      (endR, endC, _)     = head $ filter (matchesChar 'e') allPos
  in ((startR, startC), (endR, endC))

matchesChar char (_, _, c) = c == char
Categories: Code, Creative, Design

Leave a reply

Your email address will not be published. Required fields are marked *