Magic squares of doubly even order: Difference between revisions

Added Kotlin
(→‎{{header|AppleScript}}: (Updated primitive – |until| ))
(Added Kotlin)
Line 871:
24 122 123 21 20 126 127 17 16 130 131 13
133 11 10 136 137 7 6 140 141 3 2 144</pre>
 
=={{header|Kotlin}}==
{{trans|Java}}
<lang scala>// version 1.0.6
 
fun magicSquareDoublyEven(n: Int): Array<IntArray> {
if ( n < 4 || n % 4 != 0)
throw IllegalArgumentException("Base must be a positive multiple of 4")
 
// pattern of count-up vs count-down zones
val bits = 0b1001011001101001
val size = n * n
val mult = n / 4 // how many multiples of 4
val result = Array(n) { IntArray(n) }
var i = 0
for (r in 0 until n)
for (c in 0 until n) {
val bitPos = c / mult + r / mult * 4
result[r][c] = if (bits and (1 shl bitPos) != 0) i + 1 else size - i
i++
}
return result
}
 
fun main(args: Array<String>) {
val n = 8
for (ia in magicSquareDoublyEven(n)) {
for (i in ia) print("%2d ".format(i))
println()
}
println("\nMagic constant ${(n * n + 1) * n / 2}")
}</lang>
 
{{out}}
<pre>
1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
48 47 19 20 21 22 42 41
40 39 27 28 29 30 34 33
32 31 35 36 37 38 26 25
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64
</pre>
 
=={{header|PARI/GP}}==
9,490

edits