-4

I am writing the beginning of my program which is to have the computer generate 3 random numbers on the console.

They need to be 1-9 (including both), no numbers can repeat, and I need to put this answer into an array. What's needed in the main method class vs the class.

Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164

3 Answers3

1

You should try it out yourself first (site rules say so), but some hints may be provided:

1) integer random numbers can be generated using Random class. More details can be found here and an answer has been already provided about generation

2) to avoid duplicates each number should be tested against the existing list of numbers:

array.Contains(generatedNumber)

3) For your particular request, an elegant option is to generate all numbers between 1 and 9, shuffle the array and pick the first three elements:

var initArray = Enumerable.Range(1, 9).ToArray();
var randomArray = initArray.OrderBy(x => rnd.Next()).ToArray(); 

Get first three elements and those are random and distinct.

Generally, you can a subarray using the method specified here.

Community
  • 1
  • 1
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
0

Try this code below :

//range set 0 to 9
int Min = 0;
int Max = 10;

//declare an array which store 3 random number
int[] arr = new int[3]; 

Random randNum = new Random();
for (int i = 0; i < arr.Length; i++)
{
    arr[i] = randNum.Next(Min, Max);
    Console.WriteLine(arr[i]);
}
Nadimul De Cj
  • 484
  • 4
  • 16
0

Try this:

Random rnd = new Random();
int[] arr = Enumerable.Range(0, 10).OrderBy(n => rnd.Next()).Take(3).ToArray();

foreach (var n in arr)
{
    Console.WriteLine(n);
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172