Unable to understand last condition of FizzBuzz in following code - javascript

I can understand how this code produces Fizz , Buzz when divisible by 3 , 5. But confused about how it produces FizzBuzz when divisible by both 3 and 5, because i do not see any if condition which satisfies divisible by both 3 and 5. Please explain.
for (let n = 1; n <= 100; n++) {
let output = "";
if (n % 3 == 0) output += "Fizz";
if (n % 5 == 0) output += "Buzz";
console.log(output || n);
}

Both if statement conditions evaluate to true, so it adds both "Fizz" and "Buzz" to "", which results in "FizzBuzz". The += operator is appending text to output.

The use of output += ...; allows for the variable to be populated with FizzBuzz if/when the iteration is divisible by both 3 AND 5.

I'm not sure i understand your issue
You don't understand why you get FizzBuzz sometimes ?
For example when n=15 you get it.
Because 15 % 3 = 0 ( 15 = 3*5 ) and 15 % 5 = 0 (15 = 5*3 )
It is the same for 30, 45, 60, 75, 90.

Related

How can I get results from a given array with following conditions? [duplicate]

This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Does return stop a loop?
(7 answers)
Closed 12 months ago.
I'm a beginner in JavaScript and doing an online test to improve my skills. I came across to this question:
Add 1 point for each even number in the array
Add 3 points for each odd number in the array
Add 5 points every time the number 5 appears in the array
So if I am given this array as an example:
([1,2,3,4,5])
the output should be 13
This is what I have got so far:
export function find_total( my_numbers ) {
for(let i = 0; i < my_numbers.length; i++){
if(my_numbers[i] % 2 === 0) {
total = total + 1
}
if(my_numbers[i] % 2 === 1) {
total = total + 3
}
if(my_numbers[i] === 5) {
total = total + 5
}
return total
}
console.log(total)
}
But it is giving me errors. I get the logic in English but couldn't put it in JS.
What would be the right syntax here?
The problem is with your if statements.
function find_total( my_numbers ) {
let total = 0;
for(let i = 0; i < my_numbers.length; i++){
if(my_numbers[i] === 5) {
total = total + 5
}
else if(my_numbers[i] % 2 === 0) {
total = total + 1
}
else if(my_numbers[i] % 2 === 1) {
total = total + 3
}
}
return total;
}
console.log(find_total([1,2,3,4,5]))
This code should print the correct result of 13.
You were not getting an answer of 13 because 5 is odd so has 3 point and 5 point exclusive to 5. The key is not to treat 5 as having point of odd number but having it's own point irrespective of either it is odd or even.
There are following issues in your code:
total in the function find_total is never initialized
return statement is misplaced inside the for loop, it must be outside, signifying return value of the function find_total
Better to console.log the value of the function, instead of logging it inside. eg. console.log(find_total(...))
Fixing these, you will indeed get the return value as 16 for input [1, 2, 3, 4, 5] as pointed out in the comments.
function find_total(my_numbers) {
let total = 0 // Initialize total with a value of 0
for (let i = 0; i < my_numbers.length; i++) {
if (my_numbers[i] % 2 === 0) {
total = total + 1
}
if (my_numbers[i] % 2 === 1) {
total = total + 3
}
if (my_numbers[i] === 5) {
total = total + 5
}
}
return total // return outside the loop
}
console.log(find_total([1, 2, 3, 4, 5])) // console.log outside

How to sum first n number of entries in an array?

