the First one doesn't work, its just trying to find a factorial, it returns NaN, so why is it if you use else if it doesnt work?
function FirstFactorial(num) {
if (num == 0) {
return 1;
}
else if (num > 1) {
return num * FirstFactorial(num - 1);
}
}
console.log(FirstFactorial(3)) === NaN
function factorial(n) {
if(n == 0) {
return 1
}
else {
return n * factorial(n - 1);
}
}
console.log(factorial(3)) == 6
You're missing a case for num === 1, so when you do
function FirstFactorial(num) {
if (num == 0) {
return 1;
}
else if (num > 1) {
return num * FirstFactorial(num - 1);
}
}
FirstFactorial(3);
You're doing
3 * FirstFactorial(2);
3 * 2 * FirstFactorial(1);
3 * 2 * undefined; // NaN
Re-arrange the function logic thus
function FirstFactorial(num) {
if (num > 1) {
return num * FirstFactorial(num - 1);
}
return 1;
}
Related
I am trying to solve the Fizz Buzz question with an extra layer.
This is what I have so far. All this works fine but I need one more extra condition.
It's JS Unit testing
For any other input (valid or otherwise) return a string representation of the input
printFizzBuzz = function(input) {
// Your code goes here
for (var i = 1; i <= 20; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("FizzBuzz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
}
};
Thank you!
You can use .toString() (JS toString) to change the number in string:
function printFizzBuzz(input) {
// Your code goes here
for (var i = 1; i <= 20; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("FizzBuzz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i.toString());
}
}
};
printFizzBuzz();
Looking at the question, it is not asking for a loop, it is asking for any value passed to the function. So the answer should look more like this
function printFizzBuzz(input) {
// Your code goes here
if (typeof input !== ‘number’) {
return String(input)
}
let by3 = input % 3
let by5 = input % 5
switch(0) {
case by3 + by5:
return "FizzBuzz"
case by3:
return "Fizz"
case by5:
return "Buzz"
default:
return input.toString()
}
}
}
If I was the interviewer, I would prefer the answer to look more like this
function printFizzBuzz(input) {
// Your code goes here
for (var i = 1; i <= 20; i++) {
let by3 = i % 3
let by5 = i % 5
switch(0) {
case by3 + by5:
console.log("FizzBuzz")
break
case by3:
console.log("Fizz")
break
case by5:
console.log("Buzz")
break
default:
console.log(i.toString())
}
}
}
}
printFizzBuzz()
I have an (almost) working solution for a coding challenge:
function addLetters(...letters) {
let sum = 0;
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
if (typeof letters === 'undefined' || letters === [] || letters === undefined) {
return 'z';
}
for (let i = 0; i < letters.length; i++) {
sum += (alphabet.indexOf(letters[i]) + 1);
}
if (sum <= 26) {
return alphabet[sum - 1];
} else {
while (sum > 26) {
sum = (sum - 26);
if (sum <= 26) {
return alphabet[sum - 1];
}
}
}
}
console.log(addLetters())
But as you can see, in this particular case of console.log(addLetters()), it's returning undefined instead of 'z' - why is that?
I think it must have something to do with the way that ...letters is a rest / default / destructured / spread argument.
The challenge does, in fact, want the argument to appear as a spread, but I don't know how to accommodate for it.
EDIT Test specs for challenge:
letters === []
Will always be false, as these are two different references which will never evaluate to true, you need to check the length of array to check if it's empty or not
Also you can safely remove the other two conditions from if statement as letters will always be an array
function addLetters(...letters) {
let sum = 0;
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
if (letters.length === 0) {
return 'z';
}
for (let i = 0; i < letters.length; i++) {
sum += (alphabet.indexOf(letters[i]) + 1);
}
if (sum <= 26) {
return alphabet[sum - 1];
} else {
while (sum > 26) {
sum = (sum - 26);
if (sum <= 26) {
return alphabet[sum - 1];
}
}
}
}
console.log(addLetters())
Try this. :)
function addLetters(...letters) {
let sum = 0;
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
if (!letters.length) {
return 'z';
}
for (let i = 0; i < letters.length; i++) {
sum += (alphabet.indexOf(letters[i]) + 1);
}
if (sum <= 26) {
return alphabet[sum - 1];
} else {
while (sum > 26) {
sum = (sum - 26);
if (sum <= 26) {
return alphabet[sum - 1];
}
}
}
}
I wanted something to be returned as output but not able to.
function arrsort(arr){
return arr.sort(function(a, b){return a - b});
}
const binarySearch=(arr,num,start,end)=>{
arr=arrsort(arr);
start=0;
end=arr.length;
var mid = Math.floor(end / 2);
if (arr[mid] === num) {
return true;
} else if (arr[mid] < num && end > 1) {
binarySearch(arr.splice(mid, Number.MAX_VALUE), num,start,end);
} else if (arr[mid] > num && end > 1) {
binarySearch(arr.splice(start, mid), num,start, end);
} else {
return false;
}
}
I expected the output as true or false.
You need some more return statements before calling the same function again.
And while you return for every true if statement, you could omit else.
function arrsort(arr) {
return arr.sort(function(a, b) {
return a - b;
});
}
const binarySearch = (arr, num, start, end) => {
arr = arrsort(arr);
start = 0;
end = arr.length;
var mid = Math.floor(end / 2);
if (arr[mid] === num) {
return true;
}
if (arr[mid] < num && end > 1) {
return binarySearch(arr.splice(mid, Number.MAX_VALUE), num, start, end);
}
if (arr[mid] > num && end > 1) {
return binarySearch(arr.splice(start, mid), num, start, end);
}
return false;
}
I can't get theright result, "Weird" on stdin, 18 and 20. Everything looks good to me, however something must be off.
if (N % 2 == 1) {
console.log("Weird");
}
else if ((N % 2 == 0) && (2 >= N <= 5)) {
console.log("Not Weird");
}
else if ((N % 2 == 0) && (5 <= N <= 20)) {
console.log("Weird");
}
else if ((N % 2 == 0) && (N > 20)) {
console.log("Not Weird");
}
else {
console.log("Weird");
}
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.replace(/\s*$/, '')
.split('\n')
.map(str => str.replace(/\s*$/, ''));
main();
});
function readLine() {
return inputString[currentLine++];
}
function main() {
const N = parseInt(readLine(), 10);
if (N%2==1) {
console.log("Weird");
}
else if ((N % 2 == 0) && (2 >= N <= 5)) {
console.log("Not Weird");
}
else if ((N % 2 == 0) && (5 <= N && N <= 20)) {
console.log("Weird");
}
else if ((N % 2 == 0) && (N > 20)) {
console.log("Not Weird");
}
else{
console.log("Weird");
}
}
I ve added the whole code. In the main function, in the second else if condition, there seems to be the problem. When n is given 18 or 20, I can not get the right output which should be "Weird"
You can't be doing two conditions in the same time
if (5<=N<=20) {}
Will evaluate 5<=N first which produces either true/false which are when compared to numbers will evaluate to (1/0) respectively. Then the second part ( <= 20) will be evaluated.
Combine two conditions only with AND / OR operators
if (5 <= N && N <= 20) {}
This will solve your problem.
I am trying to do an exercise from here https://www.w3resource.com/javascript-exercises/javascript-recursion-function-exercise-7.php
I understand the solution, however, I am kind of curious why my program does not yield the same answer as above. The way I choose the return the function is slightly different, however, it yields a number instead of true or false.
function checkeven(num) {
if (num === 0) {
return true;
} else if (num === 1) {
return false;
} else {
console.log(num);
return num - checkEven(num - 2);
}
}
console.log(checkeven(8));
console.log(checkeven(9));
In JavaScript - when the operands to an operator are of different types - type corecion happens, i.e it tries to convert one of the operands into a type that is compatible with the operator
Try this:
console.log(2 + true) //3
console.log(true + false) //1
In your case, consider what happens when you try checkeven(2)
checkeven(2) = 2 - checkeven(0) = 2 - true = 1
Replace return num - checkeven(num - 2) with return checkeven(num - 2) in your code.
function checkeven(num) {
if (num === 0) {
return true;
} else if (num === 1) {
return false;
} else {
return checkeven(num - 2);
}
}
console.log(checkeven(8));
console.log(checkeven(9));
Concocted a solution with both positive and negative numbers!
var isEven = function (n) {
if (n > 0) {
return positive(n);
} else {
return negative(n);
}
function negative(num) {
if (num === 0) {
return true;
} else if (num === -1) {
return false;
} else {
return isEven(num + 2);
}
}
function positive(num) {
if (num === 0) {
return true;
} else if (num === 1) {
return false;
} else {
return isEven(num - 2);
}
}
};
console.log(isEven(9));
console.log(isEven(8));
console.log(isEven(-8));
your code had issue since you we trying to subtract from a boolean value , Due to which type corecion occurs as per the rules given under ecmascript guidlines.(https://www.ecma-international.org/ecma-262/7.0/#sec-ordinary-and-exotic-objects-behaviours)
you can go with the following solution:
(function fixthis() {
function checkeven(num) {
if (num === 0) {
return true;
} else if (num === 1) {
return false;
} else {
let Tempnum = num - 2;
if (checkeven(Tempnum)) {
return true;
} else {
return false;
}
}
}
console.log(checkeven(8));
console.log(checkeven(9));
})()
return checkeven(num-2);, returns a boolean value. You are trying to subtract a boolean value from a number, which won't work. Your code will work just fine if you remove num-checkeven(num-2)* and replace it with checkeven(num-2);
You can do:
odd = function(n) {if (n%2 == 0) {return true} else {return false;}}
console.log(odd(8));
console.log(odd(5));
or:
checkeven = function(num) {
if (num === 0) {
return true;
} else if (num === 1) {
return false;
} else {
return checkeven(num - 2);
}
}
console.log(checkeven(8));
console.log(checkeven(9));
You can also use the modulo operator, so you don't even need recursion
const areYouEven = n => !(n % 2)