Conditional exercise addWithSurcharge - javascript

I can't figure why b arguments greater than 20 don't work here. See results
Exercise:
Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10, the surcharge is 1. For each amount greater than 10 and less than or equal to 20, the surcharge is 2. For each amount greater than 20, the surcharge is 3.
Example: addWithSurcharge(10, 30) should return 44.
function addWithSurcharge(a,b) {
let sur1 = 0
if (a <= 10) {
sur1 = 1;
} else if (10 < a <= 20) {
sur1 = 2;
} else if (a > 20) {
sur1 = 3;
}
let sur2 = 0
if (b <= 10) {
sur2 = 1;
} else if (10 < b <= 20) {
sur2 = 2;
} else if (b > 20) {
sur2 = 3;
}
return a + b + sur1 + sur2;
}

Issue
The reason is that you condition else if (10 < a <= 20) evaluates to true.
10 < a will be evaluated to true
true <= 20 will be evaluated to true.
So the number will evaluated as boolean and every number greater than 0 evaluates to true. That's the reason why true <= 20 evaluates to true
You can check this by this snippet
console.log(true <= 20)
console.log(true <= 0)
console.log(true <= -3)
Solution
To define a range you should use the && operator like this
else if (10 < b && b <= 20)
Then it will
check if 10 < 30 evaluate to true
check if 30 <= 20 evaluate to false
true && false will evaluate to false
function addWithSurcharge(a,b) {
let sur1 = 0
if (a <= 10) {
sur1 = 1;
} else if (10 < a && a <= 20) {
sur1 = 2;
} else if (a > 20) {
sur1 = 3;
}
let sur2 = 0
if (b <= 10) {
sur2 = 1;
} else if (10 < b && b <= 20) {
sur2 = 2;
} else if (b > 20) {
sur2 = 3;
}
return a + b + sur1 + sur2;
}
console.log(addWithSurcharge(10,30))

Related

I want to check the grade of the students marks , based on average

