Compare numbers in Array using for loop - javascript

I have a prob to solve, I have to use a loop to step through each position in
an array of " winning numbers"to check whether the variable customer number (input from keyboard) matches any of the winning numbers.
I must use a For loop to step through each position in the winning numbers array and to compare the customer number to each number the array contains.
I cannot use any method to achieve this problem
Thanks for your help!
here what I did so far:
var customerNumbers = prompt("Enter your number:");
var winningNumbers = [12, 17, 24, 37, 38, 43];
for (var i = 0; i < winningNumbers.length; i++) {
if (customerNumbers == 12 || //condition determinates the winning numbers
customerNumbers == 17 ||
customerNumbers == 24 ||
customerNumbers == 37 ||
customerNumbers == 38 ||
customerNumbers == 43)
alert("This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "We have a match and a winner!");
} else {
alert("This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "Sorry you are not a winner this week");
}

You should use indexOf() to check whether customerNumbers exists in winningNumbers
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Script
var customerNumbers=prompt("Enter your number:" );
var winningNumbers=[12, 17, 24, 37, 38, 43];
if (winningNumbers.indexOf(parseInt(customerNumbers, 10)) > -1)
alert("This week Winning numbers are:"+"\n"+"\n"+winningNumbers+"\n"+"\n"+"The customer's Number is:"+"\n"+"\n"+customerNumbers+"\n"+"\n"+"We have a match and a winner!");
} else {
alert("This week Winning numbers are:"+"\n"+"\n"+winningNumbers+"\n"+"\n"+"The customer's Number is:"+"\n"+"\n"+customerNumbers+"\n"+"\n"+"Sorry you are not a winner this week");
}

Below solution loops all the winning numbers and check for a match
var customerNumbers = prompt("Enter your number:");
var winningNumbers = [12, 17, 24, 37, 38, 43];
var match = false;
for (var i = 0; i < winningNumbers.length && !match ; i++) {
if (winningNumbers[i] == customerNumbers) {
match = true;
}
}
if (match)
alert("This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "We have a match and a winner!");
} else {
alert("This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "Sorry you are not a winner this week");
}

Related

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

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.

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

Javascript number guessing game

I can't seem to make this code alert the user when the correct answer is found, nor can I make the pop-ups continue to loop to play again. I coded this as a learning exercise. In JS i'm very noob.
Can someone review my code and offer constructive criticism?
// noprotect
var targetNumber = Math.floor(Math.random() * 100 + 1);
var userGuess = prompt("Pick a number from 1 to 100 to guess which one I'm thinking about!" + " (6 guesses left.)");
for (var i=5; i>0; i--) {
if (i === 0) {
prompt("Out of guesses!" + " (" + i + " guesses left.)" + " My number was: " + targetNumber);
}
if (isNaN(userGuess) === true) {
userGuess = prompt("That value was not a number! Please pick a number from 1 to 100 to guess which one I'm thinking about!" + " (" + i + " guesses left.)");
}
if (userGuess < 1 || userGuess > 100) {
userGuess = prompt("That number was not between 1 and 100 inclusive! Please pick a number from 1 to 100 to guess which one I'm thinking about!" + " (" + i + " guesses left.)");
}
if (userGuess === targetNumber) {
userGuess = alert("You're correct! My number was: " + targetNumber);
}
if (userGuess < targetNumber) {
userGuess = prompt("You're too low, guess again" + " (" + i + " guesses left.)");
}
if (userGuess > targetNumber) {
userGuess = prompt("You're too high, guess again!" + " (" + i + " guesses left.)");
}
}
You're comparing the string value prompt() returns with a number using ===. That's not going to work.
Instead:
var userGuess = parseInt(prompt(...))
It's worth noting that prompt is an extremely clunky way to do this. What would be better is creating a form where you have a proper <input> field and a place to put the responses.
Just to add a quick note before I head home from the office. Your for loop will never allow i === 0condition to pass because the loop only continues if i > 0. You likely want to change this to i >= 0 or adjust your conditions within the loop.

Extra + in output when looping; javascript

My desired output is: 5 + 6 + 7 + 8 + 9 + 10 = 45
The output I'm getting is: 1 + 2 + 3 + 4 + 5 + = 15 (with an extra + side on the end). I'm not sure how to get it to output without the extra + at the end, and am clearly not searching for the right terms to figure it out. Thanks!
Here's my code:
function exercise7Part2() {
// PART 2: YOUR CODE STARTS AFTER THIS LINE
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart + " + ");
loopStart++;
}
document.write(" = " + total);
}
It's because you're printing loopState + "+" which will always print the + at the end. Instead you must check if it's the last value and prevent the + from printing or else, use a ternary operator to print it.
In this example, I'm checking if both loopStart and loopMax are not equal. if they're not equal then am appending + at the end.
It will be like:
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
Here (loopStart!=loopMax ? "+" : "") is a ternary operator. The loopStart!=loopMax is an boolean expression. It's evaluated and if it's true the first parameter after ? will be used so in this case + and if its false anythign after : will be used so in this case its "" empty string.
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
loopStart++;
}
document.write(" = " + total);
With normal if condition block
while (loopStart <= loopMax)
{
total += loopStart;
if(loopStart===loopMax) {
document.write(loopStart);
} else {
document.write(loopStart+ "+");
}
loopStart++;
}
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
loopStart++;
}
document.write(" = " + total);

