多维数组中的重复次数

时间:2010-03-23 11:07:51

标签: c# .net asp.net vb.net

我需要在多维数组中计算它们重复所有数字的重复次数和位置,如下所示:

1 2 1
1 1 2
2 3 1

结果必须是:

Number 1-  two times on position 1, one time on position 2, two times on position 3
Number 2-  one time on position 1, two times on position 2, one times on position 3
Number 3-  0 on position 1, one time on position 2, 0 on position 3

我怎么能这样做?谢谢!

2 个答案:

答案 0 :(得分:2)

诀窍是以这样的方式定义你的多维度,以便处理数组变得容易。

这应该有用。

int[][] jaggedArray =
{
    new[] { 1, 1, 2 },
    new[] { 2, 1, 3 },
    new[] { 1, 2, 1 }
};

foreach (var number in Enumerable.Range(1, 3))
{
    Console.Write("Number " + number + "-  ");
    for (int index = 0; index < jaggedArray.Length; index++)
    {
        int[] innerArray = jaggedArray[index];

        var count = innerArray.Count(n => n == number);

        Console.Write(count + " times on position " + (index + 1) + ", ");
    }

    Console.WriteLine();
}

我可以做些什么来做作业? : - )

答案 1 :(得分:1)

结果可能希望看起来像这样:

var listOfLists = new int[,] {
        {1,2,1},
        {1,1,2},
        {2,3,1}
};

var dict = CountEachNumber(listOfLists, 3, 3);

foreach (var number in dict)
{
    Console.WriteLine(string.Format("Number {0} - ", number.Key.ToString()));
    foreach (var occurence in number.Value)
    {
        Console.WriteLine("{0} times at position {1},", 
             occurence.Value.ToString(), 
             (occurence.Key+1).ToString());
    }
}

这是你用2个词典解决它的方法!

    static Dictionary<int, Dictionary<int, int>> 
                           CountEachNumber(int[,] list, int height, int width)
    {
        // Containging
        //      Number
        //      Information
        //          Line
        //          Occurences
        var dict = new Dictionary<int, Dictionary<int,int>>();

        for (int i = 0; i < height; i++)
        {
            for (int a = 0; a < width; a++)
            {
                var number = list[i, a];
                if (dict.ContainsKey(number))
                {

                    if (dict[number].ContainsKey(a))
                    {
                        dict[number][a]++;
                    }
                    else
                    {
                        dict[number].Add(a, 1);
                    }
                }
                else
                {
                    var val = new Dictionary<int, int>();
                    val.Add(a, 1);
                    dict.Add(number, val);
                }
            }
        }

        return dict;

    }

所以我在这里做的是我将数字存储在字典中,并且对于它的每个出现,我添加了行并增加了增量器!