Create two random values with javascript onclick event - javascript

I'm trying to store two random numbers between 0 and 10, in two different variables play1 and play2.
The maximum value for play2 will be 10 minus play1 value, ie, if play1 gets 6, maximum value for play2 will be 4.
how can I trigger play2 to store the second value? I need it to be triggered with a second click.
var min = 0;
var max = 10;
var play1;
var play2;
function myFunction() {
play1 = Math.floor(Math.random() * (max - min + 1)) + min;
max = 10 - play1
document.getElementById("result").innerHTML = play1;
if (play1 < 10 ) {
//trigger play2
}
}
<button onclick="myFunction()">Click me</button>
<p id="result"></p>

You can simply calculate the value of play2 the same way you calculated the value of play1 by using - play2 = Math.floor(Math.random()*(max-min+1)) + min;. I have updated your code below-
var min = 0;
var max = 10;
var play1;
var play2;
function myFunction() {
play1 = Math.floor(Math.random() * (max - min + 1)) + min;
max = 10 - play1
document.getElementById("result").innerHTML = play1;
if (play1 < 10 ) {
play2 = Math.floor(Math.random()*(max-min+1)) + min;
} else {
play2 = 0;
}
document.getElementById("result2").innerHTML = play2;
}
<button onclick="myFunction()">Click me</button>
<p id="result"></p>
<p id="result2"></p>

Don't repeat yourself. That's what functions are for:
function r(min, max){
return Math.floor(Math.random() * (max-min+1)) + min;
}
var min = 0;
var max = 10;
var play1;
var play2;
function myFunction() {
play1 = r(min, max);
play2 = r(min, max - (play1-min));
document.getElementById("result").innerHTML = [play1, play2];
}
<button onclick="myFunction()">Click me</button>
<p id="result"></p>
i need the second value to be triggered with a second click.
function r(min, max){
return Math.floor(Math.random() * (max-min+1)) + min;
}
var min = 0;
var max = 10;
var play1;
var play2;
var nthClick = 0;
function myFunction() {
++nthClick;
if(nthClick & 1){
//odd
play1 = r(min, max);
play2 = null;
}else{
//even
play2 = r(min, max - (play1-min));
}
document.getElementById("result").innerHTML = [play1, play2];
}
<button onclick="myFunction()">Click me</button>
<p id="result"></p>
like this?

Perhaps this
var min = 0;
var max = 10;
var play1;
var play2;
function myFunction() {
var target = document.getElementById("result");
var firstNum = parseInt(target.innerHTML);
if (isNaN(firstNum)) { // first click
play1 = Math.floor(Math.random() * (max - min + 1)) + min;
target.innerHTML = play1;
} else {
play2 = Math.floor(Math.random() * ((10 - firstNum) - min + 1)) + min;
// do what with it????? you haven't shown!
document.getElementById("result2").innerHTML = play2;
}
}
<button onclick="myFunction()">Click me</button>
<p id="result"></p>
<p id="result2"></p>

Try adding a control to the click count. Code copied and modified from Thomas' answer
var controlVariable = 1;
function r(min, max){
return Math.floor(Math.random() * (max-min+1)) + min;
}
var min = 0;
var max = 10;
var play1;
var play2;
function myFunction() {
if (controlVariable == 1) {
play1 = r(min, max);
controlVariable++;
}
else if (controlVariable == 2) {
play2 = r(min, max - (play1-min));
controlVariable = 1;
}
document.getElementById("result").innerHTML = [play1, play2];
}
<button onclick="myFunction()">Click me</button>
<p id="result"></p>

Related

How can I make a math question generator that gives 3 digit addition questions and single digit multiplication questions using JavaScript?

