Can't get it how the function works - javascript

So basically i just started learning JS and had a little exercise which was basically making a function to check if the number is even without using modular arithmetic. When i was done with it i just wanted to compare mine with the answer and i couldn't really get how does it work.
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);
}
I'm not sure how the part (n-2) works does it somehow puts the number in a loop and basically does n-=2 until the number gets 1 or 0?

Let's take a look at what is going on behind the scenes when this function is run:
isEven(8)
// isEven(8) Is 8 even?
// isEven(6) Is 6 even?
// isEven(4) Is 4 even?
// isEven(2) Is 2 even?
// isEven(0) Is 0 even? --> Yes, the function immediately returns true
// so I know the one at the top, 8, is even
And so on. For any even number, it eventually gets to 0. For any odd number it eventually gets to 1.

If the number is negative, the function makes it positive and runs itself again against the positive value, if it's > 1, it will run itself again until the number is 1 or 0, decreasing the number by 2 on each iteration. It's called recursion.

When n <0 it puts a minus before the n in the function and runs it again. If Else then the function is called again but n is decreased by 2. This runs till you get true or false.

Related

Recursions Javascript - Freecodecamp

beginner here. Was working through a code question on fcc and came across some javascript code I can't seem to understand.
function sum(arr, n) {
// Only change code below this line
if (n <= 0) {
return 0;
} else {
return sum(arr, n - 1) + arr[n - 1]
}
// Only change code above this line
}
console.log(sum([2, 3, 4, 5], 3))
// Console then spits out "9"
I understand how the second have of the return statement "arr[n - 1]" produces
4", but I'm unsure of how the first half "sum(arr, n - 1)" comes up with the number "5" that when added to 4, gives me the number "9" in the console.
I've narrowed it down to "sum(arr, 2)", but I can't seem to understand what the code is doing?
Thank you in advance!
sum(arr,2) calls the same function "sum" with the same arr parameter and a limit that's 2 instead of 3.
While the first call (inside console.log) is supposed to add a number of parameters (3), the second call (inside the first) should add all parameters but the last one (2), which is added explicitely.
That's the point of recursion: a function that calls itself until a specific condition is met. The condition in this case is if there is no element left to be added (n<=0). Up to this all numbers appear as "arr[n-1]" in the chain of calls and are added to 0 (which is the return value in the case of the ending condition). So the actual sum is calculated as all recursive calls return one after the other.

How to do something indefinitely until a condition is met, with no loop?

Whenever I use a loop, the tab crashes. I can't seem to figure out how to work this out. I just start typing while(true) {document.getElementById("loadingText").textContent++;} and before I can type if(document.getElementById("loadingText").textContent === "100") {break;} the screen freezes and the tab crashes. Can someone help me?
Since you're using an online editor with real-time browser updates based on changes, you need to make sure you don't make your code loop infinitely. Sadly that's what while (true) { // code } does if there's no code in the statement to break the loop.
For the timebeing, until you've figured out the meat of that loop, just intentionally cause an error:
while (i <= 100) { // code }
which you can go ahead an amend until you get the desired result.
There are a couple of things you should take into account.
1) You should cache the element once so you're not repeatedly grabbing it on each loop iteration.
2) textContent is a string, so you can't use el.textContent++ as it won't be successfully evaluated.
3) You'll find it difficult to slow a traditional loop down so that you can see the number increment properly.
So here's a method using setTimeout instead of a traditional loop.
// Cache the element
const el = document.getElementById("loadingText");
(function displayNumber(n, end) {
// Repeat until the iteration number (n)
// is 10 (for this example)
if (n <= end) {
el.textContent = n;
// Wait 0.5s then call the function again with an increased n
setTimeout(() => displayNumber(++n, end), 500);
}
// Pass in the initial number, and the end limit
}(1, 10));
<div id="loadingText"></div>
You are asking if your property is === "100" as ++ increment the numeric value, the loop never breaks, compare to 100 instead of "100" as string
if(document.getElementById("loadingText").textContent == "100") {break;}
or
if(document.getElementById("loadingText").textContent === 100) {break;}
I dont think that a textContent could be incremented. Try Node.value++.
If this still doesn't works. To run an infinite loop you can use setInterval(); method.
example:
var i=0;
var z = setInterval(foo,10);
function foo() { alert(i); }
In the above example the function foo() will execute infintely with a gap of 10 mili seconds. You can put it to 0 ms as well if you wish to.

Check if a word is within various sub-intervals of an array

