Program in C# to find the numbers larger than them in the collection.

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 250
Let's say we have a collection of numbers like { 16,17,4,3,5,2 }. Now the objective is to find those numbers which are greater than the rest in the collection while compare with their right elements.
Indicates that 16 compared to 17 is less and cannot be consider. While 17 compared to 4,3 5 and 2 is always greater and hence will be consider. Likewise, 4 though greater than 3 abut less than 5 will be discarded. But 5 compared to 2 is greater. And since 2 is the rightmost element will always be consider.
The below program will do so

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{

var intCollection = new List<int>() { 16,17,4,3,5,2 };
var discardedElements = new List<int>();

for(int i=0;i< intCollection.Count;i++)
{
for(int j=i+1;j< intCollection.Count; j++)
{
if (intCollection[i] < intCollection[j])
{
discardedElements.Add(intCollection[i]);
}
}
}
Console.WriteLine("Successful elements are");
intCollection.Except(discardedElements).ToList().ForEach(i => Console.WriteLine("{0}", i));
Console.ReadKey();
}
}
}


Result
-------
Successful elements are
17
5
2

Comments or Responses

Login to post response