I'm new to programming and learning about javascript recursion. It's my 5th day with JavaScript and following an online course.
The problem is that I need to sum up first n numbers of entries (first 3 numbers in this case) in an array.
But I'm ending up with sum of all and that also I'm not sure about.
var theArray = [1, 3, 8, 5, 7];
function sum(arr, n) {
if (n <= 0) {
return 1;
} else {
return arr[n - 1] + sum(arr, n - 2);
//assuming n is arr.length and n-1 is hence arr.length-1
}
}
console.log(sum(theArray, 3));
What am I doing wrong?
I checked most people are solving such with reduce method or with for of loop. I didn't learn those yet in the curriculum. But I know 'for loop' but that's good if the numbers are in incremental order I guess. Please explain this problem in my level.
When implementing something recursively, it's a good idea to think about the base condition. It does look like that's where you started, but your logic is flawed. n is the number of elements you would like to sum together. So let's say you want to sum the first n=3 elements of the array [2,3,4,5,6] and get 9. Here are the iterations.
return arr[n-1] + sum(arr, n-1) // arr[2] + sum(arr, 2) === 4 + sum(arr, 2) === 4 + 5
return arr[n-1] + sum(arr, n-1) // arr[1] + sum(arr, 1) === 3 + sum(arr, 2) === 3 + 2
return arr[n-1] // arr[0] === 2 (base case when n is 1)
I didn't solve the problem for you since this is obviously a school exercise, but the point is that the base case and the recursive call that you have are both slightly off.
Array of undetermined length, find the largest sum possible for any 3 consecutive numbers.
[2,0,1,100,200,10,7,2, 300,2,1 0] here 100,200,10 = 310 is the correct answer. Here only the combination of these 3 numbers produces the largest sum.
[2,1,0,20,71 = 0+20+7 = 27 is the answer that you should return.
const findMax = (numberArray) => {
let first = 0;
let second = 1;
let third = 2;
let max = 0;
for(; third < numberArray.length; first++, second++, third++) {
if(max < (numberArray[first] + numberArray[second] + numberArray[third])) {
max = numberArray[first] + numberArray[second] + numberArray[third];
}
}
return max;
}
console.log('Max sum of three consecutive numbers in array ===> ',findMax([2, 0, 100, 200, 10, 7, 2, 300, 2, 10]));

Checking multiples of 3 with a for loop

I'm looking to answer the question, but most important to understand where I did it wrong and why. In a certain way to learn how to do it.
So, the question is:
We've already declared a variable for you in the editor called number to which the value 42 was assigned.
Use a for loop to go through all numbers from number up to 50 (both inclusive), and check if they are multiples of 3. If they are, print them.
And I got to a point that I print to the console and I get the answer I want: 42, 45, 48.
But the console still gives me an error:
Remember the remainder operator? It might be of help to check if a number is a multiple of 3.
This is my code:
var number = 42;
var dividedbyThree = [];
for (var number = 42; number <= 50; number++) {
if (number % 3 == dividedbyThree) {
console.log(number);
}
}
What am I doing wrong?
Just replace
if (number % 3 == dividedbyThree)
with
if (number % 3 === 0)
DEMO:
var number = 42;
for (var number = 42; number <= 50; number++) {
if (number % 3 === 0) {
console.log(number);
}
}
The code will look like this
var number = 42;
for ( number = 42; number <=50; number++) {
if (number % 3===0) {
console.log(number); }
}
The number which returns 0 as the remainder when it is divisible by 3. So we check the remainder is equal to 0. if this condition satisfied console.log will print the number which is divisible by 3. if you need to push the numbers into new array, your code will look like this
var divBy3=[],number = 42;
for ( number = 42; number <=50; number++) {
if (number % 3===0) {
divBy3.push(number)
}
console.log(divBy3)
}

Sum of Array of Odd numbers - JS

Given the triangle of consecutive odd numbers:
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
// Calculate the row sums of this triangle from the row index (starting at index 1) e.g.:
rowSumOddNumbers(1); // 1
rowSumOddNumbers(2); // 3 + 5 = 8
I tried to solve this using for loops:
function rowSumOddNumbers(n){
let result = [];
// generate the arrays of odd numbers
for(let i = 0; i < 30; i++){
// generate sub arrays by using another for loop
// and only pushing if the length is equal to current j
let sub = [];
for(let j = 1; j <= n; j++){
// if length === j (from 1 - n) keep pushing
if(sub[j - 1].length <= j){
// and if i is odd
if(i % 2 !== 0){
// push the i to sub (per length)
sub.push(i);
}
}
}
// push everything to the main array
result.push(sub);
}
// return sum of n
return result[n + 1].reduce(function(total, item){
return total += item;
});
}
My code above is not working. Basically I was planning to 1st generate an array of odd numbers less than 30. Next I need to create a sub array base on the length of iteration (j) that would from 1 - n (passed). Then finally push it to the main array. And then use reduce to get the sum of all the values in that index + 1 (since the index starts at 1).
Any idea what am I missing and how to make this work?
Most code problems involve some analysis first in order to spot patterns which you can then convert into code. Looking at the triangle, you'll see the sum of each row follows a pattern:
1: 1 === 1 ^ 3
2: 3 + 5 = 8 === 2 ^ 3
3: 7 + 9 + 11 = 27 === 3 ^ 3
... etc
So from the analysis above you can see that your code could probably be simplified slightly - I won't post an answer, but think about using Math.pow.
No need for any loops.
function rowSumOddNumbers(n) {
// how many numbers are there in the rows above n?
// sum of arithmetic sequence...
let numbers_before_n_count = (n - 1) * n / 2;
let first_number_in_nth_row = numbers_before_n_count * 2 + 1;
let last_number_in_nth_row = first_number_in_nth_row + 2 * (n - 1);
// sum of arithmetic sequence again...
return n * (first_number_in_nth_row + last_number_in_nth_row) / 2;
}

JavaScript - Multiplying Even Indexed Array Elements by 2 and Odd Indexed by 3

I've been trying to write code that multiplies even indexed elements of an array by 2 and odd indexed elements by 3.
I have the following numbers stored in the variable number, which represents an array of numbers
numbers = [1,7,9,21,32,77];
Even Indexed Numbers - 1,9,32
Odd Indexed Numbers - 7, 21, 77
Please keep in mind that arrays are Zero Indexed, which means the numbering starts at 0. In which case, the 0-Indexed element is actually 1, and the 1-Indexed element is 7.
This is what I expected the output to be
[2,21,18,63,64,231]
Unfortunately, I got this output
[2,14,17,42,64,154]
Here is the code for my method
numbers = numbers.map(function(x) {
n = 0;
while (n < numbers.length) {
if (n % 2 == 0) {
return x * 2;
}
else {
return x * 3;
}
n++;
}});
return numbers;
Here I created a while loop, that executes code for every iteration of the variable n. For every value of the variable n, I'm checking if n is even, which is used by the code n % 2 == 0. While it's true that 0 % 2 == 0 it's not true that 1 % 2 == 0. I'm incrementing n at the end of the while loop, so I don't understand why I received the output I did.
Any help will be appreciated.
You created a global property called n, by doing
n = 0;
and then,
while (n < numbers.length) {
if (n % 2 == 0) {
return x * 2;
} else {
return x * 3;
}
}
n++; // Unreachable
you always return immediately. So the, n++ is never incremented. So, n remains 0 always and so all the elements are multiplied by 2 always.
The Array.prototype.map's callback function's, second parameter is the index itself. So, the correct way to use map is, like this
numbers.map(function(currentNumber, index) {
if (index % 2 === 0) {
return currentNumber * 2;
} else {
return currentNumber * 3;
}
});
The same can be written succinctly, with the ternary operator, like this
numbers.map(function(currentNumber, index) {
return currentNumber * (index % 2 === 0 ? 2 : 3);
});
To complement the other answer, the source of OP's confusion is on how "map" works. The map function is already called for each element - yet, OP attempted to use a while loop inside it, which is another way to iterate through each element. That is a double interaction, so, in essence, if OP's code worked, it would still be modifying each number n times! Usually, you just chose between a loop or map:
Using a loop:
var numbers = [1,7,9,21,32,77];
for (var i=0; i<numbers.length; ++i)
numbers[i] = i % 2 === 0 ? numbers[i] * 2 : numbers[i] * 3;
Using map:
var numbers = [1,7,9,21,32,77];
numbers.map(function(number, index){
return number * (index % 2 === 0 ? 2 : 3);
});
Or, very briefly:
[1,7,9,21,32,77].map(function(n,i){ return n * [2,3][i%2]; });
Basically you want to return a modified array that if the elements of the initial one is:
in even position, then multiply the element by 2.
in odd position, then multiply the element by 3.
You can use map with arrow functions and the conditional (ternary) operator to get this one-liner
console.log([1,7,9,21,32,77].map((num,ind) => num * (ind % 2 === 0 ? 2 : 3)));
This will output the desired
[2, 21, 18, 63, 64, 231]

Categories