Magic squares of doubly even order: Difference between revisions

Added Go implementation
(Added Go implementation)
Line 888:
16 15 51 52 53 54 10 9
8 7 59 60 61 62 2 1</pre>
 
=={{header|Go}}==
<lang Go>package main
 
import (
"fmt"
"log"
"strings"
)
 
const squareWidth int = 8
 
func splitArray(array []int, width int) [][]int {
var output [][]int
lastRowLen := len(array) % width
for i := 0; i < len(array)-lastRowLen; i += width {
var row []int
for j := 0; j < width; j++ {
row = append(row, array[i+j])
}
output = append(output, row)
}
if lastRowLen != 0 {
output = append(output, array[len(array)-lastRowLen:])
}
return output
}
 
func setupMagicSquareData(width int) ([]int, error) {
var output []int
if width < 4 || width%4 != 0 {
return []int{}, fmt.Errorf("Square width must be a positive number which is divisible by 4")
}
cornerWidth := width / 4
arrayLen := width * width
for i := 0; i < arrayLen; i++ {
if val := i + int(1); val%width <= cornerWidth || val%width > width-cornerWidth {
output = append(output, val)
} else {
output = append(output, arrayLen-i)
}
}
return output, nil
}
 
func arrayItoa(input []int) []string {
var output []string
for _, i := range input {
output = append(output, fmt.Sprintf("%4d", i))
}
return output
}
 
func main() {
data, err := setupMagicSquareData(squareWidth)
if err != nil {
log.Fatal(err)
}
rows := splitArray(data, squareWidth)
magicConstant := (squareWidth * (squareWidth*squareWidth + 1)) / 2
for _, row := range rows {
fmt.Println(strings.Join(arrayItoa(row), " "))
}
fmt.Printf("\nMagic Constant: %d\n", magicConstant)
 
}
</lang>
{{Out}}
<pre> 1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
17 18 46 45 44 43 23 24
25 26 38 37 36 35 31 32
33 34 30 29 28 27 39 40
41 42 22 21 20 19 47 48
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64
 
Magic Constant: 260</pre>
 
=={{header|Haskell}}==