开发者

Number of repeating in multidimensional array

I need to count number of repeating and position where they repeat of all number in multidimensional array like this:

1 2 1
1 1 2
2 3 1

And result need to be:

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 posit开发者_StackOverflow中文版ion 2, 0 on position 3

How i can do this? Thanks!


The trick is to define your multidimensional in such way that it becomes easy to process the array.

This should work.

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();
}

What do I get for making your homework? :-)


The result might want to be lookcing something like this:

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());
    }
}

This is how you could solve it, with 2 dictionaries!

    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;

    }

So what I am doing here is that I am storing the Number in a dictionary and for each of its occurences, I add the line and increase the incrementer!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