Magic squares of doubly even order: Difference between revisions

Content added Content deleted
No edit summary
(→‎{{header|Haskell}}: dropped splitEvery for chunksOf, updated output)
Line 637: Line 637:
=={{header|Haskell}}==
=={{header|Haskell}}==


<lang Haskell>import Data.List (transpose, unfoldr)
<lang Haskell>import Data.List.Split (chunksOf)
import Data.List (transpose, unfoldr)


magicSquare :: Int -> [[Int]]
magicSquare :: Int -> [[Int]]
Line 643: Line 644:
| rem n 4 > 0 = []
| rem n 4 > 0 = []
| otherwise =
| otherwise =
splitEvery n $
chunksOf n $
-- Taken directly from the integer series where True
-- Taken directly from the integer series where True
-- and from the reverse of that series where False
-- and from the reverse of that series where False
Line 663: Line 664:
-- minimum truth table, horizontally and vertically
-- minimum truth table, horizontally and vertically
| otherwise =
| otherwise =
concat . concat . concat . scale $
concat . concat . concat . scale $ scale <$> chunksOf 4 (magicSeries 4)
scale <$> splitEvery 4 (magicSeries 4)
where
where
scale = replicate $ quot n 4
scale = replicate $ quot n 4


------------------------------------------------------------------------
magicSeries :: Int -> [Bool]
magicSeries :: Int -> [Bool]
magicSeries = (iterate (\xs -> xs ++ (not <$> xs)) [True] !!)
magicSeries = (iterate ((++) <*> fmap not) [True] !!)

splitEvery :: Int -> [a] -> [[a]]
splitEvery n = takeWhile (not . null) . unfoldr (Just . splitAt n)


isPowerOf :: Int -> Int -> Bool
isPowerOf :: Int -> Int -> Bool
isPowerOf k n = until (\x -> rem x k /= 0) (`quot` k) n == 1
isPowerOf k n = until ((0 /=) . flip rem k) (`quot` k) n == 1


diagonals :: [[Int]] -> [[Int]]
main :: IO ()
diagonals = fmap (flip (zipWith (!!)) [0 ..]) . ((:) <*> (return . reverse))
main = mapM_ print $ magicSquare 8


-- Summed and checked---------------------------------------------------
checked :: Int -> (Int, Bool)
checked :: Int -> (Int, Bool)
checked n = (h, all (h ==) t)
checked n = (h, all (h ==) t)
Line 692: Line 687:
diagonals square -- diagonals
diagonals square -- diagonals


main :: IO ()
diagonals :: [[Int]] -> [[Int]]
main = do
diagonals xs = flip (zipWith (!!)) [0 ..] <$> [xs, reverse xs]
mapM_ print $ magicSquare 8

putStrLn ""
main2 :: IO ()
main2 = print $ checked 8</lang>
print $ checked 8</lang>

{{Out}}
{{Out}}
<pre>[1,63,62,4,60,6,7,57]
<pre>main
[1,63,62,4,5,59,58,8]
[56,10,11,53,13,51,50,16]
[56,10,11,53,52,14,15,49]
[48,18,19,45,21,43,42,24]
[48,18,19,45,44,22,23,41]
[25,39,38,28,36,30,31,33]
[25,39,38,28,29,35,34,32]
[32,34,35,29,37,27,26,40]
[33,31,30,36,37,27,26,40]
[41,23,22,44,20,46,47,17]
[24,42,43,21,20,46,47,17]
[49,15,14,52,12,54,55,9]
[16,50,51,13,12,54,55,9]
[8,58,59,5,61,3,2,64]
[57,7,6,60,61,3,2,64]


main2
(260,True)</pre>
(260,True)</pre>