Question: How do I generate a weighted random number in Visual BASIC? e.g. I want to generate a random number from 1 to 20 but 80% of the time I want the number to be between 15-20, 15% of the time I want the number to be between 5-14 and 5% of the time I want the number to be between 1-4.

Answer: One way would be to generate a random number between 1 and 20.\nIf the number is 1 generate a second random number in the range 1-4. If the first number is in the range 2 to 4, generate a second number in the range 5-14. Otherwise generate the second number in the range 15-20.\n\nAnother way would be to generate a number in the range 0-399.\nIf the number is less than 20 divide it by 5, round down, add 1.\nIf it is in the range 20-79, subtract 20, divide by 6 and round down, add 5.\nIf it is in the range 80-399, subtract 80, divide by 10, round down, then add 15.
This question from the Yahoo Q&A forum is categorized in the topic: Education & Reference