Reputation: 567
I will give you an example of what I want to do. If we have as input:
1 4 3 2
I want to print all the numbers which are bigger than all the elements to their right. Here we have to print 4, 3 and 2. I've converted the input to an array, but I don't know how to compare the elements.
int[] numbers = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToArray();
Upvotes: 0
Views: 622
Reputation: 335
You can do this using Aggregate:
int[] allNumbers = new int[] { 1, 4, 3, 2 };
int[] filteredNumbers = allNumbers.Aggregate(new List<int>(), (result, x) => {
var filteredResult = new List<int>(result.Where(y => y > x));
filteredResult.Add(x);
return filteredResult;
}).ToArray();
Upvotes: 0
Reputation: 4567
You can do that using LINQ, like this:
var numbers = new[] { 1, 4, 3, 2 };
var query =
from info in numbers.Select((n, i) => (n, i))
where numbers.Skip(info.i + 1).All(value => info.n > value)
select info.n;
The way this works is:
// Iterate over the numbers, keeping track of the index of each one
from info in numbers.Select((n, i) => (n, i))
// For each item, make sure it's greater than the ones on its right
where numbers.Skip(info.i + 1).All(value => info.n > value)
// If that's the case, select that item
select info.n;
```
Upvotes: 0
Reputation: 567
int[] numbers = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToArray();
string[] topIntegers = new string[numbers.Length];
int maximumValue = int.MinValue;
int j = 0;
for (int i = numbers.Length - 1; i >= 0; i--)
{
if (numbers[i] > maximumValue)
{
maximumValue = numbers[i];
topIntegers[j] = maximumValue.ToString();
}
j++;
}
for (int i = topIntegers.Length - 1; i >= 0; i--)
{
Console.Write($"{topIntegers[i]} ");
}
I made it in this way but I got incorrect results on this test:
14 24 3 19 15 17My output is:
24 19 17but expected is:
24 19 17
Upvotes: 0
Reputation: 1335
You can check if the current element is maximum of right slice of array :
int[] numbers = new int[]{ 1, 4 ,3 ,2 };
var result=numbers.Where((number, i) => number == numbers.Skip(i).Max()).ToList();
Output:
4,3,2
Upvotes: 3