24 Game is missing answers.
See original GitHub issueDescribe the Issue
There are tons of different ways to write this algorithim, that will come up with tons of different variations of the acceptable equation that reaches 24. My algorithim came up with the following solutions: for set 4878 my algorithm returns 7 * 8 - 4 * 8 which is 24, but that will fail the test for set (1234) my algorithm returns ( 3 + ( 1 + 2 ) ) * 4 which is 24, but will fail the test. (for set (1234) and for set 6897 we get 6 * 8 / ( 9 - 7 ) which is 24, but will fail the test and 3 * 4 / 1 * 2 and i’m sure plenty more…
The question does not specify a specific equation it wants, only that it should be 24 and fit the format. So for this reason, I think its broken, and either needs its answer bank revised, or needs to have numbers with only 1 or 2 solutions chosen for the tests.
Affected Page
https://www.freecodecamp.org/learn/coding-interview-prep/rosetta-code/24-game
Your code
function solve24 (numStr) {
let nums = numStr.split("").map((elem)=>{
return [elem, ""+elem];
})
let answer = false;
let ops = ['+','-','*','/']
const recursive24 = (nums) => {
if(nums.length == 1){
if (nums[0][0] == 24){
answer = nums[0][1];
}
return
}
if(answer){
return
}
// select first number
for(let x = 0; x < nums.length; x++){
//select a operator
for(let j = 0; j < ops.length; j++){
//select second number
for(let k = 0; k < nums.length; k++){
if (k == x){
continue
}
// copy new array, remove nums from it.
let newArr= nums.slice().filter((val, index)=>{
if (index ==k || index == x){
return false
}
return true
});
let exp = nums[x][1]+ops[j]+nums[k][1];
if (j<=1 && newArr.length > 0){
exp="("+exp+")";
}
let val = eval(exp)
newArr.push([val,exp])
recursive24(newArr)
}
}
}
}
recursive24(nums);
console.log(answer)
if(answer===false){
return "no solution exists"
}
return answer;
}
Expected behavior
Should pass the tests, but it fails because the answer bank does not have enough equation results.
Screenshots
No response
System
Desktop free code camp terminal
Additional context
No response
Issue Analytics
- State:
- Created a year ago
- Reactions:1
- Comments:11 (11 by maintainers)
Top GitHub Comments
Or we could skip all that and make a simple, lightweight expression parser.
Not really though, since we only have four operations. I’m making up a smaller parser right now