Skip to content

Instantly share code, notes, and snippets.

@GitRay
Created January 15, 2018 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GitRay/543201fc388b53910af0ed87ad97f0ff to your computer and use it in GitHub Desktop.
Save GitRay/543201fc388b53910af0ed87ad97f0ff to your computer and use it in GitHub Desktop.
Parker Square! :) # Randomly try to get lucky and find a magic square with all square numbers. # Idea came from here: https://www.youtube.com/watch?v=G1m7goLCJDY
## Parker Square! :)
# Randomly try to get lucky and find a magic square with all square numbers.
# Idea came from here: https://www.youtube.com/watch?v=G1m7goLCJDY
import sys, random, pprint
rand = random.SystemRandom()
square_size = 3
square_step_x = list(range(square_size))
square_step_y = list(range(square_size))
square = []
for x in square_step_x:
square.append( [] )
for y in square_step_y:
square[x].append(y)
while True:
# use system max as totally arbitrary upper int limit for random values
unique_vals = []
while len(unique_vals) < square_size ** 2:
new_val = rand.randint(0,sys.maxsize) ** 2
if not new_val in unique_vals:
unique_vals.append(new_val)
for x in square_step_x:
for y in square_step_y:
square[x][y] = unique_vals.pop()
# do we have a magic square?
diag_sum_1 = 0
diag_sum_2 = 0
c_sums = [0 for x in square_step_y]
r_sums = []
for x in square_step_x:
r_sums.append( 0 )
for y in square_step_y:
r_sums[x] += square[x][y]
c_sums[y] += square[x][y]
if x == y:
diag_sum_1 += square[x][y]
if x == (square_size - 1 - y):
diag_sum_2 += square[x][y]
no_match = False
for x in [ diag_sum_2 ] + c_sums + r_sums:
if diag_sum_1 != x:
# one of them didn't match... start next iteration of while loop.
no_match = True
break
if not no_match:
# if we got here, it's a win! Print the square
print('Winner!')
pprint.pprint(square)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment