キャリーオーバーを使用して配列を単純に追加したいと考えています。表示にはキャリーオーバーと結果値も必要です。このような純粋なJavascriptで配列にキャリーオーバーを追加する
何か: -
例えばvar input = [[0,0,9],[0,9,9]]; var carryover = []; var result = [];
おかげで...あなたが苦労されている場合があります
キャリーオーバーを使用して配列を単純に追加したいと考えています。表示にはキャリーオーバーと結果値も必要です。このような純粋なJavascriptで配列にキャリーオーバーを追加する
何か: -
例えばvar input = [[0,0,9],[0,9,9]]; var carryover = []; var result = [];
おかげで...あなたが苦労されている場合があります
二つの部分、私は仮定は、あなたが得るどのようになりますキャリー、そして結果を得る方法。
result [diget] = t % 10;
% 10
の部分はいわゆるモジュラスです。ここではモジュラスを10倍していますので、10の単位の値が得られます。
carryover [diget] = Math.trunc(t/10);
キャリーオーバーの場合は、10で除算した後、小数点以下を切り捨てます。それはMath.trunc
のことです。
var input = [[0,0,0,9],[0,9,9]];
var carryover = [];
var result = [];
var digetlength = Math.max(input[0].length, input[1].length);
//lets padd inputs to be same size
input[0].unshift(
...new Array(digetlength - input[0].length).fill(0));
input[1].unshift(
...new Array(digetlength - input[1].length).fill(0));
for (var diget = digetlength - 1; diget >= 0; diget -= 1) {
var t = input[0][diget] + input[1][diget];
if (diget < digetlength - 1)
t += carryover[diget + 1];
result [diget] = t % 10;
carryover [diget] = Math.trunc(t/10);
}
result.unshift(carryover[0]);
console.log('result: ' + result.join(', '));
console.log('carry: ' + carryover.join(', '));
長さが異なる2つ以上のアレイが存在する可能性がある場合は、たとえば104 + 24 + 2048が便利です。この場合、私の答えを使用してください。それ以外の場合は、これは素晴らしいです! –
@GuyWhoKnowsStuff私はそれを考えましたが、できるだけ短い答えを保つために努力していましたが、エラーを投げるのではなく、0で入力を埋め込むように更新しました。 – Keith
これは動作します!ここで
function add(...arrs /* gather arguments */) {
let result = []; // the result array
arrs.forEach(function(arr) { // loop through it and get inner arrays
// reverse the inner array so that it is easier to manipulate, and if the arrays are different lengths the indexes work
arr.reverse().forEach(function(number, i) {
if (!result[i]) {
result[i] = 0; // if the array is not big enought, make it big enough
}
result[i] += number; // add to the index
});
});
return carry(result); // carry the result
}
function carry(numbers) { // note: numbers[] is reversed
let changed = false; // did it change?
numbers.forEach(function(number, i) { // loop through numbers
if (number >= 10) { // if needs to carry
if (!numbers[i + 1]) {
numbers[i + 1] = 0; // if the array is not big enought, make it big
}
changed = true; // it changed!
numbers[i + 1] += 1; // carry over
numbers[i] -= 10; // carry over
}
});
if (changed) return carry(numbers); // if changed, recursively check untill no more carrying
return numbers.reverse(); // unreverse the array
}
console.log(add([2, 3, 5], [3, 9], [2, 0, 0, 1])); // whoop!
私の試みです。これは、入力として、次のことを受け入れる:
の数が同じである必要はありません。入力配列の任意の数の
const
input = [
[0,0,9],
[0,9,9],
[1,0,9,9]
];
function getMaxArrayLength(values) {
// Determine the number of items in the longest array. Initialize the reduce with 0.
return values.reduce((maxLength, array) => {
// Return the largets number between the last largest number and the
// length of the current array.
return Math.max(maxLength, array.length);
}, 0);
}
function sumValues(values) {
const
// Determine the number of items in the longest array.
maxLength = getMaxArrayLength(values),
result = [],
carry = [];
// Loop over the length of the longest array. The value of index will be substracted from
// the length of the input arrays. Therefore it is easier to start at 1 as this will
// return a proper array index without needing to correct it.
for (let index = 1; index <= maxLength; index++) {
const
// Get the carryover value from the last sum or 0 in case there is no previous value.
carryValue = (carry.length === 0) ? 0 : carry[carry.length-1],
// Sum up all the values at the current index of all the input arrays. After summing up
// all the values, also add the carry over from the last sum.
sum = values.reduce((sum, array) => {
// Determine the index for the current array. Start at the end and substract the
// current index. This way the values in the array are processed last to first.
const
arrayIndex = array.length - index;
// It could be the current array doesn't have as many items as the longest array,
// when the arrayIndex is less than 0 just return the current result.
if (arrayIndex < 0) {
return sum;
}
// Return the accumulated value plus the value at the current index of the
// current source array.
return sum + array[arrayIndex];
}, 0) + carryValue;
// The carry over value is the number of times 10 fits into the sum. This should be rounded
// down so for instance 5/10=.5 becomes 0.
carry.push(Math.floor(sum/10));
// Push the remainder of the sum divided by 10 into the result so 15 % 10 = 5.
result.push(sum % 10);
}
// Return the carry over and the result, reverse the arrays before returning them.
return {
carryOver: carry.reverse(),
result: result.reverse()
};
}
const
result = sumValues(input);
console.log(`Carry over: ${result.carryOver}`);
console.log(`Result: ${result.result}`);
私は、downvotesがStackOverflowの一部であり、それを動作させるものにしています。私はちょうどこの答えが投票された理由について私の頭を傷つけて残っています。それは動作し、文書化され、私はそれが質問に答えると信じています。コメントは、私が逃しているものを私に知らせるために非常に感謝していたでしょう。 – Thijs
これまでのあなたの努力の[MCVE]を入力してください。 StackOverflowはコード作成サービスではありません。あなたが既に試したことを私たちに示すことができなければ、私たちはお手伝いできません。 – evolutionxbox