While loop not stoping with random number - javascript

i'm trying to generate random number between 0 and 10, but loop is not stops when it came to 10
function testNumber () {
let i = (Math.floor(Math.random() * 10)+1)
while (i < 10) {
setInterval(() => {
document.write("Random number: " + (Math.floor(Math.random() * 10)+1)
)},1000)
return i;
}
}
function test() {
testNumber();
}

I'm not sure I understood your question, but if I did, you want to keep generating random numbers less or equal to 10, until you get 10 and show them in HTML. This is the solution for that:
HTML:
<div class="num"> </div>
JS:
const num = document.querySelector('.num');
function testNumber () {
let i = (Math.floor(Math.random() * 11)
while (i !== 10) {
num.innerHTML = `${num.innerHTML}Random number: ${i}<br>`
i = (Math.floor(Math.random() * 11)
}
}

If you want to "stop generating random numbers when you get 10", you'll probably want something like this:
function testNumber() {
let counter = 0
while (counter < 10) {
setInterval(() => {
document.write("Random number: " + (Math.floor(Math.random() * 11))
)},1000)
counter++;
}
}
testNumber();
Your loop condition is currently your random number, that's why it will run until the number is 10 by chance. You need to initialize a separate counter variable which gets incremented in each iteration of your loop.
Also your current calculation Math.floor(Math.random() * 10) + 1 would only return numbers from 1 to 10 (excluding 0).
And read about the setInterval function. I'm not sure if that's what you actually want to achieve.

I think you never change i in loop.
this works:
function testNumber () {
let i=(Math.floor(Math.random() * 10)+1)
const interval=
setInterval( () => {
i=(Math.floor(Math.random() * 10)+1)
document.write("Random number: " +i.toString())
if(i==10) clearInterval(interval)},1000)
}
function test () {
testNumber()
}
test()
clearInterval(interval) allows you to exit interval.

Related

how to increase a number by 1 after random seconds using jquery?

Is there any way to increase a number by 1 after random seconds.
For example, the base value is 10. So it will change by 1 after a random seconds(ie. 1/2/3/4/5 seconds randomly).
i have tried like this:
var startVal = 10;
setInterval(function(){
var theVal = startVal + 1;
startVal = theVal;
}, Math.round(Math.random() * (6000 - 2000)) + 2000);
Number is increasing but the time is not random. Please help.
If you want the time to change on each iteration, you will need to use setTimeout.
var startVal = 10;
function increase() {
setTimeout(function(){
var theVal = startVal + 1;
startVal = theVal;
increase();
console.log(startVal);
}, Math.round(Math.random() * (6000 - 2000)) + 2000);
}
increase()
Here is a working example. Will raise the number by one after 0,1 or 2 seconds
let number = 10;
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function addNumber() {
number++;
console.log(number)
}
setTimeout(addNumber, getRandomInt(3) * 1000)

Simple for loop does not seem work properly

I'm having a trouble to get an array with numbers from 1 to 16 randomly without repetition.
I made num array to put numbers from createNum function.
The createNum function has a for loop which gets numbers from 1 to 16 until if statement push 16 numbers into num array.
At the end, I run createNum() and display numbers on the web.
While I'm making this code it sometimes worked but now it's not working.
can somebody point out where I made mistakes?
let num = [];
function createNum () {
for (i = 0; i <= 15;) {
let numGen = Math.floor(Math.random() * 15) + 1;
if (!num.includes(numGen)) {
num.push(numGen);
i++;
};
};
}
console.log(createNum());
document.getElementById("selectedNumbersShownHere").innerHTML = num;
console.log(num);
This is because Math.random() never returns 1, so at the end Math.floor(Math.random() * 15) will returns maximum 14 and adding it to 1 will get you maximum 15.
Use Math.ceil instead of Math.floor i.e
let num = [];
function createNum () {
for (i = 0; i <=15;) {
let numGen = Math.ceil(Math.random() * 16);
console.log(numGen)
if (!num.includes(numGen)) {
num.push(numGen);
i++;
};
};
}
console.log(createNum());
document.getElementById("selectedNumbersShownHere").innerHTML = num;
console.log(num);
Hope it helps!
for (i = 0; i <= 15;) generates 16 numbers, but Math.floor(Math.random() * 15) + 1 only have 15 possible values (1~15).
A shuffle function is recommended. Your function would be slow if you generate a large size shuffled array.
How can I shuffle an array?
Your loop seems never finish because the probability to get the last value is very low, and never can happen in a short time.
Plus :
your formula is wrong : let numGen = Math.floor(Math.random() * 15) + 1;
and should be................: let numGen = Math.floor(Math.random() * 16) + 1; value 16
see => Generating random whole numbers in JavaScript in a specific range?
do this:
function createNum()
{
let num =[], lastOne =136; // 136 = 1 +2 +3 + ... +16
for (;;)
{
let numGen = Math.floor(Math.random() *16) +1;
if (!num.includes(numGen))
{
lastOne -= numGen;
if (num.push(numGen)>14) break;
}
}
num.push(lastOne); // add the missing one (optimizing)
return num;
}
let unOrdered_16_vals = createNum();
/*
document.getElementById("selectedNumbersShownHere").textContent = unOrdered_16_vals.join('');
*/
console.log( JSON.stringify( unOrdered_16_vals ), 'length=', unOrdered_16_vals.length );
console.log( 'in order = ', JSON.stringify( unOrdered_16_vals.sort((a,b)=>a-b) ) );
remark : The push() method adds one or more elements to the end of an array and returns the new length of the array.
The problem in your code is that your looking for 16 distinct numbers out of 15 possible values.
The reason for this is that Math.floor(Math.random() * 15) + 1; will only return values between 1 and 15, but your loop will run until you have 16 unique values, so you enter into an infinite loop.
What you're basically trying to achieve is randomly shuffle an array with values from 1 to 16.
One common solution with good performance (O(n)) is the so-called Fisher-Yates shuffle. Here is code that addresses your requirements based on an implementation by Mike Bostock:
function shuffle(array) {
let m = array.length, t, i;
while (m) {
i = Math.floor(Math.random() * m--);
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
// create array with values from 1 to 16
const array = Array(16).fill().map((_, i) => i + 1);
// shuffle
const shuffled = shuffle(array);
console.log(shuffled);
Compared to your approach and the approach of other answers to this question, the code above will only make 15 calls to the random number generator, while the others will make anywhere between 16 and an infinite number of calls(1).
(1) In probability theory, this is called the coupon collector's problem. For a value n of 16, on average 54 calls would have to be made to collect all 16 values.
Try like this :
let num = [];
function createNum () {
for (i = 0; num.length <= 17; i++) {
let numGen = Math.floor(Math.random() * 16) + 1;
if (!num.includes(numGen)) {
num.push(numGen);
};
};
}
console.log(createNum());
document.getElementById("selectedNumbersShownHere").innerHTML = num;
console.log(num);
Please find the working demo here
This is an infinite loop error. Because your loop variable "i" is always less than or equal to 15. and your i++ is inside the if statement. You can achieve it in multiple ways. Below is one sample.
let num = [];
function createNum () {
for (i = 0; i <= 15;) {
let numGen = Math.floor(Math.random() * 15) + 1;
if (!num.includes(numGen)) {
num.push(numGen);
};
i++;
};
}
console.log(createNum());
document.getElementById("selectedNumbersShownHere").innerHTML = num;
console.log(num);
sorry, I'm "passionate" about this question, and I can't resist presenting a second answer, which is IMHO: the best!
function createNum ()
{
let num = []
for (let len=0;len<16;)
{
let numGen = Math.ceil(Math.random() * 16)
if (!num.includes(numGen))
{ len = num.push(numGen) }
}
return num
}
let unOrdered = createNum();
console.log( JSON.stringify( unOrdered ) );
/*
document.getElementById("selectedNumbersShownHere").textContent = unOrdered_16_vals.join('');
*/

Every 1 second increase the value with a random number using decimal numbers

So I'm trying to increment the value of a number in an interval of 1 second with a decimal number between (0.01 and 0.05) and I can't seem to figure this out.
The only thing that it does is to show me numbers between 0.01 and 0.05 instead of adding them up to be an integer.
setInterval (function myFunction() {
var number = 0;
document.getElementById("computerScore").innerHTML = number +
Math.floor((Math.random() * 5) + 1)/100;
}, 1000)
<b>computer score:</b><p id="computerScore">0</p>
Your problem is that you are setting number to 0 in each execution, while it should be the current value.
You need to assign Number(document.getElementById("computerScore").textContent) to it, so it keeps updating with the added random number.
Note that I used textContent which is recommended here as it holds only the text content of the element avoiding HTML elements.
setInterval (function myFunction() {
var number = Number(document.getElementById("computerScore").textContent);
document.getElementById("computerScore").textContent= number +
Math.floor((Math.random() * 5) + 1)/100;
}, 1000)
Demo:
setInterval (function myFunction() {
var number = Number(document.getElementById("computerScore").textContent);
document.getElementById("computerScore").textContent = number +
Math.floor((Math.random() * 5) + 1)/100;
}, 1000)
<b>computer score:</b><p id="computerScore">0</p>
You need to retrieve the previous value from your score and add your random Number to it :
PS: I added .toFixed(2) to limit your result to two decimals.
let score = document.getElementById("computerScore");
setInterval (function myFunction() {
score.innerHTML = (+score.innerHTML + Math.floor((Math.random() * 5) + 1)/100).toFixed(2);
}, 1000)
<b>computer score:</b><p id="computerScore">0</p>
You set number to 0 every time you call the function, you should define number outside of the interval
var number = 0;
setInterval(function myFunction() {
document.getElementById("computerScore").innerHTML = number +
Math.floor((Math.random() * 5) + 1) / 100;
}, 1000)
You need to declare number outside the setTimeout:
var number = 0;
setInterval (function myFunction() {
number = number +
Math.floor((Math.random() * 5) + 1)/100;
document.getElementById("computerScore").innerHTML = number;
}, 1000)
JSFiddle
you can try something like this. You forgot to set the number to 0. Then you have to increment your number with the random value you're getting.
https://codepen.io/anon/pen/dgJpep
JS :
var number = 0;
function check(){
setInterval(function(){
number = number + Math.floor((Math.random() * 5) + 1)/100;
}, 3000);
}
check();
setInterval(function(){
document.getElementById('computerScore').innerHTML = number;
});
Let me know if it works for you !

How to find previous randomly generated number using Math.random in a setInterval function?

I am generating a random number between 1 and 13. This works fine. What I want to do is not generate the same number as the immediate previous number.
function showRandomDotIcon() {
var randomDot = Math.floor(Math.random() * 13) + 1;
console.log(randomDot);
}
setTimeout(showRandomDotIcon, 3500);
So something like:
if(randomDot == previousDot) {
// skip to next number
}
You could take a closure over the last random value and check against it.
function showRandomDotIcon() {
var last;
return function () {
var randomDot;
do {
randomDot = Math.floor(Math.random() * 13) + 1;
} while (last === randomDot)
last = randomDot;
console.log(randomDot);
};
}
setInterval(showRandomDotIcon(), 1000);

How to return a random number in javascript which is always greater then the previous number

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>

Categories