02 Jun 2023

Return Random Inclusive Integer

Taken from DailyCodingProblem

Using a functionrand7() that returns an integer from 1 to 7 (inclusive) with uniform probability, implement a function rand5() that returns an integer from 1 to 5 (inclusive).


This is the answer I came up with:

// typescript

function rand5(): number {
  return Math.ceil(Math.random() * 5)

This is a really simple question, and I didn’t feel satisfied so I also implemented a solution that returns a random (inclusive) integer but guarantees that the integer remains unique until the entire range is exhausted – that is, rand(10) below would never return a duplicate number until all numbers from 1 through 10 have also been previously returned.

const set = new Set()

function rand(_number: number): number {
  // If full (all numbers have been previously returned), clear the set
  if (set.size === _number) {

  let random = Math.ceil(Math.random() * _number)

  let regen = () => {
    random = Math.ceil(Math.random() * _number)

  while (set.has(random)) {
    // Regenerate the random number if it's already in the set

  // Add the random number to the set before returning
  return random


Solution tested in REPL:


Extended solution tested in REPL:


Copyright © Paramdeo Singh · All Rights Reserved · Built with Jekyll

This node last updated September 14, 2023 and is permanently morphing...

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems