Skip to content

Instantly share code, notes, and snippets.

@harry1989
Last active September 28, 2019 07:08
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 harry1989/99a01b1ebc4d5e09088d6e3fb4cc60b2 to your computer and use it in GitHub Desktop.
Save harry1989/99a01b1ebc4d5e09088d6e3fb4cc60b2 to your computer and use it in GitHub Desktop.
Map<Positon, Long> positionProb;
List<Position> finalReachableCells;
List<Position> visitedCells;
/**
* Class to represent the positon
*/
class Positon {
int x;
int y;
public Position (int a, int b) {
this.x = a;
this.y = b;
}
}
/**
* Starting point.
*/
int probabilityHorseRemainsWithinBoard (int n, int x, int y) {
//pre compute probabilities for all
// positions independently.
precompute();
probabilityHorseRemainRecur(n, x, y)
int totalProbability = finalReachableCells.stream().reduce((a,b) => a + b);
print totalProbability;
}
/**
* A utility for the recurrsive function
*/
int probabilityHorseRemainRecur (int n, int y, int x) {
Position thisPosition = new Position(x,y);
thisProbability = positionProb.get(thisPosition);
// this cell is already visited
if (visitedCells.contains(thisPosition)) {
return;
}
List<Po..> nextCells = getNextPossbileCells(x, y);
nextCells.stream().forEach(f -> positionProb.put(f, positionProb.get(f) * thisProbability));
visitedCells.add(positon);
// last cell, no further recurrsion.
if (n == 1){
finalReachableCells.add(nextCells);
return;
} else {
//call recurrsively
nextCells.stream().forEach(f -> probabilityHorseRemainRecur(n - 1, f.x, f.y));
}
}
/**
* Calculate the next possbile position for horse in the board.
*/
List<Position> getNextPossbileCells(int x, int y) {
List<Position> reachable = new ArrayList<>();
if (x + 2 <= 8 && y + 2 <= 8) {
reachable.add(new Positon(x+2, y+1))
reachable.add(new Positon(x+1, y+2))
}
.
.
.
.
}
/**
* Calculate the probability of staying after a move from this position
*
*/
void preCompute() {
for (int i = 1; i <= 8; i++ ){
for (int j =1; j <= 8; j++ ) {
Position p = new Positon(i,j);
// Calculate the valid cells that we can move to.
List<Position> nextPosibilePostion = getNextPossbileCells(p.x, p.y);
positionProb.put(Position, nextPosibilePostion/8);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment