简体   繁体   中英

How to find the maximum number of same chars in a row inside an array in C#

(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 !

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM