JavaScript Variables adds themselves and stacks up - javascript

So when I want to calculate variable1 + variable2 * variable3 it only add themselves and stacks up.
Code:
function randomRange(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function func() {
var pxL = localStorage["pxL"];
var val = document.getElementById("bp").innerHTML;
document.getElementById("bp").innerHTML = funcCalc(val, randomRange(1, 10), pxL);
}
function funcCalc(val, random, px) {
return val + random * px;
}
The thing is that in HTML document there is element which indicates the variable, and the variable would add itself + random and multiply by third variable on button click. The problem is that the variables calculate themselves and instead of changing the innerHTML, they adds it to innerHTML.
HTML:
<stat id="bpT">BPT: <textarea class="statIndic" id="bp" disabled>0</textarea></stat>
I want output like 15 and not 015 etc.

You need to get an integer, not a string:
var pxL = parseFloat(localStorage["pxL"]);
var val = parseFloat(document.getElementById("bp").innerHTML);
document.getElementById("bp").innerHTML = funcCalc(val, randomRange(1, 10), pxL);
.innerHTML returns a string for sure. Depending on how you store the variable, localStorage might return a string or number.
You can also use Number():
var pxL = Number(localStorage["pxL"]);
var val = Number(document.getElementById("bp").innerHTML);

Related

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 !

Why can't I use a variable created using prompt() within a function?

Below is a function which should produce a random number between two numbers which are specified by the user. The equation works if I manually specify the numbers. But if I use the prompt function it seems to produce a completely random number.
function randOm() {
var high = prompt("high");
var low = prompt("low");
return Math.floor(Math.random() * (high - low + 1)) + low;
}
document.write(randOm());
You will need to use parseFloat to convert it to a Number.
Convert the results of the prompt in numbers, because it returns strings:
return Math.floor(Math.random() * ((+high) - (+low) + 1)) + (+low);
prompt is known to return string, hence u have to convert the string to integer before performing your operations.And another disadvantage is that, if the user enters any characters like "hello" or "hi" in the prompt box, your function might return NaN, because cannot parse characters to numbers.
Script:
function randOm() {
var high = prompt("high");
var low = prompt("low");
var h=parseInt(high);
var l=parseInt(low);
return Math.floor(Math.random() * (h - l + 1)) + l;
}
document.write(randOm());
if (Number.isNaN(high) || Number.isNaN(low)){
alert ("both entries must be numbers!");
}
else{
low = parseFloat(low);
high = parseFloat(high);
return Math.floor(Math.random() * (high - low + 1)) + low;
}

Random integer in a certain range excluding one number

I would like get a random number in a range excluding one number (e.g. from 1 to 1000 exclude 577). I searched for a solution, but never solved my issue.
I want something like:
Math.floor((Math.random() * 1000) + 1).exclude(577);
I would like to avoid for loops creating an array as much as possible, because the length is always different (sometimes 1 to 10000, sometimes 685 to 888555444, etc), and the process of generating it could take too much time.
I already tried:
Javascript - Generating Random numbers in a Range, excluding certain numbers
How can I generate a random number within a range but exclude some?
How could I achieve this?
The fastest way to obtain a random integer number in a certain range [a, b], excluding one value c, is to generate it between a and b-1, and then increment it by one if it's higher than or equal to c.
Here's a working function:
function randomExcluded(min, max, excluded) {
var n = Math.floor(Math.random() * (max-min) + min);
if (n >= excluded) n++;
return n;
}
This solution only has a complexity of O(1).
One possibility is not to add 1, and if that number comes out, you assign the last possible value.
For example:
var result = Math.floor((Math.random() * 100000));
if(result==577) result = 100000;
In this way, you will not need to re-launch the random method, but is repeated. And meets the objective of being a random.
As #ebyrob suggested, you can create a function that makes a mapping from a smaller set to the larger set with excluded values by adding 1 for each value that it is larger than or equal to:
// min - integer
// max - integer
// exclusions - array of integers
// - must contain unique integers between min & max
function RandomNumber(min, max, exclusions) {
// As #Fabian pointed out, sorting is necessary
// We use concat to avoid mutating the original array
// See: http://stackoverflow.com/questions/9592740/how-can-you-sort-an-array-without-mutating-the-original-array
var exclusionsSorted = exclusions.concat().sort(function(a, b) {
return a - b
});
var logicalMax = max - exclusionsSorted.length;
var randomNumber = Math.floor(Math.random() * (logicalMax - min + 1)) + min;
for(var i = 0; i < exclusionsSorted.length; i++) {
if (randomNumber >= exclusionsSorted[i]) {
randomNumber++;
}
}
return randomNumber;
}
Example Fiddle
Also, I think #JesusCuesta's answer provides a simpler mapping and is better.
Update: My original answer had many issues with it.
To expand on #Jesus Cuesta's answer:
function RandomNumber(min, max, exclusions) {
var hash = new Object();
for(var i = 0; i < exclusions.length; ++i ) { // TODO: run only once as setup
hash[exclusions[i]] = i + max - exclusions.length;
}
var randomNumber = Math.floor((Math.random() * (max - min - exclusions.length)) + min);
if (hash.hasOwnProperty(randomNumber)) {
randomNumber = hash[randomNumber];
}
return randomNumber;
}
Note: This only works if max - exclusions.length > maximum exclusion. So close.
You could just continue generating the number until you find it suits your needs:
function randomExcluded(start, end, excluded) {
var n = excluded
while (n == excluded)
n = Math.floor((Math.random() * (end-start+1) + start));
return n;
}
myRandom = randomExcluded(1, 10000, 577);
By the way this is not the best solution at all, look at my other answer for a better one!
Generate a random number and if it matches the excluded number then add another random number(-20 to 20)
var max = 99999, min = 1, exclude = 577;
var num = Math.floor(Math.random() * (max - min)) + min ;
while(num == exclude || num > max || num < min ) {
var rand = Math.random() > .5 ? -20 : 20 ;
num += Math.floor((Math.random() * (rand));
}
import random
def rng_generator():
a = random.randint(0, 100)
if a == 577:
rng_generator()
else:
print(a)
#main()
rng_generator()
Exclude the number from calculations:
function toggleRand() {
// demonstration code only.
// this algorithm does NOT produce random numbers.
// return `0` - `576` , `578` - `n`
return [Math.floor((Math.random() * 576) + 1)
,Math.floor(Math.random() * (100000 - 578) + 1)
]
// select "random" index
[Math.random() > .5 ? 0 : 1];
}
console.log(toggleRand());
Alternatively, use String.prototype.replace() with RegExp /^(577)$/ to match number that should be excluded from result; replace with another random number in range [0-99] utilizing new Date().getTime(), isNaN() and String.prototype.slice()
console.log(
+String(Math.floor(Math.random()*(578 - 575) + 575))
.replace(/^(577)$/,String(isNaN("$1")&&new Date().getTime()).slice(-2))
);
Could also use String.prototype.match() to filter results:
console.log(
+String(Math.floor(Math.random()*10))
.replace(/^(5)$/,String(isNaN("$1")&&new Date().getTime()).match(/[^5]/g).slice(-1)[0])
);

How do I replace every dash (-) with a random number in javascript?

I have have some codes like ABCDE-----ABCD----ABC--, where each (-) needs to be a random number.
I have no problem using the replace function to change a single dash to a random number, but I have no clue how to make each dash a random number. Note: each number doesn't need to be unique.
Here is where I am now, but I need the numbers to not all be the same. http://jsfiddle.net/oqrstsdm/
var minNumber = 1;
var maxNumber = 9;
randomNumberFromRange(minNumber, maxNumber);
function randomNumberFromRange(min, max) {
var number = (Math.floor(Math.random() * (max - min + 1) + min));
var str = "ABCDE-----FGABC--";
var res = new RegExp("-", "g");
var code = str.replace(res, number);
document.getElementById("ccode").innerHTML = "Code: " + code;
}
You could use a function as second argument in String.prototype.replace().
var str = "ABCDE-----FGABC--";
var code = str.replace(/-/g, function() {
return Math.floor(Math.random() * (max - min + 1)) + min;
});
Do it in a while loop. Also you don't actually need a regular expression since you're just looking for a string. If you did want a regexp change str.indexOf("-") !== -1 by str.match(regexp) !== null. You also wont need the g flag with this approach.
var str = "ABCDE-----FGABC--";
var number;
while (str.indexOf("-") !== -1) {
number = Math.floor(Math.random() * 10);
str = str.replace("-", number);
}
return str;
Output:
ABCDE92136FGABC38
As an alternative to the replace method, you can use the String split method to tokenize the code, and then apply an Array reduce method to re-join the values with the appropriate numbers substituted in.
function randomNumberFromRange(min, max) {
var str = "ABCDE-----FGABC--";
return str.split("-").reduce(function(prev, val) {
return prev + rand(min, max) + val;
});
}
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// Demo code
document.getElementById("random").onclick = function() {
document.getElementById("code").innerHTML = randomNumberFromRange(1, 9);
};
<div id="code"></div>
<div>
<button id="random">Get Code</button>
</div>

Javascript: cannot override concatenation

Using the following code I want to move a line with id='seekline' by var1 (less than .1 in most cases), but I run into trouble adding var1 and j.
The plus sign concatenates instead of adding. I have tried using Number(), parseInt(), parseFloat(), and forcing addition by multiplying by 1 or adding by 0. For some reason I cannot stop the concatenation. When I use parseInt() or parseFloat() (e.g. parseInt(j,10)) the code stops working.
The string split is to remove the px from element.style.left.
function move(var1) {
element = document.getElementById('seekline');
console.log(var1, element.style.left);
var str=(element.style.left);
var n=str.split("p");
var j = n[0];
Number(j);
Number(var1);
var k = var1 + j;
var f = k.concat("px");
console.log(j, k, f);
element.style.left = f;
}
You need to assign the result of the call to Number(), as it returns the numeric value of the string passed instead of modifying the variable itself.
Note that +foo is the same as doing Number(foo).
function move(var1) {
var style = document.getElementById('seekline').style;
// removes last two 'px' characters
var oldValue = +style.left.slice(0, -2);
// converts to number type, then adds 2 to it
var1 = +var1;
var1 += 2;
// check to see if number is NaN or +/-Infinity
if (isFinite(var1)) {
// only now string concatenates the term 'px' to it
element.style.left = oldValue + var1 + 'px';
}
}
function move(var1) {
var element = document.getElementById('seekline'),
left = parseInt(element.style.left.replace('px',''),10);
element.style.left = ((left++) + var1) + 'px';
}
The secret for you to work with numbers obtained from JavaScript, is to remove the string 'px' and convert them to numbers:
parseInt(element.style.left.replace('px', ''))

Categories