trying to understand if/else loops combined with functions - javascript

so I am trying to create a function with two parameters. This function will be passed with two numbers as arguments. calculate the sum of the parameters. If the sum is less than or equal to 25, the function should return true. If not it should return false.
I know I must use a if and else loop to check the parameters (or a ternary which we have not covered yet.) This is what I have gotten so far. Please tell me if I am on the right track or completely wrong.
function sum(augment1,augment2) {
var num= augment1 + augment2;
return num;
}
var a=sum(10,30)
console.log(a);
if (num > 25) {
return true
}
else {
return false;
}

There's no reason to use an if-else statement - the <= operator returns a boolean result, so you could just return it:
function isSumEqualOrLessThan25(augment1, augment2) {
var sum = augment1 + augment2;
return sum <= 25;
}

Your conditions should be inside your function right? So if the sum is less than or equal to 25 return true else return false. Can you try following?
function sum(augment1, augment2) {
var num = augment1 + augment2;
if (num <= 25) {
return true
} else {
return false;
}
}
var a = sum(10, 30)
console.log(a); // should be false

Related

Check if number is not integer in recursion js [duplicate]

This question already has answers here:
How to check if a variable is an integer in JavaScript?
(41 answers)
Closed 1 year ago.
I have a recursion function which calculates factorial for a given number.
function findFactorial(num) {
if (num < 1 || !num.isInteger) {
return "error";
} else {
return num * findFactorial(num - 1);
}
}
console.log(findFactorial(7));
I want to check if number is less then 1 OR is not integer - and return "error" for it.
Code I tried above isn't working and giving me "error" every time function is called.
You have three issues in your code.
First your code will always return "error", since you will always come to the point where num == 0.
Second you have no termination condition (except for the wrong return "error"), so the recursion will never return a valid value.
And last but not least, you try to call a function isInteger() but this function does not exist for the num object.
Here is the valid code:
function findFactorial(num) {
if (isNaN(num) || num < 1) {
return "error";
}
if (num == 1) {
return 1;
}
return num * findFactorial(num - 1);
}
console.log(findFactorial(7));
num.isInteger function is not availble in js. We have Number.isInteger(val).
Some code changes needed.
When a number is not an integer or is a negative number then only we need to return the error.
When a number reaches 1 then we need to return 1 itself to get then factorial values.
See the below code.
function findFactorial(num) {
if (!Number.isInteger(num) || num < 0) {
return "error";
} else if (num <= 1) {
return 1;
}
else {
return num * findFactorial(num - 1);
}
}
console.log(findFactorial(7));
console.log(findFactorial(-5));
console.log(findFactorial("six"));

Javascript function that finds the next largest palindrome number

I want to write a function that finds the next largest palindrome for a given positive integer. For example:
Input: 2
Output: 3 (every single digit integer is a palindrome)
Input: 180
Output: 181
Input: 17
Output: 22
My try
function nextPalindrome(num) {
let input = num;
let numToStringArray = input.toString().split('');
let reversedArray = numToStringArray.reverse();
if (numToStringArray.length < 2) {
return Number(numToStringArray) + 1;
} else {
while (numToStringArray !== reversedArray) {
// numToStringArray = num.toString().split('');
// reversedArray = numToStringArray.reverse();
num += 1;
}
return numToStringArray.join('');
}
}
As a beginner, I thought that the numToStringArray would constantly increment by 1 and check for whether the while-statement is true.
Unfortunately it doesn't. I commented out two lines in the while-statement because they seemed somewhat redundant to me. Thanks to everyone reading or even helping me out!
The reason your code doesn't work is because you don't have any code updating the conditions of your while loop. So if you enter it once, it will loop indefinitely. You need to do something inside of the while loop that might make the condition false the next time through the loop, like so:
function getReverse(num) {
// get the reverse of the number (in positive number form)
let reversedNum = +Math.abs(num).toString().split("").reverse().join("");
// keep negative numbers negative
if (num < 0) { reversedNum *= -1; }
return reversedNum;
}
function nextPalindrome(num) {
// if single digit, simply return the next highest integer
if (num >= -10 && num < 9) {
return num+1;
}
else {
while(num !== getReverse(num)) {
num += 1;
}
return num;
}
}
console.log(nextPalindrome(3));
console.log(nextPalindrome(17));
console.log(nextPalindrome(72));
console.log(nextPalindrome(180));
console.log(nextPalindrome(1005));
console.log(nextPalindrome(-150));
console.log(nextPalindrome(-10));
You could also solve this pretty cleanly using recursion, like so:
function getReverse(num) {
// get the reverse of the number (in positive number form)
let reversedNum = +Math.abs(num).toString().split("").reverse().join("");
// keep negative numbers negative
if (num < 0) { reversedNum *= -1; }
return reversedNum;
}
function nextPalindrome(num) {
// if single digit, simply return the next highest integer
if (num >= -10 && num < 9) {
return num+1;
}
else if(num === getReverse(num)) {
return num;
}
else {
// if not the same, recurse with n + 1
return nextPalindrome(num + 1)
}
}
console.log(nextPalindrome(3));
console.log(nextPalindrome(17));
console.log(nextPalindrome(72));
console.log(nextPalindrome(180));
console.log(nextPalindrome(1005));
console.log(nextPalindrome(-150));
console.log(nextPalindrome(-10));

