diff --git a/cw/src/Challenges.hs b/cw/src/Challenges.hs index 2b360629fabe558234124ad917c559c8273d3dd3..9c5003837def694f20ec25ece711d3d41aa079e0 100644 --- a/cw/src/Challenges.hs +++ b/cw/src/Challenges.hs @@ -94,7 +94,7 @@ nextPos DownBack (x,y) = (x-1,y+1) elemAt :: [[a]] -> (Int,Int) -> a -elemAt ass (x,y) = (ass !! y) !! x --ass means list of list of a's, not associated with other meaning +elemAt ass (x,y) = (ass !! y) !! x --ass means list of list of a's, not associated with any other meaning --returns specified adjacent element in grid, relative to given position @@ -167,7 +167,7 @@ insertString rg s gen | elemAt rg (x,y) /= Rand && vDirs = validDirs rg s (x,y) addToGrid :: Orientation -> String -> (Int,Int) -> RandGrid - addToGrid dir (c:cs) (x',y') = addToGrid dir cs (nextPos dir (x',y')) charAdded + addToGrid dir (c:cs) (x',y') = addToGrid dir cs charAdded (nextPos dir (x',y')) where charAdded = insertAt2D (Letter c) (x',y') rg --addToGrid dir = map (\(c,(m,n)) -> insertAt2D (Letter c) (m,n) rg) (zip s (take (length s) $ iterate (nextPos dir) (x,y))) @@ -175,11 +175,15 @@ insertString rg s gen | elemAt rg (x,y) /= Rand && --inserts element at location in 2d array insertAt2D :: a -> (Int,Int) -> [[a]] -> [[a]] -insertAt2D newElement (x,y) grid = insertAt a x (grid !! y) +insertAt2D newElement (x,y) grid | y == 0 = insertAt newElement x (grid !! y) : drop 1 belowRows + | y == length grid - 1 = aboveRows ++ [insertAt newElement x (grid !! y)] + | otherwise = aboveRows ++ [insertAt newElement x (grid !! y)] ++ drop 1 belowRows + where + (aboveRows,belowRows) = splitAt y grid --using code from https://stackoverflow.com/questions/43291442/haskell-insert-an-element-on-nth-position insertAt :: a -> Int -> [a] -> [a] -insertAt newElement 0 as = newElement:as +insertAt newElement 0 as = newElement : drop 1 as insertAt newElement i (a:as) = a : insertAt newElement (i - 1) as