-9

我有一个函数可以在给定范围内生成随机数。我想确保我不会重新生成同一对数字。

function generateRandomInt(max) {
      return Math.floor(Math.random() * Math.floor(max));
}

let randomInt1 = generateRandomInt(10) + 1;
let randomInt2 = generateRandomInt(10) + 1;

let numberStore = randomInt1 + "" + randomInt2; 

console.log(randomInt1);
console.log(randomInt2);
console.log(parseInt(numberStore));

numberStore包含 和 的randomInt1结果randomInt2。我想避免有一对已经生成的数字。

https://codepen.io/anon/pen/wRJrrW

4

13 回答 13

3

您可以使用Set对象。使用方法add()时,值不能重复。

这是一个例子:

function random(x, max = 10) {  // x = how many random numbers and max = the max number
    const set = new Set();
    for (let i = 0; i <= x; i++) { // Generate numbers x times
      secondLoop:
      while(true) { // Run the loop until there is a match
        let random = Math.floor(Math.random() * Math.floor(max));        
        set.add(random); // Set the value          
        if (set.size === max) { // We have all the values. Let's break the loop       
          break secondLoop;          
        }
      }
    }
  return set;
}

console.log(random(10));

console.log(random(10))返回您需要的一切。你可以使用random(10).values()random(10).delete()或者任何你喜欢的。

于 2018-12-26T05:40:11.327 回答
2

您需要做的就是跟踪使用的内容。最简单的事情就是你要看到一个对象。因此,用分隔符将第一个数字与第二个数字结合起来。

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function pairGenerator(min, max) {

  var usedPairs = {} // holds the keys for what we used alreay
 
  return function() {

    const generate = function() {
      const a = getRandomInt(min, max)
      const b = getRandomInt(min, max)
      const key = a + "," + b // generate the key
      if (usedPairs[key]) { // see if it is used
        return generate() // if it is, try again
      } else {
        usedPairs[key] = 1 // mark it was not used
        return [a, b] // return the two numbers
      }
    }

    return generate()
  }
}

const myGenerator = pairGenerator(0, 10);
for (let i = 0; i < 10; i++) {
  console.log(myGenerator())
}

于 2018-12-21T15:21:01.880 回答
2

引用赏金描述:
当前答案不包含足够的细节。

我认为您不了解它在当前答案中的工作原理。因此,我想向您展示两个更简单的解决方案。

首先我想写一下随机函数。你可以在我的解决方案中使用你的函数,但你的函数永远不会得到max数字。我建议使用来自 MDN 的正确随机函数。在这种情况下,我们将得到遵循均匀分布的随机数。

使用

我们采用 Javascript 文字表示法获取一个关联数组,var numberStore = {};并使用 keys: 向其中添加值numberStore[key] = value;。我们也可以这样做:numberStore.key = value;. 如果您想阅读这些数字,那么我们可以使用value = numberStore[key];value = numberStore.key;

您可以在此处找到有关它的更多信息:使用对象