In this code, I am basically trying to create a math question generator, where I want the question generator to randomize between addition subtraction, and multiplication. As of now, I have a code that allows me to create problems that are just single digits, how can I make it so the addition and subtraction questions are 2-3 digits and multiplication is only one digit? (I am new to JavaScript so it is a little bit confusing to me)
I.e. 202+305 = 507
next question
2x4=8
So on and so forth.
Here is the code that I have until now.
<!DOCTYPE html>
<html lang="en">
<body>
<div id="11question"></div>
<input id="answer" />
<button id="check" onclick="check()">Check</button>
</body>
<script>
var operations = {
'+': function (num5, num6) {
return num5 + num6;
},
'-': function (num5, num6) {
return num5 - num6;
},
x: function (num5, num6) {
return num5 * num6;
},
};
var accans;
newquestion();
function newquestion() {
document.getElementById('answer').value = '';
document.getElementById('answer').style.backgroundColor = 'white';
var num5 = Math.floor(Math.random() * 10) + 1;
var num6 = Math.floor(Math.random() * 10) + 1;
var operationChosen = ['+', '-', 'x'][
Math.min(Math.floor(Math.random() * 3))
];
accans = operations[operationChosen](num5, num6);
document.getElementById('11question').innerHTML =
num5 + operationChosen + num6;
}
function check() {
answer = document.getElementById('answer').value;
if (accans == answer) {
document.getElementById('answer').style.backgroundColor = 'green';
setTimeout(newquestion, 1500);
} else if (accans != answer) {
document.getElementById('answer').style.backgroundColor = 'red';
setTimeout(newquestion, 1500);
}
}
</script>
'
</html>
You can define a range by getRandomInt. Check out here
Live Demo:
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
var operations = {
'+': function (num5, num6) {return num5 + num6;},
'-': function (num5, num6) {return num5 - num6;},
'x': function (num5, num6) {return num5 * num6;}
}
var accans
newquestion()
function newquestion() {
document.getElementById('answer').value = "";
document.getElementById('answer').style.backgroundColor = "white";
var operationChosen = ['+','-','x'][Math.min(Math.floor(Math.random()*3))];
if (operationChosen == 'x') {
var num5 = getRandomInt(0,10);
var num6 = getRandomInt(0,10);
}
else {
var num5 = getRandomInt(10,1000);
var num6 = getRandomInt(10,1000);
}
accans = operations[ operationChosen ]( num5, num6 )
document.getElementById("11question").innerHTML = num5 + operationChosen + num6;
}
function check() {
answer = document.getElementById('answer').value;
if (accans == answer) {
document.getElementById('answer').style.backgroundColor = "green";
setTimeout(newquestion, 1500);
}
else if (accans != answer) {
document.getElementById('answer').style.backgroundColor = "red";
setTimeout(newquestion, 1500);
}
}
<div id="11question"></div>
<input id="answer">
<button id="check" onclick="check()">Check</button>

Insert two scripts in the same <script> tag without conflicts

