2017-10-10 51 views
0

我想创建数组与carryover的简单添加。还需要结转和结果值进行显示。在纯Javascript中使用数组中的残余加法

事情是这样的: -

Image showing this task

var input = [[0,0,9],[0,9,9]]; var carryover = []; var result = [];

谢谢...

+2

请提供你的努力的[MCVE到此为止。 StackOverflow不是一种代码编写服务,如果你不告诉我们你已经尝试了什么,我们不能帮你。 – evolutionxbox

回答

0

两个部分,你可能已经挣扎,我想会是你怎么弄的携带,以及如何得到结果..

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(', '));

+0

如果可能存在两个以上不同长度的数组,那将是很好的,例如'104 + 24 + 2048'会很有用。对于这种情况使用我的答案,否则这是非常好的! –

+0

@GuyWhoKnowsStuff我的确想到了这一点,但试图尽可能缩短答案,但我已经更新了用0填充输入,而不是抛出错误。 – Keith

0

这工作!

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!

-1

这里是我的尝试。它将接受以下输入:

  • 任意数量的输入阵列
  • 输入数组并不都需要有相同数量的

我已经添加代码注释项目解释发生了什么,我希望他们足够的信息来解释答案。

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}`);

+0

我得知downvotes是StackOverflow的一部分,是什么使其工作。我只是为了解答为什么这个答案被拒绝投了赞成票。它的工作原理和记录,我相信它回答了这个问题。评论会非常感激,告诉我我错过了什么。 – Thijs

相关问题