How do I relate recursion to the remainder operator? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm using Eloquent JavaScript to learn JavaScript. I am a beginner and I would like to understand how this exercise works, it is about recursion and relating in to the remainder operator. I don't understand the comparison and I really would love to know how it works.
function isEven(n) {
if (n == 0) return true;
else if (n == 1) return false;
else if (n < 0) return isEven(-n);
else return isEven(n - 2);
}
console.log(isEven(50)) //true;
console.log(isEven(75)) //false;
console.log(isEven(-1)) //false;
I tried testing -2 in the log and it prints true, why does it do that?
I don't fully understand recursion or JavaScript that much, I would like it if this example is explained to me like I am 5.

Labeling the different decisions:
function isEven (n) {
if (n == 0) return true; // 1
else if (n == 1) return false; // 2
else if (n < 0) return isEven(-n); // 3
else return isEven(n - 2); // 4
}
when you call isEven(-2) it then calls isEven(2) according to // 3 which then calls calls isEven(0) according to // 4 which then returns true according to // 1

Related

Getting Undefined for this Javascript Function and Not Sure why [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 11 months ago.
Improve this question
Okay. So, I'm quite a newbie to JS, but not to programming in general. I've written a little bit of a recursive function (don't mind the logic here), that works perfectly in Python but returns undefined in JavaScript. This may totally be a noob thing here, but I can't really find the source of this issue, especially as it works fine in Python.
I had initially thought it was a control flow issue but I wrote other control flow functions that worked fine. Also, right before the final return statement, I console.log the array and the values are returned. Any help will be appreciated
path = []
let find_multiplier = (numb) => {
if (numb === 1) {
console.log("a result is possible for this number");
console.log(path)
return path;
} else if (numb > 1) {
if (numb % 3 === 0) {
path.push("multiply by 3");
find_multiplier(numb / 3);
} else {
path.push("add 5");
find_multiplier(numb - 5);
}
} else {
return false
}
};
console.log(find_multiplier(13)); // returns undefined. should return values.
console.log(find_multiplier(15)); // returns undefined. should return false.
The problem here is that 2 of your 4 conditions does not return anything.
You can fix this by adding the return keyword in front of your recursive call.
path = []
let find_multiplier = (numb) => {
if (numb === 1) {
console.log("a result is possible for this number");
console.log(path)
return path;
} else if (numb > 1) {
if (numb % 3 === 0) {
path.push("multiply by 3");
return find_multiplier(numb / 3); //here
} else {
path.push("add 5");
return find_multiplier(numb - 5); //here
}
} else {
return false
}
};
console.log(find_multiplier(13)); // returns undefined. should return values.
console.log(find_multiplier(15)); // returns undefined. should return false.
I believe two of your cases are missing return statements:
if (numb % 3 === 0){
path.push("multiply by 3");
return find_multiplier(numb / 3); // <-- add return here
} else {
path.push("add 5");
return find_multiplier(numb - 5); // <-- and here
}
However, you are also mutating a variable (path) outside of the scope of your function, so I would guess even they way you have it currently, path may actually contain the result you're looking for. I would choose to either mutate the out-of-scope path array and not try to also return it, or declare the variable in your function and return that, with a preference to the latter.

I need to sort out this algorithm [closed]

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 3 years ago.
Improve this question
could you please your help.
how to answer this question ?
I need your help thinks
function factorial(n) {
if (n === 0) {
return 1;
} else {
return n * n ;
}
}
factorial(6)
this is not right.. i need to use writing code with Loop javascript.
Get the factorial of n. The inheritance of n is the number 1 through n multiplied by all numbers.
example)
answer should be like this
factorial(4); // => 24
factorial(5); // => 120
One way is to use a simple for loop.
var answer = 1;
for(var i = 2; i <= n; i++)
{
answer *= i;
}
return answer;
You can also do this recursively by multiplying your input by the result of the previous value.
function factorial(n){
if(n <= 1) return 1;
return n * factorial(n-1);
}

Refactoring JS 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 7 years ago.
Improve this question
I was hoping someone could point me in the direction of a link/article that would help me understand refactoring JavaScript. I tend to use alot of nested if/else statements and want to learn to clean up code.
Any explanation on how you would refactor the code below would help tremendously. Thanks in advance!
var yourself = {
fibonacci : function(n) {
if (n === 0) {
return 0;
}
if (n === 1) {
return 1;
}
else {
return this.fibonacci(n - 1) +
this.fibonacci(n - 2);
}
}
};
For me, refactoring is mostly a matter of style and readability. First I noticed that the first two if branches look almost identical. Surely I can combine them somehow? So I did this:
var yourself = {
fibonacci : function(n) {
if (n === 0 || n === 1) {
return n;
}
else {
return this.fibonacci(n - 1) + this.fibonacci(n - 2);
}
}
};
Not too shabby. What else can we do? The if branches don't actually need braces. This is actually a dangerous habit, but I'll explain later.
var yourself = {
fibonacci : function(n) {
if (n === 0 || n === 1)
return n;
else
return this.fibonacci(n - 1) + this.fibonacci(n - 2);
}
};
Now let's get exotic and use the ternary operator!
var yourself = {
fibonacci : function(n) {
return (n === 0 || n === 1) ? n : this.fibonacci(n - 1) + this.fibonacci(n - 2);
}
};
Wow that's pretty ugly isn't it? Hard to read, all on one line, but so concise.
That's why it's important to re-evaluate every time you refactor.
Ask yourself: Is this easy to understand? Can I tell at a glance just what's going on? In that last example we lost a lot of indentation which is helpful for figuring out the general structure and flow of your code. We lost some helpful visual information by preferring concise code.
I wouldn't go with the second refactor attempt either. Removing those braces is a bad idea because it only works with one-line branches. If you go back later and add a second line, but you forget to add the braces back then you'll get a very cryptic error when you try to run your code.
I think your original code is actually great. It's concise and clear, and easy to understand. It literally spells out the definition of the fibonacci function: "If it's 0 or 1, return that. Otherwise, recursively compute the result."
Refactoring comes from experience, from twiddling with the code until it looks right, and from constantly asking yourself whether this is really an improvement. Value clarity above all, then performance, and be wary of conciseness.
For some extra reading, the AirBnB style guide is well regarded:
https://github.com/airbnb/javascript
Just use a cache.
var yourself = {
cache : {},
fibonacci : function(n) {
if (n === 0) {
return 0;
}
if (n === 1) {
return 1;
}
if(this.cache[n]){
console.log('cache return');
return this.cache[n];
}
else {
this.cache[n] = this.fibonacci(n - 1) +
this.fibonacci(n - 2);
return this.cache[n];
}
}
};
console.log(
yourself.fibonacci(12)
)
In this case I think I would note that a return is a return (exit path) from the code. The else should be unnecessary.
var yourself = {
fibonacci : function(n) {
// Return quickly for the trivial cases
if (n < 2) { return n; }
// ...otherwise calculate it recursively
return this.fibonacci(n - 1) + this.fibonacci(n - 2);
}
};
A good book is Code Complete. I can't tell you if the latest revision includes JavaScript yet it goes into great detail about cleaning up code and the benefit of good source code formatting.
Others will strongly disagree to the fact that I didn't add a hard return after the if statement and yet I find this short test-and-exit code style to make for faster reading.

Writing recursive function to identify even/odd [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 7 years ago.
Improve this question
I am working an assignment for Eloquent JavaScript asking you to write a recursive rule to test for 'evenness' of a number. I am always getting false as a return. Please someone help identify my error.
function isEven(num){
if(num===0){
return(true);
}else if (num === 1){
return(false);
}else {
num = num - 2;
return(find(num));
}
}
};
console.log(isEven(12));
The whole point of recursion if to call the function within itself. You are really close, but you call find in your function rather than isEven(num - 2)
function isEven(num){
if(num===0){
return(true);
}else if (num === 1){
return(false);
}else {
return(isEven(num - 2));
}
}
console.log(isEven(12));
function isEven(n) {
if (n === 0) return true;
if (n === 1) return false;
return isEven(n - 2);
}
However, it's very inefficient. Better to use something like this (e.g. in a real code):
function isEven(n) {
return n % 2 === 0;
}
following will solve your problem
<html>
<head>
<script language="javascript">
function isOdd(x) {
return !isEven(x);
}
function isEven(x) {
if(x===0) {
return true;
} else {
return isOdd(x-1);
}
}
alert(isOdd(6));
</script>
</head>
<body>
</body>
</html>

Javascript Equal Probability [closed]

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 8 years ago.
Improve this question
Hi I need a probability in javascript that is a function and returns X 1 in every 2 times and Y 1 in every 30.2 times. The rest of the time the function should returns Z.
The function should be able to be called many times in a row.
This is what I have came up with so far
probability(){
var randomNumber = random() * 100;
if (randomNumber > 50) {
x()
}
else if (randomNumber > 3.31125827815 ) {
y()
}
else {
z()
}
}
Currently, your function will call y() if randomNumber is between 3.3 and 50. You probably want < instead of >
else if (randomNumber < 3.31125827815 ) {
It might make it a bit more readable to sort the intervals in ascending order:
function probability(){
var r = random();
if (r < 1/30.2){
y();
}else if(r < 0.5){
z();
}else{
x();
}
}

Categories

Resources