0

我的家庭作业是:编写一个程序,找出数组中相等元素的最大序列。示例:{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 个数字长时才有效。我必须搜索数组并找到最大的序列,但我不知道如何编码。如果这个问题很愚蠢,我很抱歉,但我是新手,我在其他任何地方都找不到解决方案。谢谢

4

12 回答 12

4

如果您正在寻找优雅,请使用 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

于 2012-12-06T21:29:45.267 回答
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具有相等值的元素
  • 然后按每组的计数排序(降序)
  • 选择第一组的值(最大)
  • 从值创建一个新数组

演示

于 2012-12-06T14:07:05.830 回答
0
    // 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();
于 2015-05-01T15:47:45.960 回答
0

在没有完全回答您的问题的情况下,我建议您看一下 LINQ,因为肯定有一些简单的方法可以解决这个问题。您可以从查看Group、和扩展方法开始Count,这些方法可以为您提供答案。OrderBySelect

于 2012-12-06T14:13:23.750 回答
0

试试这个方法:

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);
于 2012-12-06T14:23:15.390 回答
0

由于这是一项家庭作业,因此可能需要建立一个算法

        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 来检查这个,所以我希望它有效 =) 无论如何有一个想法

于 2012-12-06T14:20:28.697 回答
0

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

    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);
    }
于 2012-12-06T14:46:39.503 回答
0
    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();
    }
于 2015-12-18T15:53:13.663 回答
0
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 
*/
于 2018-01-28T13:53:22.800 回答
0

//程序员: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();
    }
于 2015-12-18T16:09:22.727 回答
0

以下是我在 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
    }
于 2019-11-19T06:50:35.787 回答
-1
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] + ",");

            }


        }
    }
}
于 2014-08-15T07:41:13.263 回答