 # Perform Weighted Random with JavaScript

Weighted random is a non-uniform random method that each values has specific probability to be picked. The values with higher weight are more likely to be the random result while lower weighted one are less likely but still eligible.

## Snippet 1 (Specific Probability)

```function weightedRandom(prob) {
let i, sum=0, r=Math.random();
for (i in prob) {
sum += prob[i];
if (r <= sum) return i;
}
}```

### Usage

Pass the numbers and their weight to the function.

`let result = weightedRandom({0:0.6, 1:0.1, 2:0.1, 3:0.2});`
Note
The sum of all weights must equal to 1

## Snippet 2 (Weighted Distribution)

A random function that has normal distributed random chance from min to max parameters. The mean is a number that has the highest chance while varianceFactor determine the spread of probability. (The higher varianceFactor the higher chance that the result is close to the mean value.)

This snippet utilize the chance.js library

`<script src="https://cdnjs.cloudflare.com/ajax/libs/chance/1.0.18/chance.min.js"></script>`
```function weightedRandomDistrib(min,max,mean,varianceFactor) {
let prob = [], seq = [];
for(let i=min;i<max;i++) {
prob.push(Math.pow(max-Math.abs(mean-i),varianceFactor));
seq.push(i);
}
return chance.weighted(seq, prob);
}```

### Usage

Random number between -10 to 11 with 0 has the highest chance and variance factor of 3.

`let result = weightedRandomDistrib(-10,11,0,3);`