Zig-zag matrix: Difference between revisions

Content added Content deleted
m (→‎{{header|Haskell}}: Tidied mapAccumL version)
(→‎{{header|Haskell}}: Pruned a (now) redundant import, added signatures, tweaked name to avoid wiki glitch, preferred guards to if then.)
Line 2,149: Line 2,149:
Computing the array:
Computing the array:


<lang haskell>import Data.Array (array, bounds, range, (!))
<lang haskell>import Data.Array (Array, array, bounds, range, (!))
import Data.Monoid (mappend)
import Data.List (sortBy)
import Text.Printf (printf)
import Text.Printf (printf)
import Data.List (sortBy)


compZig (x, y) (x', y') =
compZig :: (Int, Int) -> (Int, Int) -> Ordering
compare (x + y) (x' + y') `mappend`
compZig (x, y) (x_, y_) = compare (x + y) (x_ + y_) <> go x y
where
if even (x + y)
then compare x x'
go x y
| even (x + y) = compare x x_
else compare y y'
| otherwise = compare y y_


zigZag :: (Int, Int) -> Array (Int, Int) Int
zigZag upper = array b $ zip (sortBy compZig (range b)) [0 ..]
zigZag upper = array b $ zip (sortBy compZig (range b)) [0 ..]
where
where