Skip to content

Instantly share code, notes, and snippets.

@manvillej
Created November 18, 2018 16:09
Show Gist options
  • Save manvillej/ea3c1ef651e475cb0d19a334b6475086 to your computer and use it in GitHub Desktop.
Save manvillej/ea3c1ef651e475cb0d19a334b6475086 to your computer and use it in GitHub Desktop.
Knight Solution using Numpy's linalg.matrix_power
import numpy as np
def getPossibilities(startingPosition, turns):
"""
Calculates the total number of uniques paths from the starting position in N turns for the transition matrix
"""
# edgecase: 0 turns, return 1
if turns == 0:
return 1
# our transition matrix
transitionMatrix = np.matrix([
[0, 0, 0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0],
[1, 0, 0, 1, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0, 0, 0]], dtype=object)
# get our new matrix N turns ahead
newMatrix = np.linalg.matrix_power(transitionMatrix, turns)
# sum the relevant row
return np.sum(newMatrix[startingPosition])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment