How to increment in forloop in random iterations? - javascript

I'm trying to add a random amount of "boulder" data into my "location" data. I want to use forloop to generate a random amount of boulders to put into each "location". I can't seem to get if I should use forEach or forLoop. In essence I want to know how to generate a forloop that increments in random iterations. (i.e. index=0, randomNum = 5 => nextIndex = 0+5, randomNum = 3, thirdIndex = 5+3 and so on)
here's my randomNum generator
const randomNum = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min)
}
and this is my boulder setting random forLoop (which doesnt work)
const allBoulders = async() => {await Boulder.find().exec()}
for (i=0, i < allBoulders.length; i+=upperCount;) {
console.log(i)
const area = location.area;
const place = location.place;
const latitude = location.latitude;
const longitude = location.longitude;
const boulderLocation = new Location({area: area, place: place, latitude: latitude, longitude: longitude});
const upperCount = indexCount + randomNum(1, 5)
const boulderSet = allBoulders.slice(indexCount, upperCount);
boulderLocation.boulders.push(...boulderSet);
// await boulderLocation.save()
console.log(boulderLocation)
indexCount = upperCount;
};
I'm getting the error:
for (i=0, i < allBoulders.length; i+=upperCount;) {
^
ReferenceError: upperCount is not defined
any help will be greatly appreciated!! thanks in advance!
UPDATE[SOLVED]:
I got it working thanks to answer from swift-lynx
locations.forEach(async(location) => {
const allBoulders = await Boulder.find().exec()
// console.log(foundAllBoulders);
for (let i = 0; i < allBoulders.length;) {
const area = location.area;
const place = location.place;
const latitude = location.latitude;
const longitude = location.longitude;
const boulderLocation = new Location({area: area, place: place, latitude: latitude, longitude: longitude});
const random = randomNum(1, 5);
const upperCount = i + random;
const boulderSet = allBoulders.slice(i, upperCount);
boulderLocation.boulders.push(...boulderSet);
// await boulderLocation.save()
console.log(boulderLocation);
i += random;
}
})
i used a forEach so that i can call the async function, placed a forloop where the randomNum is generated in the loop with i, being iterated from the same randomNum set to const "random".

A loop incrementing randomly, using your randomNum function, can be done like this:
const randomNum = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
}
// random increments
for (let i = 0; i < 20; i += randomNum(1, 5)) {
console.log(i);
}
If you want to use the random number inside of the for loop, you can do it like this:
// random increments and use random number inside of for loop
for (let i = 0; i < 20;) {
// generate random number
const random = randomNum(1, 5);
// use it as you like
console.log(random);
// increment i manually at the end of the loop
i += randomNum(1, 5);
}
The loop increments in random steps between 1 and 5, not including 5.

Related

How can I pick a random user from a server?

I tried making a bot command that replies with "(random user) is bot". I tried other solutions, but they didn't work. Here's my code:
if (msg.content === 'wb!bot') {
let userArray = Array.from(msg.member.guild.members);
let randomUser = userArray[Math.floor(Math.random() * msg.guild.memberCount)];
console.log(randomUser);
console.log(userArray);
msg.channel.send(randomUser + ' is bot');
}
Using math.random is pointless when the Collection class already has a .random() method
//msg.guild.members.cache if v12
const usersCollection = msg.guild.members;
const randomUser = usersCollection.random();
Your use of Math.random is incorrect.
// Generate the array for the snippet
const userArray = [];
for (let i = 0 ; i < 100 ; ++i) {
userArray.push(`user${i + 1}`);
}
// Function that returns you a random number
// https://www.w3schools.com/js/js_random.asp
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
// Pick a random user
const user = userArray[getRndInteger(0, userArray.length)];
// Display it
console.log(`${user} is bot`);

How to generate non-recurring numbers from the range JavaScript

I have array with 10 items, I calls one random item using a random number from 1 to 10, what to use to make a random number from 1 to 10, which will not happen again, and when all 10 is used, the program stops randomly? code
const num = () => Math.floor(Math.random() * 10);
const postWord = () => {
randomWord = word.innerText = words[num()].PL;
}
postWord();
submit.addEventListener("click", function() {
postWord();
});
Have you ever considered to move the array items?
var range = 10; // global variable
const num = () => Math.floor(Math.random() * range);
const postWord = () => {
randomWord = word.innerText = words[num()].PL;
for (var i=num(); i < range; i++) {
var temp = words[i];
words[i] = words[i+1];
words[i+1] = temp;
}
range--;
}
postWord();
submit.addEventListener("click", function() {
if (range) {
postWord();
}
});
I am not that familiar with JS but I guess my code can at least demonstrate my point.

Adding random number to itself in javascript

