Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Spiralled Arrays

Name: Anonymous 2007-07-28 18:53 ID:RZVt/+fJ

turn [1,2,3,4,5,6,7,8,9] into [9,2,3,8,1,4,7,6,5]. Make it work for an arbitrary array of size n^2. equally acceptable is [[1,2,3],[4,5,6],[7,8,9]] into [[9,2,3],[8,1,4],[7,6,5]].

how's it done?

pseudocode'll do

Name: Anonymous 2007-07-28 23:57 ID:13DFZExV

this VERY UGLY code may be a hint on how to do it. you'll have to rewrite it though, it's written in haskell in a sucky imperative style, which does not really suit haskell. anyway, I'm not even sure it works. basically, the idea is, you start with an empty matrix (list of lists). you keep a sort of a pointer, which stats the position and the direction you're going in the spiral. the function travels gives you the next pointer.
so, basically, you start with the first pointer, insert the item, then get the next pointer, insert the item, etc. if you want to do it in a true functional style (which would be cleaner than this piece of shit I threw together right now), collect the pointers, then sort them by the position, and pick up (i.e. map a selecting function) the items).

travel _ ("up",0,j) = ("right", 0, j + 1)
travel _ ("up",i,j) = ("up", i - 1, j)
travel n ("right", i, j) | n == j    = ("down", i - 1, j)
                         | otherwise = ("right", i, j + 1)
-- fill up the rest yourself

group [] _ = []
group l n = take 3 l : group (drop n l)

makeList _ 0 = []
makeList i n = i:makeList i (n - 1)

start i n = makeList (makeList i n) n

inserte e 0 x:xs = e:xs
inserte e p x:xs = x:inserte e (p - 1) xs

insert 0 j e x:xs = inserte e j x : xs
insert i j e x:xs = x : insert (i - 1) j e xs

spiral x:xs = concat (loop n (start x n) x:xs ("up", n div 2 + 1, n div 2 + 1))
                where n = sqrt (length x:xs)

loop _ matrix [] _ = matrix
loop n matrix x:xs (direction, i, j) = loop n (insert i j x matrix) xs (travel n (direction, i, j))

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List