function ScaleBalancing(strArr) { const a1 = JSON.parse(strArr[0])[0]; const a2 = JSON.parse(strArr[0])[1]; let weights = JSON.parse(strArr[1]); if (a1 == a2) { return 'equal' } else { for (let i = 0; i < weights.length; i++) { if (a1 + weights[i] === a2 || a2 + weights[i] === a1) { if (a1 > a2) { return 'add right side ' + weights[i]; } else { return 'add left side ' + weights[i]; } } for (let j = i + 1; j < weights.length; j++) { if (a1 + weights[i] + weights[j] === a2 || a2 + weights[i] + weights[j] === a1 || a1 + weights[i] === a2 + weights[j] || a2 + weights[i] === a1 + weights[j]) { if (a1 < a2) { return ' left side add ' + weights[i] + ', right side add ' + weights[j]; } else { return ' left side add ' + weights[j] + ', right side add ' + weights[i]; } } } } } return 'not possible'; } console.log(ScaleBalancing(["[4, 4]", "[1, 2,3, 6]"])); Si strArr es ["[5, 9]", "[1, 2, 6, 7]"] entonces esto significa que hay una balanza con un peso de 5 en el lado izquierdo y 9 en el lado derecho. Es posible equilibrar esta balanza agregando un 6 al lado izquierdo de la lista de pesos y agregando un 2 al lado derecho. Ambas escalas ahora serán 11 y están perfectamente balanceadas. Así que necesito arreglar esto para obtener un resultado como este:
Input:"[3, 4]", "[1, 2, 7, 7]" Output:"Left: 1 | Right: 0" Input:"[13, 4]", "[1, 2, 3, 6, 14]" Output:"Left: 0 | Right: 3,6" Input: "[5, 5]", "[1, 2, 3]" Output: "Equals"Bueno, fue difícil entender lo que querías hacer, pero creo que lo entendí.
necesita que el primer bucle for se ejecute solo sin el bucle scound. Hice dos bucles uno dentro del otro para entender mejor los valores, pero puedes juntarlos:
function ScaleBalancing(strArr) { const a1 = JSON.parse(strArr[0])[0]; const a2 = JSON.parse(strArr[0])[1]; let weights = JSON.parse(strArr[1]); if (a1 == a2) { return 'equal' } else { for (let i = 0; i < weights.length; i++) { if (a1 + weights[i] === a2 || a2 + weights[i] === a1) { if (a1 > a2) { return 'add right side ' + weights[i]; } else { return 'add left side ' + weights[i]; } } } for (let j = 0; j < weights.length; j++) { for (let i = 0; i < weights.length; i++) { if (a1 + weights[j] === a2 + weights[i] || a1 + weights[j] === a2 + weights[i]) { if (a1 > a2) { return ' left side add ' + weights[i] + ', right side add ' + weights[j]; } else { return ' left side add ' + weights[j] + ', right side add ' + weights[i]; } } } } } return 'not possible'; } console.log(ScaleBalancing(["[3,7]", "[1,2,3,6]"]));