What's wrong with this code? I tried get marks using array and pass the array in to function parameters and calculate the average in that function.
const marks = [100,100,80];
var summ = 0;
function calculateGrade(){
for(let i=0; i<=marks.length;i++){
summ = summ+marks[i];
var avg = (summ/marks.length);
}
if(avg<=59){
console.log('F');
}
else if(avg>=60 && avg<=69){
console.log('D');
}
else if(avg>=70 && avg<=79){
console.log('C');
}
else if(avg>=80 && avg<=89){
console.log('B');
}
else if(avg>=90 && avg<=100){
console.log('A');
}
}
console.log(calculateGrade(marks));
const sum = marks.reduce((partialSum, a) => partialSum + a, 0);
const marks = [100, 100, 80];
var summ = 0;
//issue one (Tmarks were missing )
function calculateGrade(Tmarks) {
// issues 2 ( <= should be < )
for (let i = 0; i < Tmarks.length; i++) {
summ += Tmarks[i];
}
var avg = summ / Tmarks.length;
if (avg <= 59) {
console.log("F");
} else if (avg >= 60 && avg <= 69) {
console.log("D");
} else if (avg >= 70 && avg <= 79) {
console.log("C");
} else if (avg >= 80 && avg <= 89) {
console.log("B");
} else if (avg >= 90 && avg <= 100) {
console.log("A");
}
}
console.log(calculateGrade(marks));
Following were the issues in your code
You were not getting the parameters in function definition
issues 2 ( <= should be < )
You just added an extra = in your for loop
i<=marks.length
instead of
i<marks.length
So while calculating the sum & average, a garbage value gets added up.
You are very close
const marks = [100, 100, 80];
function calculateGrade(marks) {
let summ = 0;
for (let i = 0; i < marks.length; i++) {
summ += marks[i];
}
const avg = summ / marks.length;
let grade = '';
if (avg < 59) {
grade = 'F';
} else if (avg <= 69) {
grade = 'D';
} else if (avg <= 79) {
grade = 'C';
} else if (avg <= 89) {
grade = 'B';
} else {
grade = 'A';
}
return grade;
}
console.log(calculateGrade(marks));
There are couple of mistakes in your code.
1.
for(let i=0; i<=marks.length;i++)
marks.length is 3. Array index starting from 0.
const marks = [100,100,80];
index 0 is 100.
index 1 is 100.
index 2 is 80.
When you add i<=marks.length, this is equals to i<=3.
= in here will run the loop extra circle and this will return NaN because there are only 3 elements in you array and array indexing is 0 based.
2.
for(let i=0; i<=marks.length;i++){
summ = summ+marks[i];
var avg = (summ/marks.length);
}
avg is out of scope. you have defined avg inside the loop and trying to access it outside of the loop. Anything declared in the loop is scoped to that loop and are not available outside the loop.
3.
console.log(calculateGrade(marks));
Your calculateGrade() function is not accepting any parameters. So you can't pass any parameter into this function.
4.
console.log(calculateGrade(marks));
since calculateGrade() function is not returning any value, this will print nothing. So you don't need to call this inside a console.log();.
I have simplified your code as below.
const marksArr = [100, 100, 80];
calculateGrade(marksArr);
function calculateGrade(marks) {
console.log('calling calculateGrade(marks)...');
var avg = (marksArr.reduce(function(a, b) {
return a + b;
}, 0)) / marksArr.length;
console.log('avg is', avg);
if (avg <= 59) {
console.log('Grade', 'F');
} else if (avg >= 60 && avg <= 69) {
console.log('Grade', 'D');
} else if (avg >= 70 && avg <= 79) {
console.log('Grade', 'C');
} else if (avg >= 80 && avg <= 89) {
console.log('Grade', 'B');
} else if (avg >= 90 && avg <= 100) {
console.log('Grade', 'A');
}
}
` calculateGrade(){
let marks = [100,100,80];
let summ = 0;
let avg = 0;
for(let i = 0; i < marks.length; i++){
summ = summ+marks[i];
avg = (summ/marks.length);
}
if(avg<=59){
console.log('F');
}
else if(avg>=60 && avg<=69){
console.log('D');
}
else if(avg>=70 && avg<=79){
console.log('C');
}
else if(avg>=80 && avg<=89){
console.log('B');
}
else if(avg>=90 && avg<=100){
console.log('A');
}
}`
> array start from 0

Different result of an if else on Javascript [duplicate]

This question already has answers here:
What's the prettiest way to compare one value against multiple values? [duplicate]
(8 answers)
Closed 1 year ago.
I don't know why I keep getting the console.log from if statement even both averages are above 100.
Where did I put my mistake?
const dolphinsScores = 97 + 112 + 101;
const dolphinsAverage = dolphinsScores / 3;
const koalasScores = 109 + 95 + 123;
const koalasAverage = koalasScores / 3;
console.log(dolphinsAverage);
console.log(koalasAverage);
if (dolphinsAverage || koalasAverage < 100) {
console.log('One of the team is already lost')
} else if (dolphinsAverage > koalasAverage) {
console.log('Team Dolphins are the winner of the competition! 🐬🎉');
} else if (koalasAverage > dolphinsAverage) {
console.log('Team Koalas are the winner of the competition! 🐨🎉');
}
this statement
if (dolphinsAverage || koalasAverage < 100)
resolve as
if (true || koalasAverage < 100)
what you need is
if (dolphinsAverage < 100 || koalasAverage < 100)
Your if condition was checking if there is any value in dolphinsAverage which will always be true if there is any value in dolphinsAverage. So try this if you want to know if dolphinsAverage's value is less than 100.
if (dolphinsAverage < 100 || koalasAverage < 100) {
console.log('One of the team is already lost')
} else if (dolphinsAverage > koalasAverage) {
console.log('Team Dolphins are the winner of the competition! 🐬🎉');
} else if (koalasAverage > dolphinsAverage) {
console.log('Team Koalas are the winner of the competition! 🐨🎉');
}
const dolphinsScores = 97 + 112 + 101;
const dolphinsAverage = dolphinsScores / 3;
const koalasScores = 109 + 95 + 123;
const koalasAverage = koalasScores / 3;
console.log(dolphinsAverage);
console.log(koalasAverage);
if ((dolphinsAverage < 100) || (koalasAverage < 100)) {
console.log('One of the team is already lost')
} else if (dolphinsAverage > koalasAverage) {
console.log('Team Dolphins are the winner of the competition! 🐬🎉');
} else if (koalasAverage > dolphinsAverage) {
console.log('Team Koalas are the winner of the competition! 🐨🎉');
}
your if statement should be
if (dolphinsAverage < 100 || koalasAverage < 100) {

Recursively setting a value depending on range using JavaScript

I don't know how to word this but this is what I'm trying to do:
if (score >= 0 && score <= 10) overallScore = 0;
else if (score >= 11 && score <= 20) overallScore = 1;
else if (score >= 21 && score <= 30) overallScore = 2;
else if (score >= 31 && score <= 40) overallScore = 3;
else if (score >= 91 && score <= 100) overallScore = 9;
...
Is there any way to recursively do this using a function?
overallScore = Math.max(0, Math.floor((score - 1) / 10));
no need for recursion. But if you need that:
const getOverall = score => score <= 10 ? 0 : getOverall(score - 10) + 1;
Recursion is not really appropriate here, since you can get the required value in constant time. Recursion becomes interesting when you need at least O(logn) time.
But as you ask for it, here is one way to make it recursive:
function range(score, depth = 0) {
return score <= 10 || depth >= 9 ? 0 : range(score-10, depth+1) + 1;
}
console.log(range(0)); // 0
console.log(range(10)); // 0
console.log(range(11)); // 1
console.log(range(60)); // 5
console.log(range(91)); // 9
console.log(range(110)); // 9

What is the short form of this compare variable code

Is there a way that I can combine these two codes into one? I want to check if some variables are equal to 0 or equal to 1 or equal to 2 or greater than 2 and less than 5 or greater than 5. Should I write a code for each variable or I can write a code for all variables?
<script>
if (NRIRDL==0){
XRIRDL=0;
}
else if (NRIRDL == 1){
XRIRDL = 1;
}
else if (NRIRDL == 2){
XRIRDL = 1.8;
}
else if (NRIRDL > 2 && NRIRDL < 5){
XRIRDL = 0.9 * NRIRDL;
}
else {
XRIRDL = NRIRDL - 1;
}
// code below is the same as code above, but variables are different.
if (NRIRDR==0){
XRIRDR=0;
}
else if (NRIRDR == 1){
XRIRDR = 1;
}
else if (NRIRDR == 2){
XRIRDR = 1.8;
}
else if (NRIRDR > 2 && NRIRDR < 5){
XRIRDR = 0.9 * NRIRDR;
}
else {
XRIRDR = NRIRDR - 1;
}
</script>
actually, it can be written shorter with ternary operator and without multiple if conditions, check it out:
function getValue(n) {
return n >= 2 && n < 5 ? n * 0.9 : n == 0 ? 0 : n == 1 ? 1 : n - 1;
}
var var1 = 0;
var var2 = 1;
var var3 = 2;
var var4 = 3;
var var5 = 5;
console.log(getValue(var1)); // outputs 0
console.log(getValue(var2)); // outputs 1
console.log(getValue(var3)); // outputs 1.8
console.log(getValue(var4)); // outputs 2.7
console.log(getValue(var5)); // outputs 4
Just use getValue(n) function: pass your variable and it will return needed value that can be stored into another variable like var XRIRDL = getValue(NRIRDL); or var XRIRDR = getValue(NRIRDR);
You could make it into a function:
function yourFunction(val) {
if (val == 0){
return 0;
}
else if (val == 1){
return 1;
}
else if (val == 2){
return 1.8;
}
else if (val > 2 && val < 5){
return 0.9 * val;
}
else {
return val - 1;
}
XRIDR = yourFunction(NRIDR);
XRIDL = yourFunction(NRIDL);
When you OR the two inputs together, you lose valuable information about which one of the two inputs triggered that condition.
Mike's answer might not fit your needs because you can't update the values independently of one another (i.e. if NRIDR == 0 and NRIDL == 2, it sounds like you don't want both XRIDR and XRIDL to equal 1.8.)
You could put it inside a function. Here's a copy paste of your code inside a function.
function xrirdr(dr_or_dl){
var XRIRDL = null;
if (dr_or_dl==0){
XRIRDL=0;
}
else if (dr_or_dl == 1){
XRIRDL = 1;
}
else if (dr_or_dl == 2){
XRIRDL = 1.8;
}
else if (dr_or_dl > 2 && dr_or_dl < 5){
XRIRDL = 0.9 * dr_or_dl;
}
else {
XRIRDL = dr_or_dl - 1;
}
return XRIRDL;
}
You can pass NRIRDL or NRIRDR in the function and it will get you your XRIRDL
<script>
if (NRIRDL==0 || NRIRDR==0 ){
XRIRDL=0;
XRIRDR=0;
}
else if (NRIRDL == 1 || NRIRDR == 1)){
XRIRDL = 1;
XRIRDR = 1;
}
else if (NRIRDL == 2 || NRIRDR == 2)){
XRIRDL = 1.8;
XRIRDR = 1.8;
}
else if ((NRIRDL > 2 && NRIRDL < 5) || (NRIRDR > 2 && NRIRDR < 5) ){
XRIRDL = 0.9 * NRIRDL;
XRIRDR = 0.9 * NRIRDR;
}
else {
XRIRDL = NRIRDL - 1;
XRIRDR = NRIRDR - 1;
}
</script>

Javascript IIFE changes result

I'm looking at projecteuler.net's 4th problem, and have come across a curious feature that I'm wondering if anyone could explain.
The following code returns 10001
var n = 999 * 999; //biggest product with 3 digit numbers
var x;
while (n>10000) { //smallest product of 3 digit numbers
if (n.toString() === n.toString().split('').reverse().join('')) {
x = Math.floor(Math.sqrt(n));
while (n % x !== 0 && x >= 100 && n/x <= 999) {
x--;
}
if (n % x === 0 && x>= 100 && n/x <= 999) {
n;
}
}
n--;
}
whereas when wrapped in an IIFE, it returns 906609 which is the correct answer.
(function euler4() {
var n = 999 * 999; //biggest product with 3 digit numbers
var x;
while (n>10000) { //smallest product of 3 digit numbers
if (n.toString() === n.toString().split('').reverse().join('')) {
x = Math.floor(Math.sqrt(n));
while (n % x !== 0 && x >= 100 && n/x <= 999) {
x--;
}
if (n % x === 0 && x>= 100 && n/x <= 999) {
return n;
}
}
n--;
}
}());
Does anybody know why? I can't find an explanation online. Cheers!
The lone n in the first does not terminate the algorithm, whereas the return n in the second does. This can be fixed by replacing n in the first with a simple break
var n = 999 * 999; //biggest product with 3 digit numbers
var x;
while (n>10000) { //smallest product of 3 digit numbers
if (n.toString() === n.toString().split('').reverse().join('')) {
x = Math.floor(Math.sqrt(n));
while (n % x !== 0 && x >= 100 && n/x <= 999) {
x--;
}
if (n % x === 0 && x>= 100 && n/x <= 999) {
break;
}
}
n--;
}
console.log(n);

Categories

Resources