Javascript else if statement error

I have to make a javacript code that satisfy the triangle inequality theorem, which the two smaller sides adds up to be bigger than the largest side. I have to use javascript and use a prompt for users to enter three numbers. I can not ask the user to enter the largest number i have to find it by code. So below is what i got so far, but i keep getting an error at the first else if statement and so i wont run. Any idea whats wrong with my code?
<script type="text/javascript">
<!--
var a = prompt("Enter the first side", "0");
a = Number(a);
var b = prompt("Enter the second side", "0");
b = Number(b);
var c = prompt("Enter the third side", "0");
c = Number(c);
if(a>=b, a>=c){
if (b+c>a) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality.1" );
}
else {
document.write("These numbers " + a + ", " + b + ", and " + c + " do not satisfy the triangle inequality.1" );
}
else if(b>=c, b>=a) {
if (c+a>b) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality.2" );
}
else {
document.write("These numbers " + a + ", " + b + ", and " + c + " do not satisfy the triangle inequality.2" );
}
}
else {
if (a+b>c) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality.3" );
}
else {
document.write("These numbers " + a + ", " + b + ", and " + c + " do not satisfy the triangle inequality.3" );
}
}
}
// -->
</script>
if statements test a single condition, not multiple ones. Assuming you want to know that both a is greater than or equal to b AND a is greater than or equal to c, you need to use the && operator:
if(a>=b && a>=c)
If it's an OR, it's the || operator:
if(a>=b || a>=c)
There is no such thing
if(a>=b, a>=c){
If you want to check both for true, use:
if (a >= b && a >= c)
If you want to check either or:
if (a > = || a >= c)
But in general, this code looks really bad.
if ((a >= b) && (a >= c))
Search Google for "javascript if" or something like that to learn more.
I've also noticed that your problem is very different from your answer. You say you have to ask for two sides and compute the third, but in your answer you ask for all three and just inform the user if they got the values right...
Do you have to use an if statement.
var input2 = [10, 30, 50, 150];
input2.sort(function(a, b){return b-a});
console.log(input2[0]);
You can run this in firebug console of firefox to see what it does. Corrected my answer.
Thanks guys I know my code is sloppy, but I am just starting out so in time I will get better. Here is the way i fixed the code.
<script type="text/javascript">
<!--
var a = prompt("Enter the first side", "0");
a = Number(a);
var b = prompt("Enter the second side", "0");
b = Number(b);
var c = prompt("Enter the third side", "0");
c = Number(c);
if(a>=b && a>=c && b+c>a){
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality." );
} else if(b>=c && b>=a && c+a>b) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality." );
} else if(c>=a && c>=b && a+b>c) {
document.write("These numbers " + a + ", " + b + ", and " + c + " do satisfy the triangle inequality." );
} else {
document.write("These numbers " + a + ", " + b + ", and " + c + " do not satisfy the triangle inequality." );
}
// -->
</script>

Categories

Resources