Search code examples
algorithmrandom

Randomly assign a flag with specific percentage rate requirement


I was asked to do a algorithm to assign a one out of three messages to each record of file.

Client want Message 1-- selected for 80% times of total 3 message randomly. Message 2-- selected for 10% times of total 3 message randomly. Message 3-- selected for 10% times of total 3 message randomly. I don't want to loop through to the end of the file because it would cause two round loops and the file is quite big and it is also hard to modify the program to loop for two times as well.

So I am thinking I would make a array of integer 1 to 10 and shuffle them and then sequentially assign the record's massage flag value to the corresponding array's element according the line index. It would be repeated per 10 records.

For example, if the shuffled the array like below [9,6,10,2,7,8,4,5,1,3]

My file would be ended up like: Line 1 , pick 9 Line 2 , pick 6 Line 3 , pick 10 Line 4 , pick 2 Line 5 , pick 7 Line 6 , pick 8 Line 7 , pick 4 Line 8 , pick 5 Line 9 , pick 1 Line 10, pick 3 Line 11, pick 9 Line 12, pick 6 Line 13, pick 10 Line 14, pick 2 Line 15, pick 7 Line 16, pick 8 Line 17, pick 4 Line 18, pick 5 Line 19, pick 1 Line 20, pick 3

Then I would assign message 1 if it picked between 1 to 8, then assign message 2 if it picked 9 and message 3 if it picked 10.

I think it can be sort of working but it has a limit. You can see my Line 11 to Line 20 is repeating exactly Line 1 to Line 10.

Do you know any issue with the algorithm above which I don't see and do you know whether there is any existing algorithm I can use and welcome any advice.

Appreciate your help.


Solution

  • Instead of creating this array, use a random number generator. Assign Message 1 to values between 0-0.8, Message 2 to values between 0.8-0.9, and Message 3 to values between 0.9 and 1.0.

    For example:

    var rand = Math.random();
    if (rand >= 0 && rand < 0.8) {
        ... code to assign Message 1 ...
    } else if (rand >= 0.8 && rand < 0.9) {
        ... code to assign Message 2 ...
    } else if (rand >= 0.9 && rand < 1.0) {
        ... code to assign Message 3 ...