0

I've picked a random array of 10 from 28, now I am trying to pick a random 1 from the 10 but can't seem to figure out how. Here's my code:

            Random rand = new Random();



        int[] array = new int[10];
        int count = 0;


        for (int i = 0; i < array.Length; i++)
        {
            int final = rand.Next(28);
            while (final == array[0] || final == array[1] || final == array[2] || final == array[3] || final == array[4] || final == array[5] || final == array[6] || final == array[7] || final == array[8] || final == array[9])
            {
                final = rand.Next(10);

            }
            array[i] = final;
            count++;
            Console.WriteLine($"#{count} player {array[i]}");
            string finalists = names[final].firstname.ToString();
            Console.WriteLine($"Finalist: {finalists}");
            Thread.Sleep(2000);

        }

thanks so much for any help

  • Did you try something like `array[rand.Next(10)]` to get your final random selection from the original random ten? Btw a more effective way of getting your ten numbers is probably to generate a list of all numbers between 0-28, shuffle the list and then take the first ten items. See: https://stackoverflow.com/q/273313/491907 – pinkfloydx33 Jun 15 '20 at 00:18
  • you can also order by Guid values and select the first 10 elements. OrderBy Guid.NewId() – SteinTheRuler Jun 15 '20 at 00:21
  • 2
    @SteinTheRuler - Don't use Guids for randomness. They are only guaranteed to be unique, not random. – Enigmativity Jun 15 '20 at 00:27
  • @Enigmativity you can use Guid for random if it gives you an acceptable result. and you can also use other elements. – SteinTheRuler Jun 15 '20 at 02:29
  • @SteinTheRuler - Sure, but you didn't make that disclaimer on your comment. And what do you mean by "you can also use other elements"? – Enigmativity Jun 15 '20 at 02:38

1 Answers1

1

Does this work for you?

// make an array of 28 names
string[] names =
    Enumerable
        .Range(0, 28)
        .Select(x => $"Person {x + 1}")
        .ToArray();

Random rand = new Random();

// select 10 at random
string[] random10 =
    names
        .OrderBy(x => rand.Next())
        .Take(10)
        .ToArray();

//pick one at random from the 10 selected at random
string finalist = random10[rand.Next(random10.Length)];
Enigmativity
  • 113,464
  • 11
  • 89
  • 172