Javascript generate random number from 0 to 75 - javascript

I am using something like this:
alert("Random number is: "+ Math.floor(Math.random() * 75) + 0);.
To create a random number between 0 and 75. Any idea how I can create a random number between 0 and 75 that IS NOT one of the numbers in this comma-parsed string:
$not_these_numbers = "17,26,52,75";.

Generate array of numbers (0-75, excluding those numbers) then generate random index:
var exclude = "17,26,52,75".split(',');
var numbers = [];
for (var i = 0; i <= 75; i++) {
if (exclude.indexOf(i+'') == -1)
numbers.push(i);
}
// will never be one of the numbers in exclude array
var random_number = numbers[Math.floor(Math.random() * numbers.length)];

You could use an object:
function getRandLimited() {
var invalid = { 17:17, 26:26, 52:52, 75:75};
var rand;
do {
rand = Math.floor(Math.random() * 76);
} while (rand in invalid);
return rand;
}

Related

Generate a random number without repeating a previous number

I need to generate a random number without repeating a previous number. This is my code:
getRandomInt( max:number, min:number ) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
It gives me the generated random number but keeps repeating the same number.
Example:
1,2,3,4,4
and in the second call:
1,12,3,14,15
You could easely do this:
Object.defineProperty(Array.prototype, 'shuffle', {
value: function() {
for (let i = this.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
[this[i], this[j]] = [this[j], this[i]]
}
return this
}
})
var numArray = Array.from(Array(10).keys()) //generate an array with number from 0 to 10
numArray.shuffle()
the .shuffle() method will randomly take one at a time off the array and print it out.

Random number for given counts

I am generating 4 digit random number by using Math.floor(Math.random() * 9999). Now I have another requirement. I have to get the number of random number to be generated in textbox. eg: If they enter 5 in textbox it has to return 5 four-digit random number. Any idea how to do it? any reference?
Simply call the method a couple of times, depending on input. Note that you need to use below random number creation method instead of yours to guarantee 4 digit numbers.
function getRand() {
return Math.floor(Math.random() * (9999 - 1000) + 1000);
}
document.getElementById('btn').addEventListener('click', () => {
const length = document.getElementById('foo').value;
const numbers = Array.from({length}, getRand);
document.getElementById('bar').innerText = numbers.join(', ');
});
<input id="foo" type="number">
<button id="btn">Get</button>
<div id="bar"></div>
You can simply call your 4 digit random number generator function() n time (n is given number in input field) as below:
for(let i=1;i<=this.n;i++) {
this.ara.push(this.random());
}
random() {
return Math.floor(Math.random()*(9999-1000) + 1000);
}
See this typescript implementation (Angular).
Call getRandoms with n = 5, and high = 9999. Handle the 5-element return array as you wish.
// pseudo-randomly generate an integer in the range low to high
function getRandom( high, low ) {
// default low is 0
if ('undefined' == typeof low) low = 0;
var range = high - low + 1;
var r = Math.floor( range*Math.random() + .5);
return Math.min(low + r, high);
};
// get n pseudo-random number in the range low to high
function getRandoms( n, high, low ) {
// default low is 0
if ('undefined' == typeof low) low = 0;
var randoms = new Array(); // initialize return
for (var i = 0; i < n; i++) {
randoms.push(getRandom(high, low));
}
return randoms;
};

return multiple numbers from the loop

