jQuery - choosing sum at random - javascript

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

Related

Javascript: Question Not being displayed and message when correctly answered or incorrectly answer

In my program, it is supposed to generate 2 random numbers and then the user asked what number do you get if you multiply the numbers. When I tried running it, it does not display the part of the question which tells you what the equation is. I debugged it, but it does not show any issues. I was wondering if anyone can tell me how to solve my problem. I am sorry about any inconvenience, I am new to javascript, so I really need help.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunctions()">Try it</button>
<p id="demo"></p>
<script>
function myFunctions() {
let random1 = Math.floor(Math.random() * 100 + 1);
let random2 = Math.floor(Math.random() * 100 + 1);
let answer = random1 * random2;
let counter = 0;
let max = 5;
while (attempts != answer) {
var attempts = prompt('Please answer what is', random1, '*', random2);
counter += 1;
if (counter > max) {
console.log(
'You have no more tries left.',
'The answer was',
answer,
'.'
);
}
if (attempts == answer) {
console.log(
'Congrats the number was',
answer,
'and it took you',
counter,
'tries!'
);
}
}
}
console.log(myFunctions);
</script>
</body>
</html>
Your function should be like this:
The prompt function has 2 params, the first is required which is the text to display, the second is optional (default text).
also do not use ',' in console.log function to concatenate strings.
function myFunctions() {
let random1 = Math.floor((Math.random() * 100) + 1);
let random2 = Math.floor((Math.random() * 100) + 1);
let answer = random1 * random2;
let counter = 0;
let max = 5;
while (attempts != answer) {
var attempts = prompt("Please answer what is " + random1 + " * " + random2);
counter += 1;
if (counter > max) {
console.log("You have no more tries left. The answer was" + answer +".");
break;
}
if (attempts == answer) {
console.log("Congrats the number was " + answer + " and it took you " + counter + " tries!");
}
}
}
Good luck!

Limit to 2 decimals result in JavaScript

I have an issue with the decimals in a result in my script, it gives unlimited decimals, I want to limit it to 2, I have tried using to.fixed(2) without luck, but the script broke.
This is my script:
$.each(rows, function () {
quantity = $(this).find('[data-quantity]').val();
if (quantity == '') {
quantity = 1;
$(this).find('[data-quantity]').val(1);
}
_amount = parseFloat($(this).find('td.rate input').val()) * quantity;
$(this).find('td.amount').html(_amount);
subtotal += _amount;
row = $(this);
item_taxes = $(this).find('select.tax').selectpicker('val');
if (item_taxes) {
$.each(item_taxes, function (i, taxname) {
taxrate = row.find('select.tax [value="' + taxname + '"]').data('taxrate');
calculated_tax = (_amount / 100 * taxrate);
if (!taxes.hasOwnProperty(taxname)) {
if (taxrate != 0) {
_tax_name = taxname.split('|');
tax_row = '<tr class="tax-area"><td>' + _tax_name[0] + '(' + taxrate + '%)</td><td id="tax_id_' + slugify(taxname) + '"></td></tr>';
$(discount_area).after(tax_row);
taxes[taxname] = calculated_tax;
}
} else {
// Increment total from this tax
taxes[taxname] = taxes[taxname] += calculated_tax;
}
});
}
});
The code line that does the operation is:
calculated_tax = (_amount / 100 * taxrate);
The correct is toFixed(), not to.fixed(), see the example:
let number = 12.128361;
let _amount = number.toFixed(2);
let calculated_tax = (_amount / 100 * 100);
console.log(calculated_tax);
Use this method to round to any amount of decimal places:
let v = 3.486894716724;
let rounded = Math.round(v * 100) / 100; // => 3.49
Multiply and divide by 10 to round to one DP, 100 for 2DP, 1000 for 3, etc...

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;

generate 4 digit random number using substring

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

JavaScript stops execution half way and evaluates wrong answer?, Console.log is correct

