Fermichem
Fermichem

Reputation: 121

printing all the items in an n-dimentional array that user inputs in C#

I want to write a program that takes an array of n dimensions from the user (for example user enters a 4*3*3 array - three dimensions) and prints all its items (the order is not important, maybe all the items over 1 continuous line). I've been able to achieve that for an array of 3 but I don't have the slightest clue where to begin for any array of dimension n.

Here's the code so far:

static void Main(string[] args)
        {
            int[,,] _numberGrid =
            {
                {
                    {1,2,3},
                    {4,5,6},
                    {7,8,9},
                },
                {
                    {1,2,3},
                    {4,5,6},
                    {7,8,9},
                },
                {
                    {1,2,3},
                    {4,5,6},
                    {7,8,9},
                },
                {
                    {1,2,3},
                    {4,5,6},
                    {7,8,9},
                },
                {
                    {1,2,3},
                    {4,5,6},
                    {7,8,9},
                }
            }; //4*3*3
            Console.WriteLine(_numberGrid.Rank);

            int numberOfDimentions = _numberGrid.Rank;
            int[] newArray = new int[_numberGrid.Rank];
            for (int i = 0; i<newArray.Length; i++)
            {
                newArray[i] = _numberGrid.GetUpperBound(i);
            }

            for(int i = 0; i <= newArray[0]; i++)
            {
                Console.Write("\n");
                for (int j = 0; j <= newArray[1]; j++)
                {
                    Console.Write("\n");
                    for (int k = 0; k <= newArray[2]; k++)
                    {
                        Console.Write(_numberGrid[i, j, k]);
                    }

                }
            }
            Console.ReadLine();
        }

I suppose it's doable using some sort of recursive call, but I'm not sure how to do it. The order in which the items are printed are not important, they could be printed in one continuous line. just to clarify: by any array of dimension n, I mean any desired array which is of dimension n that user enters as input.

Upvotes: 0

Views: 89

Answers (3)

Fermichem
Fermichem

Reputation: 121

This is the code I was looking for in C#

using System;
namespace _nd_arrays
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,,,] _numGrid2 =
            {
                {
                    {
                        {0,2,3},
                        {1,0,3},
                        {1,2,0}
                    },

                    {
                        {11,22,33},
                        {44,55,66},
                        {77,88,99}
                    },
                },

                {
                    {
                        {1,0,3},
                        {1,2,0},
                        {0,2,3}
                    },

                    {
                        {111,222,333},
                        {111,222,333},
                        {111,222,33333}
                    },
                },
                {
                    {
                        {1,2,0},
                        {1,2,0},
                        {1,2,0}
                    },

                    {
                        {0,0,0},
                        {0,0,0},
                        {0,0,0}
                    },
                }
            };


            int[] ranks = new int[_numGrid2.Rank]; //index.length --> number of dimentiosn 
            //index items gives us the upper boud for each dimentino 
            for (int i= 0; i < _numGrid2.Rank; i++)
            {
                ranks[i] = _numGrid2.GetUpperBound(i);
            }
            int[] indeces = new int[_numGrid2.Rank];

            Console.WriteLine(PrintCustomArray(_numGrid2, ranks, indeces, 0));

            Console.ReadLine();
        }



        static string PrintCustomArray(Array _initialArray, int[] ranks, int[] printIndeces, int currentDimension )
        {
            string result = "";
            if(currentDimension == ranks.Length - 1)
            {
                for (int i = 0; i <= ranks[currentDimension]; i++)
                {
                    printIndeces[currentDimension] = i;

                    result = result + _initialArray.GetValue(printIndeces).ToString();
                }

            }

            else
            {                           //4
                for (int i = 0; i <= ranks[currentDimension]; i++)
                {
                    printIndeces[currentDimension] = i;
                                                                                    //              //
                    result = result + PrintCustomArray(_initialArray, ranks, printIndeces, currentDimension +1);
                }

            }



            return result;


        }
    }
}

this will print all the items in an n-dimensional array over one line, using recursion

ref: http://csharphelper.com/blog/2017/08/iterate-over-items-in-an-array-with-unknown-dimensions-in-c/

Upvotes: 1

TheGeneral
TheGeneral

Reputation: 81543

Just use Array.Rank, Array.GetValue, Array.GetUpperBound, and an index array

Here is an example

Given

public static bool Inc(int[,] array, int[] index)
{
   for (var i = 0; i < index.Length; i++)
      if (++index[i] > array.GetUpperBound(i))
         index[i] = 0;
      else
         return true;
   return false;
}

public static void Print(int[,] array, int[] index = null)
{
   index = index ?? new int[array.Rank];
   do Console.WriteLine(array.GetValue(index) + " = " + string.Join(",", index));
   while (Inc(array, index));
}

Usage

var test = new[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
Print(test);

Output

1 = 0,0
3 = 1,0
5 = 2,0
7 = 3,0
2 = 0,1
4 = 1,1
6 = 2,1
8 = 3,1

Online Demo


Note : I have used a while loop, though you could use recursion, it depends how you want to display the data or what you want to actually do

You can also access the enumerator of a multidimensional array to get each element

var test = new[,] { { 1, 2, 6 }, { 3, 4, 8 }, { 5, 6, 3 }, { 7, 8, 1  } };
foreach (var item in test)
   Console.WriteLine(item);

Output

1
2
6
3
4
8
5
6
3
7
8
1

Upvotes: 3

Henning Koehler
Henning Koehler

Reputation: 2657

A couple of points to outline a solution:

Storage: You cannot use a standard n-dimensional array, as n is not known at compile time. There's at least two ways you could address this:

  1. Create your own custom data structure NArray, which consists of an array of either references to NArray (of one dimension less) or you base data type (integer).
  2. Use a 1-dimensional array of integers, and keep track of the dimensions "manually", the way n-dimensional arrays of fixed size are implemented internally. E.g. for a 3-dimensional array of dimensions 5x3x3 as in your example you'd keep track of these dimensions [5,3,3] as a variable-size array. All you need to do then is to create a function that converts a multi-dimensional index into a 1-dimensional one.

Note that option 2 will likely be more efficient, but only works if the dimensions are of fixed size (as they are in your example).

Input: You'll first need to obtain the dimension and the sizes. For fixed-size arrays this could simply be [5,3,3]. Afterwards pass in the numbers in a way that lets you identify the indices they belong to. For fixed size arrays, this could simply be the numbers in order (after all, you're just populating a 1-dimensional array).

Output: Once you have the data structure in place, printing should be fairly straight-forward using recursion on sub-arrays of lower dimension.

Example: Assume we use the 1-dimensional array approach with your data above, mapping the 3-dimensional index [a,b,c] to a*3*3 + b*3 + c. Then a print function could look something like this:

void printArray(int[] data, int[] dimensions, int[] index) {
    if ( index.size == dimensions.size ) {
        print(data[map_to_1d(dimensions, index)] + ' ');
    } else {
        print('[ ');
        for (int i = 0; i < dimensions[index.size]; i++) {
            int[] subIndex = index + { i }; // append i
            printArray(data, dimensions, subindex);
        }
        print(']');
    }
}

PS: A different approach that requires less implementation might be to use a library for json objects, which include multi-dimensional arrays as a special case.

Upvotes: 2

Related Questions