Magic squares of doubly even order: Difference between revisions

m
m (→‎{{header|Haskell}}: (Slightly simpler diagonals function – dropped a lambda))
Line 570:
magicSquare :: Int -> [[Int]]
magicSquare n
| rem n 4 > 0 = []
| otherwise = splitEvery n $
splitEvery n $
-- Taken directly from the integer series where True
-- andTaken directly from the reverse of thatinteger series where FalseTrue
-- Taken directlyand from the integerreverse of that series where TrueFalse
zipWith (\x i -> if x then i else limit - i)
serieszipWith
(\x i [1..sqr]->
series if x
then wherei
zipWith (\x i -> if x then i else limit - i)
series
[1 limit =.. sqr + 1]
where
sqr = n * n
limit = sqr + 1
series
-- For integer powers of 2, the (append not) 'magic' series directly
-- yields the truth table that we need
| isPowerOf 2 n = magicSeries $ floor (logBase 2 (fromIntegral sqr))
-- where n is not an integer power of 2, we can replicate a
-- minimum truth table, horizontally and vertically
| otherwise =
concat | otherwise =. concat . concat . concatscale .$
scale $ scale <$> splitEvery 4 (magicSeries 4)
where
sqrscale = nreplicate *$ quot n 4
limit = sqr + 1
series
-- For integer powers of 2, the (append not) 'magic' series directly
-- yields the truth table that we need
| isPowerOf 2 n =
magicSeries $ floor (logBase 2 (fromIntegral sqr))
 
-- where n is not an integer power of 2, we can replicate a
-- minimum truth table, horizontally and vertically
| otherwise = concat . concat . concat .
scale $ scale <$> splitEvery 4 (magicSeries 4)
where
scale = replicate $ quot n 4
 
 
------------------------------------------------------------------------
 
magicSeries :: Int -> [Bool]
magicSeries = (iterate (\xs -> xs ++ (not <$> xs)) [True] !!)
Line 603 ⟶ 605:
 
isPowerOf :: Int -> Int -> Bool
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 = mapM_ print $ magicSquare 8
 
------------------- Summed and checked---------------------------------------------------
 
-- Summed and checked
checked :: Int -> (Int, Bool)
checked n = (h, all (h ==) t)
where
square = magicSquare n
h:t = sum <$> square ++ -- rows
sum <$>
transpose square ++ -- cols
diagonals square ++ -- diagonalsrows
transpose square ++ -- cols
diagonals square -- diagonals
 
diagonals :: [[Int]] -> [[Int]]
diagonals xs = flip (zipWith (!!)) [0 ..] <$> [xs, reverse xs]
flip (zipWith (!!)) [0..] <$> [xs, reverse xs]
 
main2 :: IO ()
9,659

edits