I didn't think this was possible until console.log(); shown me that whats happening is impossible.
I can't understand how this is possible it's like those variables are being modified before code execution finishes.
I got this JavaScript code with debugging in it.
It's wrapped in this.
$('#buyAmountInput').keyup(function () {
var buyAmount = parseFloat($(this).val());
var totalPrice = 0;
var max = $(this).attr("max");
var min = $(this).attr("min");
if (buyAmount != $(this).val()) {
if (isNaN(buyAmount)) {
buyAmount = 1;
$(this).val('');
} else {
$(this).val(buyAmount);
}
} else {
if (buyAmount > max) {
buyAmount = max;
$(this).val(buyAmount);
} else if (buyAmount < min) {
buyAmount = min;
//$(this).val(buyAmount);
}
}
totalPrice = buyAmount * unitPrice;
//lots of code trimmed off here.
largessAmount = Math.round(buyAmount * largessRule.rebate) / 100;
////
console.log("Buy amount " + buyAmount + " LargessRebate " + largessRule.rebate);
console.log("Total Price " + totalPrice);
console.log("Largess Amount " + largessAmount);
console.log("New rate " + Number(totalPrice / (buyAmount + largessAmount)).moneyFormat());
console.log("No .moneyFormat() New rate " + Number(totalPrice / (buyAmount + largessAmount)));
console.log("( " + totalPrice + " / ( " + buyAmount + " + " + largessAmount + " ))");
////
$('#unitPrice').html(Number(totalPrice / (buyAmount + largessAmount)).moneyFormat());
});
Debug looks like this
Buy amount 5000 LargessRebate 20
Total Price 4250
Largess Amount 1000
New rate 0.71
No .moneyFormat() New rate 0.7083333333333334
( 4250 / (5000 + 1000))
function fastKeyListener content_script.js:208
Buy amount 5000 LargessRebate 20
Total Price 4250
Largess Amount 1000
New rate 0.00 //<- What happened here
No .moneyFormat() New rate 0.00008499830003399932 //<- What happened here
( 4250 / (5000 + 1000)) //<- Third line executed this will give good rate..
Even if the variables are global and this code is in a keypress up jQuery callback function.
The variables are printed before they are executed by console.log() and they are correct but the answer is dead wrong.
Here is the moneyFormat() which I don't think could be the problem could it?
var effective_bit = -2;
Number.prototype.moneyFormat = function () {
var num = this;
sign = (num == (num = Math.abs(num)));
num = Math.floor(num * Math.pow(10, -effective_bit) + 0.50000000001);
cents = num % Math.pow(10, -effective_bit);
num = Math.floor(num / Math.pow(10, -effective_bit)).toString();
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
num = num.substring(0, num.length - (4 * i + 3)) + ', ' + num.substring(num.length - (4 * i + 3));
if (effective_bit < 0) {
if (cents < 10 && effective_bit == '-2') cents = "0" + cents;
money = (((sign) ? '' : '-') + num + '.' + cents);
} else {
money = (((sign) ? '' : '-') + num);
}
return money;
};
I didn't post the whole code as it's very large, but you can see it live here
Just put into the Unit to buy of 4999, then scroll to 5000 it's all good.. try putting like 5001 or 50000 it will reset it to 5000 and give wrong answer in the process.
EDIT:
could of simplified the question to why does the console.log() functions evaluate incorrect answer if the same equation generated with the same variables just 1 line after in execution after gives correct answer, even on calculator.
Like some quantum going on here, bear with me there is nothing I could have done from 1 line to another line during that code-execution no breakpoints were set nothing plus those callbacks are functions generated in their own sandbox I believe so they are like ajax threads all working to complete sooner or later they all work separately from each other, so nothing working together here to mess it up. What you think could possibly happen here? some temporarily corruption or something?
This occurs sometimes when doing claulations using string variables.
Try converting the buyAmount and any variable that came from HTML to number before any calculation.
You can use the Number() function or parseFloat().
http://jsfiddle.net/rcdmk/63qas2kw/1/

Categories