Results 1 to 25 of 25

Thread: Unique, Random Selections from a List

  1. #1

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Unique, Random Selections from a List

    C #version here.

    This is pretty simple stuff but it's come up more than once so I thought I'd post it. If you want to randomly select objects from a list where each object can only be chosen once you can use a collection and a Random object to select indexes into that collection. Below is an example using an ArrayList and the numbers 1 to 10. The objects could be anything though, not just numbers. In .NET 2.0 you'd more likely use a Generic.List(Of T) rather than an ArrayList.
    VB Code:
    1. Dim list As New ArrayList
    2.  
    3.         For i As Integer = 1 To 10
    4.             'Add the numbers to the collection.
    5.             list.Add(i)
    6.         Next i
    7.  
    8.         Dim rand As New Random
    9.         Dim index As Integer
    10.         Dim item As Object
    11.  
    12.         'Display the items in random order.
    13.         While list.Count > 0
    14.             'Choose a random index.
    15.             index = rand.Next(0, list.Count)
    16.  
    17.             'Get the item at that index.
    18.             item = list(index)
    19.  
    20.             'Remove the item so that it cannot be chosen again.
    21.             list.RemoveAt(index)
    22.  
    23.             'Display the item.
    24.             MessageBox.Show(item.ToString())
    25.         End While

  2. #2
    Fanatic Member uniquegodwin's Avatar
    Join Date
    Jul 2005
    Location
    Chennai,India
    Posts
    694

    Re: Unique, Random Selections from a List

    Hi Jm,
    Nice handy code Well done

    I think a lot of people need code snipplets like this for simple things would be useful during an emergency or tensed situation...when we actually cant sit and try making it due to all the pressures.
    Godwin

    Help someone else with what someone helped you!

  3. #3
    Just Married shakti5385's Avatar
    Join Date
    Mar 2006
    Location
    Udaipur,Rajasthan(INDIA)
    Posts
    3,747

    Re: Unique, Random Selections from a List

    Nice Code

  4. #4
    Lively Member James Bearss's Avatar
    Join Date
    Jun 2007
    Location
    USA, Wisconsin
    Posts
    120

    Re: Unique, Random Selections from a List

    thanks, this helped
    I like doing magic tricks, and I program in Visual Basic (Duh)

    Download my garage sale helper at
    http://www.vbforums.com/showthread.p...96#post3040996

  5. #5
    Hyperactive Member
    Join Date
    Mar 2007
    Location
    Hong Kong
    Posts
    384

    Re: Unique, Random Selections from a List

    is that when gen a new number, the old value in item.toString will lose?

  6. #6
    Addicted Member
    Join Date
    Jul 2007
    Posts
    146

    Re: Unique, Random Selections from a List

    Would someone mind explaining how I'd go about using this code to extract 5 unique values from it at one time?

  7. #7

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: Unique, Random Selections from a List

    Quote Originally Posted by FooFighter
    Would someone mind explaining how I'd go about using this code to extract 5 unique values from it at one time?
    You can't get 5 at a time. You can only get 1 at a time so you'd do that 5 times. Instead of a While loop emptying the collection you'd use a For loop from 1 to 5.

  8. #8
    Addicted Member
    Join Date
    Jul 2007
    Posts
    146

    Re: Unique, Random Selections from a List

    I'm fairly new to visual basic. How exactly would I accomplish what you said? I've been trying different things and keep getting errors.

    I have 5 labels. I'm trying to put 1 unique number between 1 and 10 into each label with the click of one button.
    Last edited by FooFighter; Jul 22nd, 2007 at 10:07 PM.

  9. #9
    New Member
    Join Date
    Jul 2007
    Posts
    2

    Re: Unique, Random Selections from a List

    Foofighter, I would use something like this

    Code:
    dim selected(9) as boolean
    dim thisnumber, i as integer
    dim result(4) as integer
    
    For i = 0 To 4
          Do
          thisnumber = (Int(Rnd() * 10))
    
          Loop While selected(thisnumber) = True
          selected(thisnumber) = True
          result(i) = thisnumber 
    	  
    Next
    this will leave 5 random numbers in the result() array which you can then move to a label using label#.text=result(#) (where # is the relevent number)

    Whilst this will work, I do think the first post would be a better and prettier way of doing it.
    Last edited by bigdave; Jul 25th, 2007 at 04:44 PM.

  10. #10
    Addicted Member
    Join Date
    Jul 2007
    Posts
    146

    Re: Unique, Random Selections from a List

    I'm not using labels. I'm using 5 pictureboxes with an imagelist that contains the 52 card images. Also I have no idea where I'd put that code you listed.
    Last edited by FooFighter; Jul 25th, 2007 at 04:51 PM.

  11. #11

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: Unique, Random Selections from a List

    vb.net Code:
    1. Private Function GetRandomCardImages(ByVal count As Integer) As Image()
    2.     'Create the full list of Images here.
    3.  
    4.     Dim upperBound As Integer = count - 1
    5.     Dim selections(upperBound) As Image
    6.     For index As Integer = 0 To upperBound Step 1
    7.         selections(index) = 'Get random Image here.
    8.     Next index
    9.  
    10.     Return selections
    11. End Function

  12. #12
    Hyperactive Member
    Join Date
    Apr 2008
    Posts
    474

    Re: Unique, Random Selections from a List

    U can also use shuffle algorithm to return unique random numbers
    http://www.*************s.com/vb-net...m-numbers.html

  13. #13
    PowerPoster i00's Avatar
    Join Date
    Mar 2002
    Location
    1/2 way accross the galaxy.. and then some
    Posts
    2,388

    Re: Unique, Random Selections from a List

    I would do it with linQ:

    Code:
           Dim list As New ArrayList
    
            For i As Integer = 1 To 10
                'Add the numbers to the collection.
                list.Add(i)
            Next i
    
            Randomize()
    
            Dim RandomList = From RndList In list _
                   Select RndList _
                   Order By Rnd()
    
            For Each item In RandomList
                MsgBox(item)
            Next

  14. #14
    Junior Member
    Join Date
    Jan 2009
    Location
    UK
    Posts
    19

    Re: Unique, Random Selections from a List

    Fantastic code, and saved me countless hours fannying around with the code I already tried. How would you adapt this to be omit a range of numbers from the selection?

    I need to be able to draw a random number between, say, 1 to 1000. These numbers relate to 14 teams (each with their own range of numbers).

    If team 2 is drawn first, and their number range is 123 to 215, I need to make sure that numbers 123 to 215 are not included in the next random selection of the remaining numbers of 1-122 and 216-1000.

    It's a doozy!

  15. #15
    PowerPoster i00's Avatar
    Join Date
    Mar 2002
    Location
    1/2 way accross the galaxy.. and then some
    Posts
    2,388

    Re: Unique, Random Selections from a List

    well if you want to wouldn't u randomly pick one of the teams then - rather than randomly pick one of the players from these teams?

  16. #16
    PowerPoster i00's Avatar
    Join Date
    Mar 2002
    Location
    1/2 way accross the galaxy.. and then some
    Posts
    2,388

    Re: Unique, Random Selections from a List

    also if a team has more players they have an advantage of being picked sooner than a team with less players

  17. #17
    PowerPoster i00's Avatar
    Join Date
    Mar 2002
    Location
    1/2 way accross the galaxy.. and then some
    Posts
    2,388

    Re: Unique, Random Selections from a List

    But maybe something like this - this method will have equal probability of picking each team also:

    vb Code:
    1. Private Class Players
    2.         Public Team As String
    3.         Public Name As String
    4.         Public Sub New(ByVal Team As String, ByVal Name As String)
    5.             Me.Team = Team
    6.             Me.Name = Name
    7.         End Sub
    8.     End Class
    9.  
    10.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    11.  
    12.  
    13.         Dim list As New List(Of Players)
    14.  
    15.         list.Add(New Players("Broncos", "Antonio Winterstein"))
    16.         list.Add(New Players("Broncos", "Karmichael Hunt"))
    17.         list.Add(New Players("Broncos", "Alex Glenn"))
    18.         list.Add(New Players("Broncos", "Justin Hodges"))
    19.         list.Add(New Players("Broncos", "Jharal Yow Yeh"))
    20.         list.Add(New Players("Broncos", "Darren Lockyer"))
    21.         list.Add(New Players("Broncos", "Peter Wallace"))
    22.         list.Add(New Players("Broncos", "Nick Kenny"))
    23.         list.Add(New Players("Broncos", "Andrew McCullough"))
    24.         list.Add(New Players("Broncos", "David Taylor"))
    25.         list.Add(New Players("Broncos", "Tonie Carroll"))
    26.         list.Add(New Players("Broncos", "Sam Thaiday"))
    27.         list.Add(New Players("Broncos", "Corey Parker"))
    28.         list.Add(New Players("Broncos", "Lagi Setu"))
    29.         list.Add(New Players("Broncos", "Ben Te’o"))
    30.         list.Add(New Players("Broncos", "Josh McGuire"))
    31.         list.Add(New Players("Broncos", "Ashton Sims"))
    32.  
    33.         list.Add(New Players("St George", "Darius Boyd"))
    34.         list.Add(New Players("St George", "Matt Cooper"))
    35.         list.Add(New Players("St George", "Neville Costigan"))
    36.         list.Add(New Players("St George", "Ben Creagh"))
    37.         list.Add(New Players("St George", "Nick Emmett"))
    38.  
    39.         Randomize()
    40.  
    41.         Dim RandomList = From RndList In (From xitem In list Select xitem Group By xitem.Team Into First()) _
    42.                Select RndList _
    43.                Order By Rnd()
    44.  
    45.         For Each item In RandomList
    46.             MsgBox(item.Team)
    47.         Next
    48.     End Sub

    I have done it like the above ... as from your question it sounds like u just have a collection of players rather than a separate one of teams?

  18. #18
    Junior Member
    Join Date
    Jan 2009
    Location
    UK
    Posts
    19

    Re: Unique, Random Selections from a List

    Thank you i00 for your response,

    I tried to give an example on how I thought it could work but it wasn't the whole facts. What I actually need is:

    We have a number of field computer technicians, based out of 14 national centres, who also sell products to our customers. For every product they sell their centre gets a ticket.

    It's these tickets that get drawn at the end of each month, to decide which centre gets the prize. There are 5 prizes to be won each month, and only one prize per centre.

    Hence why one centre may only sell 30 items - and get 30 tickets, another centre may get 230 tickets. This is why it would be a higher probability that one team could win over another - because they had sold more items.

    I'll have play around with your code though to see if there is anything I can do.
    Thank you for your help.

  19. #19
    PowerPoster i00's Avatar
    Join Date
    Mar 2002
    Location
    1/2 way accross the galaxy.. and then some
    Posts
    2,388

    Re: Unique, Random Selections from a List

    Something like this then should do the trick

    vb Code:
    1. Private Class Tickets
    2.         Public TicketNo As String
    3.         Public NationalCentre As String
    4.         Public inValidated As Boolean = False
    5.         Public Sub New(ByVal TicketNo As String, ByVal NationalCentre As String)
    6.             Me.TicketNo = TicketNo
    7.             Me.NationalCentre = NationalCentre
    8.         End Sub
    9.     End Class
    10.  
    11.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    12.         Dim TicketsList As New List(Of Tickets)
    13.         'fill with some tickets
    14.         For i = 1 To 100
    15.             Select Case i
    16.                 Case Is < 10
    17.                     TicketsList.Add(New Tickets(i, "Seven Hills"))
    18.                 Case Is < 30
    19.                     TicketsList.Add(New Tickets(i, "Morningside"))
    20.                 Case Is < 50
    21.                     TicketsList.Add(New Tickets(i, "Hawthorne"))
    22.                 Case Is < 80
    23.                     TicketsList.Add(New Tickets(i, "Coorparoo"))
    24.                 Case Is < 89
    25.                     TicketsList.Add(New Tickets(i, "Park Road"))
    26.                 Case Else
    27.                     TicketsList.Add(New Tickets(i, "Brisbane CBD"))
    28.             End Select
    29.         Next
    30.  
    31.         Dim ListOfElligableNationalCentres As New List(Of String)
    32.         ListOfElligableNationalCentres = (From xitem In (From xitem2 In TicketsList Select xitem2 Group By xitem2.NationalCentre Into First()) Select xitem.NationalCentre).ToList
    33.  
    34.  
    35.  
    36.         Randomize()
    37.         Dim TicketAndPortions = From xItem In TicketsList _
    38.                                 Join xItem2 In ListOfElligableNationalCentres On xItem.NationalCentre Equals xItem2 _
    39.                                 Order By Rnd()
    40.         For i = 1 To 5
    41.             Dim SelectedNationalCenter As String = TicketAndPortions(0).xItem.NationalCentre
    42.             MsgBox(SelectedNationalCenter)
    43.             ListOfElligableNationalCentres.Remove(SelectedNationalCenter)
    44.         Next
    45.     End Sub

  20. #20
    New Member
    Join Date
    Oct 2012
    Posts
    8

    Thumbs up Re: Unique, Random Selections from a List

    Hey, thank you very much - I'm posting here so I've got this bookmarked.

  21. #21
    Junior Member
    Join Date
    Oct 2012
    Posts
    17

    Re: Unique, Random Selections from a List

    This code is very impressive. I like it a lot. I am new to the world of programming and I am trying to figure out how to use this with three text files to pull words from each to create some kind of structure. One text file is for nouns, the other is for smaller items like or/and/but,etc..., the last one is verbs. I want to be able to imput the limits and have computer generate something like a poem out of those three files. Thus a limit per line. My first step would be pulling it out of three files. How would i go about doing this?

  22. #22

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: Unique, Random Selections from a List

    Quote Originally Posted by davebold370 View Post
    This code is very impressive. I like it a lot. I am new to the world of programming and I am trying to figure out how to use this with three text files to pull words from each to create some kind of structure. One text file is for nouns, the other is for smaller items like or/and/but,etc..., the last one is verbs. I want to be able to imput the limits and have computer generate something like a poem out of those three files. Thus a limit per line. My first step would be pulling it out of three files. How would i go about doing this?
    Assuming that you have one word per line in the files, you can call File.ReadAllLines to read the file into a String array. You can then call ToList on that to get a List(Of String) and that's your collection, from which you can select and remove items.

  23. #23
    Junior Member
    Join Date
    Oct 2012
    Posts
    17

    Re: Unique, Random Selections from a List

    @jmcilhinney Thanks

  24. #24
    New Member
    Join Date
    Sep 2016
    Posts
    1

    Re: Unique, Random Selections from a List

    What is the code if I click a button.
    and it will random a picture within 10 of it without repeating?

  25. #25

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,274

    Re: Unique, Random Selections from a List

    Quote Originally Posted by OysterD3 View Post
    What is the code if I click a button.
    and it will random a picture within 10 of it without repeating?
    I'm not a code-writing service. I've demonstrated principles here in this thread. You can use those principles to achieve your aim. If you make an effort and encounter a specific issue along the way then I'm quite willing to help with that, although you should be starting a new thread of your own for that. If you are just waiting for someone to write your code for you then you'll be waiting a long time for me.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width