Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
This is the freeCodeCamp Counting Cards activity.
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/counting-cards
My solution was
let count = 0;
function cc(card) {
// Only change code below this line
if (card = 2 || 3 || 4 || 5 || 6) {
count + 1;
} else if (card = 7 || 8 || 9) {
return;
} else if (card = 10, "J", "Q", "K", "A")
count - 1;
}
if (count > 0) {
return count + " " + "Bet";
} else if {
return count + " " + "Hold";
}
// Only change code above this line
}
cc(2); cc(3); cc(7); cc('K'); cc('A');
I checked the solution and it seemed similar. Why didn't it work?
A Few Modifications were necessary for this code to work.
= is assignment operator while == is comparing operator.
else if can be replaced with just else if there is no condition.
the third else if (card = 10, "J", "Q", "K", "A") didnt have closing or opening brackets.
avoid using return at else if (card == 7 || 8 || 9) { and instead use count += 0
You need too add a condition for || Or operator like this card == 7 || card == 8 and not like card == 7 || 8
Use count++ and count-- instead of count + 1 and count - 1
After all these changes the below code works fine.
let count = 0;
function cc(card) {
// Only change code below this line
if (card == 2 || card == 3 || card == 4 || card == 5 || card == 6) {
count++;
} else if (card == 7 || card == 8 || card == 9) {
count += 0;
} else if (card == 10|| card == "J"|| card == "Q"|| card == "K"|| card == "A"){
count--;
}
if (count > 0) {
return count + " " + "Bet";
} else {
return count + " " + "Hold";
}
}
cc(2); cc(3); cc(7); cc('K'); cc('A');
There are two main issues with your code.
Wrong if condition
Your if condition card = 2 || 3 || 4 || 5 || 6 does not work like you think it does. You would need to use car === 2 || card === 3 || car === 4 || card === 5 || car === 6. You cannot use the assignment operator = like this. You should use the strict comparison operator instead.
It's even easier to use an array and includes() like this [2, 3, 4, 5, 6].includes(card).
count is not updated
You need to assign the new value to count when you increment/ decrement it. You can use count++ instead of count + 1 which is the equivalent to count = count + 1.
let count = 0;
function cc(card) {
// Only change code below this line
if ([2, 3, 4, 5, 6].includes(card)) {
count++;
} else if ([10, "J", "Q", "K", "A"].includes(card)) {
count--;
}
if (count > 0) return `${count} Bet`;
return `${count} Hold`;
}
cc(2); cc(3); cc(7); cc('K'); cc('A');
= is used to assign a value and not to make comparison. In javascript we use == or === to make comparison, and also count - 1 will not update count. use count = count - 1 or count++
let count = 0;
function cc(card) {
// Only change code below this line
if ( card >= 2 && card <= 6) {
count = count + 1;
} else if (card >= 7 && card <= 9) {
return;
} else if (card === 10 || card === "J" || card === "Q" || card === "K" || card === "A")
count = count - 1;
}
if (count > 0) {
return count + " " + "Bet";
} else if {
return count + " " + "Hold";
}
// Only change code above this line
}
cc(2); cc(3); cc(7); cc('K'); cc('A');
Related
I am having a hard time figuring out why this code is working the way it is. Below, I have all of the code that produces my tic tac toe game. The game works as intended until we come to a full board that SHOULD result in a win for either 'O' or 'X'. My current logic sometimes will work as intended and pick the correct winner but a majority of the time, it will produce a 'DRAW', even if the last move on the last square should result in a win. Given the if/else if chain, I don't see how that would work? The applicable if/else if statement is the second set.
Here is my code:
$(document).ready(function() {
let addX = "<h1>X</h1>"
let addO = "<h1>O</h1>"
let turn = []
let board = [$("#one"), $("#two"), $("#three"), $("#four"), $("#five"),$("#six"), $("#seven"), $("#eight"), $("#nine")]
let combos = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [6,4,2]]
for (let i = 0; i < board.length; i++){
board[i].click(function(){
if (turn.length === 0){
turn.push(board.indexOf(board[i].html(addX)) + "X")
} else if (turn.length % 2 !== 0 && board[i].html() === ''){
turn.push(board.indexOf(board[i].html(addO)) + "O")
} else if (turn.length % 2 === 0 && board[i].html() === ''){
turn.push(board.indexOf(board[i].html(addX)) + "X")
}
for(let i = 0; i < combos.length; i++){
if (turn.includes(combos[i][0] + 'O') && turn.includes(combos[i][1] + 'O') && turn.includes(combos[i][2] + 'O') ){
alert('O IS WINNER!')
setTimeout(function() {$("#ttt_table tbody tr td").html(""); }, 1500);
turn.length = 0
} else if(turn.includes(combos[i][0] + 'X') && turn.includes(combos[i][1] + 'X') && turn.includes(combos[i][2] + 'X') ){
alert('X IS WINNER!')
setTimeout(function() {$("#ttt_table tbody tr td").html(""); }, 1500);
turn.length = 0
break
} else if (turn.length === 9){
alert('DRAW!')
setTimeout(function() {$("#ttt_table tbody tr td").html(""); }, 1500);
turn.length = 0
}
}
})
}
});
Here is a codepen to test out the game itself:
https://codepen.io/tylerp33/pen/NeOxyY
Basically, shouldn't the game see there's a winning combo in:
else if(turn.join("").includes(combos[i][0] + 'X') && turn.join("").includes(combos[i][1] + 'X') && turn.join("").includes(combos[i][2] + 'X')
before the last
else if (turn.length === 9) produces a 'DRAW'?
Thanks for your help!
Without changing or doing much refactoring, adding this to the last condition worked. Basically, making the if/else run through all the combos before deciding on a draw did the trick. Thanks for all the help!
else if (turn.length === 9 && combos[i] === combos[combos.length - 1]) {
alert('DRAW!')
setTimeout(function() {$("#ttt_table tbody tr td").html(""); }, 1500);
turn.length = 0
}
The card function has been explained multiple times, and I understand it. For those who do not know it: my function receives a card parameter, which can be a number or a string. I then increment or decrement the global count variable according to the card's value 2,3,4,5,6 increments, 7,8,9 keeps it at 0, while 10, J, Q, K, A decrements it. My function then returns a string with the current count and the string "Bet" if the count is positive, or "Hold" if it is negative.
So I understand how the function is done, and FreeCodeCamp accepted my solution as technically it meets their conditions. But have a question regarding this function:
var count = 0;
function cc(card) {
if (card >= 2 && card <= 6) {
count++;
} else if (card >= 7 && card <= 9) {
count += 0;
} else {
count--;
}
if (count <= 0) {
return count + " Hold";
} else {
return count + " Bet";
}
}
console.log(cc(2));
console.log(cc(3));
console.log(cc(7));
console.log(cc('K'));
console.log(cc('A'));
As I can see, the first condition is fairly simple and easy to define, so is the else if. In the third case, there are both numbers and strings involved. Does this not mean that when I put ANY string into cc, it will decrement? As anything that is not between 2 and 6, or 7 and 9, will automatically decrement? Even if the user inputs something that is not a card or is not a value from the list?
I understand that there is a list of predefined card values and names, but nevertheless, is there any better way to condition my statement to make sure that my condition will ONLY run IF the card is either 10, J, Q, K or A, and not any other value?
You can change your current else, to return and error message or just return immediately in case of the input being a non-valid card, and add another else-if to check for 10 through Ace:
if (card >= 2 && card <= 6) {
count++;
} else if (card>=7 && card <=9) {
count+= 0;
} else if (card === 10 || card === 'J' || card === 'Q' || card === 'K' || card === 'A'){
count--;
}else {
//Either just return or alert an error message and return
}
There are a number of ways you could deal with this situation. You could initially parse the input, and say assign 'J' to 11, 'Q' to 12, 'K' to 13 and 'A' to 1 (if you need to distinguish), or just a common number to that category. Everything else is an invalid input and you return immediately/post an error message. Something like:
var count = 0;
function cc(card) {
if (card == 'J' || card == 'Q' || card == 'K' || card == 'A')
card = 11;
if (card >= 2 && card <= 6) {
count++;
} else if (card>=7 && card <=9) {
count+= 0;
} else if (card >= 10 && card <= 11) {
count--; // to keep structure cleaner we use dummy 11 value
} else
//error message
if (count <= 0) {
return count + " Hold";
} else {
return count + " Bet";
}
}
cc(2); cc(3); cc(7); cc('K'); cc('A');
Also, you need to make sure to handle lower case and upper case values for the picture cards.
Define a set of allowed values and check if the value you are given is within that set using .includes(). For example:
var count = 0;
function cc(card) {
// Only change code below this line
const up = [2,3,4,5,6];
const no = [7,8,9];
const down = [10, "J", "Q", "K", "A"];
if(up.includes(card))count++;
if(down.includes(card))count--;
const str = count > 0 ? "Bet" : "Hold";
return `${count} ${str}`;
// Only change code above this line
}
// Add/remove calls to test your function.
// Note: Only the last will display
cc(2); cc(3); cc(7); cc('K'); cc('A');
Bear in mind this is type sensitive.
Another possibility is something like the following, which explicitly lists the changes for each card:
const counter = () => {
let count = 0
let values = {2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 0, 8: 0,
9: 0, 10: -1, J: -1, Q: -1, K: -1, A: -1}
return (card) => {
const change = values[card] || 0 // no change if card is, say, 'XYZ' or 'Joker'
count += change
return count <= 0 ? 'Hold' : 'Bet'
}
}
const cc = counter();
console.log(cc(2));
console.log(cc(3));
console.log(cc(7));
console.log(cc('K'));
console.log(cc('A'));
For a list as short as thirteen values, I think this sort of explicit list is cleaner.
This also encapsulates the count variable in a closure. I find that cleaner than a global variable.
Where the comment talks about jokers, you might want some more robust error-handling:
if (!(card in values)) {throw 'Bad card'}
const change = values[card]
You could use a regular expression at the very top of your function to skip all the conditionals and return a handy message if the argument passed in doesn't match a valid card:
// Check if card is valid
var cardRegex = /^(10|[2-9AJQK])$/i;
if (!cardRegex.test(card)) {
return "Invalid Card";
}
So, in the context of your code, it would look like:
var count = 0;
function cc(card) {
// Check if card is valid
var cardRegex = /^(10|[2-9AJQK])$/i;
if (!cardRegex.test(card)) {
return "Invalid Card";
}
if (card >= 2 && card <= 6) {
count++;
} else if (card >= 7 && card <= 9) {
count += 0;
} else {
count--;
}
if (count <= 0) {
return count + " Hold";
} else {
return count + " Bet";
}
}
// Valid inputs
console.log(cc(2));
console.log(cc(3));
console.log(cc(7));
console.log(cc('K'));
console.log(cc('a'));
// Invalid inputs
console.log(cc('e'));
console.log(cc('L'));
console.log(cc(0));
My solution for Basic JavaScript: Counting Cards
function cc(card) {
// Only change code below this line
if(card >= 2 && card <= 6) {
count++;
} else if (card === 10 ||card === 'J' || card === 'Q' || card === 'K' || card === 'A') {
count = count - 1;
}
if (count > 0) {
return count + ' Bet';
}
return count + ' Hold';
// Only change code above this line
}
My solution, based on what we learned so far.
Maybe it isnĀ“t the best, but it also works.
var count = 0;
function cc(card) {
// Only change code below this line
switch(card){
case 2:
case 3:
case 4:
case 5:
case 6:
count++;
break
case 7:
case 8:
case 9:
count = count;
break
case 10:
case 'J':
case 'Q':
case 'K':
case 'A':
count--;
break;
}
if (count <=0) {
return count + ' Hold';
}
else {
return count + ' Bet'
}
// Only change code above this line
}
console.log(cc(2));
console.log(cc(3));
console.log(cc(7));
console.log(cc('K'));
console.log(cc('A'));
let count = 0;
function cc(card) {
switch (card) {
case 2:
case 3:
case 4:
case 5:
case 6:
count++;
break;
case 10:
case 'J':
case 'Q':
case 'K':
case 'A':
count--;
}
if (count > 0) {
return count + " Bet";
} else {
return count + " Hold";
}
}
<script>
function Play() {
var guesses = 1
var number = 0
var points = 0
var cp = 0
var level = " "
var x = 0
while (level != "a" || "A" || "b" || "B" || "c" || "C" || "d" || "D"){
level = prompt("Select Your Difficulty");
if (level == "a" || "A" || "b" || "B" || "c" || "C" || "d" || "D") {
if (level == "a" || level == "A") {
x = 30;
}
else if (level == "b" || level == "B") {
x = 50;
}
else if (level == "c" || level == "C") {
x = 70;
}
else if (level == "d" || level == "D") {
x = 100;
}
}
else if (level != "a" || "A" || "b" || "B" || "c" || "C" || "d" || "D") {
if (level == null) {
return;
}
else {
alert("You Went Sphagetti On Your Keyboard And Missed");
}
}
}
var answer = Math.floor(Math.random() * x) + 1;
number = prompt("What Is Your First Guess?");
if (number == null) {
return;
}
//The Beginning Of The While Loop
while (guesses <= 4) {
//Give The User A Point And Restart The Guesses
//Generate A New Number For Them To Guess
if (number == answer) {
alert("You Guessed Correctly! You Get One Point!");
alert("The Number Will Now Change, But Will Still Be Within 1-30");
guesses = 1;
points = points + 1;
answer = Math.floor(Math.random() * x) + 1;
number = prompt("What Is Your Guess For The New Number?");
if (number == null){
return;
}
//If The Number The User Guessed Equals The Answer
//Go Back To The Start Of The Loop
else if (number == answer) {
continue;
}
}
if (number < answer) {
alert("Wrong! The Number Is To Low! NACHO CHEESE");
}
else if (number > answer) {
alert("Wrong! The Number Is To High! YOU ARE SHELLFISH!");
}
number = prompt("You've Made " + guesses + " Guess(es)");
if (number == null) {
return;
}
if (number == answer) {
continue;
}
else if (number != answer) {
guesses = guesses + 1;
}
}
//If The User Gets Wrong On All 5 Guesses
//Tell Them They Lost And Give Them The Answer
//Display Their Total Points
alert("You Have Guessed Incorrectly 5 Times. The Number Was " + answer);
cp = points.toString();
document.getElementById("points").innerHTML= "Point Streak: " + cp;
}
</script>-
Hello, I was wondering why the conditions in my first while loop do not seem to be working properly. When I enter in a letter that should break out of the loop since the condition is while it is not equal to one of these letters, it just ends up asking me to again to ("Select Your Difficulty"). Before it was also giving me the "You Went Spaghetti On Your Keyboard And Missed") When I entered in a letter that should break out of the loop... If I am not mistaken if should not even be entering that else if in the first place if I enter in one of those letters right? Please guide me where I went wrong.
So I'm making a dice game where if either ofd the dice roll a 1, the score is 1, but I can't seem to make that work. I believe everything else it ok.
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;
}
if (die1 !== 1 || die2 !== 1){
score = die1 + die2;
}
console.log("You rolled a "+die1+" and a "+die2+" for a score of "+score);
First off, you don't set score to 0. Change score === 0 to score = 0.
Second, your second if is still evaluated. Try making it an else if:
if (die1 === 1 || die2 === 1){
score = 0;
}
else if ...
Tying together all of the great suggestions here:
if (die1 === 1 || die2 === 1) {
score = 1; // "if either of the dice roll a 1, the score is 1"
// Also, use = for assignment, not == or ===
}
else { // No need to check the inverse - just use else
score = die1 + die2;
}
if (die1 === 1 || die2 === 1) {
score = 1; // You are not comparing you are assigning here
}
else if ... // Better use else if than using if as in your code
For more information :-
else if javascript
I'm trying to do some simple tests to help further my javascript knowledge (which is quite fresh). Goal 1 is to print numbers from 1-100 that aren't divisible by 5 or 3.
I tried the following:
for (var i = 1; i <= 100; i ++)
{
if (i%3 !== 0 || i%5 !== 0){
console.log(i);
}
}
This logs EVERY number from 1-100, and I can't tell why. Probably the simplest simplest questions here but it's doing my head in!
I think you mean &&, not ||. With ||, you're basically testing to see if the number is not divisible by 3 or by 5 - only if a number is divisible by both do you reject it (in other words, multiples of 15).
The typical answer to FizzBuzz is:
if( i%3 == 0 && i%5 == 0) FizzBuzz
elseif( i % 3 == 0) Fizz
elseif( i % 5 == 0) Buzz
else number
So to get directly to the number you need for i%3==0 to be false AND i%5==0 to be false. Therefore, you want if( i%3 !== 0 && i%5 !== 0)
Here's a quite simple FizzBuzz function that accepts a range of numbers.
function fizzBuzz(from, to) {
for(let i = from; i <= to; i++) {
let msg = ''
if(i % 3 == 0) msg += 'Fizz'
if(i % 5 == 0) msg += 'Buzz'
if(msg.length == 0) msg = i
console.log(msg)
}
}
fizzBuzz(1, 25)
As for a more complex solution, that's one way you could define a higher order function which generates customized FizzBuzz functions (with additional divisors and keywords)
function fizzBuzzFactory(keywords) {
return (from, to) => {
for(let i = from; i <= to; i++) {
let msg = ''
Reflect.ownKeys(keywords).forEach((keyword) => {
let divisor = keywords[keyword]
if(i % divisor == 0) msg += keyword
})
if(msg.length == 0) msg = i
console.log(msg)
}
}
}
// generates a new function
const classicFizzBuzz = fizzBuzzFactory({ Fizz: 3, Buzz: 5 })
// accepts a range of numbers
classicFizzBuzz(1, 25)
const extendedFizzBuzz = fizzBuzzFactory({ Fizz: 3, Buzz: 5, Bazz: 7, Fuzz: 11 })
extendedFizzBuzz(1, 25)
I attacked this the same was as Niet the Dark Absol:
for (var n = 1; n <= 100; n++) {
if (n % 3 == 0 && n % 5 == 0)
console.log("FizzBuzz");
else if (n % 3 == 0)
console.log("Fizz");
else if (n % 5 == 0)
console.log("Buzz");
else
console.log(n);
}
However, you can also do it this way:
for (var n = 1; n <= 100; n++) {
var output = "";
if (n % 3 == 0)
output += "Fizz";
if (n % 5 == 0)
output += "Buzz";
console.log(output || n);
}
One of the hardest parts of learning JavaScript - or any language - for me is understanding solutions can come in many ways. I like the first example more, but it's always good to keep thinking and look at other options.