for loop in javascript is skipping else if condition half the time

I'm was just fiddling around with javascript and I wrote function using Math.random that I thought would return a coin-flip. Then I was curious so I ran it through a loop to test how often it flips true/false. I found out my loop is skipping about half of the else if conditions, and was able to verify this by catching them in the errors var. So, why is it doing this?
var truths = 0;
var alternativetruths = 0;
var errors = 0;
function game() {
var score = Math.random()*10;
return score>5;
}
for(i=0;i<999999;i++) {
if (game() === true) {
truths++
} else if (game() === false) {
alternativetruths++
} else {
errors++
}
}
console.log("truths:",truths,"alternativetruths:",alternativetruths,"errors:",errors)
truths: 500393 alternativetruths: 249580 errors: 250026
Your code calls game() twice. If the first call isn't true, then the second might or might not be true.
Just call game() once and assign the result to a variable. Don't make explicit comparisons to true and false; if statements work off boolean values, and your function already returns one of those.
for (var i = 0; i < 999999; i++) {
var result = game();
if (result)
truths++;
else
alternativetruths++;
}
Because you're calling game twice, and thus getting two different random flags.
The minimal change is to remember the number:
for(i=0;i<999999;i++) {
var flag = game();
if (flag === true) {
truths++
} else if (flag === false) {
alternativetruths++
} else {
errors++
}
}
But a couple of other notes:
If flag is a boolean (and it is, it's the result of the > operator), then if (flag === true) is pointless. Just use if (flag). The result of the === operator is a boolean too, so if you don't trust them to be true or false, where do you stop? :-) if ((flag === true) === true)?
Separately, if (flag === false) should just be if (!flag).
If flag is a boolean (and it is), then if you have if (flag), having else if (!flag) and then else doesn't make any sense. There is no way you'll reach that final else. Just if (flag) { } else { } is all you need.
But, game isn't fair, it has a very slight bias toward returning false. Remember, the range returned by Math.random() * 10 is 0 to just under 10, so checking for > 5 means you're skipping the midpoint. Because you're dealing with very small fractional numbers, you don't notice the bias, but it's there; it would be more obvious if you rounded to whole numbers, at which point it would be roughly 40%/60% true/false. You want >= 5 for fair results.
game can rather moer succinctly be written: return Math.random() >= 0.5;.
Because you're not declaring i, you're falling prey to The Horror of Implicit Globals (that's a post on my anemic little blog). Remember to declare your variables.
Re > vs. >=, here's an example where I've rounded to whole numbers to make the effect clearer:
for (var n = 0; n < 4; ++n) {
setTimeout(test.bind(null, n, true), 200 * n);
setTimeout(test.bind(null, n, false), 200 * n + 100);
}
function test(num, gte) {
var truths = 0;
var alternativetruths = 0;
var errors = 0;
function game() {
var score = Math.floor(Math.random() * 10);
return gte ? score >= 5 : score > 5;
}
for (var i = 0; i < 999999; i++) {
var flag = game();
if (flag) {
truths++;
} else {
alternativetruths++;
}
}
showStats(num, gte, truths, alternativetruths);
}
function showStats(num, gte, truths, alternativetruths) {
var total = truths + alternativetruths; // Should be 999999 of course
var truthsPercent = (truths * 100) / total;
var altPercent = (alternativetruths * 100) / total;
console.log(num, gte ? ">=" : ">", "truths:", truths, "alternativetruths:", alternativetruths, "(" + truthsPercent.toFixed(2) + "% vs. " + altPercent.toFixed(2) + "%)");
}
.as-console-wrapper {
max-height: 100% !important;
}
You need to assign game to a var before test for its value. Otherwise, everytime yout check the value with game() you will check a new value. So it can be false at the first check and true at the second and for this reason increment your errors.
Try this:
for(i=0;i<999999;i++) {
let gameResult = game();
if (gameResult === true) {
truths++
} else if (gameResult === false) {
alternativetruths++
} else {
errors++
}
}

I cannot return the real variable on processed recursion?

I have been doing this recursion in javascript; however I cannot return the real value of x on return. Instead, it is returning the processed value. The code is doing it's job but it's returning the processed variable on recursion. I tried to store the variable on x, but I still fail.
I want to return the last call stack to get the real variable.
This code returns 0 is Even, 1 is Even - how can the code be changed such that these cases would work as expected?
function isEven(x) {
var y =x;
if (x<0) {
x = x * -1;
}
if ( x===0 ) {
return console.log(y+' is Even');
} else if( x===1 ) {
return console.log(y+' is Odd');
} else {
return isEven(x-2);
}
// →
console.log(isEven(10));
console.log(isEven(-11));
}
You cannot access the initial value using your code.
The simplest way to achieve this goal is to add a function parameter, which will store the original value:
function isEven(x, initial) {
initial = initial || x; // so that isEven(10) => isEven(10, 10)
if (x<0) {
x = x * -1;
}
if(x===0) {
return initial+' is Even';
} else if(x===1) {
return initial+' is Odd';
} else
return isEven(x-2, initial);
}
// →
console.log(isEven(10));
console.log(isEven(-11));
However, the correct solution is to separate the initial call and recursive calls. For example, it can be achieved using nested functions.
It is also a good idea to abstract logics (boolean) and displayed information (string).
function isEvenString(initial) {
function isEvenBool(x) {
if (x < 0) {
x = x * -1;
}
if (x === 0) {
return true;
}
if (x === 1) {
return false;
}
return isEvenBool(x - 2);
}
return initial + (isEvenBool(initial) ? " is Even" : " is Odd");
}
// →
console.log(isEvenString(10));
console.log(isEvenString(-11));
P.S. Note that this isEven function is good for education purposes, but absolutely useless in practice. It takes 1 000 000 function calls to determine that 2 000 000 is even whilst it can be done using one line of code in O(1) operations:
function isEvenString(x) {
return x % 2 === 0;
}
I assume what you're trying to do is print the original value that was given, not the final value from the recursion. But you're reassigning y every time you recurse, so it doesn't contain the original value.
One solution is to split the function up into a main function and a recursive internal function.
function isEven(x) {
var y =x;
function isEvenRecurse(x) {
if (x<0) {
x = x * -1;
}
if(x===0) {
return y+' is Even';
} else if(x===1) {
return y+' is Odd';
} else {
return isEvenRecurse(x-2);
}
}
isEvenRecurse(y);
}
Another way is to pass an extra argument to the function when recursing.
function isEven(x, y) {
if (arguments.length == 1) {
y = x;
}
if (x<0) {
x = x * -1;
}
if(x===0) {
return y+' is Even';
} else if(x===1) {
return y+' is Odd';
} else {
return isEven(x-2, y);
}
}

Recurring function returning undefined

I have a function that checks if a number is divisible by 2.5, if it isn't it adds 0.5 then calls itself again with the new value. It returns undefined when I call it like below but if I console.log instead of returninside the function then the correct rounded up value displays.
function n(num){
if(num % 2.5 === 0){
return num;
}else{
num += 0.5;
n(num)
}
}
console.log(n(13.5))
Any ideas?
you need to return the recursive call so that your conditions will be checked again until your if condition is satisfied:
function n(num){
if(num % 2.5 === 0){
return num;
}else{
num += 0.5;
return n(num); //<-- add return
}
}
console.log(n(13.5));
Yes because the second n(num) call is not returning anything to the original caller.
Make it:
else{
num += 0.5;
return n(num);
}

Categories

Resources