FizzBuzz with a for loop switch statement [closed] - javascript

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 3 years ago.
Improve this question
I have recently been following a Javascript course on CodeCademy and have got through Switch Statements and For Loops, I then tried to create a FizzBuzz game that prints to the console using a combination of the two. I can not figure out what I have done wrong.
I have tried removing the variables using their plain text counterparts and still achieved nothing. I don't even get any errors.
let fizzCalc = (i % 3 === 0);
let buzzCalc = (i % 5 === 0);
for ( var i = 0; i >= 100; i++) {
switch(true) {
case fizzCalc:
console.log('Fizz');
break;
case buzzCalc:
console.log('Buzz');
break;
case fizzCalc && buzzCalc:
console.log('FizzBuzz');
break;
default:
console.log(i);
break;
}
}

Let's look at these two lines of code:
let fizzCalc = (i % 3 === 0);
let buzzCalc = (i % 5 === 0);
You probably get an error here that i is undefined. The thing to keep in mind is that these formulas are all evaluated immediately. They aren't saved to evaluate them when you use the names fizzCalc and buzzCalc at a later time.
To fix the problem, you can move these two lines into your for loop:
for ( var i = 0; i >= 100; i++) {
let fizzCalc = (i % 3 === 0);
let buzzCalc = (i % 5 === 0);
// ...
}
But now you will find that the loop never runs. This is because you have typed >= when you mean <=. So one more change should fix the problem:
for ( var i = 0; i <= 100; i++) {
let fizzCalc = (i % 3 === 0);
let buzzCalc = (i % 5 === 0);
// ...
}

Here are the things you need to do to fix this:
for (var i = 0; i <= 100; i++) { // fixed loop to be less than
let fizzCalc = (i % 3 === 0); // moved vars inside loop to give access to i
let buzzCalc = (i % 5 === 0);
switch (true) {
case fizzCalc && buzzCalc: // moved this case up so it matches first
console.log('FizzBuzz');
break;
case fizzCalc:
console.log('Fizz');
break;
case buzzCalc:
console.log('Buzz');
break;
default:
console.log(i);
break;
}
}

Related

How to trace/understand an algorithm given the JavaScript source code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 18 days ago.
Improve this question
I am trying to gain some JavaScript knowledge and I found this code challenge and its solution, but I don't quite understand the solution. I would like to get an explanation.
The Problem
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to n? (smallestMult(5) should return 60)
The Solution
function smallestMulT(num) {
let res = 0;
let i = 1;
let found = false;
while (found === false) {
res += num;
while (res % i === 0 && i <= num) {
if (i === num) {
found = true;
}
i++;
}
i = 1;
}
return res;
}
The solution works, I just want to understand how it works. For example, why was it necessary to repeat i = 1; inside the while loop?
Its because the function checks for each number between 1 and x (num) if its divisible by that number.
So what it basically does when you put in 5 is:
It checks if 1 is divisible by 1 (i)
it checks if 1 is divisible by 2 (i)
it checks if 1 is divisible by 3 (i)
it checks if 1 is divisible by 4 (i)
it checks if 1 is divisible by 5 (i)
Sets i back to 1
checks next number
It checks if 2 is divisible by 1 (i)
and so on....
function smallestMulT (num){
let res = 0;
let i = 1;
let found = false;
while (found === false) {
res += num;
while (res % i === 0 && i <= num) {
if (i === num) {
found = true;
};
i++;
};
i = 1;
};
return res;
};
console.log(smallestMulT(5));

