Given the numbers 1, 2, 3, 4, 5, 6, 7, 8, I am seeking to replace the x's in such a way that each side adds up to the number in the center.
*-*---*-*
|x| x |x|
*-*---*-*
|x| 12|x|
*-*---*-*
|x| x |x|
*-*---*-*
Initially, I have iterated over the numbers to identify all potential 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, the numbers have been concatenated 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]);
}
}
}
}
}
Currently, there is no check in place to ensure each set of numbers is only used once, which is my proposed solution.
I am open to suggestions on a more efficient approach to solving this problem.