//get random numbers which follows a uniform distribution
function getRandom(min, max)
{
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

var numberStore = {}, //associative array or JS-object
    length = 10;

for(var i = 0; i < length; i++)
{
    // do not forget to think about the range of numbers.
    // Because if you want generate 1000 pairs then it should
    // be a range with more than 33 numbers and not with 10.
    // In other case you will get a loop, because 33 x 33 = 999
    var val1 = getRandom(0, length),
        val2 = getRandom(0, length),
        key = val1 + '_' + val2; // generate the key

    if(numberStore[key] != undefined) //check if we have it already
    {
        i--;
        continue; //go to next loop step with i = i - 1
        //The continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
        //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue
    }
    //if we do not have it then we store it as new array:
    else
        numberStore[key] = [val1, val2]; //new array with our values
}

//we use JSON.stringify to beautify (prettify) the code output.
console.log(JSON.stringify(numberStore, null, 4));

console.log('---------------------');

//if you want to access the stored numbers, then you can ďo it like follows:
for(var key in numberStore)
{
    var val = numberStore[key];
    console.log(''+ val); //convert array to string
}

经典

我们也可以将它存储在一个经典数组中,如下所示:

function getRandom(min, max)
{
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

var numberStore = [],
    length = 10;

for(var i = 0; i < length; i++)
{
    var val1 = getRandom(0, length),
        val2 = getRandom(0, length),
        key = val1 + '_' + val2; // generate the key

    if(numberStore.indexOf(key) > -1) //check if we have it already
    {
        i--;
        continue
    }
    else
        numberStore.push(key)
}

console.log(JSON.stringify(numberStore, null, 4));

console.log('---------------------');

for(var i = 0; i < numberStore.length; i++)
{
    var arrVals = numberStore[i].split('_');
    console.log(arrVals[0] + ', ' + arrVals[1]);
}

于 2018-12-26T01:39:21.287 回答
2

这实际上是一个很酷的问题。

好的,让我们从头开始,看看我是否正确理解了问题。您想要的是一个“函数”,它返回给定范围内唯一的随机数对。

那么,当我们用完唯一对时会发生什么?那我们怎么办?

我之所以这么问,是因为我认为您在这里真正想要的是生成器函数

可以这样使用的东西:

const pairsGen = randomPairsMaker(10);
console.log(pairsGen.next().value) // [9, 5] 
console.log(pairsGen.next().value) // [3, 9]
console.log(pairsGen.next().value) // [9, 3]
console.log(pairsGen.next().value) // [4, 4]
// ...
console.log(pairsGen.next().done) // Eventually this will become true

好的,让我们编写那个生成器:

function* randomPairsMaker(range) {
  // Let's build a circularly linked data structure where we will
  // keep all the available permutations. So, that every time that 
  // we remove one we can do it in a somewhat performant manner:
  let current = {};
  const fakeInit = current;
  for (let a = 0; a < range; a++) {
    for (let b = 0; b < range; b++) {
      current.next = {pair: [a, b]};
      current = current.next;
    }  
  }
  current.next = fakeInit.next;

  // And now let's just yield the results
  for (let nAvailable = range * range; nAvailable > 0; nAvailable--) {
    const advance = Math.floor(Math.random() * nAvailable);
    for (let i = 0; i < advance; i++) current = current.next;
    yield current.next.pair;
    current.next = current.next.next;
  }
}
于 2019-01-01T16:38:45.797 回答
2

我试图用更多的面向对象的方法来解决这个问题。可能不是最标准的方法。

  • 一个值由一个数字表示并被检索。
  • 当检索到一个值时,将在processedIndexes对象中分配一个替换值。索引将等于删除的值。
  • 新添加的对象属性的值将等于最后一个索引的值或(引用值)。
  • 最后一个索引将被删除;totalIndexes会减一。
  • 使用该decode_value方法,数字由所需的输出“解码”。

阅读代码以获取更多信息。

class RandomNumberGenerator {
  integerRange1 = null;
  integerRange2 = null;
  totalIndexes = null;
  processedIndexes = {};

  constructor(integerRange1, integerRange2) {
    this.integerRange1 = integerRange1;
    this.integerRange2 = integerRange2;
    this.totalIndexes = integerRange2 * integerRange1;
  }

  get_randomValue() {
    // if all possible values are occupied throw an error and return null
    if (this.totalIndexes === 0) {
      console.error('ERROR: all indexes have already been generated');
      return null;
    }
    // calculate availableIndexes
    let availableIndexes = this.totalIndexes;
    // pick a random value
    let newIndex = Math.random() * availableIndexes;
    // round down because of 0 is the first item
    newIndex = Math.floor(newIndex);
    // 
    let newValue = this.retreive_value(newIndex);
    // decode the value to useful output
    newValue = this.decode_value(newValue);
    return newValue;
  }

  retreive_value(newIndex) {
    let value = null;
    // check if the value has already been assigned previously, if so return the new referencing value
    value = (typeof this.processedIndexes[newIndex] === 'number') ? this.processedIndexes[newIndex] : newIndex;
    // the length of the array is reduced by one
    this.totalIndexes--;
    if (typeof this.processedIndexes[this.totalIndexes] === 'number') {
      // replace the retreived value with the highest possible index we are about to remove
      this.processedIndexes[newIndex] = this.processedIndexes[this.totalIndexes];
      // remove the last index from the object, since it it no longer relevant
      delete this.processedIndexes[this.totalIndexes];
    } else {
      this.processedIndexes[newIndex] = this.totalIndexes;
    }
    // return value
    return value;
  }

  decode_value(value) {
    // this is some logic that translates the number to desireable output
    let integer1 = null;
    let integer2 = null;

    // count the amount of times 
    integer2 = Math.floor(value / this.integerRange1) + 1;
    // remaining values
    integer1 = value % this.integerRange1 + 1;

    return [integer1, integer2]
  }
}

let rng = new RandomNumberGenerator(10, 10);
for (let i = 0; i < 10; i++) {
  let values = rng.get_randomValue();
  console.log(values[0], values[1]);
}

PS:新年快乐

于 2018-12-31T18:48:14.693 回答
1

现代 JavaScript 提供了类SetMap. ASet管理唯一的密钥条目。AMap是一个扩展Set,它为每个唯一键关联一个附加对象。除了 JavaScript 的标准对象之外,SetMaps类确实有一个包含条目数量的动态大小属性。

即使支持对象和数组作为键,theSet和 theMap都没有提供深入的比较检查。相同的引用被视为相等标准。要获得不同的内容标准,您需要将内容转换为唯一值,例如带有明确分隔符的连接字符串或最通用的 JSON 表示方式。

假设您真的希望是唯一的,而不仅仅是连接的字符串,并且您可能希望分别处理两个随机数,那么Map该类就是您想要的,因为我们可以存储原始数组,而无需稍后从 JSON 重建它。

// It's always a good habit to encapsulate the script scope and enable strict mode
(()=>{
  'use strict';

  function generateRandomInt(max, min)
  {
    return Math.floor(Math.random() * Math.floor(max+min+1) + min);
  }

  function generateRandomUniquePairs(count, max, min)
  {
    // ensure proper integer arguments
    count = undefined === count ? 0 : Math.floor(count);
    max   = undefined === max   ? 0 : Math.floor(max  );
    min   = undefined === min   ? 0 : Math.ceil (min  );

    // throw error on inappropriate input arguments
    if(isNaN(count))
      throw new Error('Error: `count` must be convertible to integer.');

    if(isNaN(max))
      throw new Error('Error: `max` must be convertible to integer.');

    if(isNaN(min))
      throw new Error('Error: `min` must be convertible to integer.');

    if(Math.pow(1+max-min, 2) < count)
      throw new Error( 'Error: There is no unique set of ' + count +
                       ' pairs within a range of ' + (1+max-min) + ' values ('+min+'..'+max+'). ' +
                       '`count` must be equal or less than the range squared.');


    // basic algorithm
    // Map holds unique keys associated to any object and provides a dynamic size property
    let pairs = new Map();

    // generate `count` distinct entries
    while(pairs.size < count)
    {
      // Here you could additionally `sort()` the pair for the key only
      // or both the key and value if you consider [1,2] and [2,1] to be equal

      let pair = [generateRandomInt(max, min), generateRandomInt(max, min)];

      // use JSON string representation as unambiguous key
      pairs.set(JSON.stringify(pair), pair);
    }

    // convert the result to a simple array
    return Array.from(pairs.values());
  }


  // ***** TEST CASE *****
  let pairs = generateRandomUniquePairs(50, 9);

  // output as array of arrays
  console.log(pairs);

  // convert items to concatenated strings
  pairs.forEach( (v,i) => pairs[i] = v.join('') );

  // ordered output as array of strings as given in the example of your question
  console.log(pairs.sort());


})();

于 2019-01-01T09:18:57.480 回答
1

您的描述存在一些问题,并且“修复”每个问题都会导致不同的解决方案。

我想确保我不会重新生成同一对数字

在这里,您希望限制流程的行为,但流程本身并不存在。您的代码不是“生成一对随机数”。相反,它是“生成 2 个随机数,然后盲目配对”。让我们先解决这个问题:

function generateRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

function generateRandomIntPair(max) {
  let randomInt1 = generateRandomInt(max) + 1;
  let randomInt2 = generateRandomInt(max) + 1;
  let pair = [randomInt1, randomInt2];
  return pair;
}

let randomIntPairgenerateRandomIntPair(10);

我想避免有一对已经生成的数字。

当生成重复对时,预期的行为应该是什么?默默地失败?抛出错误?生成一个新的唯一随机对?

错误和静默失败很糟糕但微不足道

另一方面,要生成一个新的唯一随机对,您需要知道两件事:

  1. 对于给定的max,有多少个唯一的随机对是可能的
  2. 已经生成了多少对

当所有可能的配对都完成后,一种天真的方法可能会陷入无限循环

解决问题:

  1. 总对= max * max(因为您只关心排列而不是组合,并且允许重复值
  2. 总生成对可以由一个简单的计数变量管理

在全局变量中维护这种状态的问题是内存消耗

function generateRandomInt(max) {
    return Math.floor(Math.random() * Math.floor(max))
}

const totalPairsPossible = {}
const uniquePairs = {}

function generateRandomIntPair(max) {
    const N = max * max
    totalPairsPossible[max] = N

    let randomInt1 = generateRandomInt(max) + 1
    let randomInt2 = generateRandomInt(max) + 1

    let newPair = [randomInt1, randomInt2]

    uniquePairs[max] = uniquePairs[max] || []

    if (uniquePairs[max].length === totalPairsPossible[max]) {
        throw new Error('All unique pairs generated')
    }

    let isNewPairUnique = uniquePairs[max].every(
        pair => (pair[0] !== newPair[0] || pair[1] !== newPair[1])
    )

    if (isNewPairUnique) {
        uniquePairs[max].push(newPair)
        return newPair
    } else {
        return generateRandomIntPair(max)
    }
}
于 2018-12-31T09:32:06.717 回答
1

我不完全得到你真正想要的,但我会试着回答:

1)假设您要存储唯一对

function generateRandomInt(max) {
          return Math.floor(Math.random() * Math.floor(max));
    }

    const store = new Set()

    let randomInt1 = generateRandomInt(10) + 1;
    let randomInt2 = generateRandomInt(10) + 1;
    let numberStore = randomInt1 + "," + randomInt2; 

store.add(numberStore)
store.add(numberStore) // duplicate won't be added

https://jsfiddle.net/zhmtd9sg/1/

2)假设您想从唯一集合中生成随机对

let store = []

const arr = Array.from(Array(100), (_,i) => i+1) // numbers from 1 to 100

arr.forEach(firstNum => {
    arr.forEach(secondNum => {
    arr.push([firstNum, secondNum])
  })
})

let randomStoreIndex = Math.floor(Math.random()*store.length)
let randomUniquePair = store[randomStoreIndex]
store.splice(randomStoreIndex, 1)

console.log(randomUniquePair)
console.log(store)

https://jsfiddle.net/o7skenzb/

于 2018-12-29T19:26:15.170 回答
1

使用ES6 生成器,您可以以迭代器方式生成所有可能的对。

由于您正在生成整数,因此您可以使用双数组矩阵来将已生成的对存储为索引。

生成器将创建新的未使用对,直到生成所有可能的组合。然后它将返回{ value: undefined, done: true })。

