Adding numbers instead of adding increment - javascript

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();

Related

How to get a for loop create a string of 9 random 1digit number?

I need to create a random number generator with 9 total digit created from a random 1 digit number generated thru a for loop .
This one works but i need to use a for loop for it :
var random1 = Math.floor(Math.random() * 9) + 1 ;
var random2 = Math.floor(Math.random() * 9) + 1 ;
var random3 = Math.floor(Math.random() * 9) + 1 ;
var random4 = Math.floor(Math.random() * 9) + 1 ;
var random5 = Math.floor(Math.random() * 9) + 1 ;
var random6 = Math.floor(Math.random() * 9) + 1 ;
var random7 = Math.floor(Math.random() * 9) + 1 ;
var random8 = Math.floor(Math.random() * 9) + 1 ;
var random9 = Math.floor(Math.random() * 9) + 1 ;
// ... and then dump the random number into our random-number div.
$("#random-number").text(""+ random1 + random2 + random3 + random4 + random5 + random6 + random7 + random8 + random9);
var results = ""+ random1 + random2 + random3 + random4 + random5 + random6 + random7 + random8 + random9 ;
$("#results").prepend(results + " <br>");
the above code works in creating a random 9 digit number but i need to use a for loop to make my code concise .
You can use for loop. Create a string and in each loop concentrate the new random number with that string.
let random = '';
for(let i =0;i<9;i++){
random += Math.floor(Math.random() * 9) + 1 ;
}
$("#random-number").text(random);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="random-number"></div>
Another way can be using map() and join()
let random = [...Array(9)].map(x => Math.floor(Math.random() * 9) + 1).join('')
$("#random-number").text(random);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="random-number"></div>
You can try this way with all digits is in range [0, 9] and you should relize that first digit can be zero:
var digits = [];
for (let i=0; i<9; i++) {
let n = Math.floor(Math.random()*10);
digits.push( n );
}
var number = digits.join('')
Construct a new array where the items are random numbers and then join the array with an empty string.
const random = length => Array.from(Array(length), _ => Math.floor(Math.random() * 9) + 1).join('');
console.log(random(9));
console.log(random(9));
console.log(random(9));
console.log(random(9));
console.log(random(9));
In case you want to have all the 9 number to be unique you can use a object to keep track of added previously added numbers and if it is not included add a it to random number as well as object
let random = '';
let included = {}
for(let i =0;i<9;i++){
let temp = true
while(temp){
let num = Math.floor(Math.random() * 9) + 1 ;
if(included[num] === undefined){
temp = false
random += num
included[num] = num
}
}
}
$("#random-number").text(random);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="random-number"></div>

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 !

Loop keeps returning the same integer

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;

Math.random and mixture of letters abcd etc

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;

Generate incremented random numbers between 0 to 100 every second where new number should be greater than the previous nymber

I need a javascript where with every second call i get a random number between 0-100 where current number should be greater than previous number. I wrote a code to get random numbers every second but stuck at generating it with increment.
<script>
var span = document.getElementsByTagName("span")[3];
var i = 100;
(function randNumber() {
var a = Math.floor((Math.random() * i) + 1);
span.innerHTML = "RandNumber: " + a;
setTimeout( randNumber, 1000);
})();
Note : The numbers should generate randomly.
example result may be : 2,5,7,8,22,23,34,56,78,88.....
You should not create a new random number between zero and your maximum (i), but just between the last created number (lastNumber) and max (i).
Also you might want to stop, when the random numbers reached the maximum.
var span = document.getElementsByTagName("span")[3],
i = 100,
lastNumber = 0;
function randNumber() {
lastNumber = lastNumber + Math.floor( Math.random() * (i - lastNumber) + 1 );
span.innerHTML = lastNumber;
if( lastNumber < i ) {
setTimeout( randNumber, 1000 );
}
}
randNumber();
AS for the comments and the requirement of a minimum amount of steps until reaching the maximum:
In each iteration, just increase you number by a random value between 1 and ((max - min) / steps. It is pretty much the same code as above.
var span = document.getElementsByTagName("span")[3],
max = 100,
min = 0,
lastNumber = 0,
minSteps = 30;
// how wide can the average step be at most?
var stepWidth = (max - min) / minSteps;
function randNumber() {
lastNumber = lastNumber + Math.floor( Math.random() * stepWidth + 1 );
span.innerHTML = lastNumber;
if( lastNumber < max ) {
setTimeout( randNumber, 1000 );
}
}
randNumber();
If you extract the "between two numbers" logic into its own function like this, this becomes a lot easier. This way, you just generate a number between your last generated number and your maximum.
var max = 100
var last_number = 1
var interval_id = setInterval(function(){
last_number = get_random_number_greater_between(last_number, max)
span.innerHTML = "RandNumber: " + last_number;
if(last_number >= max){
window.clearInterval(interval_id)
}
}, 1000)
function get_random_number_greater_between(low, high){
return Math.floor(Math.random() * (high - low + 1) + low);
}
Try this:
// generate a random number from 0 to max - 1.
function rand(max) {
return Math.floor(max * Math.random());
}
// generate a random number from min to max.
function range(min, max) {
return min + rand(1 + max - min);
}
// the loop function
function next(n, callback) {
var m = range(n, 100);
if (m < 100) setTimeout(next, 1000, m + 1, callback);
callback(m);
}
var span = document.getElementById("rand");
next(0, function (m) {
span.innerHTML = "Random number: " + m;
});
<span id="rand"></span>

Categories