Created
March 3, 2018 15:10
-
-
Save aindong/22af844ec16bfffee225389875b83956 to your computer and use it in GitHub Desktop.
My dirty solution to magic square problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
from math import floor | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument("size", help="The size of the square. Please only input odd numbers") | |
args = parser.parse_args() | |
size = int(args.size) | |
if size % 2 == 0: | |
print("Please input only odd number") | |
exit() | |
grid = create_grid(size) | |
processed_grid = process_magic_square(size, grid) | |
# Show the grid | |
show_grid(processed_grid) | |
# Grid creator, will create a 2 dimensional array | |
def create_grid(size): | |
grid = [] | |
for _ in range(size): | |
row = [] | |
# Build the row | |
for _ in range(size): | |
row.append(0) | |
# Append the row to the grid | |
grid.append(row) | |
return grid | |
# Show the grid in cli | |
def show_grid(grid): | |
for row in grid: | |
for col in row: | |
str_col = str(col) | |
str_element = str_col if len(str_col) > 1 else " " + str_col | |
print(str_element + " ", end="") | |
print() | |
# Get the middle number | |
def get_middle_col(size): | |
return floor(size / 2) | |
# Limit the bounds of index or move | |
def clamp(n, size): | |
return n % size | |
# Process the magic square | |
def process_magic_square(size, grid): | |
# Insert the number 1 on the middle column on first row | |
middle_col = get_middle_col(size) | |
grid[0][middle_col] = 1 | |
# Initial index position | |
current_row_index = 0 | |
current_col_index = middle_col | |
# Iterate numbers | |
for i in range(size ** 2): | |
current_number = i+1 | |
grid[current_row_index][current_col_index] = current_number | |
# Move up of the current index (-1) | |
move_to_row_index = clamp(current_row_index - 1, size) | |
# Move right of the current index | |
move_to_col_index = clamp(current_col_index + 1, size) | |
# Check column if available | |
if grid[move_to_row_index][move_to_col_index] > 0: | |
# If the current column is greater than 0, then it is occupied | |
# we have to go back to the current indexes and put this | |
# new element below or -1 row | |
# Move up of the current index | |
move_to_row_index = clamp(current_row_index + 1, size) | |
# Move right of the current index | |
move_to_col_index = current_col_index | |
# Update the position | |
current_row_index = move_to_row_index | |
current_col_index = move_to_col_index | |
return grid | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment