hugo
hugo

Reputation: 475

Generate 4 differents numbers randomly

I am a novice in Xamarin ,

I want to generate randomly 4 numbers which are in a list and this 4 numbers must be different .

In the example below I have a list of Ids and I am trying to pick 4 id randomly in the list and those 4 Ids must be each differents.

Here is my methode, I cannot see how I can continue and make it simple :

   public MyWordsList()
            {
                InitializeComponent();


              Dictionary<int, int> WordId = new Dictionary<int, int>();
                int u= 0;
                // TestAnswer.IsVisible = false;
                foreach (var w in mywords)
                {
                    WordId[u] = w.ID;
                    u++;
                }

                Random rnd = new Random();
// this is not ok because I can have the same number
                word11.Text = WordsList[rnd.Next(1, 20)];
                word12.Text = WordsList[rnd.Next(1, 20)];
                word13.Text = WordsList[rnd.Next(1, 20)];
                word14.Text = WordsList[rnd.Next(1, 20)];

    }

If you have a better solution, I will take. Thanks

Upvotes: 1

Views: 843

Answers (3)

Deadzone
Deadzone

Reputation: 814

You can write a short generic function which picks X amount of random and unique items from a specified collection and returns them:

private static IEnumerable<T> GetUniqueRandomItems<T>(int count, IList<T> allItems)
{
    if (new HashSet<T>(allItems).Count < count)
    {
        throw new ArgumentException(nameof(allItems));
    }
    Random random = new Random();
    HashSet<T> items = new HashSet<T>();
    while (items.Count < count)
    {
        T value = allItems[random.Next(0, allItems.Count)];
        items.Add(value);
    }
    return items;
}

You can later use it like this:

string[] randomIds = GetUniqueRandomItems(4, WordsList).ToArray();
word11.Text = randomIds[0];
word12.Text = randomIds[1];
word13.Text = randomIds[2];
word14.Text = randomIds[3];

Upvotes: 3

Mert Akcakaya
Mert Akcakaya

Reputation: 3129

You probably won't need this, but just to show a method of unique random number generation with no duplicate check:

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var randoms = GenerateRandoms(10, 1, 10).OrderBy(v => v);
            foreach (var random in randoms)
            {
                Console.WriteLine(random);
            }

            Console.ReadLine();
        }

        private static int[] GenerateRandoms(int randomCount, int min, int max)
        {
            var length = max - min + 1;
            if (randomCount > length) { throw new ArgumentException($"Cannot generate {randomCount} random numbers between {min} and {max} (inclusive)."); }

            var values = new List<int>(length);
            for (var i = 0; i < length; i++)
            {
                values.Insert(i, min + i);
            }

            var randomGenerator = new Random();
            var randoms = new List<int>();
            for (var i = 0; i < randomCount; i++)
            {
                var val = randomGenerator.Next(0, values.Count);
                randoms.Add(values[val]);
                values.RemoveAt(val);
            }

            return randoms.ToArray();
        }
    }
}

Upvotes: 0

Jonathan
Jonathan

Reputation: 5018

call a method like the following:

    private int CreateUniqueRandom(int min, int max, ICollection<int> existingNums)
    {
        var rnd = new Random();
        var newNum = rnd.Next(min, max);

        while (existingNums.Contains(newNum))
            newNum = rnd.Next(min, max);

        return newNum;
    }

Passing through a list of the numbers that you have created so far

Upvotes: 0

Related Questions