Carrying over additions in arrays using only Javascript

I'd like to implement a basic array addition with carryover. Additionally, I need to display the carryover and result values.

For instance:

e.g

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

Thank you!

Answer №1

If you've been struggling with two parts, it's likely how to calculate the carry and pinpointing the result accurately.

result [digit] = t % 10;

The % 10 operation is known as modulus. In this case, we are applying a modulus by 10 to determine the value of the tens place.

carryover [digit] = Math.trunc(t / 10);

To find the carryover, you simply divide by 10 and then utilize Math.trunc to remove any decimal points.

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

var digitLength = Math.max(input[0].length, input[1].length);

// Standardizing inputs to have equal lengths
input[0].unshift(
  ...new Array(digitLength - input[0].length).fill(0));
input[1].unshift(
  ...new Array(digitLength - input[1].length).fill(0));

for (var digit = digitLength - 1; digit >= 0; digit -= 1) {
  var t = input[0][digit] + input[1][digit];
  if (digit < digitLength - 1) 
    t += carryover[digit + 1];
  result [digit] = t % 10;
  carryover [digit] = Math.trunc(t / 10);
}
result.unshift(carryover[0]);

console.log('result: ' + result.join(', '));
console.log('carry:  ' + carryover.join(', '));

Answer №2

    1.convert both numbers into arrays of individual digits and reverse the order.
    2.calculate the end index for the for-loop based on the maximum length of the two arrays.
    3.initialize a third array to store carryover digits with zeros (remember the extra digit).
    4.Add the corresponding digits from step 1 and step 3,
       while iterating through each digit from right to left,
    4.1 if the sum is greater than 9, add 1 to the next carryover position.
    5. at the end of the loop, you will have an array of carried over digits,
         count the number of 1s in this array.
function numberOfCarryOperations(number1, number2) {
    const digits1 = [...number1.toString()].reverse()
    const digits2 = [...number2.toString()].reverse()
    const endIndex = Math.max(digits1.length, digits2.length)
    const carryOverArray = Array(endIndex + 1).fill(0)
    for (let j = 0; j < endIndex; j++) {
        if (((Number(digits1[j] ? digits1[j] : 0)) + Number(digits2[j] ? digits2[j] : 0) + carryOverArray[j]) > 9) {
            carryOverArray[j + 1] = 1
        }
    }
    return carryOverArray.reduce((total, current) => total + current)
}

Answer №3

My solution to the problem is designed to handle multiple input arrays with varying lengths:

  • The number of items in each array can differ
  • All types of input arrays are accepted

I have included explanatory comments within the code to make it easier to understand the logic behind the solution.

const
  input = [
    [0,0,9],
    [0,9,9],
    [1,0,9,9]
  ];
  
function getMaxArrayLength(values) {
  // This function determines the length of the longest array by using reduce with an initial value of 0.
  return values.reduce((maxLength, array) => {
      // Compare and return the larger value between the previous length and the current array's length.
      return Math.max(maxLength, array.length);
    }, 0);
}
  
function sumValues(values) {
  const
    maxLength = getMaxArrayLength(values),
    result = [],
    carry = [];

  for (let index = 1; index <= maxLength; index++) {
    const
      carryValue = (carry.length === 0) ? 0 : carry[carry.length-1],
      
      sum = values.reduce((sum, array) => { 
        const 
          arrayIndex = array.length - index;
        
        if (arrayIndex < 0) {
          return sum;
        }
        
        return sum + array[arrayIndex];
      }, 0) + carryValue;
     
    carry.push(Math.floor(sum / 10));
    
    result.push(sum % 10);
  }
  
  return {
    carryOver: carry.reverse(),
    result: result.reverse()
  };
}

const
  result = sumValues(input);
  

console.log(`Carry over: ${result.carryOver}`);
console.log(`Result: ${result.result}`);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to redirect to a different page following a successful execution of a mutation in React-query

I am facing an issue where a memory leak warning appears when I redirect to another page after a mutation. Despite trying various methods, I have not been able to find a solution. The specific warning message is: Warning: Can't perform a React state ...

The API response indicates that the service is currently not accessible

I'm attempting to retrieve a report from the MOZ API, but I keep receiving this response: { "status" : "503", "error_message" : "Service Temporarily Unavailable" } This is the code I am using: function MozCall(callback) { var mozCall = ' ...

Tips for transferring an item to PHP

