I don't know why my console always outputs the same thing - javascript

I was given this simple scenario: “Write a program that simulates the rolling of two dice. Keep rolling the dice UNTIL the sum of the dice is either a 7 OR an 11. Your program should display the results of each roll."
It's very easy, I know. But the sum of each print is always the same and it's not adding properly. Probably just not seeing something right, but I'm a mega-beginner.
NOTE- the write() function just displays text on a screen in this case.
Here is my code:
var die1 = randomNumber(1, 6);
var die2 = randomNumber(1, 6);
var sum = die1 + die2;
while (!(sum == 7 || sum == 11)) {
die1 = randomNumber(1,6);
die2 = randomNumber(1,6);
write("Rolled " + die1 + " and " + die2 + ", sum is " + sum);
}
write("Done.");

You forgot to recalculate the sum inside of the while loop:
var die1 = randomNumber(1, 6);
var die2 = randomNumber(1, 6);
var sum = die1 + die2;
while (!(sum == 7 || sum == 11)) {
die1 = randomNumber(1,6);
die2 = randomNumber(1,6);
// FIX: recalculate sum
sum = die1 + die2;
write("Rolled " + die1 + " and " + die2 + ", sum is " + sum);
}
write("Done.");
Also it would be cleaner with a do-while loop:
var die1, die2, sum;
do {
die1 = randomNumber(1,6);
die2 = randomNumber(1,6);
sum = die1 + die2;
write("Rolled " + die1 + " and " + die2 + ", sum is " + sum);
} while(!(sum == 7 || sum == 11));
write("Done.");
Note: It is also depend on logic written inside randomNumber() function.

Related

How do I print a reversed times table in Javascript

