生成范围内的'n'个唯一随机数

问题描述:

我需要在1到100的特定范围内生成5个随机数,且不能重复.

I need to generate 5 random number within a specific range from 1 to 100 with out duplicates.

A1 = 1(from)
A2 = 100(to)
A3 = 5 (Required random number)
A4,A5,A6,A7,A8 in cell should generate random number

正如fafl所指出的,您可以使用列表.

As fafl pointed you can use a list.

  • 根据范围生成列表
  • 弹出n个数字,一一随机显示
  • 将弹出的数字写到表中

这里是一个例子.

/*Note: The Code does not have validations like the random number needed should be less
than the range etc. You  should take care of such issues and improvise the code for the
same.
Rest of the code is optimized and makes a single read and write from Spread Making it
run fast*/
function myFunction() {
  //var ss = SpreadsheetApp.getActiveSpreadsheet();
  var ss = SpreadsheetApp.openById("1_xoBxknhDm1pM3MBw0Jbat3BTV4HXep7nZlOPw4tEWg");
  var sheet = ss.getSheets()[0];
  var values = sheet.getRange(1, 2, 3, 1).getValues();
  var nRandomNumbers = getNRandomNumbers(values[0][0], values[1][0], values[2][0]);
  sheet.getRange(4,2,values[2][0],1).setValues(nRandomNumbers);
}
function getRandomNumber(min, max) {
  return Math.random() * (max - min) + min;
}
function getNRandomNumbers(from, to, n){
  var listNumbers = [];
  var nRandomNumbers = [];
  for(var i = from; i <= to; i++) {
    listNumbers.push(i);
  }
  for(var i = 0; i < n; i++) {
    var index = getRandomNumber(0, listNumbers.length);
    nRandomNumbers.push([listNumbers[parseInt(index)]]);
    listNumbers.splice(index, 1);
  }
  return nRandomNumbers;
}

演示链接:(请将代码复制到您的驱动器/工作表中,无法获得许可的作用)

Demo Link:(Please Copy the code into your drive/sheet, can't get the permission working)

脚本: https://script.google.com/d/1hsWiGCFZ3DlxiSB3ysTr5ThWvDzThS-vBVzHrJCIEW8zM4_DzndCwGkQ/edit?usp=sharing

表格:: https://docs.google.com/spreadsheets/d/1_xoBxknhDm1pM3MBw0Jbat3BTV4HXep7nZlOPw4tEWg/edit#gid=0