Advertisement
Python253

magic_square_generator

May 12th, 2024 (edited)
753
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.14 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: magic_square_generator.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9.    - This script generates magic squares using the Siamese method, where all rows, columns, and diagonals sum to the same value.
  10.    - The Siamese method initializes by placing the number 1 in the middle column of the top row.
  11.    - Subsequent numbers are then positioned diagonally up and right from the previous number, wrapping around to the last row or first column if necessary.
  12.    - If a cell is already occupied, the next number is placed one row down from the current cell.
  13.    - Padding is applied to ensure uniform appearance across different square dimensions.
  14.    - As the size of the square increases, padding is added to numbers to maintain a consistent number of digits for aesthetic purposes.
  15.    - The algorithm specifically supports odd dimensions for the magic square, as even dimensions are incompatible with the Siamese method.
  16.  
  17. Parameters:
  18.    - n (int): The size of the magic square (n x n).
  19.  
  20. Padding:
  21.    * Padding is applied to ensure consistent digit representation in the generated magic squares.
  22.  
  23.    - For dimensions 3x3 to 9x9, 1-digit numbers are padded with leading zeros to have 2 digits.
  24.    - For dimensions 11x11 to 31x31, 2-digit numbers are padded with leading zeros to have 3 digits.
  25.    - For dimensions 33x33 to 99x99, 3-digit numbers are padded with leading zeros to have 4 digits.
  26.    - For dimensions 101x101 to 315x315, 4-digit numbers are padded with leading zeros to have 5 digits.
  27.    - For dimensions 317x317 to 999x999, 5-digit numbers are padded with leading zeros to have 6 digits.  
  28.    - For dimensions 1001x1001 to Infinity, 6-digit numbers are padded with leading zeros to have 7 digits.
  29.  
  30.    * Please note that higher dimensions containing 7-digit values are not padded further.
  31.    
  32. Requirements:
  33.    - Python3.x
  34.    
  35. Functions:
  36.    - magic_square(n): Generates a magic square of size n x n.
  37.    
  38. Usage:
  39.    - Run the script in a Python environment.
  40.    - Follow the on-screen prompts to enter an odd number greater than 1 as the size of the magic square.
  41.    
  42. Example Expected Output:
  43. ------------------------------------------------------------------------------        
  44.                   :: MAGIC SQUARE GENERATOR ::
  45.  
  46. Enter an odd number greater than 1 as the size of the Magic Square (n x n): 5
  47.  
  48.                        ┌────────────────┐
  49.                        │ 09 03 22 16 15 │
  50.                        │ 02 21 20 14 08 │
  51.                        │ 25 19 13 07 01 │
  52.                        │ 18 12 06 05 24 │
  53.                        │ 11 10 04 23 17 │
  54.                        └────────────────┘
  55.  
  56.              The sum of each row/column/diagonal is: 65.0
  57. ------------------------------------------------------------------------------
  58.  
  59. Additional Notes:
  60.    - This algorithm only supports odd dimensions for the magic square.
  61.    - Magic squares for dimensions less than or equal to 1 are not allowed.
  62.    - Dimensions exceeding 8-digit values are not padded further.
  63. """
  64.  
  65. # Function to create Magic Square
  66. def magic_square(n):
  67.     if n < 3:
  68.         print(
  69.             "- Magic squares for dimensions less than 3 are not supported by this algorithm!\n"
  70.         )
  71.         return
  72.     elif n % 2 == 0:
  73.         print("- Even dimension values are not supported by this algorithm!\n")
  74.         return
  75.    
  76.     # Initialize the magic square with zeros
  77.     magicSquare = []
  78.     for i in range(n):
  79.         listt = []
  80.         for j in range(n):
  81.             listt.append(0)
  82.         magicSquare.append(listt)
  83.        
  84.     # Initialize starting position
  85.     i = n // 2
  86.     j = n - 1
  87.  
  88.     # Set the number of elements to insert
  89.     num = n * n
  90.     count = 1
  91.  
  92.     # Populate the magic square
  93.     while count <= num:
  94.         if i == -1 and j == n:  # condition 4
  95.             j = n - 2
  96.             i = 0
  97.         else:
  98.             if j == n:  # column value is exceeding
  99.                 j = 0
  100.  
  101.             if i < 0:  # row  is becoming -1
  102.                 i = n - 1
  103.  
  104.         # Check if cell is occupied
  105.         if magicSquare[i][j] != 0:
  106.             j = j - 2
  107.             i = i + 1
  108.             continue
  109.  
  110.         else:
  111.             magicSquare[i][j] = count
  112.             count += 1
  113.  
  114.         # Move to the next cell
  115.         i = i - 1
  116.         j = j + 1  # condition 1
  117.  
  118.     # Print top border
  119.     if n >= 1001:
  120.         print("\t\t\t┌" + "─" * (8 * n + 1) + "┐")  # 1001x1001 - Infinity (not padded further)
  121.     elif n >= 317:
  122.         print("\t\t\t┌" + "─" * (7 * n + 1) + "┐")  # 317x317 - 999x999
  123.     elif n >= 101:
  124.         print("\t\t\t┌" + "─" * (6 * n + 1) + "┐")  # 101x101 - 315x315
  125.     elif n >= 33:
  126.         print("\t\t\t┌" + "─" * (5 * n + 1) + "┐")  # 33x33 - 99x99
  127.     elif n >= 11:
  128.         print("\t\t\t┌" + "─" * (4 * n + 1) + "┐")  # 11x11 - 31x31
  129.     else:
  130.         print("\t\t\t┌" + "─" * (3 * n + 1) + "┐")  # 3x3 - 9x9
  131.  
  132.     for i in range(n):
  133.         print("\t\t\t│ ", end="")
  134.         for j in range(n):
  135.             # Format each number to have leading zeros if needed (up to 7-Digits)
  136.             if n >= 1001:
  137.                 num_str = str(magicSquare[i][j]).zfill(7) # 7-Digit Values            
  138.             elif n >= 315:
  139.                 num_str = str(magicSquare[i][j]).zfill(6) # 6-Digit Values
  140.             elif n >= 101:
  141.                 num_str = str(magicSquare[i][j]).zfill(5) # 5-Digit Values
  142.             elif n >= 33:
  143.                 num_str = str(magicSquare[i][j]).zfill(4) # 4-Digit Values
  144.             elif n >= 11:
  145.                 num_str = str(magicSquare[i][j]).zfill(3) # 3-Digit Values
  146.             else:
  147.                 num_str = str(magicSquare[i][j]).zfill(2) # 2-Digit Values
  148.             print(f"{num_str} ", end="")
  149.         print("│")  # Print vertical line
  150.  
  151.     # Print bottom border
  152.     if n >= 1001:
  153.         print("\t\t\t┌" + "─" * (8 * n + 1) + "┐")  # 1001x1001 - Infinity (not padded further)
  154.     elif n >= 319:
  155.         print("\t\t\t└" + "─" * (7 * n + 1) + "┘") # 317x317 - 999x999
  156.     elif n >= 101:
  157.         print("\t\t\t└" + "─" * (6 * n + 1) + "┘") # 101x101 - 315x315
  158.     elif n >= 33:
  159.         print("\t\t\t└" + "─" * (5 * n + 1) + "┘") # 33x33 - 99x99
  160.     elif n >= 11:
  161.         print("\t\t\t└" + "─" * (4 * n + 1) + "┘") # 11x11 - 31x31
  162.     else:
  163.         print("\t\t\t└" + "─" * (3 * n + 1) + "┘") # 3x3 - 9x9
  164.  
  165.     # Print sum information
  166.     print(
  167.         "\n\t  The sum of each row/column/diagonal is: " + str(n * (n**2 + 1) / 2),
  168.         "\n",
  169.     )
  170.  
  171. # Main Function for Magic Square
  172. if __name__ == "__main__":
  173.     """
  174.    Main function to execute the script.
  175.    """
  176.     print("\t\t    :: MAGIC SQUARE GENERATOR ::\n")
  177.     n = int(
  178.         input(
  179.             "Enter an odd number greater than 1 as the size of the Magic Square (n x n): "
  180.         )
  181.     )
  182.     if n <= 1:
  183.         print(
  184.             "\n\t- Magic squares for dimensions less than or equal to 1 are not allowed.\n"
  185.         )
  186.     else:
  187.         magic_square(n)
  188.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement