Taking two mathrandom values and adding them on loop - javascript

I have to make a game of dice where I add the values of both the dice and give the sum. You get another turn if both the dice end up on the same number (such as 2 and 2 which is 4) then you roll the dice again and the 2 new numbers get added to the previous sum (like 4 mentioned earlier).
For example -
1st try 3 and 3, sum is 6.
2nd try 4 and 5, sum is 6 + 4 + 5 = 15
I'm able to get the first sum right, but the subsequent numbers are getting messed up sometimes even giving twice as much.
function oneRandom(){
var my1 = Math.floor(Math.random() * 6 ) +1 ;
var my2 = Math.floor(Math.random() * 6 ) +1 ;
var num1 = Number(my1);
var num2 = Number(my2);
var sum = num1 + num2;
console.log(sum);
var resultfield = document.getElementById("total").innerHTML = "<h1>"+sum+"</h1>";
document.getElementById("cilc").style.display = "none";
if (getImage.src == get2.src){
document.getElementById("cilc").style.display = "block";
var sum2 = num1 + num2;
var total = sum2 + sum;
var resultfield = document.getElementById("total").innerHTML = "<h1>"+total+"</h1>";
}
}
The getImage and get2 are arrays to match dice images to give another turn in case of same numbers loading.

You can try this,
function rollDice (times) {
var num1 = Math.floor(Math.random() * Math.floor(6));
var num2 = Math.floor(Math.random() * Math.floor(6));
console.log(times, num1, num2);
var total = num1 + num2;
return num1 === num2 ? total + rollDice(times + 1) : total;
}
console.log(`result is ${rollDice(0)}`);

Related

Prompt user for input then print smallest number

Im trying to accept 2 inputs from a user then compare the 2 to find the smallest number.
Finally print to the console. I feel Im going in the wrong direction.
Any advice?
Below is my code
//prompt variable for user input
let num1 = prompt("Enter 1st number ", "i.e. 7 ");
let num2 = prompt("Enter 2nd number ", "i.e. 4 ");
// for loop returning lowest input
for (let i = 1; i < num1.length; i++){
if (num1[i] <= num2){
num2 = num1[i];
}
}
console.log(num2);
If there's only 2 inputs and you're trying to console.log the smallest number then you can just use an if statement. No need to iterate through num1.
let num1 = 5;
let num2 = 10;
if(num1 > num2){
console.log(num2);
}else if (num2 > num1){
console.log(num1);
}else{
console.log(num1 + ' and '+num2+' are equal');
}

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>

Sum of two numbers and the numbers between them

