1

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
halfer
  • 19,824
  • 17
  • 99
  • 186
Nagaraj Shet
  • 37
  • 1
  • 2
  • 8

2 Answers2

1

A simple way could be:

  • Generate a list of the 100 numbers
  • Shuffle the list using the Fisher-Yates algorithm
  • Take the first 5 numbers

There are faster ways, but for only 100 integers it should be fine.

Edit: Try this code:

function shuffleArray(array) { // from http://stackoverflow.com/a/12646864/5710637
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

function Randomnumber() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange("c2:C5");
  var min = sheet.getRange("A1").getValue();
  var max = sheet.getRange("A2").getValue();
  var numbers = []
  for (var i = min; i <= max; i++) {
    numbers.push(i);
  }
  shuffleArray(numbers)
  var counter = 0;
  for (var x = 1; x <= range.getWidth(); x++) {
    for (var y = 1; y <= range.getHeight(); y++) {
      range.getCell(y, x).setValue(numbers[counter]);
      counter++;
    }
  }
};
fafl
  • 7,222
  • 3
  • 27
  • 50
  • function Randomnumber() { var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("c2:C5"); var min = sheet.getRange("A1").getValue(); var max = sheet.getRange("A2").getValue(); for (var x = 1; x <= range.getWidth(); x++) { for (var y = 1; y <= range.getHeight(); y++) { var number = (Math.floor(Math.random() * (max - min + 1)) + min); range.getCell(y, x).setValue(number); } } }; – Nagaraj Shet Dec 16 '16 at 13:04
  • Thanks for taking initiative....currently I used below script and working fine but random number coming duplicates and within specified range. However instead of specified range I need specified 5 random number under the cell A4 to A8. – Nagaraj Shet Dec 16 '16 at 13:04
  • function Randomnumber() { var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("c2:C5"); var min = sheet.getRange("A1").getValue(); var max = sheet.getRange("A2").getValue(); for (var x = 1; x <= range.getWidth(); x++) { for (var y = 1; y <= range.getHeight(); y++) { var number = (Math.floor(Math.random() * (max - min + 1)) + min); range.getCell(y, x).setValue(number); } } }; – Nagaraj Shet Dec 16 '16 at 13:05
  • @NagarajShet: if that code is relevant to your question, please add it to your question, in order to stop it from being put on hold. It has two close votes already, for being too brief/broad. – halfer Dec 17 '16 at 23:54
0

As fafl pointed you can use a list.

  • Generate list according to Range
  • Pop n Numbers out of them randomly one by one
  • Write popped Numbers to sheet

Here is an example.

/*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)

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

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

Saurabh Harwande
  • 161
  • 6
  • 18
  • If you don't mind can you share the spreadsheet. I could not run script – Nagaraj Shet Dec 16 '16 at 13:16
  • @Nagaraj Shet I have made this code on a note pad i will edit it a bit and add some more description. Hope it helps. I will link a working appscript when i reach home. Right now I cant. – Saurabh Harwande Dec 16 '16 at 13:18
  • Here is the spreadsheet link https://docs.google.com/spreadsheets/d/1ikLPx7ltkmliwxhq-UOMAagZD1IKzJJyFlrbpEHOMKQ/edit#gid=0 – Nagaraj Shet Dec 16 '16 at 13:21
  • Try the new code. I had misinterpreted the sheet format. Just edited the code. – Saurabh Harwande Dec 16 '16 at 13:26
  • also remove from to and other things from column A. Put numbers there. – Saurabh Harwande Dec 16 '16 at 13:26
  • I have shared the spreadsheet please add script in script edit tab and let me know. – Nagaraj Shet Dec 16 '16 at 13:33
  • @NagarajShet Finally got access to my google account. I have edited the post. I have added the links as your code was not accessible to me. Some problem with permissions I guess. Please check the code once its working now tried it myself. – Saurabh Harwande Dec 16 '16 at 16:52
  • @SaurabhHarwande: please note that links requiring sign-in to a third-party are not very convenient for a wider audience. I agree they are very helpful for the original poster, but we're trying to create a set of answers for a wide audience here that can be accessed on Stack Overflow itself. Answers that rely on external links may break in the future (and when they do, extra work is created for someone else). – halfer Dec 17 '16 at 23:56
  • 1
    @halfer Actually I spent 1 hr to get the links opened without signin but could not understand why it can't be opened. I have selected anyone on web can see the links in the sharing options. – Saurabh Harwande Dec 18 '16 at 04:11
  • @NagarajShet If you are having a doubt please post it as a question instead of suggesting pathetic edit on someones reply that has helped you. Also please try and search/find solutions yourself first. God has given us brain for a purpose, so fulfill it for his sake. – Saurabh Harwande Jan 17 '17 at 10:08