Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

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 !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...