I'm trying to print to screen this times table in reverse like the photo but can't figure what I need to change to do that.
var digit = 9, multiplier = 9, textresult = "", result = 0;
while (digit > 0) {
for (multiplier = 9; multiplier >= digit; multiplier--) {
result = digit * multiplier;
if (digit == multiplier) {
textresult += digit + " x " + multiplier + " = " + result + "
<br>";}
else {
textresult += digit + " x " + multiplier + " = " + result +
" ";}
}
digit--;}
strong textdocument.write(textresult);
any Ideas?
Try this correction
var digit = 1,
textresult = "<pre><code>",
max = 9;
while (digit <= max) {
for (var multiplier = digit; multiplier <= max; multiplier++) {
var result = digit * multiplier;
textresult += digit + " * " + multiplier + " = " + result;
if (10 > result) {
textresult += " ";
}
if (max == multiplier) {
textresult += "<br/>";
} else {
textresult += " ";
}
}
digit++;
}
textresult += "</pre></code>";
document.write(textresult);
Count from digit of 1 up, rather than from 9 down. On each inner loop, initialize multiplier to digit instead of 9, and similarly, count up with multiplier:
var digit = 1,
textresult = "";
while (digit < 10) {
for (let multiplier = digit; multiplier < 10; multiplier++) {
const result = digit * multiplier;
textresult += digit + " x " + multiplier + " = " + result + (multiplier === 9 ? '<br>' : " ");
}
digit++;
}
document.write(textresult);

My code isn't recognizing a condition

I am trying to solve this following problem (Udacity's Intro to Javascript):
Directions:
Write a loop that prints out the following song. Starting at 99, and ending at 1 bottle.
Example:
99 bottles of juice on the wall! 99 bottles of juice! Take one down, pass it around... 98 bottles of juice on the wall!
98 bottles of juice on the wall! 98 bottles of juice! Take one down, pass it
around... 97 bottles of juice on the wall!
...
2 bottles of juice on the wall! 2 bottles of juice! Take one down, pass it around... 1 bottle of juice on the wall!
1 bottle of juice on the wall! 1 bottle of juice! Take one down, pass it around... 0 bottles of juice on the wall!
and my code doesn't appropriately output the last line (it doesn't include "s" after "bottle"):
My code looks like this:
var num = 99;
while (num >= 1) {
num == 1 ? ((plural = "") && (nextPlural = "s")) :
num == 2 ? ((plural = "s") && (nextPlural = "")) :
((plural = "s") && (nextPlural = "s"));
console.log (num + " bottle" + plural + " of juice on the wall! " + num + "bottle" + plural + " of juice! " + "Take one down, pass it around... " + (num - 1) + " bottle" + nextPlural + " of juice on the wall!");
num = num - 1
}
why is this code ignoring my condition for "num == 2?" at the last line of output?
FYI, I was able to solve this using the following code, but it didn't look clean so I wanted to optimize this:
var num = 99;
var plural = "s";
var nextNum = num - 1;
var nextPlural = "s";
while (num >= 1) {
if (num > 1 && nextNum > 1){
plural = "s";
nextPlural = "s";
}
else if (num > 1 && nextNum == 1){
plural = "s";
nextPlural = "";
}
else if (num == 1 && nextNum <= 1){
plural = "";
nextPlural = "s";
}
console.log(num + " bottle" + plural + " of juice on the wall! " + num + " bottle"+ plural + " of juice! " +
"Take one down, pass it around... " + nextNum + " bottle" + nextPlural + " of juice on the wall!");
num = num - 1;
nextNum = num - 1;
}
Alright, so the question, if I understand it right, is why the last line for the first code sample outputs "0 bottle" instead of "0 bottles".
So let's translate what you attempted to achieve with your code into English and figure out what the interpreter does:
Set num to 99.
While num greater or equal to 1, do the following:
2.1 If num equals 1, set plural to "" and nextPlural to "s".
2.2 Else if num equals 2, set plural to "s" and nextPlural to "".
2.3 Else set both plural and nextPlural to "s".
The console output is trivial, so I won't mention it here.
Set num equal to num-1.
You might notice that substituting the ternary operator with an if statement yields the correct result:
var num = 1;
var plural = '';
var nextPlural = '';
while (num >= 1) {
if(num==1) { plural = ''; nextPlural='s'; }
/*num == 1 ? ((plural = "") && (nextPlural = "s")) : (num == 2 ? ((plural = "s") && (nextPlural = "")) : ((plural = "s") && (nextPlural = "s")));*/
console.log (num + " bottle" + plural + " of juice on the wall! " + num + " bottle" + plural + " of juice! " + "Take one down, pass it around... " + (num - 1) + " bottle" + nextPlural + " of juice on the wall!");
num = num - 1
}
What does that mean? That there is a syntax error with your use of the ternary operator. What could it possibly be? Let's declare a new variable and try setting and outputting it along with the others.
var num = 1;
var plural = '';
var nextPlural = '';
var test = '';
while (num >= 1) {
//if(num==1) { plural = ''; nextPlural='s'; }
num == 1 ? ((plural = "") && (nextPlural = "s") && (test = "test")) : (num == 2 ? ((plural = "s") && (nextPlural = "")) : ((plural = "s") && (nextPlural = "s")));
console.log (num + " bottle" + plural + " of juice on the wall! " + num + " bottle" + plural + " of juice! " + "Take one down, pass it around... " + (num - 1) + " bottle" + nextPlural + " of juice on the wall!");
console.log(test);
num = num - 1
}
You will notice that test remains equal to an empty string, just like nextPlural. That's because using && is not the correct way of instantiating variables inside ternary constructions, so this code will work as intended:
var num = 99;
var plural = '';
var nextPlural = '';
while (num >= 1) {
//if(num==1) { plural = ''; nextPlural='s'; }
num == 1 ? (plural = "", nextPlural = "s") : (num == 2 ? (plural = "s", nextPlural = "") : (plural = "s", nextPlural = "s"));
console.log (num + " bottle" + plural + " of juice on the wall! " + num + " bottle" + plural + " of juice! " + "Take one down, pass it around... " + (num - 1) + " bottle" + nextPlural + " of juice on the wall!");
--num;
}
If you are interested, this is how I would probably program the solution:
for(var i=99, w=' on the wall!'; i>0; i--) {
console.log(returnEmpties(i)+w+' '+returnEmpties(i)+'! Take one down, pass it around... '+returnEmpties(i-1)+w);
}
function returnEmpties(n) { return n+' bottle'+(n==1?'':'s')+' of juice'; }
The ternary operator stuff is just a big mess, I've tried to figure it out, but it's really worth trying to fix since it's just not a good idea to use ternary operators like that. You've nested a ternary inside another ternary and basically have an if, else if, else condensed into 3 lines.
You can avoid doing extra logic and realize that you need only add an 's' when the number is not 1.
By extracting this logic into a function that returns the string 's' or the empty string '', you can simply plug this function into your loop and provide it with n and n-1.
function plural(n) {
return n == 1 ? '' : 's'; // note this is the appropriate usage of a ternary operator
}
You can then simply your loop to just
while (num >= 1) {
console.log('...'); // left as an exercise for you to fill in the required function call and string concatenations.
num--; // same thing as num = num - 1;
}

Dice Game - need to roll more dice based upon circumstances

I am developing a game idea. Weapons can be equipped on your character. Different weapons have different amounts of damage dice and critical hit dice. I have it working currently so that the program rolls the appropriate amount of dice based on your equipped weapon.
However, the program only rolls one critical dice, despite whether the equipped weapon contains two critical roll dies.
var WepEquipped = { "name": "Broken Sword", "attack_dice": "2", "critical_dice": "1", "min_base_dmg": "2", "max_base_dmg": "12", "max_total_dmg": "24", "weapon_type": "Slash" };
function Attack(rolls) {
var total = 0;
var dice = [];
for (var i = 1; i <= rolls; i++) {
var d6 = Math.floor((Math.random() * 6) + 1);
$("#dice_container").append("<div class='die_roll'><p class='atk-roll'>" + d6 + "</p></div>");
dice.push(d6);
total += d6;
}
// Needs to be able to roll for multiple critical dice
if ($.grep(dice, function (elem) {
return elem === dice[0];
}).length == rolls) {
var d12 = Math.floor((Math.random() * 12) + 1);
total += d12;
$("#dice_container").append("<div class='die_roll'><p id='crit-roll'>" + d12 + "</p></div>");
}
$("#attack").html("<div>You attack for " + total + "</div>");
};
$('#attack_button').off('click').on('click', function(){
$('.die_roll').hide();
Attack(WepEquipped.attack_dice);
// Attack(WepEquipped.attack_dice);
});
I can explain much more, but I hope this is enough code to grasp what I'm asking. Something here needs to change but I cannot figure out what:
// Needs to be able to roll for multiple critical dice
if ($.grep(dice, function (elem) {
return elem === dice[0];
}).length == rolls) {
var d12 = Math.floor((Math.random() * 12) + 1);
total += d12;
$("#dice_container").append("<div class='die_roll'><p id='crit-roll'>" + d12 + "</p></div>");
}
$("#attack").html("<div>You attack for " + total + "</div>");
};
your grep returns the number of elements in the dice array that equal to your first roll and if the length of that array equals the number of rolls that were made you roll the critical dice once.
if ($.grep(dice, function (elem) {
return elem === dice[0];
}).length == rolls) {
var d12 = Math.floor((Math.random() * 12) + 1);
total += d12;
$("#dice_container").append("<div class='die_roll'><p id='crit-roll'>" + d12 + "</p></div>");
}
$("#attack").html("<div>You attack for " + total + "</div>");
};
If you're trying to roll as many times as the grep returns you need something like this.
var crits = $.grep(dice, function (elem) {return elem === dice[0];});
if( crits.length == rolls ){
for( var x=0;x<crits.length;x++){
var d12 = Math.floor((Math.random() * 12) + 1);
total += d12;
$("#dice_container").append("<div class='die_roll'><p id='crit-roll'>" + d12 + "</p></div>");
}
}
Sorry for the double post, was on an abandoned account.

