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 am trying to figure out what I am doing wrong with this problem. I seem to be missing something that is not allowing my code to work. I need to use a function to create an array that takes one number n, and that loops through an array from the numbers 1 - 16, while also replacing all the numbers divisible by 3 with the string 'fizz', and all divisible by 5 with the word 'buzz', and any number that is divisible by both must be replaced by the string 'fizzbuzz'.
I have gone over this several times but for some reason keep coming up with just an empty array for my result when it is logged to the console. I would greatly appreciate it if someone could give me some tips as to why my code isn't working so that I can understand the concept easier. Here is my code:
const results = [];
const fizzbuzz = (n) => {
var results = []
for (let n = 1; results.length < 16; n++) {
if (n % 3 === 0 && n % 5 === 0) {
results.push('FizzBuzz')
} else if (n % 3 === 0) {
results.push('fizz');
} else if (n % 5 === 0) {
results.push('buzz')
} else {
results.push(n)
}
}
return results
};
fizzbuzz(16);
console.log(results);
This is what it is supposed to come out to:
[1, 2, 'fizz', 4, 'buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz', 13, 14, 'fizzbuzz', 16]
But this is what I keep getting as an answer:
[]
Your fizzbuzz function returns results, so just assign that to a variable and log it:
var results = fizzbuzz(16);
console.log(results);
You are playing with another results inside the function, and outside the function result will remain empty. If you remove the variable which is inside the function now every manipulation will be on the same variable.
const results = [];
const fizzbuzz = (num) => {
for(let n=1; n<num; n++){
if(n%3 === 0 && n % 5 === 0){
results.push('FizzBuzz')
}
else if(n % 3 === 0){
results.push('fizz');
}
else if(n % 5 === 0){
results.push('buzz')
}
else {
results.push(n)
}
}
};
fizzbuzz(16);
console.log(results);
Your first issue is that the results variable declared outside your function and the results variable declared inside your function are totally different variables. You only need to declare the variable in the function, then you can make a new variable to hold the function result:
const res = fizzbuzz(16);
console.log(res);
or even simpler:
console.log(fizzbuzz(16));
The second issue is in your for loop, you are reassigning n when you should be making a new variable (most commonly called i). You also use a static number (16) as your limit in the expression results.length < 16, when you should use the variable n:
for (let i = 0; results.length < n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
results.push('FizzBuzz')
} else if (i % 3 === 0) {
results.push('fizz');
} else if (i % 5 === 0) {
results.push('buzz')
} else {
results.push(i)
}
}
Overall you are taking the correct approach, but you should review variables and for loops as you are using both a bit incorrectly.
There are two glaring issues with your code.
You define the variable results twice, one as a constant and one as var.
If you remove the var results = [] definition, your code will work, as it's able to store the results through closures. Basically, the scope of your const results encapsulates the scope of your function, so your function will have access to const results = []
Your function isn't returning anything. This wouldn't be a problem if you were attempting to store the results via closures, but looking at your code, that wasn't your intention. What you should've done is store the results in a variable, as
const results = fizzbuzz(16)
This is my FizzBuzz implementation that uses Array.from() to generate an array with the fizz/buzz/number according to the rules:
const fizzbuzz = length => Array.from({ length }, (_, i) => {
if (i % 3 === 0 && i % 5 === 0) return 'FizzBuzz';
if (i % 3 === 0) return 'fizz';
if (i % 5 === 0) return 'buzz';
return i;
})
const results = fizzbuzz(16); // assign the return value of the function to results
console.log(results);
Related
I'm struggling to comprehend recursion (I'm just a student) at its core, right now with one particular exercise I'm trying to do.
In the exercise, I'm trying to sum over the odd numbers of an integer, to do that, I have set another condition in order to only check odds (n % 2 === 0) n = n - 1:
const addOdds = (n) => {
if (n === 0) return 0;
if (n % 2 === 0) n = n - 1;
let result = n + addOdds(n - 1);
return result;
}
console.log('Result of addOdds:',addOdds(7));
Shouldn't the recursion count down from 7? It goes up 1, 3, 5, 7 until the base case is met.
Well, check first condition, n===0, it's not and pass the next one:
7%2 = 1. It means it doesn't equal zero then It will move to the next one and call function. Here the main case is calling function recursively and then n starts execution
Im solving a codewars problem and im pretty sure i've got it working:
function digital_root(n) {
// ...
n = n.toString();
if (n.length === 1) {
return parseInt(n);
} else {
let count = 0;
for (let i = 0; i < n.length; i++) {
//console.log(parseInt(n[i]))
count += parseInt(n[i]);
}
//console.log(count);
digital_root(count);
}
}
console.log(digital_root(942));
Essentially it's supposed to find a "digital root":
A digital root is the recursive sum of all the digits in a number.
Given n, take the sum of the digits of n. If that value has two
digits, continue reducing in this way until a single-digit number is
produced. This is only applicable to the natural numbers.
So im actually getting the correct answer at the end but for whatever reason on the if statement (which im watching the debugger run and it does enter that statement it will say the return value is the correct value.
But then it jumps out of the if statement and tries to return from the main digital_root function?
Why is this? shouldn't it break out of this when it hits the if statement? Im confused why it attempt to jump out of the if statement and then try to return nothing from digital_root so the return value ends up being undefined?
You're not returning anything inside else. It should be:
return digital_root(count);
^^^^^^^
Why?
digital_root is supposed to return something. If we call it with a one digit number, then the if section is executed, and since we return from that if, everything works fine. But if we provide a number composed of more than one digit then the else section get executed. Now, in the else section we calculate the digital_root of the count but we don't use that value (the value that should be returned). The line above could be split into two lines of code that makes it easy to understand:
var result = digital_root(count); // get the digital root of count (may or may not call digital_root while calculating it, it's not owr concern)
return result; // return the result of that so it can be used from the caller of digital_root
Code review
My remarks is code comments below
// javascript generally uses camelCase for function names
// so this should be digitalRoot, not digital_root
function digital_root(n) {
// variable reassignment is generally frowned upon
// it's somewhat silly to convert a number to a string if you're just going to parse it again
n = n.toString();
if (n.length === 1) {
// you should always specify a radix when using parseInt
return parseInt(n);
} else {
let count = 0;
for (let i = 0; i < n.length; i++) {
//console.log(parseInt(n[i]))
count += parseInt(n[i]);
}
// why are you looping above but then using recursion here?
// missing return keyword below
digital_root(count);
}
}
console.log(digital_root(942));
Simple recursive solution
With some of those things in mind, let's simplify our approach to digitalRoot...
const digitalRoot = n =>
n < 10 ? n : digitalRoot(n % 10 + digitalRoot((n - n % 10) / 10))
console.log(digitalRoot(123)) // => 6
console.log(digitalRoot(1234)) // 10 => 1
console.log(digitalRoot(12345)) // 15 => 6
console.log(digitalRoot(123456)) // 21 => 3
console.log(digitalRoot(99999999999)) // 99 => 18 => 9
Using reduce
A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.
If you are meant to use an actual reducing function, I'll show you how to do that here. First, we'll make a toDigits function which takes an integer, and returns an Array of its digits. Then, we'll implement digitalRoot by reducing those those digits using an add reducer initialized with the empty sum, 0
// toDigits :: Int -> [Int]
const toDigits = n =>
n === 0 ? [] : [...toDigits((n - n % 10) / 10), n % 10]
// add :: (Number, Number) -> Number
const add = (x,y) => x + y
// digitalRoot :: Int -> Int
const digitalRoot = n =>
n < 10 ? n : digitalRoot(toDigits(n).reduce(add, 0))
console.log(digitalRoot(123)) // => 6
console.log(digitalRoot(1234)) // 10 => 1
console.log(digitalRoot(12345)) // 15 => 6
console.log(digitalRoot(123456)) // 21 => 3
console.log(digitalRoot(99999999999)) // 99 => 18 => 9
its a recursive function the code should be somewhat like this
function digital_root(n) {
// ...
n=n.toString();
if(n.length === 1){
return parseInt(n);
}
else
{
let count = 0;
for(let i = 0; i<n.length;i++)
{
//console.log(parseInt(n[i]))
count+=parseInt(n[i]);
}
//console.log(count);
return digital_root(count);
}
}
you should return the same function instead of just calling it to get the correct call stack
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
can anybody please hint me what is wrong in my Javascript function below?
I am finding the maximum multiple between two numbers.
When I write the code which is not inside the function in my testing window it works and it gives me what I need, but if I want to enclose it in my function the output is undefined. I believe that I miss something stupid but I have been solving that for several hours and I can not see it.
function maxMultiple(d, b){
const arr = [];
for (let i=b; i<=d; i+=b) { // i = i + b
arr.push(i)}
if (d>0 && b>0){
return arr.pop(); // does not work - undefined
} else {
return d; }
}
console.log(maxMultiple(7,100)); // Output is undefined
// it works....
/*
let b = 7;
const d = 100;
const arr = [];
for (let i=b; i<=d; i+=b) { // i = i + b
arr.push(i);
}
console.log(arr.pop()); //Output is 98
*/
Looks like you've interchanged the variables b and d. Just swap the parameters in the function signature, and you'll get what you expect.
The example you've shared will is working because you've used b as 7 and d as 100.
While in the actual code, the params you're passing are as follows:
b - 100, d - 7.
Therefore the for loop isn't executing even once, thereby logging undefined as mentioned by you.
Hope that helps!
Issue with this line for (let i = b; i <= d; i += b). In your program d is 7 and b is 100 so no element is ever pushed to array
function maxMultiple(d, b) {
const arr = [];
for (let i = b; i <= d; i += b) { // i = i + b
arr.push(i)
}
if (d > 0 && b > 0) {
return arr.pop(); // does not work - undefined
} else {
return d;
}
}
console.log(maxMultiple(7, 100));
Because 100 is less than 7. Array is empty. Nothing ever got pushed.
My guess is you got the two parameters in the wrong order.
function maxMultiple(d, b){
const arr = [];
for (let i=b; i<=d; i+=b) { // i = i + b
arr.push(i)
}
console.log(arr.length === 0); // array is empty here
if (d>0 && b>0){
let res; // cache result
// pop() on empty array always gives undefined
console.log([].pop() === (res = arr.pop()));
return res; // does not work - undefined
} else {
return d;
}
}
console.log(maxMultiple(7,100)); // Output is undefined
http://instacode.dev/#CmZ1bmN0aW9uIG1heE11bHRpcGxlKGQsIGIpewogIGNvbnN0IGFyciA9IFtdOyAKICBmb3IgKGxldCBpPWI7IGk8PWQ7IGkrPWIpIHsgLy8gaSA9IGkgKyBiCiAgICAgICBhcnIucHVzaChpKQogIH0KICAKICBjb25zb2xlLmxvZyhhcnIubGVuZ3RoID09PSAwKTsgLy8gYXJyYXkgaXMgZW1wdHkgaGVyZQogIAogIGlmIChkPjAgJiYgYj4wKXsKICAgIGxldCByZXM7IC8vIGNhY2hlIHJlc3VsdAogICAgLy8gcG9wKCkgb24gZW1wdHkgYXJyYXkgYWx3YXlzIGdpdmVzIHVuZGVmaW5lZAogICAgY29uc29sZS5sb2coW10ucG9wKCkgPT09IChyZXMgPSBhcnIucG9wKCkpKTsKICAgICByZXR1cm4gcmVzOyAvLyBkb2VzIG5vdCB3b3JrIC0gdW5kZWZpbmVkCiAgfSBlbHNlIHsgCiAgCXJldHVybiBkOwogIH0KIH0KCmNvbnNvbGUubG9nKG1heE11bHRpcGxlKDcsMTAwKSk7ICAvLyBPdXRwdXQgaXMgdW5kZWZpbmVkCg==
I'm doing a kata on Codewars. I'm supposed to write a function that returns the index of which number, is not like the others, in evenness(i.e. [1, 2, 4] should return 0). I believe I have a solution, and it proves true when copy/pasting the code, and console.logging on freecodecamps live server, however, when i try to run the code where it is written, it only passes one test. What is going wrong here?
I've tried testing with console.logs, and my solution holds. I know I could just use filter to solve the problem, but i wan't to practice fundamentals.
let odd = [];
let even = [];
function isEven(num) {
if (num % 2 === 0) {
return true;
} else {
return false;
}
}
function iqTest(numbers) {
let nums = numbers.split(' ').map(function(item) {
return parseInt(item, 10);
})
for (let i in nums) {
if (isEven(nums[i])) {
even.push(nums[i])
} else {
odd.push(nums[i])
}
}
if (even.length > odd.length) {
return nums.indexOf(odd[0]) + 1;
} else {
return nums.indexOf(even[0]) + 1;
}
}
The function should accept a string of numbers, one of which will not be either even or odd, then return the index of that number + 1.
You could take the in comments mentioned approach and search for at least one odd and one even and one additional item, at least three items and exit early if this combination is found.
No need to convert the values in advance, because the value get converted to number by using the remainder operator of isEven function.
For a faster return value store the index instead of the value and omit a later indexOf seach.
function isEven(i) { return i % 2 === 0; }
function iqTest(numbers) {
var even = [], odd = [], values = numbers.split(' ');
for (let i = 0; i < values.length; i++) {
(isEven(values[i]) ? even : odd).push(i);
if (even.length && odd.length && even.length + odd.length > 2)
return (even.length < odd.length ? even : odd)[0] + 1;
}
}
console.log(iqTest("1 2 4")); // 1
console.log(iqTest("2 4 7 8 10")) // 3
console.log(iqTest("1 2 1 1")); // 2
Should add all the natural numbers below 1000 that are multiples of 3 or 5.
var sum = _.reduce( _.range(1, 1000), function(x, n) {
if (n % 3 == 0 || n % 5 == 0) { return x+=n; }
}, 0);
I expect the output to be 233168 but I get NaN.
For some reason sum is not accepting the initialized value of 0. However if I preface this with var sum = 0; then it works and returns the proper output of 233168
Why doesn't it accept the initialized value?
The problem is the reducing function returns undefined when the conditional fails .. thus x evaluates to undefined (the last return value) in the subsequent invocation .. and undefined + a number is .. well, NaN.
Also, reduce is being used incorrectly; it should carry its own state. Compare it with:
var sum = _.reduce( _.range(1, 1000), function(x, n) {
// Add n to the tally if it is a valid multiple..
// (the returned value is used as the *next* value of x)
if (n % 3 == 0 || n % 5 == 0) { return x + n; }
// ..or simply return the current tally.
else { return x; }
}, 0);
Note that the sum variable was not assigned from within the reducing function (it would have been overwritten by the outside assignment anyway). This keeps reduce a pure operation, not withstanding the occasional abuse of a mutable memo, truer to its functional roots.