Subtract from a number the values to your right in a list

Asked

Viewed 331 times

1

I have a situation that is as follows:

given an array with for example 5 positions [5, 10, 8, 2, 7] I need an algorithm that allows me to do the following:

  1. Take the 5 and subtract by the numbers that are after your position [10, 8, 2, 7]

  2. Take the 10 and subtract by the numbers that are after your position [8, 2, 7]

  3. Take 8 and subtract by the numbers that are after your position [2, 7]

And so on. I need to store the result of these subtractions in a new array.

Can be in either of the two languages.

  • One thing to note is that this is not directly possible using a stack, unless the language/technology does not respect the concepts of the structure. If it is a college exercise or the like, it will be necessary to move the elements of this stack to another structure.

1 answer

3


There is no mystery, just make a loop to go through all elements of the array and within this loop make another loop that goes through all elements after the current and subtract.

There’s nothing piling on it, maybe the array which is received can be used as a stack, but then the logic would be the other way around, ie the first element to be used would be the 7 and the 5 would be the last.

var arr = [5, 10, 8, 2, 7];

for(var i = 0; i < arr.length; i++) {
  var sub = arr[i];
  for(var j = i + 1; j < arr.length; j++) {
    sub -= arr[j];
  }
  
  console.log(arr[i], sub);
}

In C#:

using System;
using static System.Console;                
public class Program
{
    public static void Main()
    {
        var arr = new [] { 5, 10, 8, 2, 7 };

        for(var i = 0; i < arr.Length; i++) 
        {
            var sub = arr[i];
            for(var j = i + 1; j < arr.Length; j++) 
            {
                sub -= arr[j];
            }

            WriteLine($"Elemento: {arr[i]}  Subtração: {sub}");
        }
    }
}

You can see running on . NET Fiddle.

  • That’s just what I need. The sub variable you accumulate the subtractions I will replace with an array that stores the result of each operation ex: 5 - 10, 5 - 8, 5 - 2 and so on.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.