FizzBuzz game- how to create a comma-separated string - javascript

I should create a function called 'fizzBuzz()' that takes two arguments 'start' and 'stop' and returns a comma-separated string. The arguments represents the starting point and stop point of the game 'Fizz Buzz'. (http://en.wikipedia.org/wiki/Fizz_buzz). Shortly it means, in a range of numbers I should print all numbers that are divisible by three as Fizz and the numbers divisible by 5 as Buzz, the rest as is. The function should run from start to stop and add 'Fizz', 'Buzz' or both to the 'result'-variable at the appropriate numbers.
If 'stop' is equal or lower than 'start', the function should return an error message.
function fizzBuzz(start, stop) {
for(var i= start; i <= stop; i++) {{
if (i % 5 == 0)
print "Buzz";
else if (i % 3 == 0)
print "Fizz";
else
print i;
}
console.log(",")
}
My problem is that I don´t know how to make the loop work. Right now when I try to print fizzBuzz(2,24) Nothing comes out. The console tells me that there is semi colon missing at row 4 (same line as "Buzz".
Also, I wonder if this will work with an if/else statement since there are some numbers that are both divisible by 3 and 5. Would it be more clever to use a switch?
Lastly, I want to add an if-statement like the following somewhere.
if(start == stop || start> stop)
alarm("choose different numbers");
Should it be inside the function? || means "or", is that correct?
Thanks in advance!

The problem with your code (apart from the extra {) is that you are calling return in your for loop. This causes the function to stop and return only 2.
What you want to do is make a string variable where you add the numbers and then return that. Here is an example of what I mean:
function fizzBuzz(start, stop) {
var returnString = "";
for (var i= start; i <= stop; i++) {
if (i % 5 == 0)
returnString += "Buzz";
else if (i % 3 == 0)
returnString += "Fizz";
else
returnString += i;
returnString += ",";
}
return returnString;
}
Edit: Sorry, I didn't see your second question! Yes, you should put the if statement for if(start == stop || start> stop) alarm("choose different numbers"); at the beginning of the function, before any other code is run (in my example, before var returnString = ""; but after the {). However, there are two things that you should note. First, the function to show a message in JavaScript is alert, not alarm. Second, you should include a return; statement in the if after your alert so that your function doesn't continue after alerting the user to pick different numbers.

Related

Infinite While loop mod 3

I basically just want to print numbers a list of numbers a skip multiples of 3. I got it to work but the initial way i tried it did not work and i do not understand why, just need someone to please explain why it doesn't work and goes into an infinite loop.
This is the problem, why does it go into an infinite loop? I am clearly missing a key concept about code, if someone could help thanks.
var i = 0;
while (i <= 10) {
if (i % 3 == 0) {
continue;
}
document.write( i + "</br>");
i++;
}
I know you can do it this way.
while (i <= 10)
{
if (i % 3 != 0) {
document.write("Number is " + i + "<br />");
}
i++
}
If we ignore the code producing the output and look only at the code checking and modifying i, it might become a little more clear why it's not working. It also helps to format our code for extra clarity.
var i = 0;
while (i <= 10) {
if (i % 3 == 0) {
continue;
}
i++;
}
Start with i = 0.
i <= 10 is true. Enter the loop.
i % 3 == 0 is true. Enter the if block.
continue;. Go straight to the top of the while loop again. Do not pass i++;. Do not collect 1.
Lather. Rinse. Repeat (infinitely).
continue jumps to the next iteration and doesnt complete the rest of your code in the while. So i is not being incremented but rather staying as 0 becuase you wrote continue before incrementing the i. so therefore it is in an endless loop, it is always less than 10

Freecodecamp - Counting Cards

I know there are a number of ways to complete this challenge and I can simply a different approach to pass the requirement however I am struggling to understand what's wrong with my code.
Challenge - https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/counting-cards/
Any help would be much appreciated.
var count = 0;
function cc(card) {
// Only change code below this line
if (card < 7){
count++;
} else if (card < 10){
count+=0;
} else (count--;)
if (count > 0){
return count + " Bet";
} else (
return count + " Hold";
)
// 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');
Firstly, when you try to execute your code, you should be seeing a Syntax Error, pointing to the semicolon in (count--;). The reason for this is: else expects a statements, if it sees a parenthesis it means the statement is an expression, and in an expression, semicolons can't appear inside parentheses (this is rather simplified). The correct way to write it is either without parentheses (generally frowned upon) as else count--;, or with curly braces: else { count--; }.
When you fix that error, there will be another one of the same kind, as you seem to systematically use parentheses instead of curly braces after else.
After that, your code kind of works. There's questionable comparisons of card, that can be a letter or a number, with an integer, but it coincidentally works the way you hope it does (because 'K', 'Q' and 'J' happen to be evaluated as greater than 7 and 10.) It would be better to not rely on such magic, and have a translation table between letters and values - or at least, if you're going to rely on magic, comment so that readers are aware you are aware of the magic. Also, count+=0 is a void statement, it does nothing, and could have been left out. That leaves you with an empty else if, but that's not an error. However, it would probably be much more readable if you had if (card < 7) { count--; } else if (card >= 10) { count++; }.
stupid mistake's.
answer is below:
var count = 0;
function cc(card) {
// Only change code below this line
if (card < 7){
count++;
} else if (card < 10){
count;
} else {count--;
}
if (count > 0){
return count + " Bet"
} else {
return count + " Hold"
}
// Only change code above this line
}

Comparing Letters in a Palindrome (JavaScript) [duplicate]

This question already has answers here:
Palindrome check in Javascript
(45 answers)
Closed 7 years ago.
My objective is to test if a word (under 10 letters) that a user enters is a palindrome. I want to do this my comparing the first letter to the last, 2nd letter to the 2nd to last, 3rd letter to the 3rd to last...
I am using a for loop and an array to do this. I cannot use the reverse() method. My main issue is formatting the comparison equation that I have:
(lettersArray[i] + 1) == (lettersArray[i].length - 1)
This is supposed to compare the first to last, 2nd and 2nd to last, and so on. Is this the right format? Am I right in my method of accessing the last index in the array and counting it down? Please let me kow what I am doing wrong since it's not running. Here is my code:
var usersWord = prompt("Enter a Palindrome");
var lettersArray =usersWord.split(""); // this is the array
for(var i=0; lettersArray.length < 11; i++) {
if((letters[i] + 1) == (lettersArray.length[i]-1)) {
alert("is palindrome");
} //end if statement
else{
alert("is not palindrome");
} // end else statement
} // end for statement
The issue with your code is that you are reporting results after checking each character; however, we can't tell whether a word is a palindrome or not without checking every character. A function such as the following might better suit your requirements.
function checkPalindrome(word) {
var len = word.length;
for (var i = 0; i < (len / 2); i++) {
if (word.charAt(i) !== word.charAt(len - 1 - i))
return false;
}
return true;
}
Another important point to note is that you should be checking until word.length / 2, not an arbitrary number 11 that may change depending on the word used as an input. Note also that word.length / 2 is an optimized case. The loop could also have been run till the word length but there is no need to check again that last char == first char when already first char == last char

Recursion and Loops - Maximum Call Stack Exceeded

I'm trying to build a function that adds up all the numbers within a string... for example, 'dlsjf3diw62' would end up being 65.
I tried to be clever and put together a recursive function:
function NumberAddition(str) {
var numbers='1234567890';
var check=[];
str=str.split[''];
function recursive(str,check) {
if (str.length==0)
return check;
else if (numbers.indexOf(str[0])>=0)
{
for (i=0;i<str.length;i++){
if (numbers.indexOf(str[i])<0)
check.push(str.slice(0,i));
str=str.slice(i);
return recursive(str,check);
}
}
else
str.shift();
return recursive(str,check);
}
You'll see that I'm trying to get my numbers returned as an array in the array named check. Unfortunately, I have a maximum call stack size exceeded, and I'm not sure why! The recursion does have a base case!! It ends once str no longer has any contents. Why wouldn't this work? Is there something I'm missing?
-Will
You can achieve the same thing with a far easier solution, using regular expressions, as follows:
var str = 'dlsjf3diw62';
var check = str.match(/\d+/g); // this pattern matches all instances of 1 or more digits
Then, to sum the numbers, you can do this:
var checkSum = 0;
for (var i = 0; i < check.length; i++) {
checkSum += parseInt(check[i]);
}
Or, slightly more compact:
var checkSum = check.reduce(function(sum, num){ return sum + parseInt(num) }, 0);
The reason your recursion doesn't work is the case where you do enter the for loop, because you've found a digit, but the digits continue to the end of the string. If that happens, the return inside the for loop never happens, and the loop ends. After that, the .shift() does not happen, because it's in that else branch, so you return re-process the same string.
You shouldn't solve this particular problem that way, but the code makes a good example of the anti-pattern of having return statements inside if bodies followed by else. Your code would be clearer (and would work) if it looked like this:
function recursive(str, check) {
if (str.length == 0)
return check;
if (numbers.indexOf(str[0]) >= 0) {
// Find the end of the string of digits, or
// the end of the whole thing
for (var i = 0; i < str.length && numbers.indexOf(str[i]) >= 0; i++);
check.push(str.slice(0, i));
str = str.slice(i);
return recursive(str, check);
}
// A non-digit character
str.shift();
return recursive(str, check);
}
In that version, there are no else clauses, because the two if clauses always involve a return. The for loop is changed to simply find the right value of "i" for the subsequent slicing.
edit — one thing this doesn't fix is the fact that you're pushing arrays into your "check" list. That is, the substring "62" would be pushed as the array ["6", "2"]. That's not a huge problem; it's solved with the addition of a .join() in the right place.

Function not calling itself... enough

Each string in an array is a number, for example array1 = ["1296", "12", "27"];
For each string above, if possible to divide by 6 evenly without remainders, I want to do so at least once, then if the result is still longer than 2 characters, repeat. Then replace the string in the same position, such that the array would become ["36", "2", "27"];
so far, my code partly works.
w=0;
function divideBySix(){
if ((array1[w] / 6) == (Math.floor(array1[w] / 6))) {
var temp = array1[w] / 6;
array1[w] = temp.toString();
if (array1[w].length < 3) {
w++;
}
divideBySix();
}
The function successfully divides the first string by 6 once, and then calls itself again and again until the result is within 2 chars long. At that point, it should continue calling itself, and do the same to the next string of the array. But it doesn't do the next string. I don't know why it stops after finishing the first string. So the array looks like this ["36", "12", "27"]; Also, w successfully gets incremented. So I know its getting at least that far...
The function you give has unbalanced { }. When I add one at the end and run it, I get the result you say you want — ["36", "2", "27"]. There must be something else wrong, or you have not copied the code correctly.
In order to understand the operation, I added this to the beginning of divideBySix:
console.log(w, array1.toString());
i think you could just go with the modulo operator, if this is what you wanted to achieve
if(array1[w] % 6 == 0) doSomething()
and to solve your current problem you could introduce a second function ; for me it works with :
function divideBySix(array){
for(var i = 0; i < array.length; i++){
array[i] = divideNumber(array[i], 0);
}
}
function divideNumber(nr, ct){
if((ct < 1 || nr > 99) && nr%6 == 0 ) return divideNumber(nr/6, ct+1);
else return nr;
}
var array1 = ["1296", "12", "27"];
divideBySix(array1);
alert(array1);
​
When I test the code, that's what it does:
http://jsfiddle.net/Guffa/x4fNP/

Categories