JavaScript generate random number except some values

后端 未结 13 1644
野性不改
野性不改 2021-01-05 11:26

I\'m generating random numbers from 1 to 20 by calling generateRandom(). How can I exclude some values, say 8 and 15?

function generateRandom(mi         


        
13条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-05 11:50

    You could take an offset for random values greater or equal than zerow ith a sorted (ascending) array and return a sum with adjusted random value.

    const
        getRandomWithoutZero = (lower, upper, gaps) => () => {
            const r = Math.floor(Math.random() * (upper - lower + 1 - gaps.length) + lower);
            return gaps.reduce((s, g) => s + (s >= g), r);
        },
        random = getRandomWithoutZero(-9, 9, [-3, 0, 4]),
        count = {};
    
    for (let i = 0; i < 1.6e6; i++) {
        const r = random();
        count[r] = (count[r] || 0) + 1;
    }
    
    console.log(count);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题