我想創建數組與carryover的簡單添加。還需要結轉和結果值進行顯示。在純Javascript中使用數組中的殘餘加法
事情是這樣的: -
如var input = [[0,0,9],[0,9,9]]; var carryover = []; var result = [];
謝謝...
我想創建數組與carryover的簡單添加。還需要結轉和結果值進行顯示。在純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(', '));
如果可能存在兩個以上不同長度的數組,那將是很好的,例如'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