Magic squares of doubly even order: Difference between revisions

Content added Content deleted
(Added Go implementation)
(Corrected my existing code)
Line 898: Line 898:
)
)


const squareWidth int = 8
const dimensions int = 8


func splitArray(array []int, width int) [][]int {
func setupMagicSquareData(d int) ([][]int, error) {
var output [][]int
var output [][]int
if d < 4 || d%4 != 0 {
lastRowLen := len(array) % width
return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4")
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")
}
}
var bits uint = 0x9669 // 0b1001011001101001
cornerWidth := width / 4
arrayLen := width * width
size := d * d
for i := 0; i < arrayLen; i++ {
mult := d / 4
for i, r := 0, 0; r < d; r++ {
if val := i + int(1); val%width <= cornerWidth || val%width > width-cornerWidth {
output = append(output, val)
output = append(output, []int{})
for c := 0; c < d; i, c = i+1, c+1 {
} else {
bitPos := c/mult + (r/mult)*4
output = append(output, arrayLen-i)
if (bits & (1 << uint(bitPos))) != 0 {
output[r] = append(output[r], i+1)
} else {
output[r] = append(output[r], size-i)
}
}
}
}
}
Line 942: Line 931:


func main() {
func main() {
data, err := setupMagicSquareData(squareWidth)
data, err := setupMagicSquareData(dimensions)
if err != nil {
if err != nil {
log.Fatal(err)
log.Fatal(err)
}
}
magicConstant := (dimensions * (dimensions*dimensions + 1)) / 2
rows := splitArray(data, squareWidth)
for _, row := range data {
magicConstant := (squareWidth * (squareWidth*squareWidth + 1)) / 2
for _, row := range rows {
fmt.Println(strings.Join(arrayItoa(row), " "))
fmt.Println(strings.Join(arrayItoa(row), " "))
}
}
fmt.Printf("\nMagic Constant: %d\n", magicConstant)
fmt.Printf("\nMagic Constant: %d\n", magicConstant)

}
}
</lang>
</lang>
Line 958: Line 945:
<pre> 1 2 62 61 60 59 7 8
<pre> 1 2 62 61 60 59 7 8
9 10 54 53 52 51 15 16
9 10 54 53 52 51 15 16
17 18 46 45 44 43 23 24
48 47 19 20 21 22 42 41
25 26 38 37 36 35 31 32
40 39 27 28 29 30 34 33
33 34 30 29 28 27 39 40
32 31 35 36 37 38 26 25
41 42 22 21 20 19 47 48
24 23 43 44 45 46 18 17
49 50 14 13 12 11 55 56
49 50 14 13 12 11 55 56
57 58 6 5 4 3 63 64
57 58 6 5 4 3 63 64


Magic Constant: 260</pre>
Magic Constant: 260
</pre>


=={{header|Haskell}}==
=={{header|Haskell}}==