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());
Related
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.
Okay, so let's say I store some of my data like this,
var thisList = {
"items":[
{"name":"Item1", "image":"/img/item1", "chance":0.25},
{"name":"Item2", "image":"/img/item2", "chance":0.25},
{"name":"Item3", "image":"/img/item3", "chance":0.50}
]
}
Now I'd like to create a function that randomly picks a item out of this list with the chances being 25% of getting [0], another 25% of getting [1] and a 50% chance of getting [2]!
Is this possible? If so, how'd I do this?
Kind regards!
You can actually play it like this, tou generate a number between 0 and 100 and then you cycle on each element and sum the chance to check if it is between the value or not:
var thisList = {
"items":[
{"name":"Item1", "image":"/img/item1", "chance":0.25},
{"name":"Item2", "image":"/img/item2", "chance":0.25},
{"name":"Item3", "image":"/img/item3", "chance":0.50}
]
};
function getRandom(){
var rnd = Math.floor(Math.random() * 100);
console.log("The number is: " + rnd);
var counter = 0;
for(i=0;i<thisList.items.length;i++)
{
counter += thisList.items[i].chance * 100;
if(counter > rnd){
console.log(thisList.items[i]);
break;
}
}
}
getRandom();
EDIT:
If you want to control even with a variant chance you can do this:
var thisList = {
"items":[
{"name":"Item1", "image":"/img/item1", "chance":0.25},
{"name":"Item2", "image":"/img/item2", "chance":0.25},
{"name":"Item3", "image":"/img/item3", "chance":0.50}
]
};
function getRandom(){
var sum = 0;
for(i=0;i<thisList.items.length;i++)
{
sum += thisList.items[i].chance;
}
var rnd = Math.floor(Math.random() * (sum * 100));
console.log("The number is: " + rnd);
var counter = 0;
for(i=0;i<thisList.items.length;i++)
{
counter += thisList.items[i].chance * 100;
if(counter > rnd){
console.log(thisList.items[i]);
break;
}
}
}
getRandom();
You need to look at the cumulative sum of all odds seen so far in the array. With the sample data you've given those values would be 0.25, 0.5, 1.0
Then given a random number in the range [0, 1), just pick the first entry where the cumulative value is less than that number.
Here's an example implementation:
const pickRandom = (() => {
let target = Math.random(), total = 0.0;
return (e, i, a) => {
total += e.chance;
return target < total;
}
});
let picked = thisList.items.find(pickRandom());
The pickRandom function needs to be called exactly once per round, and returns a function that encapsulates the state necessary to accumulate the chances seen so far, and the random number that is to be used.
That function then becomes the predicate used by Array.prototype.find to extract the appropriate random item.
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.
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;
}
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();