评论

收藏

[R语言] 生成随机ID且唯一

编程语言 编程语言 发布于:2021-07-30 20:17 | 阅读数:303 | 评论:0

var T = [
{P:11,G:2},
{P:101,G:7},
{P:1009,G:26},
{P:10007,G:59},
{P:100003,G:242},
{P:1000003,G:568},
{P:10000019,G:1792},
{P:100000007,G:5649},
{P:2147483647,G:16807},
 ]
 // bits 为位数
 function RandUnique(bits){
   let t = T[bits-1];
  if(!t) {
    throw Error('bits >= 1  and bits <= 9');
  }
  this.p = t.P;
  this.g = t.G;
  this.seed = t.G;
  this.n = 10**bits-1;
}
 RandUnique.prototype.next = function(){
   let seed = this.seed;
   seed = (this.g * seed) % this.p;
  while( seed > this.n)
     seed = (this.g * seed) % this.p;
  this.seed = seed;
  return seed;
}
let ru = new RandUnique(2);
for(let i=0;i<100;i++){
console.log(ru.next());
}

运行结果:
DSC0000.png



关注下面的标签,发现更多相似文章