Author Topic: Magic Squares of Odd Order (Rosetta Code task)  (Read 2962 times)

0 Members and 1 Guest are viewing this topic.

Offline AndyA

  • Newbie
  • Posts: 73
    • View Profile
Magic Squares of Odd Order (Rosetta Code task)
« on: April 16, 2021, 12:14:16 am »
https://rosettacode.org/wiki/Magic_squares_of_odd_order#QB64

'==================================================
Task
For any odd   N,   generate a magic square with the integers   1 ──► N,   and show the results here.

Optionally, show the magic number.

You should demonstrate the generator by showing at least a magic square for   N = 5.
'==================================================

Code: QB64: [Select]
  1. _Title "Magic Squares of Odd Order"
  2. '$Dynamic
  3. DefLng A-Z
  4. Dim Shared As Long m(1, 1)
  5.  
  6. Call magicSquare(5)
  7. Call magicSquare(15)
  8.  
  9.  
  10. Sub magicSquare (n As Integer)
  11.     Dim As Integer inc, count, row, col
  12.  
  13.     If (n < 3) Or (n And 1) <> 1 Then n = 3
  14.     ReDim m(n, n)
  15.     inc = 1
  16.     count = 1
  17.     row = 1
  18.     col = (n + 1) / 2
  19.     While count <= n * n
  20.         m(row, col) = count
  21.         count = count + 1
  22.         If inc < n Then
  23.             inc = inc + 1
  24.             row = row - 1
  25.             col = col + 1
  26.             If row <> 0 Then
  27.                 If col > n Then col = 1
  28.             Else
  29.                 row = n
  30.             End If
  31.         Else
  32.             inc = 1
  33.             row = row + 1
  34.         End If
  35.     Wend
  36.     Call printSquare(n)
  37.  
  38. Sub printSquare (n As Integer)
  39.     Dim As Integer row, col
  40.     'Arbitrary limit ensures a fit within console window
  41.     'Can be any size that fits within your computers memory limits
  42.     If n < 21 Then
  43.         Print "Order "; n; " Magic Square constant is "; Str$(Int((n * n + 1) / 2 * n))
  44.         For row = 1 To n
  45.             For col = 1 To n
  46.                 Print Using "####"; m(row, col);
  47.             Next col
  48.             Print
  49.             ' Print
  50.         Next row
  51.     End If