Ask user to enter a number. Then ask the user to enter a number bigger than the first number. Calculate a value that is the sum of all the numbers from the first number to the second number including the end points. For example, if the user enters 5 and 10 then calculate the total of 5 + 6 + 7 + 8 + 9 + 10. Display the results. MUST USE A WHILE LOOP
This is what I have so far. I can't seem to get the sum to be correct. If I enter the numbers from the example above, I get 49 instead of 45. I understand where I went wrong and why it is 49 based on my code but can't figure out how to make it correct.
// declare constants
const INITIAL_VALUE = 0;
const COUNTER_VALUE = 1;
// declare variables
var number1;
var number2;
var sum;
var counter;
var difference;
var middlePoint;
var middlePointSum;
// assigning values
sum = INITIAL_VALUE;
difference = INITIAL_VALUE;
counter = COUNTER_VALUE;
middlePoint = COUNTER_VALUE;
middlePointSum = INITIAL_VALUE;
// prompt user to enter two numbers
number1 = prompt("Enter first number: ");
number2 = prompt("Enter a number bigger than first number: ");
// convert user input into numbers
number1 = Number(number1);
number2 = Number(number2);
// display number1
document.write(number1);
difference = number2 - number1;
middlePoint += number1;
while (counter < difference) {
document.write(" + " + middlePoint);
middlePoint = middlePoint + 1;
counter++;
middlePointSum += middlePoint;
}
// calculate the sum
sum = number1 + middlePointSum + number2;
// display number1, middle points, number2, and sum
document.write(" + " + number2 + " = " + sum);
// prompt user to enter two numbers
var number1 = prompt("Enter first number: ");
var number2 = prompt("Enter a number bigger than first number: ");
// convert user input into numbers
var number1 = Number(number1);
var number2 = Number(number2);
var start_point= number1;
var sum=0;
// display number1
document.write(start_point);
sum += start_point;
start_point++;
while (start_point <=number2) {
document.write(" + " + start_point);
sum += start_point;
start_point++;
}
// display sum
document.write(" = " + sum);
Welcome to StackOverflow!
The cause of error is at this part of the code
while (counter < difference) {
document.write(" + " + middlePoint);
middlePoint = middlePoint + 1; // you are already increasing the middlePoint number
counter++;
middlePointSum += middlePoint;
}
Therefore, the sum is always over by the number of counter - 1. What you should have done, is execute middlePointSum += middlePoint; first before increasing the value of middlePoint and counter.
while (counter < difference) {
document.write(" + " + middlePoint);
middlePointSum += middlePoint;
middlePoint = middlePoint + 1;
counter++;
}
This code should work for you. Variabel sum should contain your desired sum.
var sum = 0;
var firstNumber = 0;
var secondNUmber = 0;
var firstNumberStr = '';
var secondNUmberStr = '';
// prompt user to enter two numbers
firstNumberStr = prompt("Enter first number: ");
while(isNaN(firstNumberStr)){
firstNumberStr = prompt("Enter Correct first number: ");
}
secondNUmberStr = prompt("Enter a number bigger than first number: ");
while(isNaN(secondNUmberStr) || parseInt(firstNumberStr) >= parseInt(secondNUmberStr)){
secondNUmberStr = prompt("Enter a number bigger than first number: ");
}
firstNumber = parseInt(firstNumberStr);
secondNUmber = parseInt(secondNUmberStr);
while(firstNumber <= secondNUmber){
sum += firstNumber;
firstNumber++
}
You did a very small mistake in the code . The bug is in while loop.
while (counter < difference) {
document.write(" + " + middlePoint);
middlePoint = middlePoint + 1;
counter++;
middlePointSum += middlePoint;
}
you are incrementing the middlepoint before middlePointSum is Calculated. It should be incremented after calculating the middlePointSum.
while (counter < difference) {
document.write(" + " + middlePoint);
counter++;
middlePointSum += middlePoint;
middlePoint = middlePoint + 1;
}
Your middlePointSum is starting from 1 intead of 0 so you got: 5 + (7 + 8 + 9 + 10) + 10 to fix your code set middlePointSum to INITIAL_VALUE
For simplification just ignore the difference between the numbers, increment number1 until you reach number 2
var number1 = prompt("Enter first number: ");
var number2 = prompt("Enter a number bigger than first number: ");
var incNumber;
var strResult = [];
number1 = incNumber = Number(number1);
// use incNumber if you need to preserve number1 value or just use number 1 value instead
number2 = Number(number2);
var sum = 0;
while(incNumber <= number2) {
strResult.push(incNumber);
sum += incNumber++;
// this means add incNumber to sum then increment it by 1
}
document.write(`${strResult.join(' + ')} = ${sum}`);
One problem is that your middlePointSum does not take into account the first number after the number1, for example, the 6 in your example. Another problem is that your counter < difference test is inaccurate - you would have to iterate until counter + 1 < difference:
// declare constants
const INITIAL_VALUE = 0;
const COUNTER_VALUE = 1;
// declare variables
var number1;
var number2;
var sum;
var counter;
var difference;
var middlePoint;
var middlePointSum;
// assigning values
sum = INITIAL_VALUE;
difference = INITIAL_VALUE;
counter = COUNTER_VALUE;
middlePoint = COUNTER_VALUE;
middlePointSum = INITIAL_VALUE;
// prompt user to enter two numbers
number1 = prompt("Enter first number: ");
number2 = prompt("Enter a number bigger than first number: ");
// convert user input into numbers
number1 = Number(number1);
number2 = Number(number2);
// display number1
document.write(number1);
difference = number2 - number1;
middlePoint += number1;
middlePointSum = middlePoint;
while (counter + 1 < difference) {
document.write(" + " + middlePoint);
middlePoint = middlePoint + 1;
counter++;
console.log(middlePointSum);
middlePointSum += middlePoint;
}
// calculate the sum
sum = number1 + middlePointSum + number2;
// display number1, middle points, number2, and sum
document.write(" + " + number2 + " = " + sum);
But this seems far, far more complicated than it needs to be - why not simply iterate from number1 to number2, adding to sum along the way?
const number1 = Number(prompt("Enter first number: "));
const number2 = Number(prompt("Enter a number bigger than first number: "));
document.write(number1);
let sum = number1;
for (let i = number1 + 1; i <= number2; i++) {
sum += i;
document.write(' + ' + i);
}
document.write(' = ' + sum);
Or, create an array of the numbers, join by plus signs, and calculate the sum with reduce:
const number1 = Number(prompt("Enter first number: "));
const number2 = Number(prompt("Enter a number bigger than first number: "));
const nums = Array.from(
{ length: number2 - number1 + 1 },
(_, i) => i + number1
);
const sum = nums.reduce((a, b) => a + b);
document.write(nums.join(' + ') + ' = ' + sum);
var num1 = Number(prompt("Enter a number"));
var num2 = Number(prompt("Enter a larger number"));
document.write(num1 + "+" + num2 + "=" + (num1+num2));
// now lets find the sum of numbers between these two numbers.
document.write("<br>"); // new line
var counter = num1; // we will start countring from the smaller number
var sum = 0;
//keep looping until we reach the bigger number (num2)
while(counter<=num2) {
sum += counter;
// print the current number
document.write(counter);
//print a plus sign
if(counter<num2) {
// only put a (plus sign) if we are not yet reached num2
document.write("+");
}
//increment to control the loop
counter ++;
}
//finally put the result
document.write("=" + sum);
You are setting counter to the constant COUNTER_VALUE which is 1.
Then, in your program, you are entering 5 and 6 as input. The difference is 6-5 which is 1.
Your while loop has a condition to only execute when counter<difference . In your case, counter=1 and difference=1. This means that they are equal, and thus, the loop will not execute.
I hope this sheds light on what needs to be done from your side to fix this bug.

