Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

js random in range

function ran(min, max, exclude = false) {
  let range = max - min + 1;

  //if you don't want to exclude any number then just returns numbr in range
  if (!exclude) return Math.floor(Math.random() * range + min);
  //If you want to exlude only one number then here's O(1) solution.
  //number from range 1-4 but never get 3:
  //get number between 1-3 and if its 3 then return 4
  if (!exclude?.length) {
    let num = Math.floor(Math.random() * (range - 1) + min);
    return num == exclude ? range : num;
  }
  //if you want to exlude multiple numbers here's O(n) solution:
  //foreach number in range i want to check if its not on exlude list
  //but i dont want to use indexOf or find functions as they are O(n) making this O(n^2)
  //i create object with keys being exluded numbers as reading object by key is O(1)
  // ?. operator returns null if such key doesnt have value
  let badNum = {};
  for (let i = 0; i < exclude.length; i++) {
    badNum[exclude[i]] = true;
  }
  let googNum = [];
  for (let i = 0; i < range; i++) {
    if (!badNum?.[i]) googNum.push(i);
  }
  return googNum[Math.floor(Math.random() * googNum.length)];
}
Source by developer.mozilla.org #
 
PREVIOUS NEXT
Tagged: #js #random #range
ADD COMMENT
Topic
Name
1+2 =