代码示例:

function* pairGen (maxRange) {

  // create an array with the inclusive range as size
  const store = new Array(maxRange + 1)

  // inclusive int gen with min=0
  function int (max) {
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - 0 + 1)) + 0;
  }

  // update the store with a given pair
  function update(x, y) {
    store[x] = store[x] || new Array(maxRange + 1)
    store[x][y] = true
  }

  // check if there is any pair available (=falsey)
  function available() {
    for (let entry of store) {
      if (typeof entry === 'undefined') return true
      for (let value of entry) {
        if (!value) return true
      }
    }
    return false
  }

  let int1, int2
  while (available()) {
    int1 = int(maxRange)
    int2 = int(maxRange)

    // only yield if the values are still available
    if (!store[int1] || !store[int1][int2]) {
      update(int1, int2)
      yield [int1, int2]
    }
  }
}

有了这个,您可以生成所有对,直到不再有可用的对。

用法:

let gen = pairGen(2);
let value = gen.next().value
while (value) {
  console.log(value)
  value = gen.next().value
}

可能的输出:

[0, 2]
[1, 2]
[0, 0]
[2, 1]
[1, 1]
[0, 1]
[2, 2]
[2, 0]
[1, 0]

优点

  • 所有必需的变量都在生成器的块范围内。
  • 没有无限循环。
  • 生成所有可能的对。

