Magic squares of odd order: Difference between revisions
→Haskell :: Transpose . cycled: Tidied.
(→Haskell :: Transpose . cycled: Tidied.) |
|||
Line 1,825:
Defining the magic square as two applications of ('''transpose . cycled''') to a simply ordered square.
<lang Haskell>import
import Data.List (maximumBy, transpose)
import Data.List.Split (chunksOf)
import Data.Ord (comparing)
magicSquare :: Int -> [[Int]]
magicSquare n
| 1 == mod n 2 =
applyN 2 (transpose . cycled) $
plainSquare n
| otherwise = []
plainSquare :: Int -> [[Int]]▼
plainSquare = chunksOf <*> enumFromTo 1 . (^ 2)▼
-------------------------- TEST ---------------------------
main :: IO ()
main =
main = mapM_ putStrLn $ showSquare . magicSquare <$> [3, 5, 7]▼
mapM_ putStrLn $
------------------------- GENERIC -------------------------
Line 1,846 ⟶ 1,858:
let n = length rows
d = quot n 2
in zipWith
(\d xs -> take n $ drop (n - d) (cycle xs))
[d, subtract 1 d .. - d]
rows
▲plainSquare :: Int -> [[Int]]
▲plainSquare = chunksOf <*> enumFromTo 1 . (^ 2)
-
justifyRight :: Int -> a -> [a] -> [a]
justifyRight n c = (drop . length) <*> (replicate n c
showSquare :: Show a => [[a]] -> String
showSquare rows =
let srows = fmap show <$> rows▼
)
▲ in unlines $ fmap (justifyRight w ' ' =<<) srows</lang>
{{Out}}
<pre> 8 1 6
|