Hello to anyone who is reading this. I have an issue with problem 205 on Project Euler. It seems I have achieved the correct solution, but the code evaluates is as incorrect.
Here’s my solution, sorry for the messy code.
function diceGame() {
let pColin = probabilityArray(6,6);
let pPeter = probabilityArray(9,4);
let peterWins = 0;
let minPeter = 4;
let maxPeter = 36
//For every possible result of Peter's dice throws, calculates the probability that Colin gets a lower result, and adds it to the total.
for(let i = minPeter; i <= maxPeter; i++){
peterWins += pPeter[i-1]*accumulatedProbability(i,pColin);
}
peterWins = (peterWins.toFixed(7));
console.log(peterWins)
return peterWins;
}
function accumulatedProbability(num,pArr){
let res = 0;
for(let i = 1; i < num; i++){
res += pArr[i-1];
}
return res;
}
//Calculates the probability, given amount of dices and faces of dices, of getting a particular result. Uses some kind of DFS
function probabilityArray(dices, faces){
let res = Array(dices*faces).fill(0);
let singularProbability = 1/(faces**dices) //The probability of getting a given set of throws.
let currentThrow = 1;
let currentSum = 1; //Updates the value of the sum of a given set of throws
let throwValues = Array(dices).fill(1); //shows the current set of throws
let graphCompleted = false;
while (!graphCompleted){
if(currentThrow == 1 && throwValues[0] > faces){
graphCompleted = true;
}
else if(currentThrow == dices){//Evaluating all possible values of the last throw
while(throwValues[currentThrow-1] <= faces){
res[currentSum-1]+= singularProbability;
currentSum ++;
throwValues[currentThrow-1]++;
}
//after evaluating all possible values, adds one to the second to last throw and continues
throwValues[currentThrow-1] = 1;
currentSum = currentSum - faces;
currentThrow--;
throwValues[currentThrow-1] ++;
}
//if any non-final throw is less than the amount of faces in the dice, increments its value by one and evaluates the next throw
else if(throwValues[currentThrow-1] <= faces){
currentSum ++;
currentThrow++;
}
//When any non-last throw exceeds the number of faces, resets it to one, and increases the previous throw by one.
else if(throwValues[currentThrow-1] > faces){
currentSum -= faces;
throwValues[currentThrow-1] = 1;
currentThrow--;
throwValues[currentThrow-1]++;
}
}
return (res)
}
diceGame();
If you log the result of the function, its output matches the correct result. I tried converting the result into a string, to see if it’s a type problem, but it doesn’t seem so.
Thank you for your help
Challenge: Problem 205: Dice Game
Link to the challenge: