我需要在1到100的特定范围内生成5个随机数,但没有重复。
A1 = 1(from)
A2 = 100(to)
A3 = 5 (Required random number)
A4,A5,A6,A7,A8 in cell should generate random number
答案 0 :(得分:0)
一种简单的方法可能是:
有更快的方法,但只有100个整数才应该没问题。
编辑:试试这段代码:
let-pokemon="item"
答案 1 :(得分:0)
正如fafl所指出的,你可以使用一个列表。
这是一个例子。
/*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;
}
演示链接:(请将代码复制到您的驱动器/工作表中,无法获得许可)
工作表: https://docs.google.com/spreadsheets/d/1_xoBxknhDm1pM3MBw0Jbat3BTV4HXep7nZlOPw4tEWg/edit#gid=0