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

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 will allow me to do the following:

  • Get 5 and subtract by the numbers that are after your position [10, 8, 2, 7]

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

  • Get 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.

    It can be in any of the two languages.

        
    asked by anonymous 24.05.2017 / 14:03

    1 answer

    3

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

    There is nothing stack in it, maybe the array that is received can be used as a stack, but then the logic would be the opposite, ie the first element to use would be < strong> 7 and 5 would be the last one.

    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 it working in .NET Fiddle.

        
    24.05.2017 / 14:15