+ Reply to Thread
Results 1 to 8 of 8

Weighted Random Number Generator Code Needed

Hybrid View

BenGT Weighted Random Number... 10-24-2012, 10:58 AM
tigeravatar Re: Weighted Random Number... 10-24-2012, 11:09 AM
BenGT Re: Weighted Random Number... 10-24-2012, 11:24 AM
tigeravatar Re: Weighted Random Number... 10-24-2012, 11:49 AM
BenGT Re: Weighted Random Number... 10-24-2012, 12:16 PM
tigeravatar Re: Weighted Random Number... 10-24-2012, 12:38 PM
BenGT Re: Weighted Random Number... 10-24-2012, 01:56 PM
tigeravatar Re: Weighted Random Number... 10-24-2012, 02:09 PM
  1. #1
    Registered User
    Join Date
    10-24-2012
    Location
    Pittsburgh, Pennsylvania
    MS-Off Ver
    Excel 2010
    Posts
    4

    Exclamation Weighted Random Number Generator Code Needed

    Hello,

    I am running an excel based Jeopardy game and need a way to randomly choose three winners based on their number of entries gained throughout the game. I need a code which is able to take in columns of information (example below) and randomly pick three student numbers, taking into account different weights based on the total number of entries per student.

    Student Number/ Automatic Entries / Jeopardy Entries / Total # of Entries
    1 / 2 / 2 / 4
    2 / 2 / 3 / 5
    3 / 2 / 1 / 3
    4 / 2 / 1 / 3
    5 / 2 / 6 / 8

    Obviously, I want the code to reflect the fact that student 5 has more entries than any other student, so on a weighted random number, they should be picked most preferentially. I have attached a file with the example data which will be generated from a game of Jeopardy. Each student present receives an automatic 2 entries, and additional entries are gained by correctly answering questions throughout the game.

    One point that you will notice from the file is that there can be anywhere between 1 and 130 students in the game (depending on attendance). The code needs to be able to adjust itself to account for the number of students that will be playing. In the attached file, you can see that only 15 students played the game. I want to be able to tell the program what this total number of playing students is so that a random student number of 33 isn't picked when only 32 students were played the game.

    I also don't want the program to randomly pick the same student twice. I want to give out the three prizes to three separate students.

    I have never attempted VBU before, and I wasted some time yesterday trying to figure this out on my own. I have seen that one route to do this is to create an array with a variable number of elements. After I tell the program the total number of students that played, it can calculate the total number of entries. After creating that number of blanks in the array, it can then just fill in the blanks with the appropriate student numbers. Then, it can randomly pick three index numbers, extract the student numbers (making sure that they are three different ones), and then report those three numbers.

    An explanation in the answer of how to actually incorporate this function, how to direct the function to the needed input data, and have it display these three winning student numbers would also be much appreciated. At this point I have no idea how to get a function to export these three numbers to three cells in the workbook.

    Any help will be greatly appreciated!

    Data File Example.xlsx

    Ben

  2. #2
    Forum Expert tigeravatar's Avatar
    Join Date
    03-25-2011
    Location
    Colorado, USA
    MS-Off Ver
    Excel 2003 - 2013
    Posts
    5,361

    Re: Weighted Random Number Generator Code Needed

    Ben,

    Welcome to the forum!
    How does Excel know how many students participated? In your example file, students 11 and 12 got 0 correct answers so it looks like they didn't participate. What if 16 students participated and the 16th student got 0 right answers? Excel wouldn't be able to tell that #16 was a participant because it looks identical to students 17-130. If a student gets 0 correct answers, should they simply be ineligible to win prizes?
    Hope that helps,
    ~tigeravatar

    Forum Rules: How to use code tags, mark a thread solved, and keep yourself out of trouble

  3. #3
    Registered User
    Join Date
    10-24-2012
    Location
    Pittsburgh, Pennsylvania
    MS-Off Ver
    Excel 2010
    Posts
    4

    Re: Weighted Random Number Generator Code Needed

    Hi Tiger Avatar,

    Thanks for your quick response! I will enter the total number of students playing into cell K4 on worksheet "Entry Summary" to tell the program how many students are playing. This is so that (in regard to the attached example data) the program will know that student 16 was present also, and will also have a chance to win one of the three prizes. Students 11 and 12 were also present but just didn't get a chance to answer a question. I have another random number generator in the program which will use this K4 entry to randomly pick students to attempt a question; however, I want all students present to have a chance to win one of the three prizes. Thanks!

    Ben

  4. #4
    Forum Expert tigeravatar's Avatar
    Join Date
    03-25-2011
    Location
    Colorado, USA
    MS-Off Ver
    Excel 2003 - 2013
    Posts
    5,361

    Re: Weighted Random Number Generator Code Needed

    Ben,

    In the example file, there is no worksheet named "Entry Summary". Is 'Sheet1' supposed to be named "Entry Summary"? and then I can populate cell K4 with the number of participants and create the macro? Or is "Entry Summary" supposed to be a different sheet from 'Sheet1' in your example file?

  5. #5
    Registered User
    Join Date
    10-24-2012
    Location
    Pittsburgh, Pennsylvania
    MS-Off Ver
    Excel 2010
    Posts
    4

    Re: Weighted Random Number Generator Code Needed

    Hi Tiger Avatar,

    I have uploaded a new example data file to give you a better idea of the exact layout of the workbook. In my real file there are many other worksheets which are sending information into these two tables on the worksheet "Entry Summary". The top table is just to summarize which students answered which questions. I am hoping for a macro that will take information from rows 23 and down (depending on the number of students playing entered into cell K4) and the columns in the Student Information Table. I would then like the three randomly picked student numbers to be presented in cells I7, I10, and I13. Does this clarify more?

    Updated Data File Example.xlsx

    Thanks!

    Ben

  6. #6
    Forum Expert tigeravatar's Avatar
    Join Date
    03-25-2011
    Location
    Colorado, USA
    MS-Off Ver
    Excel 2003 - 2013
    Posts
    5,361

    Re: Weighted Random Number Generator Code Needed

    Ben,

    Here is commented code that should perform as desired:
    Sub tgr()
        
        'Declare variables
        Dim ws As Worksheet             'Used to access the sheet 'Entry Summary'
        Dim rngEntries As Range         'Used to store the range of entries of participants
        Dim EntryCell As Range          'Used to loop through rngEntries
        Dim rngFindWinner As Range      'Used to find winners
        Dim lCalc As XlCalculation      'Used to store the current calculation state
        Dim arrParticipants() As String 'Used to store the weighted participant entries for finding winners
        Dim strFirst As String          'Used to prevent duplicates when finding winners
        Dim strWinners As String        'Used to build the winners list
        Dim ParticipantIndex As Long    'Used to build arrParticipants
        Dim lNumParticipants As Long    'Used to determine how many participants there are
        Dim i As Long                   'Generic counter variable
        
        'Assign variable ws and get the number of participants
        Set ws = Sheets("Entry Summary")
        lNumParticipants = ws.Range("K4").Value
        
        If lNumParticipants = 0 Then Exit Sub   'no participants
        
        'Disable events, alerts, and screenupdating, set calculation to manual
        'This prevents "screen flickering" and allows the code to run faster
        With Application
            lCalc = .Calculation                'Store the current calculation state
            .Calculation = xlCalculationManual  'Set to manual calculation
            .EnableEvents = False               'Disable events
            .DisplayAlerts = False              'Disable alerts
            .ScreenUpdating = False             'Disable screenupdating
        End With
        
        'Assume code will fail and provide error handler
        On Error GoTo CleanExit
        
        'Assign variable rngEntries and dimension arrParticipants to the correct size
        Set rngEntries = ws.Range("E23").Resize(lNumParticipants)
        ReDim arrParticipants(1 To WorksheetFunction.Sum(rngEntries))
        
        'Loop through each cell in rngEntries
        For Each EntryCell In rngEntries.Cells
            'Add the participant for each entry (2 automatic + any correctly answered questions)
            For i = 1 To EntryCell.Value
                ParticipantIndex = ParticipantIndex + 1
                arrParticipants(ParticipantIndex) = ws.Cells(EntryCell.Row, "B").Text
            Next i
        Next EntryCell
        
        'Use a new sheet that will not be seen
        'This sheet is used to find the winners
        With Sheets.Add
            'Put arrparticipants, a randomization formula, and a formula to find unique entries in this new sheet
            .Range("A1").Resize(ParticipantIndex).Value = Application.Transpose(arrParticipants)
            .Range("B1").Resize(ParticipantIndex).Formula = "=Rand()"
            .Range("C1").Resize(ParticipantIndex).Formula = "=Countif(A$1:A1,A1)"
            
            'Randomize the weighted participants list
            Randomize
            .Calculate
            .UsedRange.Sort .Range("B1").Resize(ParticipantIndex), xlAscending, Header:=xlNo
            
            'Find the first three unique entries and build the winners list
            Set rngFindWinner = .Columns("C").Find(1, .Range("C" & Rows.Count), xlValues, xlWhole)
            If Not rngFindWinner Is Nothing Then
                i = 0
                strFirst = rngFindWinner.Address
                Do
                    strWinners = strWinners & Chr(10) & .Cells(rngFindWinner.Row, "A").Text
                    i = i + 1
                    If i = 3 Then Exit Do
                    Set rngFindWinner = .Columns("C").Find(1, rngFindWinner, xlValues, xlWhole)
                Loop While rngFindWinner.Address <> strFirst
            End If
            
            'Delete the temp sheet now that the winners list has been completed
            .Delete
        End With
        
        'Output the winners
        ws.Range("I7").Value = Split(strWinners, Chr(10))(1)
        ws.Range("I10").Value = Split(strWinners, Chr(10))(2)
        ws.Range("I13").Value = Split(strWinners, Chr(10))(3)
        
    'Error handler
    'The code will exit here even if there wasn't an error
    CleanExit:
        
        'Re-enable events, alerts, and screenupdating, set calculation back to its current state
        With Application
            .Calculation = lCalc    'Set calculation back to its current state
            .EnableEvents = True    'Enable events
            .DisplayAlerts = True   'Enable alerts
            .ScreenUpdating = True  'Enable screenupdating
        End With
        
        'Display error message (if any)
        If Err.Number <> 0 Then
            MsgBox Err.Description, , "Error: " & Err.Number
            Err.Clear
        End If
        
        'Object variable cleanup
        Set ws = Nothing
        Set rngEntries = Nothing
        Set EntryCell = Nothing
        Set rngFindWinner = Nothing
        Erase arrParticipants
        
    End Sub

  7. #7
    Registered User
    Join Date
    10-24-2012
    Location
    Pittsburgh, Pennsylvania
    MS-Off Ver
    Excel 2010
    Posts
    4

    Re: Weighted Random Number Generator Code Needed

    Hi Tiger Avatar,

    Wow! That worked perfectly! Thank you so much! I can't believe that that much code was needed simply to pick a few numbers. Thanks again, I would have never been able to put that together. Also, thanks for the comments throughout the code so that I could follow along and figure out what each line does.

    Ben

  8. #8
    Forum Expert tigeravatar's Avatar
    Join Date
    03-25-2011
    Location
    Colorado, USA
    MS-Off Ver
    Excel 2003 - 2013
    Posts
    5,361

    Re: Weighted Random Number Generator Code Needed

    You're very welcome

    If that takes care of your need, please mark this thread as solved.
    New quick method:
    Select Thread Tools-> Mark thread as Solved. To undo, select Thread Tools-> Mark thread as Unsolved.

    Or you can use this way:
    How to mark a thread Solved
    Go to the first post
    Click edit
    Click Go Advanced
    Just below the word Title you will see a dropdown with the word No prefix.
    Change to Solved
    Click Save

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

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

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1