Probability based on percent

Is there a way to extract the value based on a percentage?

Probability value:
Bad: 1%
Normal: 29%
Good: 70%

var move ["bad","normal","good"];

Simple conditional statement:

if (move == "bad") {
bad_move = "That a bad move!";
} else if (move == "normal") {
normal_move = "Classic move!";
} else {
good_move = "Amazing move!";
}

Then is PHP better than Javascript for this problem?

+4
source share
2 answers

You can write a function that displays values ​​with given percentages of probability:

function weightedSample(pairs) {
  const n = Math.random() * 100;
  const match = pairs.find(({value, probability}) => n <= probability);
  return match ? match.value : last(pairs).value;
}

function last(array) {
  return array[array.length - 1];
}

const result = weightedSample([
  {value: 'Bad', probability: 1},
  {value: 'Normal', probability: 29},
  {value: 'Good', probability: 70}
]);

console.log(result);
Run codeHide result

I can’t say if PHP will be better. This problem should not be more / less complicated in PHP. What you should use (JS or PHP) really depends on whether the function should run on the server or client.

+1
source

.

, .

.

function getRandomIndexByProbability(probabilities) {
    var r = Math.random(),
        index = probabilities.length - 1;

    probabilities.some(function (probability, i) {
        if (r < probability) {
            index = i;
            return true;
        }
        r -= probability;
    });
    return index;
}

var i,
    move = ["bad", "normal", "good"],
    probabilities = [0.01, 0.29, 0.7],
    count = {},
    index;

move.forEach(function (a) { count[a] = 0; });

for (i = 0; i < 1e6; i++) {
    index = getRandomIndexByProbability(probabilities);
    count[move[index]]++;
}

console.log(count);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hide result
0

Source: https://habr.com/ru/post/1673915/


All Articles