Skip to content

Instantly share code, notes, and snippets.

@hamg26
Last active May 20, 2019 04:44
Show Gist options
  • Save hamg26/643b9f5de4a0abef103ea843f59b71f0 to your computer and use it in GitHub Desktop.
Save hamg26/643b9f5de4a0abef103ea843f59b71f0 to your computer and use it in GitHub Desktop.
You are provided this flip function: function flip() { return Math.random() >= 0.5; }. You must implement a randomNumber(n) function that generates a random number greater than or equal to 0, and less than input n. n must be greater than 0. n must be less than 1,000,000. Your only source of randomness must be the provided flip() function. You ca…
function flip() {
return Math.random() >= 0.5;
}
function randomNumber(n) {
if(n === undefined) throw new Error("n is required");
if(n <= 0) throw new Error("n must be greater than 0");
if(n > 1000000) throw new Error("n must be lower than 1,000,000");
// No need to further calculations
if(n === 1) return 0;
// Returns a string of random 0s and 1s with length m
function randomBinary(m){
binary = "";
for (var i=0; i<m; i++) {
binary+= flip()? "1" : "0";
}
return binary;
}
// Get the maximum posible value as binary;
var maxPosibleValue = n-1;
// Calculate the minimal length to express as binary
// the maximum posible value
var k = maxPosibleValue.toString(2).length;
var r;
do {
// Get a random number
r = parseInt(randomBinary(k), 2);
// and check if meets the maximum posible value
} while (r > maxPosibleValue);
return r;
}
@iecoding
Copy link

respect!!

@charliechauri
Copy link

Awesome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment