How can I get weighted random selections from an array in Perl?

Tags: perl random

I need to random some elements from an array. I'm doing that by randomizing the index $array[int(rand(100))]. I want some of the elements to appear more often. How do I do it?

I thought of a stupid solution of having those elements duplicated several times in the array, but I'm sure you guys can do better.

By : Chaggster


If you know the frequency with which you want the random numbers to appear, you could use the rand() function. Let's say you want the number 0 to appear 33% of the time, and 1 to appear the other 66%. Then you would check if rand()

By : avpx

Another option is to have a structure similar to the following: (pardon my language, I don't actually know Perl all that well)

  (1, 10),
  (2, 50),
  (3, 80),
  (4, 100)

Then when you get the value from int(rand(100)) you can compare it to each of the second elements in turn and return the first element.

This page provides the theory for generating random numbers from arbitrary distribution.

By : bgbg

This video can help you solving your question :)
By: admin