缺点

  • 可用性检查涉及双 for 循环,并且随着范围的扩大和生成对的数量增加,可能会变得非常低效。
  • while如果没有生成循环,它只会产生一个新的对,这使得循环有时会再次运行很多次。这是因为没有生成数字的策略,而是一种随机方法,可能会导致大量已经生成的对随着商店的增长。
于 2018-12-31T21:13:14.590 回答
1

使用函数发生器Set的组合。

工作示例:

function randomNumber(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

function* uniquePair(max) {

  const pairs    = new Set();
  const maxPairs = max * max;

  while (true) {
    const res = [randomNumber(max), randomNumber(max)];
    const resStr = res.join(",");
    switch (true) {
      case !pairs.has(resStr):
        pairs.add(resStr);
        yield res;
        break;
      case pairs.size === maxPairs:
        //done
        return;
      default:
        console.log(resStr + " Exists...");
    }
  }
}


const gen10 = uniquePair(10);

const si = setInterval(function() {
  const next = gen10.next();
  if (next.done === true) {
    clearInterval(si);
    console.log("Done");
  } else {
    console.log(next.value);
  }
}, 500);
.as-console-wrapper { max-height: 100% !important; top: 0; }

这是如何运作的?

const gen = uniquePair(10);

这将为给定的最大范围创建一个新的生成器。


function* uniquePair(max) {

  const pairs    = new Set();
  const maxPairs = max * max;

  /** more code **/

}

前两行只创建一次。记住已经创建的pairs唯一组合(开始时为空)并maxPairs了解最大可能的唯一组合。


function* uniquePair(max) {

  /** more code **/

  while (true) {
    const res = [randomNumber(max), randomNumber(max)];
    const resStr = res.join(",");

    /** more code **/
  }
}

在这里,我们创建了一个无限循环。每个循环我们创建两个值的随机组合。我们还创建了这两个值的字符串表示形式(例如:[1,0] -> "1,0")。


function* uniquePair(max) {

  /** more code **/

  while (true) {
    /** more code **/
    switch (true) {
      case !pairs.has(resStr):
        pairs.add(resStr);
        yield res;
        break;
      /** more code **/
    }
  }
}

对于 while 循环的每次迭代,我们检查两个值的字符串表示是否存在于我们的集合中。如果没有,我们将该字符串表示添加到集合和yield数组中。

yield 是我们暂时“离开”我们的生成器并发回结果的地方,然后可以通过以下方式访问:

const next = gen.next();
//next.value -> [1,0] , next.done -> false

function* uniquePair(max) {

  /** more code **/

  while (true) {
    /** more code **/
    switch (true) {
      /** more code **/
      case pairs.size === maxPairs:
        //done
        return;
      /** more code **/
    }
  }
}

如果值的字符串表示形式已经存在于我们的集合中,我们检查该集合的大小是否等于最大对数。如果是,我们可以假设没有更多的结果,我们只需return

此时生成器已完成,将不再返回任何值:

const next = gen.next();
//next.value -> undefined , next.done -> true

function* uniquePair(max) {

  /** more code **/

  while (true) {
    /** more code **/
    switch (true) {
      /** more code **/
      default:
        console.log(resStr + " Exists...");
    }
  }
}

如果前面的情况都不匹配,那么我们可以假设 1. 当前组合已经存在,并且 2. 仍然存在组合。然后我们进行下一次循环迭代并提出一个新的组合并重新开始,直到找到一个新的唯一组合。

可运行多个实例:

此代码还允许运行生成器的多个实例,每个实例具有不同的最大数量。

const gen2 = uniquePair(2);
const gen4 = uniquePair(4);
const gen6 = uniquePair(6);

let cycle = 1;
const si = setInterval(function(){

  console.log(`Cycle: ${cycle}`);

  const next2 = gen2.next();
  const next4 = gen4.next();
  const next6 = gen6.next();
  
  if(next2.done === false){
    console.log(`2: [${next2.value.join(",")}]`);
  } else {
    console.log("2: DONE");
  }
  
  if(next4.done === false){
    console.log(`4: [${next4.value.join(",")}]`);
  } else {
    console.log("4: DONE");
  }
  
  if(next6.done === false){
    console.log(`6: [${next6.value.join(",")}]`);
  } else {
    console.log("6: DONE");
  }
  
  console.log("-------");
  cycle++;
  if(cycle === 40) clearInterval(si);

}, 1000);



function randomNumber(max){return Math.floor(Math.random()*Math.floor(max))}
function*uniquePair(max){const pairs=new Set();const maxPairs=max*max;while(!0){const res=[randomNumber(max),randomNumber(max)];const resStr=res.join(",");switch(!0){case!pairs.has(resStr):pairs.add(resStr);yield res;break;case pairs.size===maxPairs:return;}}}
.as-console-wrapper { max-height: 100% !important; top: 0; }

最小最大解决方案:

function randomNumber(max,min) {
  return Math.floor(Math.random() * (max - min) + min);
}

function* uniquePair(max, min = 0) {

  const pairs = new Set();
  const maxPairs = Math.pow(max-min, 2);
  console.log(maxPairs);

  while (true) {
    const res = [randomNumber(max, min), randomNumber(max, min)];
    const resStr = res.join(",");
    switch (true) {
      case !pairs.has(resStr):
        pairs.add(resStr);
        yield res;
        break;
      case pairs.size === maxPairs:
        //done
        return;
      default:
        console.log(resStr + " Exists...");
    }
  }
}


const gen10 = uniquePair(10,5);

const si = setInterval(function() {
  const next = gen10.next();
  if (next.done === true) {
    clearInterval(si);
    console.log("Done");
  } else {
    console.log(next.value);
  }
}, 500);

预先计算所有可能性的解决方案:

我所拥有的主要示例的主要问题是,请求的组合越多,算法就越难找到一个独特的组合。这当然可以忽略不计,如果:

  1. 不到100对
  2. 仅请求了 60-70% 的可能匹配项

如果上述两点都是错误的,那么这个解决方案将是最佳的:

function randomNumber(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

function generateAllPossibilities(max){
  const res = [];
  for(let i = 0; i < max; i++){
    for(let j = 0; j < max; j++){
      res.push([i,j]);
    }
  }
  return res;
}

function* uniquePair(max) {

  const pairs    = generateAllPossibilities(max);
  
  while (true) {
    const len = pairs.length;
    if(len === 0) return;
    yield pairs.splice(randomNumber(len), 1).shift();
  }
}


const gen10 = uniquePair(10);

const si = setInterval(function() {
  const next = gen10.next();
  if (next.done === true) {
    clearInterval(si);
    console.log("Done");
  } else {
    console.log(next.value);
  }
}, 200);
.as-console-wrapper { max-height: 100% !important; top: 0; }

于 2019-01-02T00:15:02.013 回答
0

您已经有了生成随机对的答案。这可以通过将生成的对保存在Set.

这种方法的问题是算法可能会继续生成已经创建的对。因此,这种方法不可能有已知的摊销分析。

生成具有良好性能的有保证的新对的解决方案

通过循环产生所有对并将它们存储在一个数组pairArray中。现在,生成一个随机数i<= 数组大小。您的新对将等于pairArray[i]

为防止此元素重新出现在结果中,您应该将其从pairArray. 代码:pairArray.splice(i,1)

我相信您可以轻松实现这一点,因为您看起来精通该语言。此外,拼接会影响性能。欢迎您选择适合您需要的其他数据结构。

于 2018-12-30T07:01:41.523 回答
0

使 numberStore 具有键为 (input1+input2) 和值 randomInt1 + "" + randomInt2 的对象;在向 numberStore 对象添加新键之前,请检查该键是否已存在于对象中

function generateRandomInt(max) {
      return Math.floor(Math.random() * Math.floor(max));
    }

let randomInt1 = generateRandomInt(10) + 1;
let randomInt2 = generateRandomInt(10) + 1;
let numberStore={};
numberStore.values=[];
var key={[randomInt1]:randomInt1,[randomInt2]:randomInt2};

  if(!numberStore[key[randomInt1]] && !numberStore[key[randomInt2]]){
     numberStore.values.push(randomInt1 + "" + randomInt2); 
     }

console.log(randomInt1);
console.log(randomInt2);
console.log(numberStore);
于 2018-12-21T14:55:37.453 回答
0

听起来您在问,如果您一遍又一遍地生成这些数字对,如何避免冲突(意思是多次返回相同的数字对)。

传统上有两种方法可以做到这一点:

1) 跟踪您曾经生成的每个号码,并确保您生成的号码不在列表中。如果是,则生成另一个。循环直到你产生一个你以前没见过的数字。

2)使随机数的数字空间非常非常大,这样碰撞的可能性很小。

方法 #1 包括将随机数列表保存在内存中,一直到,例如,生成一个数字并将其插入到具有唯一索引的 MySQL 表中(如果发生冲突,您可以重新生成号,然后再试一次,等等)。

方法 #2 通常涉及选择具有较大输出空间的更好(加密)随机数生成器,或使用 GUID 生成器等。

于 2018-12-21T14:55:53.303 回答