xorvralin2
xorvralin2

Reputation: 29

Having trouble rotating a 3-dimensional list of chars in Haskell

I'm relatively new to Haskell and functional programming but right now I'm working on a project where I attempt to solve 3D-cube puzzles.

I have the following 3-Dimensional list where ' ' represent empty space and 'C' represents a part of the structure:

myShape = [["CC", " C"], [" C", "  "]]

I want to be able to rotate this structure along all three axises to try it in different positions. I know that I can rotate it along one axis by independently rotating every 2D-layer.

My question is: How can I rotate along the other axises without hard-coding the rotations?

Upvotes: 0

Views: 167

Answers (1)

xorvralin2
xorvralin2

Reputation: 29

Well, i solved myself:

rotate2dArr :: [[Char]] -> Int -> [[Char]]                                                                                                                                                              
rotate2dArr arr 0 = arr
rotate2dArr arr r = rotate2dArr (transpose $ [reverse row | row <- arr]) (r-1)

rotateX :: [[[Char]]] -> Int -> [[[Char]]]
rotateX arr 0 = arr
rotateX arr r = rotateX (transpose $ [reverse plane| plane <- arr]) (r-1) 

rotateY :: [[[Char]]] -> Int -> [[[Char]]]
rotateY arr 0 = arr
rotateY arr r = rotateY (rotateX (rotateZ (rotateX arr 1) 1) 3) (r - 1)

rotateZ :: [[[Char]]] -> Int -> [[[Char]]]
rotateZ arr r = [rotate2dArr plane r | plane <- arr]

rotate3dArr :: [[[Char]]] -> Char -> Int -> [[[Char]]]
rotate3dArr arr axis r = case axis of 
        'x' -> rotateX arr r -- Rotates cube on x axis backwards 
        'y' -> rotateY arr r -- Rotates cube clockwise as seen from above
        'z' -> rotateZ arr r

It might not be all that pretty but it works

Upvotes: 2

Related Questions