Advertisement
grubcho

Sum adjacent equal numbers - Lists

Jun 23rd, 2017
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.20 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. //Write a program to sum all adjacent equal numbers in a list of decimal numbers, starting from left to right.
  7. //After two numbers are summed, the obtained result could be equal to some of its neighbors and should be summed as well(see the examples below).
  8. //Always sum the leftmost two equal neighbors(if several couples of equal neighbors are available).  
  9. namespace Sum_Adjacent_Equal_Numbers
  10. {
  11.     class Program
  12.     {
  13.         static void Main(string[] args)
  14.         {
  15.             List<decimal> list = Console.ReadLine().Split(' ').Select(decimal.Parse).ToList();
  16.             for (int index = 0; index < list.Count - 1; index++)
  17.             {
  18.                 if (list[index] == list[index+1])
  19.                 {
  20.                     list[index] += list[index + 1];
  21.                     list.RemoveAt(index + 1);
  22.                     index-=2;
  23.                     if (index < -1)
  24.                     {
  25.                         index = -1;
  26.                     }
  27.                 }
  28.                
  29.             }
  30.             Console.WriteLine(string.Join(" ", list));
  31.         }
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement