Skip to content

Instantly share code, notes, and snippets.

@manvillej
Last active November 17, 2018 14:34
Show Gist options
  • Save manvillej/b089488f4acc62a8b0b98519910b159e to your computer and use it in GitHub Desktop.
Save manvillej/b089488f4acc62a8b0b98519910b159e to your computer and use it in GitHub Desktop.
fully recursive solution to the getMatrix function of the Knight's Dialer
def getMatrix(matrix, turns):
"""
returns a matrix equal to the original matrix multiplied by itself a number of times euqal to the number of turns minus one
"""
if turns==1:
return matrix
else:
turnsBaseTwo = math.log(turns, 2)
if turnsBaseTwo.is_integer(): # recursive path 1
tempMatrix = getMatrix(matrix, turns/2) # recursive path 1
tempMatrixTwo = tempMatrix # recursive path 1
else: # recursive path 2
tempTurns = 2**math.floor(turnsBaseTwo) # recursive path 2
tempTurnsTwo = turns - tempTurns # recursive path 2
tempMatrix = getMatrix(matrix, tempTurns) # recursive path 2
tempMatrixTwo = getMatrix(matrix, tempTurnsTwo) # recursive path 2
return tempMatrix*tempMatrixTwo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment