【问题标题】:maximal sequence of equal elements in an array数组中相等元素的最大序列
【发布时间】:2019-11-19 14:50:35
【问题描述】:

我的家庭作业是:编写一个程序,找出数组中相等元素的最大序列。示例:{2, 1, 1, 2, 3, 3, 2, 2, 2, 1} = {2, 2, 2}。 我想出了这个:

Console.WriteLine("Enter array lenght");
            int arrLenght = int.Parse(Console.ReadLine());
            int[] arr = new int[arrLenght];
            Console.WriteLine("Enter array elements");
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = int.Parse(Console.ReadLine());
            }
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] == arr[i + 1] && arr[i] == arr[i + 2])
                {
                    Console.WriteLine("Maximal sequence of numbers is: {0},{1},{2}",arr[i],arr[i+1],arr[i+2]);
                    break;
                }

            }

这仅适用于序列正好是 3 个数字长的情况。我必须搜索数组并找到最大的序列,但我不知道如何编码。如果问题很愚蠢,我很抱歉,但我是新手,我在其他任何地方都找不到解决方案。谢谢

【问题讨论】:

    标签: c# arrays equals


    【解决方案1】:

    如果您正在寻找优雅,请使用 Linq

    var seq = new int[] {2, 1, 1, 2, 3, 3, 2, 2, 2, 1};
    
    int[] max = seq.Select((n, i) => new { Value = n, Index = i})
        .OrderBy(s => s.Value)
        .Select((o, i) => new { Value = o.Value, Diff = i - o.Index } )
        .GroupBy(s => new { s.Value, s.Diff})
        .OrderByDescending(g => g.Count())
        .First()
        .Select(f => f.Value)
        .ToArray();
    

    这就是为什么我♥ Linq

    【讨论】:

    • LINQ 基本上是 C# 中的 SQL 对吧?它让生活更轻松:)
    • 没有。 Linq 本身就是一种语言。但是,您可以使用 Linq to SQL 从 Linq 运行 SQL 查询。 msdn.microsoft.com/en-us/library/bb386976.aspx。还要确保您接受答案,以便人们知道这是关闭的。
    【解决方案2】:

    使用 Linq:

    int count = seq.Count();
    int[] maxSeq = seq
        .Select((i, index) => new{ 
            Item = i, index,
            PrevEqual = index == 0 || seq.ElementAt(index - 1) == i,
            NextEqual = index == count - 1 || seq.ElementAt(index + 1) == i,
        })
        .Where(x => x.PrevEqual || x.NextEqual)
        .GroupBy(x => x.Item)
        .OrderByDescending(g => g.Count())
        .First().Select(x => x.Item).ToArray();
    

    解释

    • 选择具有bool 属性的匿名类型,该属性指示它是否与前一个值相同
    • 因为我们只对那些感兴趣,所以使用Where 限制查询
    • GroupBy 具有相同值的元素
    • 然后按每组的计数排序(降序)
    • 选择第一组的值(最大)
    • 根据值创建一个新数组

    Demo

    【讨论】:

    • 当最大序列位于序列末尾时,此算法不起作用。示例:{ 2, 1, 1, 1 }
    • @AndreaAngella:很好的收获。已更正。
    【解决方案3】:

    试试这个方法:

    int MaximimalSequence<T>(IList<T> list, out T value)
    {
        T aux = default(T);
        value = default(T);
        int max = 0, hist = 0;
        bool first = true;
    
        foreach (var i in list)
        {
            if (!first && aux.Equals(i))
            {
                max++;
            }
            else
            {
                first = false;
                max = 1;
            }
    
            if (hist < max)
            {
                hist = max;
                value = i;
            }
    
            aux = i;
        }
    
        return hist;
    }
    

    称呼它:

    int value;
    var maximumSequence = MaximimalSequence<int>(new List<int> { 2, 1, 1, 2, 3, 3, 2, 2, 2, 1 }, out i);
    

    【讨论】:

      【解决方案4】:

      如果没有完全回答您的问题,我建议您看看 LINQ,因为肯定有一些简单的方法可以解决这个问题。您可以先查看GroupCountOrderBySelect 扩展方法,这些方法可以为您提供答案。

      【讨论】:

      • 我还没有学过这些,但我会研究一下。感谢您的提示。
      【解决方案5】:

      因为这是一个家庭作业,所以可能需要建立一个算法

              int[] arr = new int[30];//your array
              Random rand = new Random(100);
              int maxCount = 0, curCount, value = 0;          
      
              for (int i = 0; i < arr.Length; i++)
                  arr[i] = rand.Next(15);//fill the aray with random values               
      
      
              arr = arr.OrderBy(a => a).ToArray();
      
              for (int i = 0; i < arr.Length; i++)
              {
                  curCount = 1;//found new value. and now count == 1
                  for (int j = i+1/*search from next array element*/; 
                           j < arr.Length-1/*to the end*/; 
                           j++)
                          {
                              if (arr[i] == arr[j])
                                  curCount++;//counts the count
                              else
                                  break;//met new value
                          }
                          if (curCount > maxCount)//we've found new sequence 
                      {
                          maxCount = curCount;//new sequence length
                          value = arr[i];//sequence values
                          i += maxCount;//we don't need to watch the sequence again
      
      
                      }
              }
      

      我现在没有 VS 来检查这个,所以我希望它有效 =) 无论如何有一个想法

      【讨论】:

        【解决方案6】:

        这是一个可以通过序列的单次迭​​代来解决的问题。重要的是要确保算法在所有情况下都有效,包括最大序列位于序列末尾时。

            private static IEnumerable<int> GetMaxSequence(IList<int> seq)
            {
                if (seq == null || seq.Count == 0)
                {
                    return new List<int>();
                }
        
                int value = seq[0];
        
                int currentSequenceStartIndex = 0;
                int currentSequenceLength = 1;
        
                int maxSequenceStartIndex = 0;
                int maxSequenceLength = 0;
        
                for (int i = 1; i < seq.Count; i++)
                {
                    if (seq[i] == value)
                    {
                        currentSequenceLength++;
                        continue;
                    }
        
                    if (currentSequenceLength > maxSequenceLength)
                    {
                        maxSequenceLength = currentSequenceLength;
                        maxSequenceStartIndex = currentSequenceStartIndex;
                    }
        
                    currentSequenceStartIndex = i;
                    currentSequenceLength = 1;
                    value = seq[i];
                }
        
                if (currentSequenceLength > maxSequenceLength)
                {
                    maxSequenceLength = currentSequenceLength;
                    maxSequenceStartIndex = currentSequenceStartIndex;
                }
        
                return seq.Skip(maxSequenceStartIndex).Take(maxSequenceLength);
            }
        

        【讨论】:

          【解决方案7】:
              // create two list holding ints. One for the temporary value and one for the longest sequence
              List<int> longestSequence = new List<int>();
              List<int> temp = new List<int>();
              // create count to count how many elements are holding the same value
              // and counter to assign this value when max is reached
              int count = 0;
              int counter = 0;
          
              // with for loop compare every element with the elements that follow it
              for (int i = 0; i < arr.Length - 1; i++)
              {
                  int nextElement = i+1;    // element that follows
                  count = 0;                // ignore for now see the end of the for loop
                  temp.Clear();             // ignore for now see the end of the for loop
                  temp.Add(arr[i]);         // add the compared element in to the temp list
                  // while the value is the same as following element add this to the temporary list
                  // and add count (count++)
                  while (arr[i] == arr[nextElement])
                  {
                      temp.Add(arr[nextElement]);
                      nextElement++;
                      count++;
                  }
                  // after that see if the count is bigger than counter (maximum amount of elements so far)
                  // it is set to 0 at the beginning
                  if (count > counter)
                  {
                      longestSequence.Clear();
                      // if it is bigger assign count value to counter
                      counter = count;
                      // and copy the temporary list to the longestSequence list
                      for (int k = 0; k < temp.Count; k++)
                      {
                          longestSequence.Add(temp[k]);
                      }
                  } 
              // at the beggining of the for loop the count will be set to 0 again
              // and the temporary list will be cleared
              }
              Console.WriteLine();
              // print the longestSequence list
              foreach (int element in longestSequence)
              {
                  Console.Write(element + " ");
              }
              Console.WriteLine();
          

          【讨论】:

          • 一些关于你的方法的描述性文字会很好。
          • 我已经编辑了答案并添加了解释方法的 cmets。如果需要更多解释,请告诉我。
          【解决方案8】:
              static int num;
              static void Main(string[] args)
              {
                  int[] array;
                  Console.Write("enter the size of array : ");
                  int input = int.Parse(Console.ReadLine());
          
                  int[] temp;
                  temp = new int[10];
          
                  int a = 0;
                  int count = 0;
          
                  array = new int[input];
          
                  for (int i = 0; i < input; i++)
                  {
                      Console.Write("enter value ( " + i + ", " + input+") :");
                      array[i] = int.Parse(Console.ReadLine());
                  }
          
                  for (int i = 0; i < 20; i++)
                  {
                      for (int j = 0; j < array.Length; j++)
                      {
                          if (i == array[j])//compare i with array
                          {
                              count++;
                              if (a < count)//if greator found
                              {
          
                                  a = count;
                                  num = i;
                              }
                          }
                          else
                          {
                              count = 0;
                          }
                      }   
                  }
                  Console.WriteLine(num +" repeated " + a +" times");
                  Console.ReadKey();
              }
          

          【讨论】:

            【解决方案9】:

            //程序员:Hamza Jany //P-Lang = C#

                static int num;
                static void Main(string[] args)
                {
                    int[] array;
                    Console.Write("enter the size of array : ");
                    int input = int.Parse(Console.ReadLine());
            
                    int[] temp;
                    temp = new int[10];
            
                    int a = 0;
                    int count = 0;
            
                    array = new int[input];
            
                    for (int i = 0; i < input; i++)
                    {
                        Console.Write("enter value ( " + i + ", " + input+") :");
                        array[i] = int.Parse(Console.ReadLine());
                    }
            
                    for (int i = 0; i < int.MaxValue; i++)
                    {
                        for (int j = 0; j < array.Length; j++)
                        {
                            if (i == array[j])//compare i with array
                            {
                                count++;
                                if (a < count)//if greator found
                                {
            
                                    a = count;
                                    num = i;
                                }
                            }
                            else
                            {
                                count = 0;
                            }
                        }   
                    }
                    Console.WriteLine(num +" repeated " + a +" times");
                    Console.ReadKey();
                }
            

            【讨论】:

              【解决方案10】:
              static void Main(string[] args)
                {
                  int[] array1 = { 1, 1, 1, 2, 3, 2, 2, 2, 2, 1 };
                  int start = 0;
                  int length  = 0;
                  int bestStart = 0;
                  int bestLength = int.MinValue;
                  for (int i = 0; i < array1.Length - 1; i++)
                      {
                          if ((i == 0) || (array1[i] != array1[i - 1]))
                          {
                              start = i;   
                          }
                          if(array1[start] == array1[start + 1])
                          {
                              length++;
                              if (length > bestLength)
                              {
                                  bestLength = length;
                                  bestStart = start;
                              }         
                          }
                          else
                          {
                              length = 0;
                          }
                      }
                     Console.Write("The best sequence is :");
                     for (int i = bestStart; i < bestLength + bestStart; i++)
                      {
                          Console.Write(" " + array1[i]);             
                      }
               }
               /* 
                   This will give : The best sequence is : 2 2 2 2 
              */
              

              【讨论】:

                【解决方案11】:

                以下是我对 C# 问题的解决方案。我尽量减少代码,使其更具可读性和可理解性。

                public static void Main(string[] args)
                    {
                        int[] intList = new int[] { 1, 1, 2, 2, 3, 3, 3, 4, 4, 5 };
                
                        foreach (var item in intList) {
                            Console.Write(item + " ");
                        }
                
                        #region Calculating sequence and printing details
                        int length = 1, start = 0, finalIndx = 0,
                        bigSeqNum = 0, finalLen = 0;
                
                        for (int i = 1; i < intList.Length; i++) {
                            if (intList[i] == intList[start]) {
                                length++;
                                if (length > finalLen) {
                                    finalLen = length;
                                    finalIndx = start;
                                    bigSeqNum = intList[start];
                                }
                            } else {
                                start = i;
                                length = 1;
                            }
                        }
                        Console.WriteLine("\nBig Seq. Num: " + bigSeqNum);
                        Console.WriteLine("Start index: " + finalIndx);
                        Console.WriteLine("Length: " + finalLen);
                        Console.WriteLine();
                        #endregion
                    }
                

                【讨论】:

                  【解决方案12】:
                  static void Main(string[] args)
                          {
                  
                              Console.WriteLine("enter length of the array");
                              int n = int.Parse(Console.ReadLine());
                              int[] myarray = new int[n];
                              for (int i = 0; i < n ; i++)
                              {
                                  Console.WriteLine("enter value of array" + " " + i);
                                  myarray[i]=int.Parse(Console.ReadLine());
                              }
                              int length = 1;
                              int start = 0;
                              int bestlength=0;
                              int beststart=0;
                              for (int i = 1; i < n; i++)
                              {
                                  if (myarray[i - 1] == myarray[i])
                                  {
                                      length++;
                                      continue;
                                  }
                                  if (bestlength<length)
                                  {
                                      bestlength = length;
                                      beststart = start;
                                  }
                                  length = 1;
                                  start = i;
                              }
                              Console.WriteLine("the best sequence is");
                  
                              for (int j = beststart; j < bestlength + beststart; j++)
                              {
                  
                  
                                  Console.Write(myarray[j] + ",");
                  
                              }
                  
                  
                          }
                      }
                  }
                  

                  【讨论】:

                    猜你喜欢
                    • 2012-11-09
                    • 2015-02-15
                    • 1970-01-01
                    • 2017-02-02
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2011-04-13
                    相关资源
                    最近更新 更多