How to resolve the algorithm Magic squares of doubly even order step by step in the Nim programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Magic squares of doubly even order step by step in the Nim programming language

Table of Contents

Problem Statement

A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant).
A magic square of doubly even order has a size that is a multiple of four   (e.g.     4, 8, 12). This means that the subsquares also have an even size, which plays a role in the construction.

Create a magic square of   8 × 8.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Magic squares of doubly even order step by step in the Nim programming language

Source code in the nim programming language

import bitops, sequtils, strutils

type Square = seq[seq[int]]

func magicSquareDoublyEven(n: int): Square =
  ## Build a magic square of doubly even order.

  assert n >= 4 and (n and 3) == 0, "base must be a positive multiple of 4."
  result = newSeqWith(n, newSeq[int](n))

  const bits = 0b1001_0110_0110_1001  # Pattern of count-up vs count-down zones.
  let size = n * n
  let mult = n div 4                  # How many multiples of 4.

  var i = 0
  for r in 0..<n:
    for c in 0..<n:
      let bitPos = c div mult + r div mult * 4
      result[r][c] = if bits.testBit(bitPos): i + 1 else: size - i
      inc i


func `$`(square: Square): string =
  ## Return the string representation of a magic square.
  let length = len($(square.len * square.len))
  for row in square:
    result.add row.mapIt(($it).align(length)).join(" ") & '\n'


when isMainModule:
  let n = 8
  echo magicSquareDoublyEven(n)
  echo "Magic constant = ", n * (n * n + 1) div 2


  

You may also check:How to resolve the algorithm Constrained random points on a circle step by step in the Tcl programming language
You may also check:How to resolve the algorithm Hamming numbers step by step in the Perl programming language
You may also check:How to resolve the algorithm Detect division by zero step by step in the Rust programming language
You may also check:How to resolve the algorithm Accumulator factory step by step in the Quackery programming language
You may also check:How to resolve the algorithm Chaos game step by step in the Wren programming language