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());
}
Related
I am very new to JavaScript and I'm sure this question has been answered quite a bit, but when I search my question I don't seem to find an answer (or one that I actually understand :D)
Currently, I'm trying to create a tool to help kids with there multiplication facts and I'm having trouble getting the program to generate new random numbers.
var r1 = Math.floor(Math.random() * 13);
var r2 = Math.floor(Math.random() * 13);
function start() {
println("Welcome to the multipilcation helper! ");
var num = readLine("Pick a number you want to practice or type 'random'!");
var ques = readLine("How many questions do you want?");
if (num == "random") {
for (var i = 0; i < ques; i++) {
var answer = r1 * r2;
println(r1 + "*" + r2);
var check = readLine("what is the answer");
if (check == answer) {
println("thats correct!");
} else {
println("thats wrong! ");
}
}
}
}
The problem is that my variables seem to pick a random number as soon as the script starts and stick with it instead of giving me a new random number.
Can anyone help me out and tell me how to get a new random number every time the variable is called?
Simply create yourself a method like the one below and use it like r() to get a new random number every call.
function r() {
return Math.floor(Math.random() * 13);
}
console.log(r());
console.log(r());
console.log(r());
In your loop you should be reassigning the random numbers so that they are reassigned every iteration of the loop. Otherwise they stay static to the value you give them at the top.
Also, you should use triple equals in Javascript when checking for equality as it is best practice.
function start() {
console.log("Welcome to the multipilcation helper! ");
var num = prompt("Pick a number you want to practice or type 'random'!");
var ques = prompt("How many questions do you want?");
if (num == "random") {
for (var i = 0; i < ques; i++) {
var r1 = Math.floor(Math.random() * 13);
var r2 = Math.floor(Math.random() * 13);
var answer = r1 * r2;
console.log(r1 + "*" + r2);
var check = prompt("what is the answer");
if (check == answer) {
console.log("thats correct!");
} else {
console.log("thats wrong! ");
}
}
}
}
start()
You random numbers are being static at the moment. They need to be called again. Move your r1 and r2 assignments inside the for.
I don't have enough reputation to comment, but will update the answer
if you explain it with more details.
You need to put the random call in a function in order for it to create a new number each time. When you assign it directly to a variable as you have, it only runs once and stores that value in the variable.
// pick a number between 0 and 13
var random = function() {
return Math.floor(Math.random() * 13);
}
function start(){
for(var i = 0; i < 15; i++){
// call random function for each number and store in a var
var number1 = random();
var number2 = random();
var answer = number1 * number2;
console.log('equation:', number1 + '*' + number2);
console.log('answer:', answer);
}
}
// call the start function
start()
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.
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.
I have a function that loops over an array of words, and checks if a string passed to the function contains any of the letters in the word. The word with the most matching letters is returned.
My issue is that the const I am copying to the loop scope is getting overriden. Specifically let loopIndex = alphabetIndex; How can I make a variable that I can manipulate in the loop, without it overriding the const?
import _forEach from 'lodash/foreach';
const dictionary = require('./dictionary.json');
/**
* #constructor
*/
var Game = function () {
};
/**
* #desc Return an object of the repeating string characters.
* #param string
* #returns {{}}
*/
Game.prototype.setAlphabet = function (string) {
let alphabet = {};
for (let i = 0; i < string.length; i += 1) {
if (string[i] in alphabet) {
alphabet[string[i]] += 1;
} else {
alphabet[string[i]] = 1;
}
}
return alphabet;
};
/**
* #desc Return the largest word using the string passed to the function.
* #param string
*/
Game.prototype.getWinningWord = function (string) {
let max = 0;
let maxIndex = 0;
// Get the amount of letters used in the string as an object.
const alphabetIndex = this.setAlphabet(string);
// Loop through every word in the dictionary
_forEach(dictionary, function (word, position) {
let sum = 0;
let loopIndex = alphabetIndex;
// For each of the letters, check the index; and if the letter exists in the word, add to the sum.
for (let i = 0; i < word.length; i += 1) {
if (loopIndex[word[i]] > 0) {
sum += 1;
loopIndex[word[i]] -= 1;
}
}
// If the current word has more matching letters than the previous max, set this word to max.
if (sum > max) {
max = sum;
maxIndex = position;
}
if (position > 10) return false;
});
return dictionary[maxIndex];
};
/**
* Init game.
* #type {Game}
*/
var newGame = new Game();
console.log(newGame.getWinningWord('eeosnndsm'));
The distinction here is that while a const variable can never be assigned to again, if the value of that variable is a reference then that reference can change. To avoid this, you need to make a new copy in each iteration of your loop, a simple way to do this is to use Object.assign():
let loopIndex = Object.assign({}, alphabetIndex);
I use a function that randomly selects another function, which works.
But sometimes it runs the same function twice or even more often in a row.
Is there a way to prevend this?
My current code:
window.setInterval(function(){
var arr = [func1, func2, func3],
rand = Math.floor(Math.random() * arr.length),
randomFunction = arr[rand];
randomFunction();
}, 5000);
Pretty simple so far. But how do I prevent func1 (for example) to run twice in a row
You can simply store the index of the last function called and the next time, get a random number which is not the last seen index, like this
var lastIndex, arr = [func1, func2, func3];
window.setInterval(function() {
var rand;
while ((rand = Math.floor(Math.random() * arr.length)) === lastIndex) ;
arr[(lastIndex = rand)]();
}, 5000);
The while loop is the key here,
while ((rand = Math.floor(Math.random() * arr.length)) === lastIndex) ;
Note: The ; at the end is important, it is to say that the loop has no body.
It will generate a random number and assign it to rand and check if it is equal to lastIndex. If they are the same, the loop will be run again till lastIndex and rand are different.
Then assign the current rand value to the lastIndex variable, because we dont't want the same function to be called consecutively.
How about a simple check to prevent picking an index that matches the previous pick?
var arr = [func1, func2, func3, ...];
var previousIndex = false;
var pickedIndex;
if (previousIndex === false) { // never picked anything before
pickedIndex = Math.floor(Math.random() * arr.length);
}
else {
pickedIndex = Math.floor(Math.random() * (arr.length - 1));
if (pickedIndex >= previousIndex) pickedIndex += 1;
}
previousIndex = pickedIndex;
arr[pickedIndex]();
This will pick a random function in constant time that is guaranteed to be different from the previous one.
You can select random values from 0-1. And after every run, swap the recently executed function in the array with the last element in the array i.e. arr[2].
var arr = [func1, func2, func3];
window.setInterval(function(){
var t, rand = Math.floor(Math.random() * (arr.length-1)),
randomFunction = arr[rand];
t = arr[rand], arr[rand] = arr[arr.length-1], arr[arr.length-1] = t;
randomFunction();
}, 5000);