B
B
ByJumping2021-12-11 15:36:41
JavaScript
ByJumping, 2021-12-11 15:36:41

How to make a percentage probability of displaying a particular picture from 2 arrays?

There are 2 arrays

const truePhotos = ['1 фото', '2 фото', '3 фото','4 фото',...'100 фото',]
const funnyPhotos = ['1 фото', '2 фото']

I do a random display of a picture from the first array

function getPhoto() {
    return truePhotos[Math.floor(Math.random() * truePhotos.length)]
}

Now I want to implement in this function a 10% chance of displaying a blot - a funny photo)) That is, when a person calls the getPhoto() function, he received a photo from the funnyPhotos array with a 10% probability.

And I would like to do it for the future if there are, for example, 4 arrays, one has a 10% chance, the other has 40%, etc.

I can't quite get my head around this idea.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-12-11
@ByJumping

function weightedRandom(arr, weightKey, valueKey) {
  const weightsSum = arr.reduce((acc, n) => acc + n[weightKey], 0);
  return () => {
    const rand = Math.random() * weightsSum;
    let sum = 0;
    return arr.find(n => (sum += n[weightKey]) > rand)[valueKey];
  };
}


const getRandomPhotosArray = weightedRandom([
  [ 9,  truePhotos ],
  [ 1, funnyPhotos ],
], 0, 1);

function getPhoto() {
  const photos = getRandomPhotosArray();
  return photos[Math.random() * photos.length | 0];
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question