I want to create a function that returns 50 random numbers out of 100. If I write console.log(getMines), it returns all fifty numbers. But if I want to actually use them, my loop returns only one number. What's the problem?
var getMines = function() {
for (count; count <= 100; count++) {
return "d" + (Math.floor(Math.random() * 50));
}
}
You can only return a single value from a function. So once you return your first number, the loop essentially ends.
Try this instead!
var getMines = function() {
var minesArray = [];
for (var count=0; count <= 100; count++) {
minesArray.push("d" + (Math.floor(Math.random() * 50)));
}
return minesArray;
}
This will return an array of all the numbers, which you can then iterate through to do what you need. You can sort the numbers, or sum them etc.
I feel I should point out that your code is returning 100 random numbers between 1 and 50, not 50 random numbers between 1 and 100. If thats what you want and you misspoke in the OP nbd, but if you want 50 random numbers between 1 and 100 change count to <= 50 and multiply Math.random() by 100 instead.
You need create a var and push randoms, like this
var getMines = function() {
var returnArray = [];
for (var count = 0; count <= 100; count++) {
returnArray.push("d" + (Math.floor(Math.random() * 50)));
}
return returnArray;
}
you can only return only once from a function, you can use an array or object, add all values to it and return it.
var getMines = function() {
var arr = [];
for (count; count <= 100; count++) {
arr.push("d" + (Math.floor(Math.random() * 50)));
}
return arr;
}
If I read you question right, you need 50 numbers with a random value out of 100.
You need to switch the numbers in the for loop and the factor for getting a random number and take a initial value of zero for the looping variable, as well as not return some value inside of the for loop.
var getMines = function() {
var count,
array = [];
for (count = 0; count < 50; count++) {
array.push("d" + (Math.floor(Math.random() * 100)));
}
return array;
}
console.log(getMines());
.as-console-wrapper { max-height: 100% !important; top: 0; }
That can also be done with some cool ES6 tricks:
const getMines = ()=> Array.from(
{length:50},
()=> "d" + Math.floor( Math.random() * 100 )
);
If you need any random 50 numbers between 1 and 100 (both inclusive, I have tweaked your version to following. See if that helps.
var getMines = function() {
var nums = [];
for (var count=1; count <= 50; count++) {
nums[count-1]=Math.floor(Math.random() * 100) + 1;
}
return nums;
}
console.log(getMines());

Check if randomized number is in an array, if true then randomize again?

I'm creating a battleship game, and I'm trying to randomize the computer's ships. However, it sometimes randomizes the same location more than once, thus creating less than 8 ships in some rounds. I tried to fix this using indexOf but I can't seem to get it to work no matter how I change the code. If the randomized number is in the array shipLocations then I want to reroll the number again until it's a number that doesn't match any number in the array. Any ideas?
var shipLocations = [];
function randShips() {
for (i = 0; i < 8; i++) {
var randomize = Math.floor(Math.random() * 64 + 1);
if (shipLocations.indexOf(randomize) == true) {
var randomize = Math.floor(Math.random() * 64 + 1);
}
else {
shipLocations.push(randomize);
}
} //end of i loop
} //end of randShips()
randShips();
console.log(shipLocations);
EDIT: So after trying out a few of the answers, this seems to be working the way it should be after testing about 100 times.
var shipLocations = [];
function randShips() {
while (shipLocations.length < 8) {
var randomize = Math.floor(Math.random() * 64 + 1);
while (shipLocations.indexOf(randomize) > -1) {
randomize = Math.floor(Math.random() * 64 + 1);
}
shipLocations.push(randomize);
}
}
randShips();
var shipLocations = [];
function randShips() {
while ( shipLocations.length < 8 ) {
var randomize = Math.floor(Math.random() * 64 + 1);
while ( shipLocations.indexOf(randomize) >= 0 ) {
randomize = Math.floor(Math.random() * 64 + 1);
}
shipLocations.push(randomize);
}
} //end of randShips()
randShips();
console.log(shipLocations);
Since you want 8 unique values, it's quite possible that 2 numbers created in a row are both in the array already. So I think you'll want to do a while:
while (shipLocations.indexOf(randomize) != -1) {
randomize = Math.floor(Math.random() * 64 + 1);
}
The var part shouldn't be there, that is only necessary for the first instance of the variable.
In javascript false conditions are returned with a value of -1.
Hence, change the if-else condition to :
if (shipLocations.indexOf(randomize) != -1) { //true condition equivalent
var randomize = Math.floor(Math.random() * 64 + 1);
}
else {
shipLocations.push(randomize);
}
indexOf doesn't return boolean value, it returns the index (int) of the matched element.
So the code should be
if (~shipLocations.indexOf(randomize)) {
var randomize = Math.floor(Math.random() * 64 + 1);
}
You could use this function to get a true unique number that for the array.
function uniqueRandom( arr) {
var num = Math.floor(Math.random() * 64 + 1);
if (~arr.indexOf(num)) {
uniqueRandom(arr);
} else {
return num;
}
}
Btw, the logic you had written has a problem. If you found a duplicate number, you just randomize it again, without pushing it into the array. so using a while or a recursive function should do the job quite well.

javascript - generate a new random number

I have a variable that has a number between 1-3.
I need to randomly generate a new number between 1-3 but it must not be the same as the last one.
It happens in a loop hundreds of times.
What is the most efficient way of doing this?
May the powers of modular arithmetic help you!!
This function does what you want using the modulo operator:
/**
* generate(1) will produce 2 or 3 with probablity .5
* generate(2) will produce 1 or 3 with probablity .5
* ... you get the idea.
*/
function generate(nb) {
rnd = Math.round(Math.random())
return 1 + (nb + rnd) % 3
}
if you want to avoid a function call, you can inline the code.
Here is a jsFiddle that solves your problem : http://jsfiddle.net/AsMWG/
I've created an array containing 1,2,3 and first I select any number and swap it with the last element. Then I only pick elements from position 0 and 1, and swap them with last element.
var x = 1; // or 2 or 3
// this generates a new x out of [1,2,3] which is != x
x = (Math.floor(2*Math.random())+x) % 3 + 1;
You can randomly generate numbers with the random number generator built in to javascript. You need to use Math.random().
If you're push()-ing into an array, you can always check if the previously inserted one is the same number, thus you regenerate the number. Here is an example:
var randomArr = [];
var count = 100;
var max = 3;
var min = 1;
while (randomArr.length < count) {
var r = Math.floor(Math.random() * (max - min) + min);
if (randomArr.length == 0) {
// start condition
randomArr.push(r);
} else if (randomArr[randomArr.length-1] !== r) {
// if the previous value is not the same
// then push that value into the array
randomArr.push(r);
}
}
As Widor commented generating such a number is equivalent to generating a number with probability 0.5. So you can try something like this (not tested):
var x; /* your starting number: 1,2 or 3 */
var y = Math.round(Math.random()); /* generates 0 or 1 */
var i = 0;
var res = i+1;
while (i < y) {
res = i+1;
i++;
if (i+1 == x) i++;
}
The code is tested and it does for what you are after.
var RandomNumber = {
lastSelected: 0,
generate: function() {
var random = Math.floor(Math.random()*3)+1;
if(random == this.lastSelected) {
generateNumber();
}
else {
this.lastSelected = random;
return random;
}
}
}
RandomNumber.generate();

Categories

Resources