I am generating a random number on click in jQuery. At the end of this post, you can see the code that I am working with.
Is there a way where every time a new random number gets generated it gets added to the old one in a variable called totalRandomNumbers?
I want to do it for all three variables random, random_0, random_1.
$("#reset").click(function(){
var random = Math.floor(Math.random() * 12);
var random_0 = Math.floor(Math.random() * 12);
var random_1 = Math.floor(Math.random() * 12);
$("#push0").html(random);
$("#push1").html(random_0);
$("#push2").html(random_1);
$('input[name="hamPush"]').val($("#push0").html());
$('input[name="zikPush"]').val($("#push1").html());
$('input[name="musPush"]').val($("#push2").html());
})
At the start of your JavaScript, make a variable:
var totalRandomNumbers = 0;
And when you generate your random number, add it to the variable.
totalRandomNumbers += (code to generate random number)
var randomSum = 0;
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
};
function sumRandom() {
randomSum += getRandomInt(1, 100)
};
$('.genRandomButton').on('click', function() {
console.log(randomSum)
}
Just tried in browser console:
var _totalRandomNumbers = 0;
Object.defineProperty(window, "totalRandomNumbers", {
get: function() { return _totalRandomNumbers += Math.random(); }
});
console.log(totalRandomNumbers);
console.log(totalRandomNumbers);
and so on :-)
You can do anything in get accessor, store old values etc.

JavaScript - Random numbers and variables between functions

I am new to JavaScript, I have two roll functions for each roll of a frame. I am unable to get the values of each of those rolls into a frame function to call on and use. If someone could help this would be great! thanks in advance, My code is below.
var Bowling = function() {
var STARTING_TOTAL = 0;
ROLL_ONE = Math.floor(Math.random() * 11);
ROLL_TWO = Math.floor(Math.random() * 11);
this.score = STARTING_TOTAL;
var firstScore;
var secondScore;
var totalScore;
Bowling.prototype.firstRoll = function() {
firstScore = ROLL_ONE
return firstScore;
};
Bowling.prototype.secondRoll = function() {
secondScore = Math.floor(Math.random() * 11 - firstScore);
return secondScore;
};
Bowling.prototype.frameScore = function () {
totalScore = firstScore + secondScore
return totalScore;
};
};
I can only guess what you're trying to achieve. I refactored you code a little bit:
var Bowling = function () {
var STARTING_TOTAL = 0;
this.score = STARTING_TOTAL; // remains unused; did you mean "totalScore"?
this.firstScore = 0;
this.secondScore = 0;
};
Bowling.prototype.firstRoll = function () {
this.firstScore = Math.floor(Math.random() * 11);
return this.firstScore;
};
Bowling.prototype.secondRoll = function () {
this.secondScore = Math.floor(Math.random() * 11 - this.firstScore);
return this.secondScore;
};
Bowling.prototype.frameScore = function () {
this.totalScore = this.firstScore + this.secondScore
return this.totalScore;
};
// now use it like this:
var bowling = new Bowling();
console.log(bowling.firstRoll());
console.log(bowling.secondRoll());
console.log(bowling.frameScore());
In my approach however, firstScore and secondScore are public properties.
To address the question of why the second roll can be negative: as your code currently stands, if the second roll is smaller than the first roll, the result will be negative. If you want it so that if the first roll is 6, the second roll will be a number between 0 and 4, try something like:
function randomInt(maxNum) {
return Math.floor(Math.random() * maxNum)
}
var maxRoll = 11
var rollOne = randomInt(maxRoll)
var rollTwo = randomInt(maxRoll - rollOne)
console.log(rollOne)
console.log(rollTwo)
Press "Run Code Snippet" over and over again to see it work.
Changes I've made:
I made a function, randomInt that gives a random number from 0 to some max number. This saves you from needing to write the same code twice.
I created a variable maxRoll that keeps track of what the highest possible roll is.
I subtract maxRoll from the first roll to determine what the max number for the second roll should be (maxRoll - rollOne). That's then given to randomInt.

Javascript : generate random number function and push into array

I'm trying to push a random number of bunnies into a canvas from 1~10 in Javascript.
However, the Math.random() method doesn't seem to be working. It just gives me one bunny. What am I doing wrong?
var field = [];
var randomNum = Math.floor(Math.random() * 10);
field.push(randomNum * new Bunny());
function Bunny() {
...
}
It won't give you any bunnies at all. randomNum * new Bunny() will be NaN1, because you're trying to multiply an object with a number.
If you want multiple bunnies, you have to create them, probably in a loop:
var field = [];
var randomNum = Math.floor(Math.random() * 10);
for (var n = 0; n < randomNum; ++n) { // Loop
field.push(new Bunny()); // creating and pushing
} // multiple bunnies
function Bunny() {
// ...
}
1 Or a number, if you've overridden valueOf on Bunny.prototype, which seems unlikely.
var field = [];
var randomNum = Math.floor(Math.random() * 10);
for (k=0; k<randomNum; k++)
{
field.push(new Bunny());
}

Categories