1
次のプロンプトが表示されています。 スケールの片側に重みがあるとします。他の重みの配列がある場合は、スケールが均衡するかどうかを確認してください。どちらの側でもウェイトを使用することができ、すべてのウェイトを使用する必要はありません。重みの配列によるスケールの調整
私はjavascriptを使用してソリューションを実装しようとしていますが、マッチするまで重みを累積することで問題の1つを解決できました。最終的にこれはスケールの左側に追加する場合にのみ機能しますが、右側にも重みを追加できることを考慮すると最適ではありません。以下はこれまでの私の実装です。
const balance = (arrayOfWeights) => {
//Sort the array and pop off the max number to be stored on the right side of the scale
let right = arrayOfWeights.sort().pop();
let balanced;
let weight;
const subroutine = (lSide, rSide, weightList) => {
//Determine if there is a direct match
if(lSide === rSide) {
balanced = true;
return balanced;
}
//Return false if a match hasn't been found
if(weightList.length === 0) {
balanced = false;
return balanced
}
//Shift the first element of the array to be added to left side
weight = weightList.shift();
subroutine(lSide + weight , rSide, weightList);
}
subroutine(0, right, arrayOfWeights);
return balanced;
};
//Array of weights to be passed to balance function
let weights = [3,6,2,5,1];
すべての組み合わせをチェックする必要があるすべての手順を書き留めてから、コードを書き始める必要があります。 – Jonathan
このようなサウンドは、https://en.wikipedia.org/wiki/Partition_problemに似ています。ここでも尋ねられます:http://math.stackexchange.com/questions/55149/split-a-set-of-numbers-into-2-sets-where-the-sum-of-each-set-is-as-近くに1つ –