2023-06-02

 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).

Solution

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) {
    set.clear()
  }

  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
    regen()
  }

  // Add the random number to the set before returning
  set.add(random)
  return random
}

Testing

Solution tested in REPL:

https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAJwIZgCYFYAUBKALkTBAFsAjAU2UQG8AoRFSqEZJAWVSgAsA6CJRgAbHF1580mOKXyIAVIix56AX3r1hLRDEQBeRAAZ6Adx4jKiHLoA8iAEyG8dRoggIAznC19hcAOY4Utj4KkwwANQRavRAA

Extended solution tested in REPL:

https://www.typescriptlang.org/play?#code/MYewdgzgLgBBCmsC8MzwO4wMqIBQEoAoQgMwFcxgoBLcGAJwEMwATXAfTDIFsAjeegC5UPfvXzCufATADehGDGokYuBFAB0EagC94MJIZidRA-HIWK4iDcAA28RvQKWAvsUUPYTViG4GYAFlGKAALW3hqO1xgsI0fFj8CGAAqYykxIksvBngAc3gwAOSkAD4LKwZmRP8UWPDgSOj6+Oqk8zSTaXE3Dxh0UKj9NRtQxghcBL98c3lK+nzCl0V3S3UNRhY2Ke4iRQWoMnoincJVnOoAgAZCAaHVS4AeGAAmK9nLUEgQBw07EDyk2quAAjO89koANSQs6EIA

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

This node last updated October 9, 2024 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