Skip to content

Instantly share code, notes, and snippets.

@alexgolec
Created October 7, 2018 04:03
Show Gist options
  • Save alexgolec/50d120cac9c419dfecfe077d040ff5a5 to your computer and use it in GitHub Desktop.
Save alexgolec/50d120cac9c419dfecfe077d040ff5a5 to your computer and use it in GitHub Desktop.
def count_sequences(start_position, num_hops):
prior_case = [1] * 10
current_case = [0] * 10
current_num_hops = 1
while current_num_hops <= num_hops:
current_case = [0] * 10
current_num_hops += 1
for position in range(0, 10):
for neighbor in neighbors(position):
current_case[position] += prior_case[neighbor]
prior_case = current_case
return current_case[start_position]
@moshejs
Copy link

moshejs commented Nov 20, 2018

Transcribed to Javascript for those interested

class KnightsDialer {
  constructor() {
      this.NEIGHBORS_MAP = {
        1: [6, 8],
        2: [7, 9],
        3: [4, 8],
        4: [3, 9, 0],
        5: [],
        6: [1, 7, 0],
        7: [2, 6],
        8: [1, 3],
        9: [2, 4],
        0: [4, 6]
    };
  }

  countSequences(startPosition, numHops) {
    let priorCase = Array(10).fill(1);
    let currentCase = Array(10).fill(0);
    currentNumHops = 1;

    while (currentNumHops <= numHops) {
      currentCase = Array(10).fill(0);
      currentNumHops += 1;

      for (let position = 0; position < 10; position++) {
        for (const neighbor of this.NEIGHBORS_MAP[position]) {
          currentCase[position] += priorCase[neighbor];
        }
      }
      priorCase = currentCase;
    }
    return currentCase[startPosition];
  }
}

const kd = new KnightsDialer();
console.log(kd.countSequences(6,2)); // output: 6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment