Ternary operator not working properly in JS [duplicate] - javascript

This question already has answers here:
Operator precedence with JavaScript's ternary operator
(7 answers)
Ternary operation JS not working
(3 answers)
Closed 3 years ago.
I am running the following code and getting unexpected results:
var a = 1, b =2 ,c = 3;
console.log(5*a+ b>0?b:c);
Expected result was : 7 but getting 2.

Your code has the right concept, but wrong execution. The ternary is doing its job properly.
At the moment, your code is executing like this:
const a = 1
const b = 2
const c = 3
// This will evaluate to true, since 5 * 1 + 2 = 7, and 7 is greater than 0
if (5 * a + b > 0) {
// So return b
console.log(b)
} else {
console.log(c)
}
You should use brackets to separate the ternary:
const a = 1
const b = 2
const c = 3
console.log(5 * a + (b > 0 ? b : c));

Related

Array.reduce() not working as expected, returns 0 [duplicate]

This question already has answers here:
console.log() shows the changed value of a variable before the value actually changes
(7 answers)
console.log() async or sync?
(3 answers)
Is Chrome’s JavaScript console lazy about evaluating objects?
(7 answers)
Closed 4 months ago.
hello! I'm trying to add numbers from an array. I went with the .reduce method, however it's not working. It keeps giving me a result of 0. I console logged the array, and indeed the values are there. Why isn't it doing the addition then?
const cubitMeters =
(parseInt(height) * parseInt(width) * parseInt(length) * parseInt(count)) / 1000000
totalW.push(cubitMeters)
const totalW = []
const sum = totalW.reduce((a, b) => a + b, 0)
console.log('sum: ' + sum)
console.log(totalW)
and here's screenshot of console.log results
Looks like you need to move the array declaration to top. And then perform the push operation.
const totalW = []
const cubitMeters =
(parseInt(height) * parseInt(width) * parseInt(length) * parseInt(count)) / 1000000
totalW.push(cubitMeters)
const sum = totalW.reduce((a, b) => a + b)
console.log('sum: ' + sum)
console.log(totalW)

JavaScript function default parameters [duplicate]

This question already has answers here:
Skip arguments in a JavaScript function
(9 answers)
Passing values to function with multiple default parameters
(1 answer)
Default parameter of a JavaScript function is not working when intermittent value is missing
(1 answer)
Pass only the second argument in javascript
(4 answers)
Omit/Skip a parameter with default value while calling a function in JS
(2 answers)
Closed last year.
const add = (a = 1, b = 1, c = 1) => a + b + c
add(4, , 2)
Throws Uncaught SyntaxError, unexpected token ','
How do I call the function so b defaults to the value 1
Just take undefined as value.
const add = (a = 1, b = 1, c = 1) => a + b + c
console.log(add(4, undefined, 2));
Pass undefined as value
Check this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters#passing_undefined_vs._other_falsy_values
const add = (a = 1, b = 1, c = 1) => a + b + c
console.log(add(4, undefined, 2))

Reverse Integer Without converting to a string Javascript? [duplicate]

This question already has answers here:
JavaScript: How to reverse a number?
(19 answers)
Closed 2 years ago.
So i am trying to reverse an integer and so far the code works but i am trying to find a solution to reverse the integer without converting into a string first? Any help would be appreciated. This is my code snippet so far to reverse the integer.
function reverseInt(num) {
const reversed = num.toString().split('').reverse().join('')
return parseInt(reversed) * Math.sign(num)
}
console.log(reverseInt(-500));
I am trying to do it using javascript.
Try this:
function reverseInt(number) {
var isNegative = number < 0 ? true : false;
if(isNegative)
number = number * -1;
var reverse = 0, lastDigit = 0;
while (number >= 1) {
reverse = Math.floor(reverse * 10 + (number % 10));
number = number / 10;
}
return isNegative == true ? reverse*-1 : reverse;
}
console.log(reverseInt(-500));
console.log(reverseInt(501));

What is a non-mathematical explanation for the Big O of recursive fibonacci?

I read both articles on Big O for Recursive Fibonacci sequence but still do not have a conceptual understanding of why it is O(2^n).
This is not a duplicate of this link. Please don't mark as a duplicate. I'm looking for a conceptual answer.
This is one of the simplest recursive functions out there and I want to understand how to look at it and determine the the Big O without complex math and proofs.
// O(2^n)
function fiboR(n){
if( n === 0 || n === 1 ){
return n;
} else if ( n >=2 ){
return fiboR(n-1) + fiboR(n-2);
}
}
For example Big O for the iterative version is O(n). I can just look and see that as n increases the while loop iterations increase linearly. No complex math or long proofs needed.
// O(n)
function fibo(n){
let prev0 = 0;
let prev1 = 1;
if( n === 0 || n === 1 ){
return n;
}
while( n-- >= 2){
sum = prev0 + prev1;
prev0 = prev1;
prev1 = sum;
}
return sum;
}
It is simple to calculate by diagraming function calls. Simply add the function calls for each value of n and look at how the number grows.
The Big O is O(Z^n) where Z is the golden ratio or about 1.62.
Both the lenoardo numbers and the fibonacci numbers aproach this ratio as we increase n.
2 (2 -> 1, 0)
4 (3 -> 2, 1) (2 -> 1, 0)
8 (4 -> 3, 2) (3 -> 2, 1) (2 -> 1, 0)
(2 -> 1, 0)
14 (5 -> 4, 3) (4 -> 3, 2) (3 -> 2, 1) (2 -> 1, 0)
(2 -> 1, 0)
(3 -> 2, 1) (2 -> 1, 0)
22 (6 -> 5, 4)
(5 -> 4, 3) (4 -> 3, 2) (3 -> 2, 1) (2 -> 1, 0)
(2 -> 1, 0)
(3 -> 2, 1) (2 -> 1, 0)
(4 -> 3, 2) (3 -> 2, 1) (2 -> 1, 0)
(2 -> 1, 0)
A good number of naive recursive functions have exponential complexity, so this is good intuition to keep in mind.
Consider this function:
function fiboR1(n){
if( n === 0 || n === 1 ){
return n;
} else if ( n >=2 ){
return fiboR1(n-1) + fiboR1(n-1);
}
}
Okay, so fiboR1 doesn't actually compute the Fibonacci sequence. That doesn't matter. Notice that its asymptotic complexity will be at least that of fiboR. This is because the two recursive calls to fiboR1(n-1) are more expensive than one call to fiboR(n-1) and one call to fiboR(n-2). So let's think about what the complexity of fiboR1 is.
Let's consider an example call to fiboR1(100).
fiboR1(100) = 2 * fiboR1(99)
= 4 * fiboR1(98)
= 8 * fiboR1(97)
= 16 * fiboR1(96)
= 32 * fiboR1(95)
= 64 * fiboR1(94)
...
See the pattern now? We have O(2^n) recursive calls to fiboR1, and each call is a constant time branch. So fiboR1 is O(2^n), which means that by extension, fiboR is also O(2^n), as big-O is an upper-bound function.
If you know the closed form for the Fibonacci sequence, we can also just do this example for fiboR directly. Let's consider fiboR(100):
fiboR(100) = fiboR(99) + fiboR(98)
= 2 * fiboR(98) + fiboR(97)
= 3 * fiboR(97) + 2 * fiboR(96)
= 5 * fiboR(96) + 3 * fiboR(95)
= 8 * fiboR(95) + 5 * fiboR(94)
= 13 * fiboR(94) + 8 * fiboR(93)
...
The number of recursive function calls follows the Fibonacci sequence. The closed form for the Fibonacci sequence is exponential in n. In fact, it is O(((1+sqrt{5})/2)^n), which is about O(1.6^n).
Assuming you accept that the function is correct, i.e. that it does calculate the Fibonacci numbers, then it is very easy to show that its running time must be exponential: it only returns 0 or 1 in the base case, and it only produces larger results by adding smaller results together.
Since the Fibonacci numbers grow exponentially, the only way you could make them by adding a lot of 1s together is by adding exponentially many 1s. Each result only gets added to the final total once, so the base case must be executed exponentially many times to produce all of those 1s as different results.

Javascript parseFloat issue [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 7 years ago.
I am facing a new problem. I have the below use case.
var a = parseFloat(10); // Returns 10
var b = parseFloat(1.62); // Returns 1.62
var c = a + b; // Returns 11.620000000000001
I want the c to return 11.62. What is the problem here?
var a = parseFloat(10); // Returns 10
var b = parseFloat(1.62); // Returns 1.62
var c = a + b; // Returns 11.620000000000001
console.log(c.toFixed(2))
Output: 11.62
console.log(c.toPrecision(4))
Output: 11.62
var a = parseFloat(10); // Returns 10
var b = parseFloat(1.62); // Returns 1.62
var c = a + b; // Returns 11.620000000000001
console.log(c.toPrecision(4));
Output: 11.62

Categories

Resources