Magic squares of odd order: Difference between revisions

Line 1,825:
Defining the magic square as two applications of ('''transpose . cycled''') to a simply ordered square.
 
<lang Haskell>import DataControl.ListMonad (transpose, maximumByjoin)
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
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 $
main = mapM_ putStrLn $ showSquare . magicSquare <$> [3, 5, 7]
 
 
------------------------- 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)
 
-- FORMATTING ----------------------- FORMATTING ----------------------
justifyRight :: Int -> a -> [a] -> [a]
justifyRight n c = (drop . length) <*> (replicate n c ++<>)
 
showSquare :: Show a => [[a]] -> String
:: Show a
=> [[a]] -> String
showSquare rows =
in( unlines(\xs $w fmap-> unlines ((justifyRight w ' ' =<<) srows</lang$> xs))
let srows = fmap show <$> rows
w =<*> succ $. maximum (length. <$>fmap length concat. srows)join
)
in unlines $ fmap (justifyRight w ' ' =<<) srows</lang>
let srows =$ fmap show <$> rows</lang>
{{Out}}
<pre> 8 1 6
9,655

edits