Reputation: 19
(Tried to look for earlier answers for my question and didn't find any...)
lets say I have an array like this :
string[] chars = {"1", "x", "1", "x", "x", "x", "x", "x", "1", "1", "1", "x", "1", "x", "x", "x"};
I need to find the way to extract the max number of "x" in a row in an array, so in this example I have total of 10 "x" but only 5 in a row, so I need the extract the number 5.
Tried this method... but how of course it wont work with the first char (i-1).
string[] chars = { "1", "x", "1", "x", "x", "x", "x", "x", "1", "1", "1", "x", "1", "x", "x", "x" };
int count = 0;
for (int i=0; i < chars.Length; i++)
{
if ((chars[i] == "x") && (chars[i] == chars[i - 1])) ;
count++;
}
Console.WriteLine(count);
Thanks for the help !
Upvotes: -1
Views: 260
Reputation: 81573
Low tech generic approach with just a foreach
and an iterator method
Given
public static IEnumerable<(T item, int count)> GetStuff<T>(IEnumerable<T> source)
{
T current = default;
var started = false;
var count = 0;
foreach (var item in source)
{
if (!EqualityComparer<T>.Default.Equals(item,current) && started)
{
yield return (current, count);
count = 0;
}
current = item;
count++;
started = true;
}
yield return (current, count);
}
Usage
string[] chars = {"1", "x", "1", "x", "x", "x", "x", "x", "1", "1", "1", "x", "1", "x", "x", "x"};
var results = GetStuff(chars);
foreach (var result in results)
Console.WriteLine(result);
Results
(1, 1)
(x, 1)
(1, 1)
(x, 5)
(1, 3)
(x, 1)
(1, 1)
(x, 3)
If you wanted the max of something
var results = GetStuff(chars)
.Where(x => x.Item == "x")
.Max(x => x.Count);
Upvotes: 2