Finding the outlier in an array [closed]

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 2 years ago.
Improve this question
I have written a function which given an array full of all odd numbers and one even number, it returns the one even number. Given an array full of all even numbers and one odd number, it returns the one odd number.
ex : findOutlier([2,6,8,10,3]) will return 3, since it is the only odd number in the array
I have gotten this to work, but for some reason it will not work with certain large negative numbers? It returns undefined instead of the outlier number.
Here is my code:
function findOutlier(integers){
let testingForOdds = true;
let evenCounter = 0;
let oddCounter = 0;
for (let i = 0; i < 3; i++){
if (integers[i] % 2 === 0){
evenCounter = evenCounter + 1
if (evenCounter === 2){
testingForOdds = true;
}
}
else if (integers[i] % 2 === 1){
oddCounter = oddCounter + 1
if (oddCounter === 2){
testingForOdds = false;
}
}
}
if (testingForOdds){
for (let i = 0; i < integers.length; i++){
if (integers[i] % 2 === 1){
return integers[i]
}
}
} else {
for (let i = 0; i < integers.length; i++){
if (integers[i] % 2 === 0){
return integers[i]
}
}
}
}
findOutlier([-100000000007, 2602, 36]);
For some reason, findOutlier([-100000000007, 2602, 36]); returns undefined. However, findOutlier([2,6,8,10,3]) will successfully return 3. Why is this happening?
As Michael has pointed out, you get the issue because -100000000007 % 2 evaluates to -1. As a side note, you can optimize your logic to reduce the number of comparisons done like so:
function findOutlier(arr) {
let isEven = true;
const a = arr[0];
const b = arr[1];
if (([-1, 1].includes(a % 2) && [-1, 1].includes(b % 2))) {
isEven = false;
} else if (!(a % 2 === 0 && b % 2 === 0)) {
const c = arr[2];
if (c % 2 === 1) isEven = false;
}
for (let i = 0; i < arr.length; i += 1) {
const even = arr[i] % 2 === 0;
if (even !== isEven) return arr[i];
}
}