I have an array of words (25 of them, 0-24) and I want to do tests in a for loop that checks whether the randomly chosen word is within the interval 0-4, 5-9, 10-14 etc..
How do I do this?
else if (words[i > 4 && <= 9]){}
I tried that line in a for loop, but it gives me a syntax error.
Uncaught SyntaxError: Unexpected token <=
You're missing a left comparison in your condition. Use this as a condition:
i > 4 && i <= 9
However, note that you're not doing anything useful with the condition. Your result will be akin to words[true] or words[false].
Update
You've now elaborated a little more. If I understand you correctly, you want to pick a random word from your array, and then work out which interval of 5 it resides at within the array.
In the below example, the interval is indexed; so 0 = 0-4, 1 = 5-9, 2 = 10-14 and so on...
var words = [ "Synergetic", "unsteeped", "goldcup", "coronach", "swamper", "rehearse", "rusty", "reannotation", "dunne", "unblenched", "classification", "interpolation", "toper", "grisliest.", "Rechart", "imbower", "reilluminating", "glucagon", "interassuring", "parallelepipedon", "doyenne", "neenah", "tetragram" ];
function pickARandomWordAndCheckTheInterval(){
var randomIndex = Math.floor(Math.random() * words.length);
var word = words[randomIndex]
var interval = Math.floor(randomIndex / 5);
console.log('The random word is:' + word);
console.log('The interval is:' + interval );
}
pickARandomWordAndCheckTheInterval();
To explain it really really simple way you just forgotten to tell the language what needs to be less than or equal 9.
You assumed it processes logic condition like humans do (we would assume that after && operator you're still thinking about i, but that's not what JS interpreter would do).
What comes after && needs to be an expression that can be evaluated. <= 9 doesn't evaluate to value (it is not treated as valid expression because <= is kind of binary operator which requires two operands, one before and one after).
For JS interpreter it just means "less than or equal to 9". But what is "less than or equal to 9"? You need to tell it "i is less than or equal to 9".
i > 4 && i <= 9 is the correct way to write that.

Recursive even function issue with understanding (Javascript)

The problem is very simple, I have a function from 'Javascript Allonge' book, and having a hard time in understanding it.
The function is called even, and it's as follows:
var even = function(num) {
return (num === 0) || !(even(num -1));
}
it checks whether the number is even or not, but I do not understand how. It calls itself recursively, and technically, always reaches zero, no? How does that work?
This is based on an inductive definition of numbers being odd or even - a number, n is 'even' when the number before it, n - 1 is odd. This thinking naturally makes sense - 4 is even if 3 is odd.
And so the function even is defined as:
1. even(0) is true - because 0 is even
2. even(n) is the negation of even(n - 1)
Another way to think of it is imagine even(4) being called step by step. By hand, replace the even(4) with result of evaluation it with your function:
even(4)
= !(even(3))
= !(!even(2))
= !(!(!even(1))
= !(!(!(!even(0)))
= !(!(!(!true))
= true
// ...even(4) == true
Well, divide and conquer.
First of all you have two expressions to calculate. The first one is just stopping the recursion at the point when the number is 0, this is easy.
The second expression
!(even(num -1))
is a bit more complicated. It always starts with a call even(num -1) and then negates it.
For the first element !(even(num -1) === true), so now you see that for every second element starting from 1 (1, 3, 5 etc.) it will return false, for others the inverted value.
But there is a negation on the recursive call to even, so that, for every activation record on the stack, the return value gets inverted:
0 --> true
1 --> true --> false
2 --> true --> false --> true
This function indeed calls itself recursively, but with an added inversion each time. return (num === 0) returns true when num equals zero. If num is greater than zero, it calculates the result of even(num-1) and inverses it.
So, with num = 1, the function returns the inverse of even(0), which is true, making the end result false. With num = 2, the function returns the inverse of even(1), which we've just shown to be false, making the end result true. The same principle applies for all integers.

Dart game level end

I require assistance with some logic concerning how a game of darts will end.
So far I have the following rules. A player has 3 throws per turn to whittle the score (501) down to 0. Each throw is added to an array (which holds up to three elements). Once the last dart has been thrown, the total value of all three elements is deducted from the score.
1 - if the player's score is less than zero or equal to one - bust,reset the players running total to the score at the start of the turn.
2 - player's score is equal to zero - finish the game.
3 - player must end the game on a double score (if 10 remaining, get a double 5 to finish)
This is what I have so far (pseudo code)
if(score < 0 or score == 1)
{
console.log("bust")
score = array[0];
}
else if(score == 0)
{
console.log("game finished")
}
else if(score -(scoreNumber * 2) == 0)
{
console.log("double out. game finished")
}
Fiddle added - https://jsfiddle.net/j7bzq5k7/
Score is not enough to solve this information.
When somebody throws 18, it can be single 18, double 9 or triple 6, so just knowing '18' is not enough. You have to know whether they threw doubles or trips. And if you have that information, the logic is easy.
One thing to have in mind: you don't have to throw three darts in the last turn. If you just throw one double and finish, you already have won. So you need to evaluate the win-situation after each throw.
#tba just add a variable ' isDouble = false ' so your fiddle example can run correctly. otherwise your program checks or calculate after 3 throws only as #GolezTrol said . the game would end in several scenarios . so consider them all , i mean calculate the score after every throw (mental calculation).to check if it ends the game or not . at the third throw you can always excute your current program . that's at least what i think .

Categories