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

5
  • 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: stackoverflow.com/q/273313/491907 Commented Jun 15, 2020 at 0:18
  • you can also order by Guid values and select the first 10 elements. OrderBy Guid.NewId() Commented Jun 15, 2020 at 0:21
  • 2
    @SteinTheRuler - Don't use Guids for randomness. They are only guaranteed to be unique, not random. Commented Jun 15, 2020 at 0:27
  • @Enigmativity you can use Guid for random if it gives you an acceptable result. and you can also use other elements. Commented Jun 15, 2020 at 2: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"? Commented Jun 15, 2020 at 2:38

1 Answer 1

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)];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.