adding a number to an array in JavaScript [closed]

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 6 years ago.
Improve this question
I want to add a number to an array in JS, but only if the number is a multiple of three. Here's my code:
var numbers = [];
for (i = 1; i <= 200; i++) {
if i % 3 === 0 {
numbers.push(i);
}
}
alert(numbers);
But the code does not print anything. It works fine without the if statement though, when I just add the numbers between 1 and 200...
Can you find the error?
Thanks!
The quick fix is if (i % 3 === 0) {
But why don't you write for (i = 3; i <= 200; i += 3) instead and remove the modulus check?
You need some brackets for the if statement.
var numbers = [];
for (i = 1; i <= 200; i++) {
if (i % 3 === 0) {
// ^ ^
numbers.push(i);
}
}
console.log(numbers);
var numbers = [];
for (var i = 1; i <= 200;i++) {
if (i % 3 == 0) { // () execution brackets necessary
numbers.push(i);
}
}
// better way to do
var numbers = [];
var i = 3; // better to declare it here
for (; i <= 200; i += 3) {
// if (i % 3 == 0) { not required as Bathsheba's answer
numbers.push(i);
// }
}

Getting to grips with a basic JS for and if loops [closed]

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 6 years ago.
Improve this question
I have a very basic loop that I currently don't understand fully.
for (var i = 1; i <= 100; i++) {
if (i / 3) {
$(".counterWrapper").append("fizz" + "<br>");
}
else {
$(".counterWrapper").append(i + "<br>");
}
}
Basically I am wanting it to only return the word 'fizz' if the variable i's value is divisible by 3. Currently it is only returning the word 'fizz', so it would seem that it is getting stuck in the if loop and running it each time.
This is a very simple loop, but I think it might do with the way I am doing my comparisons. What would be the best way in order for it to work out if the variable i is dividable by 3?
Your conditional is always going to be true. Use the modulus operator
if (i % 3 == 0) {
// print 'fizz'
}
In javascript true and false are treated uniquely. 0 is false, any other number is true. Take a look at:
if (i / 3) {
$(".counterWrapper").append("fizz" + "<br>");
}
What you're saying is if i divided by 3 append fizz. So when looping:
if (0 / 3) // this would be 0 so it would be false
if (1 / 3) // this would not be zero so it is true
if (2 / 3) // this would not be zero so it is true
and so on.
You need to use modulo (%) which checks for remainders and use a comparison.
if (i % 3 === 0)
If you ran through the loop
if (0 % 3 === 0) // remainder is 0, so it is true
if (1 % 3 === 0) // remainder is 1, so it is false
if (2 % 3 === 0) // remainder is 2, so it is false
if (3 % 3 === 0) // remainder is 0, so it is true
The value in your if statement isn't a valid comparison. Try using modulo and equality:
for (var i = 1; i <= 100; i++) {
if (i % 3 == 0) {
$(".counterWrapper").append("fizz" + "<br>");
}
else {
$(".counterWrapper").append(i + "<br>");
}
}
if ( i % 3 === 0 )
This is a very basic question, with a very basic syntax issue.

javascript fizzbuzz switch statement

I'm currently taking the code academy course on Javascript and I'm stuck on the FizzBuzz task. I need to count from 1-20 and if the number is divisible by 3 print fizz, by 5 print buzz, by both print fizzbuzz, else just print the number. I was able to do it with if/ else if statements, but I wanted to try it with switch statements, and cannot get it. My console just logs the default and prints 1-20. Any suggestions?
for (var x = 0; x<=20; x++){
switch(x){
case x%3==0:
console.log("Fizz");
break;
case x%5===0:
console.log("Buzz");
break;
case x%5===0 && x%3==0:
console.log("FizzBuzz");
break;
default:
console.log(x);
break;
};
};
Switch matches the x in switch(x){ to the result of evaluating the case expressions. since all your cases will result in true /false there is no match and hence default is executed always.
now using switch for your problem is not recommended because in case of too many expressions there may be multiple true outputs thus giving us unexpected results. But if you are hell bent on it :
for (var x = 0; x <= 20; x++) {
switch (true) {
case (x % 5 === 0 && x % 3 === 0):
console.log("FizzBuzz");
break;
case x % 3 === 0:
console.log("Fizz");
break;
case x % 5 === 0:
console.log("Buzz");
break;
default:
console.log(x);
break;
}
}
I thought switch too,but no need.
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);
}
Switch statement checks if the situation given in the cases matches the switch expression. What your code does is to compare whether x divided by 3 or 5 is equal to x which is always false and therefore the default is always executed. If you really want to use a switch statement here is one way you can do.
for (var i=1; i<=30; i++){
switch(0){
case (i % 15):
console.log("fizzbuzz");
break;
case (i % 3):
console.log("fizz");
break;
case (i % 5):
console.log("buzz");
break;
default:
console.log(i);
}
}
Not to too my own horn but this is much cleaner:
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for (var i = 1; i <= numbers.length; i++) {
if (i % 15 === 0) {
console.log("FizzBuzz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else {
console.log(i);
}
};
The switch(true) part of this statement helped me. I was trying to do a switch statement for fizzbuzz. My solution incorporates the coding style of Rosettacodes - general solution. Most significantly the use of force typing to shorten the primary conditionals. I thought, it was valuable enough to post:
var fizzBuzzSwitch = function() {
for (var i =0; i < 101; i++){
switch(true) {
case ( !(i % 3) && !(i % 5) ):
console.log('FizzBuzz');
break;
case ( !(i % 3) ):
console.log('Fizz');
break;
case ( !(i % 5) ):
console.log('Buzz');
break;
default:
console.log(i);
}
}
}
Here's what made it clear for me, might help :
It's a misinterpretation of what switch (x){} means.
It doesn't mean : "whenever whatever I put inbetween those brackets is true, when the value of x changes."
It means : "whenever x EQUALS what I put between those brackets"
So, in our case, x NEVER equals x%3===0 or any of the other cases, that doesn't even mean anything. x just equals x all the time. That's why the machine just ignores the instruction. You are not redefining x with the switch function. And what you put inbetween the brackets describes x and x only, not anything related to x.
In short :
With if/else you can describe any condition.
With switch you can only describe the different values taken by the variable x.
Here's a solution incorporating #CarLuvr88's answer and a switch on 0:
let fizzBuzz = function(min, max){
for(let i = min; i <= max; i++){
switch(0){
case i % 15 : console.log('FizzBuzz'); break;
case i % 3 : console.log('Fizz'); break;
case i % 5 : console.log('Buzz'); break;
default : console.log(i); break;
}
}
}
fizzBuzz(1,20)
We can use a function to find a multiple of any number and declare two variables to identify these multiples so that if you want to change the multiples you only need to change at max 2 lines of code
function isMultiple(num, mod) {
return num % mod === 0;
}
let a = 3;
let b = 5;
for(i=0;i<=100;i++){
switch(true){
case isMultiple(i,a) && isMultiple(i,b):
console.log("FizzBuzz")
case isMultiple(i,a):
console.log("Fizz");
case isMultiple(i,b):
console.log("Buzz");
default:
console.log(i);
}
}

Categories

Resources