0

I made a two dimensional array in c # with random numbers but I want the numbers are not repeated For example, a successful output giving the input 4 (x), 4 (y), 15 (maxElem), would be:

14|8|1|7

3|13|2|4

2|6|12|8

10|9|4|

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

namespace TwoDimensionArray
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 4;
            int y = 4;
            int[,] z = new int[x, y];

            Random r = new Random();
            for (int i = 0; i < x; i++)
            {
                for (int j = 0; j < y; j++)
                {
                    z[i, j] = r.Next(1, 15);
                }
            }
            for (int i = 0; i < x; i++)
            {
                for (int j = 0; j < y; j++)
                {
                    if (i == 3 && j == 3)
                    {
                        Console.Write("  ");
                        break;
                    }
                    else
                    {
                         if (z[i, j] > 9)
                            Console.Write(z[i, j] + " ");
                         else
                            Console.Write(z[i, j] + "  ");
                    }
                }
                Console.WriteLine();
            }
            Console.ReadKey();
        }
    }
}
  • You have an issue with your current code that you may not have realised - by generating random numbers with `r.Next(1, 15)` you only get values from `1 .. 14` as the second parameter is an exclusive upper bound. So by trying to generate 16 numbers from a pool of only 14 you are **ensuring duplicates**. – Enigmativity Nov 03 '14 at 02:27

2 Answers2

1

Generate an array containing the valid numbers, then use a shuffle algorithm to randomize the order in the array, and then finally populate your two-dimensional array by retrieving in order the values from your shuffled array.

Community
  • 1
  • 1
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
0

Try doing it like this:

int x = 4;
int y = 4;
int[,] z = new int[x, y];

Random r = new Random();

var values =
    Enumerable
        .Range(1, x * y)
        .OrderBy(n => r.Next())
        .ToArray();

for (int i = 0; i < x; i++)
{
    for (int j = 0; j < y; j++)
    {
        z[i, j] = values[i * 4 + j];
    }
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172