I am facing a challenge in sending data from the client side (javascript) to the server (php) using ajax. My object structure is as follows: sinfo={ topic_title:title, topic_id: tid, section_name:section_name, ...

Array Filtering with Redux

I have come across similar queries, but I am still unable to find a solution. While typing in the search box, the items on the screen get filtered accordingly. However, when I delete a character from the search box, it does not show the previous items. For ...

Adjust image size as the page is resized

My challenge is to resize images that are typically too large for the current window size, ensuring they fit within 85% of the client window. I tried creating a function utilizing onload and onresize events but encountered issues. function adjustImages(){ ...

Utilizing the sAjaxSource property in Datatables to fetch data through Ajax from multiple tables while dynamically passing arguments

I am facing an issue with populating two datatables using data retrieved from a flask API through a GET request. My data source URL is localhost:5000/data, but for some reason, I am unable to display the data in the datatables. Interestingly, when I use a ...

Initializing Three.js to load the model

I have a 3D model that I initially had in the 3DS format. I then converted it to OBJ and finally to JS format. Now, my goal is to load this model into another JS file. Below you'll find the code snippet I've written for this purpose: var loader ...

Creating a jQuery AJAX data object that contains numerous values for a single key

My goal is to make an ajax call with multiple values in the same key within the data object. var data = { foo: "bar", foo: "baz" } $.ajax({ url: http://example.com/APIlocation, data: data, success: function (results) { console.log(res ...

Having trouble with the anchor tag not functioning properly

I'm looking to create a unique video experience by having an iframe video play automatically and opening a third-party video player in a lightbox style when clicked. Currently, the video autoplays, but I want it so that when the user clicks on the vi ...

Error: Unable to access the property 'fn' of an undefined object in electron version 2 using Angular 6

I am currently utilizing Angular 6.0.3 and electronjs 2.0.2 with the package.json configuration shown below: { "name": "test", "version": "1.0.0", "license": "MIT", "main": "electron-main.js", "author": { "name": "Moh ...

React Native images failing to render at the same time

I have created a React Native app that loads images simultaneously from Supabase storage using a custom hook. The goal is to display these images in a list using SwipeListView: const fetchImages = async (recipes) => { if (!recipes) { return; ...

Unexpected obstacles encountered when implementing the jqTouch JavaScript/AJAX combination on Android

In jqtouch, I'm using vanilla ajax calls to load multiple pages: <li class="arrow"><a href="folder/another/somepage.html" >BRAVIA HDTVs</a><small class="counter">2</small></li></li> I want to incorporate a v ...

Effortlessly sending multiple values from text fields using jQuery

i am using jQuery to fetch all values from text fields with the same field name. $('input[name^="StudentName"]').each(function() { StudentName += $(this).val(); alert(StudentName); }); when I alert, all the values are displayed as one s ...

Having trouble with dragging a file from one box to another in HTML5. The functionality is not working

Encountering an issue where the image does not display in the left box after dropping it. Here is the sequence of events: Before dragging the image: https://i.sstatic.net/C6JSM.png After dragging the image, it fails to display: https://i.sstatic.net/7Du0 ...

Solving runtime JavaScript attribute issues by deciphering TypeScript compiler notifications

Here is a code snippet I am currently working with: <div class="authentication-validation-message-container"> <ng-container *ngIf="email.invalid && (email.dirty || email.touched)"> <div class="validation-error-message" *ngIf=" ...

Diverse behaviors exhibited by an array of promises

I've developed a function that generates an array of promises: async addDefect(payload) { this.newDefect.setNote(payload.note); this.newDefect.setPriority(payload.priority); const name = await this.storage.get(StorageKeys.NAME); ...

I am attempting to use $.map to transfer values into a new array, but unfortunately, it is not producing the desired result

This task seems easy at first glance, but unfortunately it's not working for me. Can someone please point out what I might be doing wrong? var oldArr = [0, 1, 2]; var newArr = []; /* * This function is supposed to add 1 to each element in the array ...

What is the best way to incorporate raw HTML code into a .jsx file within a NextJS website?

I need to integrate Razorpay code into my NextJS website, but it's currently in pure HTML format. For example, the code looks like this: <form><script src="https://cdn.razorpay.com/static/widget/subscription-button.js" data-subscrip ...

Tips for shutting down a modal box without using the "x" button?

I'm currently working on creating a modal box using HTML and Javascript, and I came across this example (reference https://www.w3schools.com/howto/howto_css_modals.asp), which seems to fit my needs quite well... I made some modifications to it... &l ...

Steps for removing all inline styles within an element:1. Access the element's

I have a group of span elements containing texts generated by tinymce. <span class="ArticleSummary"> This content is produced using a text editor and may include various inline styles. </span> Typically, this text includes numerous inline s ...