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);
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;
I am trying to execute below code:
var a = Math.floor(100000 + Math.random() * 900000);
a = a.substring(-2);
I am getting error like undefined is not a function at line 2, but when I try to do alert(a), it has something. What is wrong here?
That's because a is a number, not a string. What you probably want to do is something like this:
var val = Math.floor(1000 + Math.random() * 9000);
console.log(val);
Math.random() will generate a floating point number in the range [0, 1) (this is not a typo, it is standard mathematical notation to show that 1 is excluded from the range).
Multiplying by 9000 results in a range of [0, 9000).
Adding 1000 results in a range of [1000, 10000).
Flooring chops off the decimal value to give you an integer. Note that it does not round.
General Case
If you want to generate an integer in the range [x, y), you can use the following code:
Math.floor(x + (y - x) * Math.random());
This will generate 4-digit random number (0000-9999) using substring:
var seq = (Math.floor(Math.random() * 10000) + 10000).toString().substring(1);
console.log(seq);
I adapted Balajis to make it immutable and functional.
Because this doesn't use math you can use alphanumeric, emojis, very long pins etc
const getRandomPin = (chars, len)=>[...Array(len)].map(
(i)=>chars[Math.floor(Math.random()*chars.length)]
).join('');
//use it like this
getRandomPin('0123456789',4);
$( document ).ready(function() {
var a = Math.floor(100000 + Math.random() * 900000);
a = String(a);
a = a.substring(0,4);
alert( "valor:" +a );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Your a is a number. To be able to use the substring function, it has to be a string first, try
var a = (Math.floor(100000 + Math.random() * 900000)).toString();
a = a.substring(-2);
You can get 4-digit this way .substring(startIndex, length), which would be in your case .substring(0, 4). To be able to use .substring() you will need to convert a to string by using .toString(). At the end, you can convert the resulting output into integer by using parseInt :
var a = Math.floor(100000 + Math.random() * 900000)
a = a.toString().substring(0, 4);
a = parseInt(a);
alert(a);
https://jsfiddle.net/v7dswkjf/
The problem is that a is a number. You cannot apply substring to a number so you have to convert the number to a string and then apply the function.
DEMO: https://jsfiddle.net/L0dba54m/
var a = Math.floor(100000 + Math.random() * 900000);
a = a.toString();
a = a.substring(-2);
$(document).ready(function() {
var a = Math.floor((Math.random() * 9999) + 999);
a = String(a);
a = a.substring(0, 4);
});
// It Will Generate Random 5 digit Number & Char
const char = '1234567890abcdefghijklmnopqrstuvwxyz'; //Random Generate Every Time From This Given Char
const length = 5;
let randomvalue = '';
for ( let i = 0; i < length; i++) {
const value = Math.floor(Math.random() * char.length);
randomvalue += char.substring(value, value + 1).toUpperCase();
}
console.log(randomvalue);
function getPin() {
let pin = Math.round(Math.random() * 10000);
let pinStr = pin + '';
// make sure that number is 4 digit
if (pinStr.length == 4) {
return pinStr;
} else {
return getPin();
}
}
let number = getPin();
Just pass Length of to number that need to be generated
await this.randomInteger(4);
async randomInteger(number) {
let length = parseInt(number);
let string:string = number.toString();
let min = 1* parseInt( string.padEnd(length,"0") ) ;
let max = parseInt( string.padEnd(length,"9") );
return Math.floor(
Math.random() * (max - min + 1) + min
)
}
I've created this function where you can defined the size of the OTP(One Time Password):
generateOtp = function (size) {
const zeros = '0'.repeat(size - 1);
const x = parseFloat('1' + zeros);
const y = parseFloat('9' + zeros);
const confirmationCode = String(Math.floor(x + Math.random() * y));
return confirmationCode;
}
How to use:
generateOtp(4)
generateOtp(5)
To avoid overflow, you can validate the size parameter to your case.
Numbers don't have substring method. For example:
let txt = "123456"; // Works, Cause that's a string.
let num = 123456; // Won't Work, Cause that's a number..
// let res = txt.substring(0, 3); // Works: 123
let res = num.substring(0, 3); // Throws Uncaught TypeError.
console.log(res); // Error
For Generating random 4 digit number, you can utilize Math.random()
For Example:
let randNum = (1000 + Math.random() * 9000).toFixed(0);
console.log(randNum);
This is quite simple
const arr = ["one", "Two", "Three"]
const randomNum = arr[Math.floor(Math.random() * arr.length)];
export const createOtp = (): number => {
Number(Math.floor(1000 + Math.random() * 9000).toString());
}
I really don't know what im doing wrong. I want to change the width of the image to a random number from 0 - 100%. Can someone tell me what i'm doing wrong?
function progress(){
$("body").append("<div class='main_div'></div>");
var x = Math.floor(Math.random() * 10) + 1;
var x = 5;
for(var i = 0; i < x; i++){
$(".main_div").append("<div class='statusbar'></div>");
$(".statusbar:nth-child(" + x + ")").append("<img src='project_status.gif'>");
var c = Math.floor(Math.random() * 100) + 1;
$(".statusbar:nth-child(" + x + ") img").css({ "width", "(" + c +")%" });
}
}
There are errors in your Math.floor() function: Instead of
Math.floor(Math.random() * 10) + 1;
It should be
Math.floor((Math.random() * 10) + 1));
with the +1 within the Math.floor brackets.
I don't know if it would be helpful or not, but I have previously produced a random-size progress bar here: http://jsfiddle.net/cu22W/10/
The issue is with this statement:
$(".statusbar:nth-child(" + x + ") img").css({ "width", "(" + c +")%" });
You should read up on JQuery .css() function : http://api.jquery.com/css/
But when you use the .css() function with { } brackets the syntax is the same as CSS itself.
So for your statement the proper way would be :
.css({ width : c +"%" })
or, if you wanted to keep it the way you have it just remove the { } brackets :
.css( "width", c +"%")
I am also pretty sure you don't need to wrap c in ()
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