Hamko Bnavy
Hamko Bnavy

Reputation: 29

Entering Random numbers to a 2D array with no Duplicates

I want to enter 64 different numbers into an 8*8 array but I am having problems...

int[,] check = new int[8, 8];
        Random rnd = new Random();
        int[,] T = new int[8, 8];
        for (int i = 0; i <=7; i++)
        {
            for (int j = 0; j <=7; j++)
            {
                int num = rnd.Next(1, 64);
                check[i, j] = num;
                while (num != check[i,j])
                {
                    T[i, j] = num;

                }
                Console.Write("{0}\t", T[i, j]);
            }
            Console.Write("\n\n");
        }

Upvotes: 2

Views: 441

Answers (1)

jdweng
jdweng

Reputation: 34421

Try following which randomly assigned the numbers 0 to 63 to the array :

    class Program
    {
        const int ROWS = 8;
        const int COLS = 8;
        static void Main(string[] args)
        {
            Random rnd = new Random();

            int[] values = Enumerable.Range(0, ROWS * COLS)
                .Select(x => new { number = x, rand = rnd.Next()})
                .OrderBy(x => x.rand)
                .Select(x => x.number).ToArray();

            int[,] T = new int[ROWS, COLS];

            int count = 0;
            for(int row = 0; row < ROWS; row++)
            {
                for(int col = 0; col < COLS; col++)
                {
                    T[row, col] = values[count++];
                }
            }

        }

Upvotes: 1

Related Questions