Magic squares of doubly even order: Difference between revisions
Content added Content deleted
(→{{header|Haskell}}: Made the test more direct) |
(→{{header|Haskell}}: Updated primitives and output) |
||
Line 636: | Line 636: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
<lang Haskell>import Data.List (transpose, unfoldr, intercalate) |
|||
import Data.List.Split (chunksOf) |
|||
import |
import Control.Monad (forM_) |
||
magicSquare :: Int -> [[Int]] |
magicSquare :: Int -> [[Int]] |
||
Line 668: | Line 668: | ||
isPowerOf k n = until ((0 /=) . flip rem k) (`quot` k) n == 1 |
isPowerOf k n = until ((0 /=) . flip rem k) (`quot` k) n == 1 |
||
diagonals :: [[Int]] -> [[Int]] |
|||
-- TEST AND DISPLAY FUNCTIONS -------------------------------------------------- |
|||
⚫ | |||
checked :: [[Int]] -> (Int, Bool) |
checked :: [[Int]] -> (Int, Bool) |
||
checked square = |
checked square = |
||
let diagonals = |
|||
where |
|||
⚫ | |||
h:t = |
|||
h:t = |
|||
sum <$> |
|||
square ++ -- rows |
|||
transpose square ++ -- cols |
|||
diagonals square -- diagonals |
|||
in (h, all (h ==) t) |
|||
table :: String -> [[String]] -> [String] |
|||
table delim rows = |
|||
let justifyRight c n s = drop (length s) (replicate n c ++ s) |
|||
in intercalate delim <$> |
|||
transpose |
|||
((fmap =<< justifyRight ' ' . maximum . fmap length) <$> transpose rows) |
|||
main :: IO () |
main :: IO () |
||
main = |
main = |
||
forM_ [4, 8, 16] $ |
|||
⚫ | |||
\n -> do |
|||
mapM_ print square |
|||
⚫ | |||
⚫ | |||
putStrLn $ unlines (table " " (fmap show <$> test)) |
|||
print $ checked |
print $ checked test |
||
⚫ | |||
{{Out}} |
{{Out}} |
||
<pre>main |
|||
⚫ | |||
1 15 14 4 |
|||
⚫ | |||
12 6 7 9 |
|||
⚫ | |||
8 10 11 5 |
|||
⚫ | |||
13 3 2 16 |
|||
⚫ | |||
⚫ | |||
(34,True) |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
(260,True) |
|||
1 255 254 4 252 6 7 249 248 10 11 245 13 243 242 16 |
|||
240 18 19 237 21 235 234 24 25 231 230 28 228 30 31 225 |
|||
224 34 35 221 37 219 218 40 41 215 214 44 212 46 47 209 |
|||
49 207 206 52 204 54 55 201 200 58 59 197 61 195 194 64 |
|||
192 66 67 189 69 187 186 72 73 183 182 76 180 78 79 177 |
|||
81 175 174 84 172 86 87 169 168 90 91 165 93 163 162 96 |
|||
97 159 158 100 156 102 103 153 152 106 107 149 109 147 146 112 |
|||
144 114 115 141 117 139 138 120 121 135 134 124 132 126 127 129 |
|||
128 130 131 125 133 123 122 136 137 119 118 140 116 142 143 113 |
|||
145 111 110 148 108 150 151 105 104 154 155 101 157 99 98 160 |
|||
161 95 94 164 92 166 167 89 88 170 171 85 173 83 82 176 |
|||
80 178 179 77 181 75 74 184 185 71 70 188 68 190 191 65 |
|||
193 63 62 196 60 198 199 57 56 202 203 53 205 51 50 208 |
|||
48 210 211 45 213 43 42 216 217 39 38 220 36 222 223 33 |
|||
32 226 227 29 229 27 26 232 233 23 22 236 20 238 239 17 |
|||
241 15 14 244 12 246 247 9 8 250 251 5 253 3 2 256 |
|||
( |
(2056,True)</pre> |
||
=={{header|Java}}== |
=={{header|Java}}== |