biased rand

Hi all,

I have an algorithm that depends on the generation of a random number. The thing is very simple: I generate a random number between 0 and 8 and do something different depending on the generated number.

Now I want to change my algorithm so that some numbers are more likely to occur than others: for example i want to have an higher chance of having 2, 6 or 7 then the other numbers. Anyone has a suggestion on how to implement that?

thanks

[hr]
[italic]How beautiful, if Sorrow had not made sorrow more beautiful than Beauty itself.[/italic]
JOHN KEATS

Comments

  • 1) Create a std::vector (or array) with the numbers from 0 to 8 in yhr frequencies you want (e.g. 1x a zero, 100x a one, etc).
    2) Draw a random index in from this std::vector
    3) Use the number at that index

    Have fun,


    bilderbikkel

  • : Hi all,
    :
    : I have an algorithm that depends on the generation of a random number. The thing is very simple: I generate a random number between 0 and 8 and do something different depending on the generated number.
    :
    : Now I want to change my algorithm so that some numbers are more likely to occur than others: for example i want to have an higher chance of having 2, 6 or 7 then the other numbers. Anyone has a suggestion on how to implement that?
    :
    : thanks
    :
    : [hr]
    : [italic]How beautiful, if Sorrow had not made sorrow more beautiful than Beauty itself.[/italic]
    : JOHN KEATS
    :
    :

    Bilderbikkels solution is fine, but maybe a bit technical. Here's the general idea behind it:
    Suppose you want to generate a random number between 1 and 8.
    Say you want to have 3 occur twice as much and 7 occur three times as much as the other numbers.
    Now create an array consisting of the following numbers:
    1,2,3,3,4,5,6,7,7,7,8
    You have 11 elements in the array.
    Generate a random number between 1 and 11 (or 0 and 10 for zero-based indices) and use that number as an index into the above array.

    The sequence of the numbers in the array doesn't matter. If it is easier to code, you may fill the array like this:
    1,2,3,4,5,6,7,8,3,7,7





    Greets,
    Eric Goldstein
    www.gvh-maatwerk.nl


  • Thanks! That's exactly what I was looking for!

    [hr]
    [italic]How beautiful, if Sorrow had not made sorrow more beautiful than Beauty itself.[/italic]
    JOHN KEATS


Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories