数组中相等元素的最大序列

时间:2012-12-06 14:03:23

标签: c# arrays equals

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

12 个答案:

答案 0 :(得分:3)

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

的原因

答案 1 :(得分: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 :(得分:0)

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

答案 3 :(得分: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来检查这个,所以我希望有效吗=)无论如何有一个想法

答案 4 :(得分: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);

答案 5 :(得分: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);
    }

答案 6 :(得分: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();

答案 7 :(得分:0)

SELECT 
  locations."name", 
  contacts.name, 
  array_agg(roles."name") AS "Roles"
FROM locations INNER JOIN contacts ON locations."id" = contacts.location_id
   INNER JOIN "public".memberships ON "public".memberships.contact_id = contacts."id"
   INNER JOIN roles ON "public".memberships.role_id = roles."id"
 group by locations."name", contacts.name

答案 8 :(得分: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();
    }

答案 9 :(得分: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 
*/

答案 10 :(得分: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
    }

答案 11 :(得分:-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] + ",");

            }


        }
    }
}