Skip to content

Instantly share code, notes, and snippets.

@colmmacc
Last active December 14, 2015 17:29
Show Gist options
  • Save colmmacc/5122632 to your computer and use it in GitHub Desktop.
Save colmmacc/5122632 to your computer and use it in GitHub Desktop.
import random
def choose_N(matrix):
"""Choose N elements from an N x N square matrix, such that;
1. The elements are chosen at-random
2. One element per row
3. One element per column
"""
assert isinstance(matrix, list)
columns = range( len(matrix) )
rows = range ( len(matrix) )
random.shuffle(columns)
random.shuffle(rows)
chosen = []
for i in range( len(matrix) ):
# Make sure we have a square matrix
assert isinstance(matrix[i], list)
assert len(matrix[i]) == len(matrix)
chosen.append(matrix[ columns[i] ][ rows[i] ])
return chosen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment