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

それは宿題なので、おそらくアルゴリズムを構築する必要があります

        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

この方法で試してください:

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

これは、シーケンスを1回繰り返すだけで解決できる問題です。最大シーケンスがシーケンスの最後にある場合を含め、すべての場合にアルゴリズムが機能することを確認することが重要です。

    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

//プログラマー: 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

あなたの質問に対する答えを完全に与えることなく、これを理解するいくつかの簡単な方法が間違いなくあるので、LINQ を見てみることをお勧めします。GroupCountOrderByおよび拡張メソッドを調べることから始めてSelect、答えを得ることができます。

于 2012-12-06T14:13:23.750 に答える
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 に答える
-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 に答える