I have to put these two scripts in a single tag without them coming into conflict but I can not make it. Please, how can I do it?
Also is it better to insert multiple scripts in the same tag?
Script 1
var sec = 04;
var hour = 00;
var time0, time1;
var delay=0;
var duringtime = 1000;
time1 = (hour *10000 + min * 100 + parseInt(sec)).toString();
console.log("time1", time1);
function refresh() {
........
}
}
refresh();
Script 2
var min = 80;
var max = 85;
var random = Math.floor(Math.random() * (max - min)) + min;
if (localStorage.getItem("stockcount_99")) {
if (localStorage.getItem("stockcount_99") >= duration) {
var value = random;
} else {
var value = localStorage.getItem("stockcount_99");
}
} else {
var value = random;
}
document.getElementById('divCounter').innerHTML = value;
var stockcount_99 = function() {
if (value <= stopValue) { // end count down. <= or >=
clearInterval(interval);
value = stopValue;
} else {
value = parseInt(value) - 1; // + 1 or - 1
localStorage.setItem("stockcount_99", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(function() {
stockcount_99();
}, speedcontrol);
With the following method can I isolate the two scripts and thus prevent any conflicts?
(function() {
...script 1...
})()
(function() {
...script 2...
})()

Calculation of JQuery in while loop

Trying to calculate Break Even Point (BEP) using jquery:
function roundToTwo(num) {
return +(Math.round(num * 100) / 100);
}
var text = ""
var quantity = 1;
var buy = 0;
var sell = 10;
var bep_pnl = -0.5;
if (buy == 0) {
buy = roundToTwo(sell - 0.01);
while (bep_pnl < 0.01) {
total_amnt_trade = roundToTwo((quantity * buy) + (quantity * sell));
var brokerage_amnt_buy = ((buy * quantity) * 0.08) / 100;
if (brokerage_amnt_buy >= 25) {
var brokerage_buy = 25;
} else {
var brokerage_buy = brokerage_amnt_buy;
}
var brokerage_amnt_sell = ((sell * quantity) * 0.08) / 100;
if (brokerage_amnt_sell >= 25) {
var brokerage_sell = 25;
} else {
var brokerage_sell = brokerage_amnt_sell;
}
var brokerage = roundToTwo(brokerage_buy + brokerage_sell); //brokerage
var transaction_charges = roundToTwo((((buy * quantity) + (sell * quantity)) * 0.00325) / 100); //Transaction Charges
var gst = roundToTwo((((transaction_charges * 18) / 100) + (brokerage * 18) / 100)); //GST
var total_charges = roundToTwo(brokerage + transaction_charges + gst);
bep_pnl = roundToTwo(((sell - buy) * quantity) - total_charges);
text += "<br />New Buy " + buy + " and profit " + bep_pnl;
buy = roundToTwo(buy - 0.01);
}
var bep = roundToTwo(sell - buy);
$('#demo').text(bep);
document.getElementById("testing").innerHTML = text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p id="demo"></p>
<h1 id="testing"></h1>
While running the above codes the result of BEP is 0.04. But it should be 0.
I think it's a technical problem (maybe in while loop) as the formula is correct. (Can be cross-checked in <h1>
It's that extra buy = roundToTwo(buy - 0.01); before the while loop expires that's giving the .04 result. You need to decrement buy at the beginning of the loop, not the end. Set buy = sell before it enters the while, then move buy = roundToTwo(buy - 0.01); to the beginning of the loop.
That would give .03 as the result of var bep = roundToTwo(sell - buy);, which is consistent with the output New Buy 9.97 and profit 0.01.

How can i limit function-(slot play) just for 5 turn - with do/while loop

I wanna create a slot machine with 3 number by javascript - but I want to finish my function when three numbers are equal.
I think that if I write it with do/while it will be work, but I can't do it
this is my js code:
function myF() {
var slotOne = Math.floor(Math.random() * 3) + 1;
var slotTwo = Math.floor(Math.random() * 3) + 1;
var slotThree = Math.floor(Math.random() * 3) + 1;
document.getElementById("slotOne").innerHTML = slotOne;
document.getElementById("slotTwo").innerHTML = slotTwo;
document.getElementById("slotThree").innerHTML = slotThree;
if(slotOne == slotTwo && slotTwo == slotThree) {
document.getElementById("slotOne").style.backgroundColor = "#48bd48";
document.getElementById("slotTwo").style.backgroundColor = "#48bd48";
document.getElementById("slotThree").style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
}
}
this function is set onclick attr of a button tag
Adding to comment, if you want to run function for no of times then just use a counter variable to check no of attempts:
Added a reset button to reset the game.
var counter = 0;
function myF() {
if (counter != 5) {
counter++;
document.getElementById("slotLeft").innerHTML = "Try count: " + counter;
var slotOne = Math.floor(Math.random() * 3) + 1;
var slotTwo = Math.floor(Math.random() * 3) + 1;
var slotThree = Math.floor(Math.random() * 3) + 1;
document.getElementById("slotOne").innerHTML = slotOne;
document.getElementById("slotTwo").innerHTML = slotTwo;
document.getElementById("slotThree").innerHTML = slotThree;
if (slotOne == slotTwo && slotTwo == slotThree) {
document.getElementById("slotOne").style.backgroundColor = "#48bd48";
document.getElementById("slotTwo").style.backgroundColor = "#48bd48";
document.getElementById("slotThree").style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
counter = 5; // Edited this line
}
} else {
console.log('Game over');
}
}
function myF1(){
counter = 0;
document.getElementById("slotOne").innerHTML = "";
document.getElementById("slotTwo").innerHTML = "";
document.getElementById("slotThree").innerHTML = "";
}
<button onclick="myF()">Check</button>
<button onclick="myF1()">Restart Game</button>
<div id="slotLeft">
</div>
<div id="slotOne">
</div>
<div id="slotTwo">
</div>
<div id="slotThree">
</div>
<div id="winner">
</div>
function myF() {
var slotOneElem = document.getElementById("slotOne");
var slotTwoElem = document.getElementById("slotTwo");
var slotThreeElem = document.getElementById("slotThree");
var generateRand = function() {
return Math.floor(Math.random() * 3) + 1;
}
return (function () {
var slotOne = generateRand();
var slotTwo = generateRand();
var slotThree = generateRand();
slotOneElem.innerHTML = slotOne;
slotTwoElem.innerHTML = slotTwo;
slotThreeElem.innerHTML = slotThree;
if (slotOne === slotTwo && slotTwo === slotThree) {
slotOneElem.style.backgroundColor = "#48bd48";
slotTwoElem.style.backgroundColor = "#48bd48";
slotThreeElem.style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
// Here is the win
return true;
}
return false;
})();
}
var finished = myF();
while (!finished) {
finished = myF();
}

Coin toss with JavaScript and HTML

I need help fixing my script. Basically, I want it to flip a coin and update a <span> with the result, i.e. if it's heads or tails. At the moment, nothing happens when I click the button.
JavaSript:
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("heads");
}else{
flip("tails");
}
};
function flip(coin) {
document.getElementById("result").innerHTML = coin;
};
HTML:
<button id="click" type="button">CLICK ME</button>
<p>
You got: <span id="result"></span>
</p>
That's simply because you need to attach the event handler:
document.getElementById('click').onclick = click;
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("heads");
}else{
flip("tails");
}
};
function flip(coin) {
document.getElementById("result").innerHTML = coin;
};
<button id="click" type="button">CLICK ME</button>
<p>
You got: <span id="result"></span>
</p>
var prob1 = Math.floor(Math.random() * 2) +1;
var prob2 = Math.floor(Math.random() * 2) +1;
if( prob1 === prob2){
document.write('You Got TAIL');
}else{
document.write('You Got HEAD');
document.getElementById('click').onclick = click;
var heads = 0;
var tails = 0;
function click() {
x = (Math.floor(Math.random() * 2) == 0);
if(x){
flip("heads");
}else{
flip("tails");
}
};
function flip(coin) {
document.getElementById("result").innerHTML = coin;
};
<button id="click" type="button" onclick="click()">CLICK ME</button>
<p>
You got: <span id="result"></span>
</p>
function flip(Throws) {
let coinArray = [];
for (var i = 0; i < Throws; i++) {
rndNo = Math.floor(Math.random() * 2 + 1);
if (rndNo === 1) {
Toss = 'H';
} else {
Toss = 'T'
} // if (rnd === 1)
coinArray.push(Toss);
}
return coinArray;
}
console.log(flip(10));
function flipHeadCoin() {
let coinArray = [];
let numHeads = 0;
do {
rndNo = Math.floor(Math.random() * 2 + 1);
// ternary operators
Toss = (rndNo === 1) ? 'H' : 'T';
numHeads += (Toss === 'H') ? 1: 0;
coinArray.push(Toss);
} while (numHeads < 6);
return coinArray;
}
console.log(flipHeadCoin());
const coinFlip = num_of_coin_flips => {
heads = 0;
tails = 0;
for(i = 0; i < num_of_coin_flips; i++){
randomNumber = Math.floor(Math.random() * 2);
roundNum = Math.round(randomNumber* 100) / 100;
roundNum === 0
? heads += 1
: tails += 1;
}
return `There are ${heads} heads and ${tails} tails. That's a ${((heads / num_of_coin_flips) * 100)} % / ${((tails / num_of_coin_flips) * 100)} % split`
}
console.log(coinFlip(3))
<!DOCTYPE html>
<html>
<body>
<p id="Another way"></p>
<script>
var x;
x = (Math.floor(Math.random() * 2) == 0);
if (x==1) {
x="Blue"
} else {
x="Red"
};
document.getElementById("Another way").innerHTML =
"The color of the pill is " + x + "!.";
</script>
</body>
</html>
And ofcourse this still needs an event handler ;) it's late guys :)

Categories