Can any of you guys explain to me why my loop keeps returning the same integer? I personally have no idea why it isn't a random integer.
Kind Regards..
CODE:
var currentTry = 2;
for(;;){
var randomInt = Math.floor(Math.random * 100) + 1;
if(1/currentTry*100 < randomInt){
currentTry = currentTry+1;
}else{
console.clear();
console.log("This took me: " + currentTry + " tries!");
break;
}
}
This:
var randomInt = Math.floor(Math.random * 100) + 1;
will evaluate to NaN. That's why the if is never entered. Math.random is a function not a variable so you should call it like this Math.random(). Here is what you should do:
var randomInt = Math.floor(Math.random() * 100) + 1;
Related
This is how I generate 6 different numbers:
window.random_row = Math.floor(Math.random() * (len_board - 1)) + 1;
window.random_column = Math.floor(Math.random() * (len_board - 1)) + 1;
window.random_row2 = Math.floor(Math.random() * ((len_board-1) - 1)) + 1;
window.random_column2 = Math.floor(Math.random() * ((len_board-1) - 1)) + 1;
window.random_row3 = Math.floor(Math.random() * ((len_board+1) - 1)) + 1;
window.random_column3 = Math.floor(Math.random() * ((len_board+1) - 1)) + 1;
However, I don't want the rows/columns to be the same number, e.g random_row == random_column is allowed, but I don't want random_row == random_row2. I was thinking of using an if/else statement. Something along the lines of: if (random_row == random_row2) then generate a new random_row2 but it came to my mind that the number could be the same again so I guess that would not be the right way to go about it. Does anyone have an idea about how to solve this issue?
I saw a good answer in https://stackoverflow.com/a/2380113/5108174
Adapting to your question:
function generate(qt, len_board) {
var arr = [];
while(arr.length < qt) {
var randomnumber = Math.floor(Math.random() * (len_board - 1)) + 1;
if(arr.indexOf(randomnumber) > -1) continue;
arr.push(randomnumber);
}
return arr;
}
var rows=generate(3,len_board);
var columns=generate(3,len_board);
window.random_row = rows[0];
window.random_column = columns[0];
window.random_row2 = rows[1];
window.random_column2 = columns[1];
window.random_row3 = rows[2];
window.random_column3 = columns[2];
Create an array of numbers from 1 .. len-board
shuffle it (sort with Math.random() < 0.5 sort function)
take the first 6.
Think of it as like shuffling a deck of cards, that you cannot pull the same card twice.
All "unique".
What about trying with a while cycle?
while(random2 == random1 || random2 == random3)
{
random2= math.....;
}
I have a small script that increments the number by the number in a given time period. If incrementing by one value++ works, if I want to add another value of the type generated by the math.random function instead of adding, add to the existing value. How can I change this? I want the generated number to add to an existing value in innerHTML.
document.getElementById("data-gen").innerHTML = Math.floor((Math.random() * 100000) + 1) + Math.floor((Math.random() * 100) + 1);
nowResources = function() {
document.getElementById("data-gen").innerHTML += Math.floor((Math.random() * 10) + 1);
setTimeout(nowResources, 1000);
}
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>
You append numbers to a string. Convert your innerHTML to a number with parseInt and it'll work as you expecting.
document.getElementById("data-gen").innerText = Math.floor((Math.random() * 100000) + 1) + Math.floor((Math.random() * 100) + 1);
nowResources = function() {
// parseInt( yourString, radix )
const num = parseInt( document.getElementById("data-gen").innerText, 10 );
document.getElementById("data-gen").innerText = num + Math.floor((Math.random() * 10) + 1);
setTimeout(nowResources, 1000);
}
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>
But one downside is, that you are querying the DOM each time you want to change it. It's better to store your number outside of your timeout and use an interval like this:
let num = Math.floor((Math.random() * 100000) + 1) + Math.floor((Math.random() * 100) + 1);
document.getElementById("data-gen").innerText = num;
nowResources = function() {
num += Math.floor((Math.random() * 10) + 1);
document.getElementById("data-gen").innerText = num;
}
setInterval( nowResources, 1000 );
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>
This way you don't need to parse your number with each iteration.
When you use + it takes as string and concatenate as a string, convert it to an integer using parseInt
document.getElementById("data-gen").innerHTML = parseInt( document.getElementById("data-gen").innerHTML) + (Math.floor((Math.random() * 10) + 1));
DEMO
document.getElementById("data-gen").innerHTML = Math.floor((Math.random() * 100000) + 1)+ Math.floor((Math.random() * 100) + 1);
nowResources = function() {
document.getElementById("data-gen").innerHTML = parseInt( document.getElementById("data-gen").innerHTML) + (Math.floor((Math.random() * 10) + 1));
setTimeout(nowResources, 1000);
}
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>
To keep the logic clear, just use a local variable to store the value, no need to backward converting via parseInt and weary (and expensive, and messy) DOM element methods dancing:
var value = 0;
function setValue(addValue) {
value += addValue;
document.getElementById("data-gen").innerHTML = value;
}
nowResources = function() {
setValue(Math.floor((Math.random() * 10) + 1))
setTimeout(nowResources, 1000);
}
nowResources();
I'm generating a random number with the code below:
Math.floor((Math.random() * 9999) * 7);
Some of the results I'm getting:
45130,
2611,
34509,
36658
How would I get results like this(with 2 letters included):
TT45130,
PO2611,
KL34509,
GH36658
Side question:
What is the range of numbers that Math.random() carries? Can I set a specific range of values? Not necessary to answer but just curious.
You can use a function like below to get a random uppercase character:
function getRandomUppercaseChar() {
var r = Math.floor(Math.random() * 26);
return String.fromCharCode(65 + r);
}
So to generate a code as you specified with a two-letter prefix:
function generateCode() {
var prefix = new Array(2).fill().map(() => getRandomUppercaseChar()).join(""),
integer = Math.floor((Math.random() * 9999) * 7);
return prefix + integer;
}
NOTE: The above generateCode function uses modern ES6 and ES5 javascript, which is perfectly fine in a modern environment (such as Node.js or a current browser). However, if you wanted greater compatibility (for example, to ensure that it works in old browsers), you could rewrite it like so:
function generateCode() {
var integer = Math.floor((Math.random() * 9999) * 7);
for (var i = 0, prefix = ""; i < 2; ++i)
prefix += getRandomUppercaseChar();
return prefix + integer;
}
Try the simpler answer
var randomNumber = function () {
return Math.floor((Math.random() * 9999) * 7);
}
var randomChar = function () {
return String.fromCharCode(64 + Math.floor((Math.random() * 26)+1));
}
console.log(randomChar()+randomChar()+randomNumber());
//Sample outputs
HB10527 DR25496 IJ12394
Or you can use Number#toString for this purpose with radix = 36.
function getRChar() {
return (Math.random() * 26 + 10 | 0).toString(36).toUpperCase();
}
var s = getRChar() + getRChar() + Math.floor((Math.random() * 9999) * 7);
document.write(s);
If you need to generate a random string with JS, the most common way is to define an alphabet and pick random indices from that:
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numbers = "0123456789";
var randomString = "";
// Pick two random chars
for (var i = 0; i < 2; i++) {
var rand = Math.floor(Math.random()*alphabet.length);
randomString = randomString + alphabet.charAt(rand);
}
// Pick four random digits
for (var i = 0; i < 4; i++) {
var rand = Math.floor(Math.random()*numbers.length);
randomString = randomString + numbers.charAt(rand);
}
// randomString now contains the string you want
Sample strings:
OJ8225
YL5053
BD7911
ES0159
You could use String.fromCharCode() with a random integer between 65 and 90 to get an uppercase letter, i.e.
String.fromCharCode(Math.random() * 26 + 65) + String.fromCharCode(Math.random() * 26 + 65) + Math.floor((Math.random() * 9999) * 7);
gives med the results: "SH21248", "BY42401", "TD35918".
If you want to guarantee that the string always has the same length, you could also use
String.fromCharCode(Math.random() * 26 + 65) + String.fromCharCode(Math.random() * 26 + 65) + Math.floor(Math.random() * 59993 + 10000);
Math.random() always returns a number between 0 and 1, but never 0 or 1 exactly.
An array of the alphabet, a random number is generated to get a random letter, repeated to get a second random letter and then joined to the random number generated as in your code:
var alphabet=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
var ranletter1 = alphabet[Math.floor(Math.random() * alphabet.length)];
var ranletter2 = alphabet[Math.floor(Math.random() * alphabet.length)];
var ranNum = Math.floor((Math.random() * 9999) * 7);
var ranCode = ranletter1 + ranletter2+ ranNum;
How can I return a random number in javascript which is always greater then the previous random number every time the code reruns. For example when the code runs first time it returns 1000 and then when it runs second time it returns 1300.
Conditions: The number must always be an integer.
function randomFunction() {
var x = 0
return function() {
x = x + Math.round( Math.random() * 100 )
return x
}
}
var nextRandom = randomFunction()
nextRandom() // => 51
nextRandom() // => 127
nextRandom() // => 203
How about this?
function myRnd(prev, max) {
return prev + Math.floor(Math.random() * max) + 1;
}
var last;
last = myRnd(1000, 500);
last = myRnd(last, 500);
EDIT
Being inspired by #dimakura's outstanding answer, here is my closure-based function which accepts start value and next max random step:
function myRndFunc(baseValue) {
return function(max) {
baseValue += Math.floor(Math.random() * max) + 1;
return baseValue;
};
}
var myRnd = myRndFunc(1000);
myRnd(300);
myRnd(500);
How about simply adding the previous number?
Try this :
for (i = 0; i < n; i++) {
newR = Math.floor((Math.random() * 1000) + oldR);
// use newR here.
oldR = newR;
}
Conbine Math.random() with Math.floor() setting the minimum end of your range to the last result.
var min = 0;
var max = 10000;
$("#randomise").click(function() {
var result = Math.floor(Math.random() * (max - min)) + min;
$("#result").text(result);
min = result;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
<button id="randomise">Randomise</button>
I am creating a "whack-a-mole" style game for primary school children where they have to click on the correct number in correspondence to the sum given.
At the moment the program is generating addition sums like this.
function createPlusSum(total) {
console.log(total)
var int1 = Math.ceil(Math.random() * total);
var int2 = total - int1;
$('#target').html(int1 + ' + ' + int2 + ' = ?');
}
I have done this again for subtraction and it works, but I don't know where to go from here in regards to randomizing whether an addition or subtraction question is produced. Here is the function to produce a subtraction question.
function createTakeSum(total) {
console.log(total)
var int1 = Math.ceil(Math.random() * total);
var int2 = total + int1;
$('#target').html(int2 + ' - ' + int1 + ' = ?');
}
I use this to create the addition sums
createPlusSum(total);
How would I say I want
createPlusSum(total);
or
createTakeSum(total);
Try this:
function createSum() {
total = Math.ceil(Math.random() * 10);
if(Math.random() > 0.5)
{
createTakeSum(total);
} else {
createPlusSum(total)
}
}
I would use random numbers again:
var rand = Math.floor(Math.random()*2);
switch (rand) {
case 0:
createPlusSum(total);
break;
case 1:
createTakeSum(total);
break;
}
I am not suggesting that this is how you should do it, but I am merely providing an alternative answer for thoroughness. (Pardon me, if the code is wrong. I'm a bit rusty with JS.
{
0: createPlusSum,
1: createTakeSum
}[Math.floor(Math.random() * 2)](total);
you can assign functions to array fields and call them random.
var func = new Array();
func[0] = function createPlusSum(total) {....};
func[1] = function createTakeSum(total) {....};
var rand = Math.floor(Math.random() * func.length);
func[rand](total);
this should do the trick, plus you can add as many functions as you want, just append them to the "func"-array
Here's a script that creates a random "add" or "subtract" question within the given range, and posts the correct answer in the console.log:
<div id="target"></div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
var total = {low: 10, high: 30}; // range
jQuery(document).ready(function() {
var total = Math.floor(Math.random() * (total.high - total.low) + total.low);
var int1 = Math.floor(Math.random() * total);
var int2 = total - int1;
if (Math.random() > 0.5) { // add
var question = int1 + ' + ' + int2 + ' = ?';
var answer = total;
}
else { // subtract
var question = total + ' - ' + int1 + ' = ?';
var answer = int2;
}
$('#target').html(question);
console.log('Correct answer: ' + answer);
});
</script>
Here's the working jsFiddle example