I have the code like below to return the number that makes the sum of each line the same.
let getnums = () => {
var numsarray = [];
var arrays = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var len = arrays.length;
while (len > 0) {
var rans = Math.floor(Math.random() * len);
numsarray.push(arrays[rans]);
arrays.splice(rans, 1);
len = len - 1;
}
return numsarray;
};
let done = false
function test(num){
while (!done) {
let output = getnums();
if (
output[0] + output[1] + output[2] == 15 &&
output[1] + output[4] + output[7] == 15 &&
output[2] + output[5] + output[8] == 15 &&
output[0] + output[3] + output[6] == 15 &&
output[2] + output[4] + output[6] == 15 &&
output[3] + output[4] + output[5] == 15 &&
output[6] + output[7] + output[8] == 15 &&
output[0] + output[4] + output[8] == 15
) {
done = true
console.log(output)
}
}
}
test()
The code works fine, but I am looking for ways to shorten the if statement.
My current code only will work result 3*3 because of the specific if
statement , I am looking for a better and that will work for all different sizes:
E.g: 4*4, a function produces:
if(
output[0] + output[1] + output[2] +output[3]
output[4] + output[5] + output[6] +output[7]
....
)
I have already had idea or using loop to make randomnumber, but don’t know how to make if statement.
Is it possible I could use loop or other methods to create the if statement?
Any suggestions or ideas?
Thank you!