1

では、特定の値が配列に現れるたびに、別の配列のカウンターに 1 を追加するループを C# で作成するための優れた単純なアルゴリズムは何でしょうか?

たとえば、私はこれを持っています:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication22
{
    class Program
    {
        const int SIZE = 12;

        static void Main(string[] args)
        {
            int[] numbers = new int[SIZE] {5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1};
           string[] letters = new string[SIZE] { "m", "m", "s", "m", "s", "s", "s", "m", "s", "s", "s", "s" };
            int[] values = new int[SIZE] {15, 22, 67, 45, 12, 21, 24, 51, 90, 60, 50, 44};
            string[] status = new string[SIZE] { "f", "m", "f", "a", "m", "f", "f", "f", "m", "f", "m", "f" };

            int[] Count = new int[4];
            int x = 0;
            int i = 0;

            for (i = 0; i < SIZE - 1; i++)
            {
                if (numbers[i] > 0 && numbers[i] < SIZE)
                {
                    x = Count[i];
                    Count[x]++;
                }
            }

            for (i = 0; i < 4; i++)
            {
                Console.WriteLine("{0}", Count[4]);
            }
        }
    }
}

数字配列に4つの数字が現れる回数だけを数えています。誰かが最初のループでメソッドを使用することを提案しましたが、機能していないようで、インデックスが配列の範囲外であるというエラーが発生します。これらの数字 (5、7、9、および 1) がそれぞれ 4 行に表示される回数を表示したいと考えています。

編集:LINQや辞書などの他の凝ったものを使用せずに。

4

6 に答える 6

0

これは、「値が配列に現れる回数を数える」を見つけるための単純なソリューションです。

using System.Collections.Generic;
using System.Text;

namespace GetArrEleFrequency
{
    class Program
    {
      static int[] Arr = new int[5] { 3, 3, 0, 2, 0 };
      static int[] Key = new int[5];
      static int[] value = new int[5];
      static void Main(string[] args)
      {
         int keyItr = -1, ValueItr = -1, tempIndex = 0, tempValue = 0;
         for (int i=0; i <= Arr.Length-1;i++) {
              if (!(isPresent(Arr[i]))) {
                   keyItr += 1;ValueItr += 1;
                   Key[keyItr] = Arr[i];
                   value[ValueItr] = 1;
             } else {
                   
                   value[tempIndex] = value[getIndex(Arr[i])] + 1;
            }
        }
        for (int i=0;i<=Key.Length-1;i++) {
              Console.WriteLine(Key[i] + "-" + value[i]);
        }
        Console.ReadKey();
     }
     public static Boolean  isPresent(int num) {
      Boolean temp = false;
      for (int i=0; i <= Key.Length-1;i++) {
        if (Key[i] == num) {
              temp = true;
              break;
        } else {
              temp = false;
        }
     }
     return temp;
   }
   public static int getIndex(int num) {
       int temp = 0;
       for (int i=0;i<=Key.Length-1;i++) {
             if (Key[i] == num) {
               break;
             } else {
             temp += 1;
       }
  }
  return temp;
   }
 }
}

Output :

    3 - 2
    0 - 2
    2 - 1
    0 - 0
    0 - 0
于 2021-01-13T15:51:15.513 に答える