Home > Net >  Creating an array of 10 elements and assigning them by counting randomly
Creating an array of 10 elements and assigning them by counting randomly

Time:08-17

Creating an array of 10 elements and assigning them by counting randomly, assigning a new number if the same numbers are repeated I tried to use the contains method but it didn't appear in the list after the array, I used the exists method but it didn't work either, what kind of way should I follow? thanks

static void Main(string[] args)
{
 Random Rnd = new Random();
 int[] Numbers = new int[10];

 for (int i = 0; i < Numbers.Length; i  )
 {
     int rast = Rnd.Next(10);
     bool b = Array.Exists(Numbers, element => element == rast);
     if (!b)
     {
         i--;
     }
     else { Numbers[i] = rast; }  
  }

  foreach (int item in Numbers)
  {
      Console.WriteLine(item);
  }    
}

CodePudding user response:

It appears that you want the numbers from 0 to 9 in an array in random order. If that is so:

var rng = new Random();
var numbers = Enumerable.Range(0, 10).OrderBy(n => rng.NextDouble()).ToArray();

CodePudding user response:

You're close, but there are two issues in your algorithm:

  1. if (!b) should be if (b)
  2. Rnd.Next(1,10) gets numbers between 1 and 9 so you will never get a 10 and the algorithm will never finish.

After fixing these two your program will work.


Anyway, here's a version that uses .Contains

Random Rnd = new Random();
int[] Numbers = new int[10];

 for (int i = 0; i < Numbers.Length; i  )
 {
     //   1 because the range of return values includes minValue but not maxValue.
     int r = Rnd.Next(minValue: 1, maxValue: Numbers.Length   1);
     while(Numbers.Contains(r))
     {
        r = Rnd.Next(minValue: 1, maxValue: Numbers.Length   1);
     }
     
     Numbers[i] = r;   
  }

Console.WriteLine(string.Join(",", Numbers));
  

Example output:

9,8,7,1,4,6,3,10,5,2

CodePudding user response:

Here's an example. I hope this is the output you want.

public static void Main()
{
     Random Rnd = new Random();
     int[] Numbers = new int[10];

     for (int i = 0; i < Numbers.Length; i  )
     {
         int rast = Rnd.Next(10);
         
         bool b = Array.Exists(Numbers, element => element == rast);
         if (!b)
         {
             Numbers[i] = rast;
             Console.WriteLine(rast);
         }
         else {
             i--;
         } 
      }
}
  •  Tags:  
  • c#
  • Related