Magic squares of doubly even order: Difference between revisions
Content added Content deleted
m (→{{header|Haskell}}: (Slightly simpler diagonals function – dropped a lambda)) |
m (→{{header|Haskell}}: layout) |
||
Line 570: | Line 570: | ||
magicSquare :: Int -> [[Int]] |
magicSquare :: Int -> [[Int]] |
||
magicSquare n |
magicSquare n |
||
| rem n 4 > 0 = [] |
|||
| otherwise = |
|||
splitEvery n $ |
|||
⚫ | |||
-- Taken directly from the integer series where True |
|||
⚫ | |||
⚫ | |||
zipWith |
|||
(\x i -> |
|||
⚫ | |||
⚫ | |||
⚫ | |||
series |
|||
⚫ | |||
where |
|||
sqr = n * n |
|||
limit = sqr + 1 |
|||
series |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
| otherwise = |
|||
⚫ | |||
⚫ | |||
where |
where |
||
scale = replicate $ quot n 4 |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
| isPowerOf 2 n = |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
scale = replicate $ quot n 4 |
|||
------------------------------------------------------------------------ |
------------------------------------------------------------------------ |
||
magicSeries :: Int -> [Bool] |
magicSeries :: Int -> [Bool] |
||
magicSeries = (iterate (\xs -> xs ++ (not <$> xs)) [True] !!) |
magicSeries = (iterate (\xs -> xs ++ (not <$> xs)) [True] !!) |
||
Line 603: | Line 605: | ||
isPowerOf :: Int -> Int -> Bool |
isPowerOf :: Int -> Int -> Bool |
||
isPowerOf k n = |
isPowerOf k n = until (\x -> rem x k /= 0) (`quot` k) n == 1 |
||
until (\x -> rem x k /= 0) |
|||
(`quot` k) n == 1 |
|||
main :: IO () |
main :: IO () |
||
main = mapM_ print $ magicSquare 8 |
main = mapM_ print $ magicSquare 8 |
||
-- |
-- Summed and checked--------------------------------------------------- |
||
-- Summed and checked |
|||
checked :: Int -> (Int, Bool) |
checked :: Int -> (Int, Bool) |
||
checked n = (h, all (h ==) t) |
checked n = (h, all (h ==) t) |
||
where |
|||
square = magicSquare n |
|||
h:t = |
|||
sum <$> |
|||
⚫ | |||
square ++ -- rows |
|||
⚫ | |||
diagonals square -- diagonals |
|||
diagonals :: [[Int]] -> [[Int]] |
diagonals :: [[Int]] -> [[Int]] |
||
diagonals xs = |
diagonals xs = flip (zipWith (!!)) [0 ..] <$> [xs, reverse xs] |
||
flip (zipWith (!!)) [0..] <$> [xs, reverse xs] |
|||
main2 :: IO () |
main2 :: IO () |