Given numbers 1,2,3,4,5,6,7,8 I need them to replace the x's so that each side adds up to the number in the centre.
*-*---*-*
|x| x |x|
*-*---*-*
|x| 12|x|
*-*---*-*
|x| x |x|
*-*---*-*
As a start I have looped over the numbers to find all of the possible combinations.
var range = [1,2,3,4,5,6,7,8];
var target = 12;
var matches = [];
for (x = 0; x < range.length; x ++){
for (y = 0; y < range.length; y ++){
if (y === x){
continue;
}
for (z = 0; z < range.length; z ++){
if (z === y || z === x){
continue;
}
if (range[x] + range[y] + range[z] === target){
matches.push([range[x], range[y], range[z]]);
}
}
}
}
Next I have joined the numbers together end to end
for (j=0; j < matches.length; j++){
for (k=0; k < matches.length; k++){
if (j==k) continue;
//if (matches[j][2] != matches[k][0]) continue;
for (l=0; l < matches.length; l++){
if (l==j || l==k) continue;
//if (matches[k][2] != matches[l][0]) continue;
for (m=0; m < matches.length; m++){
if (m==j || m==k || m==l) continue;
if (matches[l][2] != matches[m][0]) continue;
if (matches[m][2] != matches[j][0]){
console.log(matches[j], matches[k], matches[l], matches[m]);
}
}
}
}
}
I have not currently put a check in to make sure each combination of numbers is only used once, which is how I would solve this.
I really would like to know an overall better approach to solving this problem.