在范围 (0 - X) 内生成唯一编号,保留历史记录以防止重复 [英] Generate unique number within range (0 - X), keeping a history to prevent duplicates

查看:16
本文介绍了在范围 (0 - X) 内生成唯一编号,保留历史记录以防止重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个挑战,我需要一个函数来返回 0 - X 给定范围内的随机数.不仅如此,我还要求返回的数字唯一;不复制先前调用该函数时已经返回的数字.

I ran into the challenge where I need a function that returns a random number within a given range from 0 - X. Not only that, but I require the number returned to be unique; not duplicating numbers that have already been returned on previous calls to the function.

可选地,完成后(例如,范围已用尽"),只需返回范围内的随机数.

Optionally, when this is done (e.g. the range has been 'exhausted'), just return a random number within the range.

人们会怎么做呢?

推荐答案

我写了这个函数.它保留自己的带有生成数字历史的数组,防止初始重复,如果范围内的所有数字都输出一次,则继续输出随机数:

I wrote this function. It keeps its own array with a history of generated numbers, preventing initial duplicates, continuing to output a random number if all numbers in the range have been outputted once:

// Generates a unique number from a range
// keeps track of generated numbers in a history array
// if all numbers in the range have been returned once, keep outputting random numbers within the range
var UniqueRandom = { NumHistory: new Array(), generate: function(maxNum) {
        var current = Math.round(Math.random()*(maxNum-1));
        if (maxNum > 1 && this.NumHistory.length > 0) {
            if (this.NumHistory.length != maxNum) {
                while($.inArray(current, this.NumHistory) != -1) { current = Math.round(Math.random()*(maxNum-1)); }
                this.NumHistory.push(current);
                return current;
            } else {
                //unique numbers done, continue outputting random numbers, or we could reset the history array (NumHistory = [];)
                return current;
            }
        } else {
            //first time only
            this.NumHistory.push(current);
            return current;
        }
    }
};

这是一个有效的小提琴

我希望这对某人有用!

正如下面的 Pointy 所指出的那样,在大范围内它可能会变慢(这里是fiddle,范围从 0 到 1000,这似乎运行良好).然而;我不需要很大的范围,所以如果您希望生成和跟踪一个很大的范围,这个函数可能确实不适合.

as pointed out by Pointy below, it might get slow with a large range (here is a fiddle, going over a range from 0-1000, which seems to run fine). However; I didn't require a very large range, so perhaps this function is indeed not suited if you look to generate and keep track of an enormous range.

这篇关于在范围 (0 - X) 内生成唯一编号,保留历史记录以防止重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