1

I'm creating another random generator from ListBox. I want them to randomly pick 3 items from listBox and then display it on TextBox.

Random random = new Random();
int a = random.Next(0, listBox1.Items.Count);
listBox1.SelectedItem = listBox1.Items[a];
int b = random.Next(0, listBox1.Items.Count);
listBox1.SelectedItem = listBox1.Items[b];
int c = random.Next(0, listBox1.Items.Count);
listBox1.SelectedItem = listBox1.Items[c];
listBox1.Select();
textBox1.Text = listBox1.Items[a] + ", " + listBox1.Items[b] + ", " + listBox1.Items[c];

The issue is sometimes the items are selected twice. Example:

listBox items: One, Two, Three, Four, Five, Six

Output: One, Six, One (the item 'One' is selected twice, which I don't want to)

Thanks.

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
Alfian
  • 43
  • 7
  • Use enumerable.range to get a list of integers from 0 to list.count - 1. Look up a shuffling algorithm. Like shuffling a deck of cards. – Derek Jul 19 '17 at 09:15
  • Possible duplicate of [Generating random, unique values C#](https://stackoverflow.com/questions/14473321/generating-random-unique-values-c-sharp) – EpicKip Jul 19 '17 at 09:22

3 Answers3

0

You could put it in a while loop and only exit when they don't match:

Random random = new Random();
int listBoxItemCount = listBox1.Items.Count;
var itemA = listBox1.Items[random.Next( listBoxItemCount )];
var itemB = listBox1.Items[random.Next( listBoxItemCount )];
var itemC = listBox1.Items[random.Next( listBoxItemCount )];

while(itemA == itemB || itemA == itemC || itemB == itemC)//While any pair matches
{ 
    itemB = listBox1.Items[ random.Next( listBoxItemCount ) ];
    itemC = listBox1.Items[ random.Next( listBoxItemCount ) ];
}

This will result in a unique itemA, itemB and itemC

EpicKip
  • 4,015
  • 1
  • 20
  • 37
  • @Downvote explain please so I can improve my post. This solution does work – EpicKip Jul 19 '17 at 09:19
  • I'm not the one who downvote it, I can't even upvote since I'm still new user. by the way, thanks for answering and it works. I will use this as temporarily workaround, as there will be a better answers, maybe. – Alfian Jul 19 '17 at 09:35
  • @Alfian I already saw you couldn't downvote :) and I don't really mind the vote itself its just that I can't improve my post without feedback and losing progress towards silver c# badge -_- – EpicKip Jul 19 '17 at 09:37
0

I would change your logic like this:

  1. Get 3 random numbers
  2. Select the values from the ListBox

Code could look like. This code will get a new random number when the current was already selected and stores it in a List<int>.

Random random = new Random();
List<int> numbers = new List<int>();
for (int i = 0; i < 3; i++)
{
    int number = random.Next(0, listBox1.Items.Count);
    while (numbers.Contains(number))
    {
        number = random.Next(0, listBox1.Items.Count);
    }
    numbers.Add(number);
}

and then

textBox1.Text = $"{listBox1.Items[numbers[0]]}, {listBox1.Items[numbers[1]]}, {listBox1.Items[numbers[2]]}";

If you have less then 3 items in your ListBox this will end in an infinity loop, be aware of this.

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
  • Thanks. By the way, what's `$` for in the `textBox1.Text`? – Alfian Jul 19 '17 at 09:41
  • @Alfian `String interpolation` https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interpolated-strings thats so you can add variables in the text like this `$"this is text this is {variableName}"` – EpicKip Jul 19 '17 at 09:42
  • @Alfian Short form for [string.format](https://msdn.microsoft.com/de-de/library/system.string.format(v=vs.110).aspx) Your welcome and when it's working please accept the answer ;) – Mighty Badaboom Jul 19 '17 at 09:42
  • Thanks for the clarification, all. and thanks @MightyBadaboom for the answer and it works. You might edit your post by removing `(` on `textBox1.Text` as it was make me confused before. – Alfian Jul 19 '17 at 09:47
0

See: Randomize a List<T>

I modified and made a .net fiddle: https://dotnetfiddle.net/a7RJbm

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

public class Program
{
    public static void Main()
    {
        List<int> list = Enumerable.Range( 0, 6 ).ToList();
        list.Shuffle();
        int a = list[0];
        int b = list[1];
        int c = list[2];
        Console.WriteLine( a );
        Console.WriteLine( b );
        Console.WriteLine( c );
    }       

}

public static class ListShuffler
{
    private static Random rng = new Random();
    public static void Shuffle<T>(this IList<T> list)
    {
        int n = list.Count;
        while (n > 1)
        {
            n--;
            int k = rng.Next(n + 1);
            T value = list[k];
            list[k] = list[n];
            list[n] = value;
        }
    }
}

The benefit of shuffling is that you can go randomly through all of the items in the list. If you wanted to do more than 3 items some other approaches start to get a bit ugly.

Derek
  • 7,615
  • 5
  • 33
  • 58