what's wrong with my code here

Can somebody help me with this. Here I have a set of 3 different numbers as strings that I get from a user and I also have another 3 randomly generated numbers that I want to compare with the set of numbers that I get from a users but since I'm not gonna do any calculations with the number I didn't see any reason to convert them so I'm trying to compare them as strings
function radGenerator(userno1,userno2,userno3,wnum1, wnum2, wnum3,dvresult) {
$(wnum1).text("" + Math.floor((Math.random() * 10) + 1));
$(wnum2).text("" + Math.floor((Math.random() * 10) + 1));
$(wnum3).text("" + Math.floor((Math.random() * 10) + 1));
var num1 = num2 = num3 = "";
if($(userno1).text()== $(wnum1).text()||
$(userno1).text()== $(wnum2).text()||
$(userno1).text()== $(wnum3).text()){
num1 = $(userno1).text();
}
if($(userno2).text()== $(wnum1).text()||
$(userno2).text()== $(wnum2).text()||
$(userno2).text()== $(wnum3).text()){
num2 = $(userno2).text();
}
if($(userno3).text()== $(wnum1).text()||
$(userno3).text()== $(wnum2).text()||
$(userno3).text()== $(wnum3).text()){
num3 = $(userno3).text();
}
$(dvresult).text("Winning Numbers: " + num1 +" "+ " "+ num2 + " "+ num3);
}
radGenerator("#uans1","#uans2","#uans3","#wno1", "#wno2", "#wno3","#divresult");
In order to compare strings in JavaScript, you should the localeCompare() function. "string".localeCompare("otherString"); will return 1 because "string" comes after "otherString". The function would return 0 if they are equal and -1 if the first string comes before the string you are comparing it to.

JS sum of 2 numbers return a bad result

I calculate a lot of number with javascript. In some calculation i have a bad result.
Exemple: http://jsfiddle.net/6et8d10c/
var num1 = 2.01;
var num2 = 22.29;
var result = num1 + num2; //24.29 (should be 24.30)
For now I fix with:
(2.01*100 + 22.29*100) / 100 = 24.30
That's not perfect. Why can't i calculate 2.01 + 22.29 ?

Categories