I am having trouble with a few javascript do while loops

I am writing a code guessing program to test the security of some iPhone passwords (This is not in anyway connected to anything illegal or is used to break into actual iPhones). The do/while loops just end all response once they occur and the last two lines don't print to the console.
print("Hi!");
print("I am a password security tester.");
var tries = 0
var guess1 = 0
var guess2 = 0
var guess3 = 0
var guess4 = 0
var guess = (guess1 * 1000) + (guess2 * 100) + (guess3 * 10) + guess4;
var password1 = (Math.floor(Math.random()*9));
var password2 = (Math.floor(Math.random()*9));
var password3 = (Math.floor(Math.random()*9));
var password4 = (Math.floor(Math.random()*9));
var password = (password1 * 1000) + (password2 * 100) + (password3 * 10) + password4;
print("This is the randomly genorated password: " + password);
print("And now begins the guessing");
do{
guess1 + 1;
tries + 1;
}while (password1 != guess1);
do{
guess2 + 1;
tries + 1;
}while (password2 != guess2);
do{
guess3 + 1;
tries + 1;
}while (password3 != guess3);
do{
guess4 + 1;
tries + 1;
}while (password4 != guess4);
print("Complete in " + tries + " tries");
print("The answer is: " + guess);
Jacob Ewing's answer is correct, but another problem is that guess will still be 0 at the end, because it doesn't automatically update. You'll need to do:
var guess = (guess1 * 1000) + (guess2 * 100) + (guess3 * 10) + guess4;
Before:
print("Complete in " + tries + " tries");
print("The answer is: " + guess);
You need to be using a += operator instead of just +
Saying guess1 + 1 returns the value of guess1 + 1, but does not increment that value directly, so you get an infinite loop.

Another dice error, code not quite working

Line 6 says it's expecting an identifier.
I'm trying to make it so rolling a 1 on either die makes the score 0, and rolling doubles doubles your score, otherwise, the score is the sum of the two die.
var die1 = Math.floor(Math.random()*6 + 1);
var die2 = Math.floor(Math.random()*6 + 1);
var score;
if(die1 === 1 || die2 === 1){
score = 0;
else {
score = die1 + die2;
}
if(die1 === die2)
score = 2*(die1 +die2);
else{
score = die1 + die2;
}
}
console.log("You rolled a "+die1+" and a "+die2+" for a score of "+score);
You never closed the bracket before the "else".
Change
if(die1 === 1 || die2 === 1){
score = 0;
else {
score = die1 + die2;
}
to be
if(die1 === 1 || die2 === 1){
score = 0;
} else {
score = die1 + die2;
}
Here is your code properly formatted and with the if statements cleaned:
var die1 = Math.floor(Math.random() * 6 + 1);
var die2 = Math.floor(Math.random() * 6 + 1);
var score;
if (die1 === 1 || die2 === 1)
score = 0;
else if (die1 === die2)
score = 2 * (die1 + die2);
else
score = die1 + die2;
console.log("You rolled a " + die1 + " and a " + die2 + " for a score of " + score);

Categories

Resources