Javascript: + 1 Limit for Counter/Conditional Statement - javascript

In my javascript game i have a function that is called every 0.1 seconds with setInterval:
updateTimerID = setInterval(function(e) {checkProgress();}, 100);
I store a users score in a variable and have a conditional statement inside the checkProgress function which checks when my slider x position falls between 45 - 48:
var score = 0;
function checkProgress(){
if( slider_1.x => 45 && slider_1.x <= 48 ) {
score = score + 1
}
}
I then increase the score variable by one when this happens. The problem i have is i only want the score to be updated by 1 every time, not everytime - so with my function being called every .1 seconds - at the moment my score is adding at least 3 each time
if( slider_1.x => 50 && slider_1.x <= 60 ) {
score ++;
}
Can i limit it to 1 each time?

Something like this maybe?:
var isOver = false;
function checkProgress(){
if( slider_1.x => 45 && slider_1.x <= 48 && !isOver ) {
score = score + 1;
isOver = true;
} else if( slider_1.x < 45 && slider_1.x > 48 ) {
isOver = false;
}
}

you can do that by storing the score update time at a variable than substract it from current time to look for the time passed from last update is greater than 1 second
var score = 0;
var last_update =0;
function checkProgress(){
if( slider_1.x => 45 && slider_1.x <= 48 && ((new Date().getTime()-last_update) > 1000) ) {
score = score + 1
last_update=new Date().getTime();
}
}

Something like this will do the trick
var score = 0;
var inc = true;
function checkProgress(){
if( slider_1.x => 45 && slider_1.x <= 48 ) {
if(inc)
{
score = score + 1
inc = false;
}
}
if(slider_1.x < 45 || slider_1.x > 48)
{
inc = true;
}
}

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

average of five valuesin javascript

I work for a charter school and I'm just learning my way around javascript. I've got some code written by the person who formerly filled my position and it seems to me that it should work, but it doesn't.
This is what I have in the custom HTML page in my SIS:
GED Status: <script language="Javascript">gedCheck('~(ELC_tspp_GED_read_score)','~ (ELC_tspp_GED_wri_score)','~(ELC_tspp_math_GED_score)','~(ELC_science_state_exam_score)','~(soc_sci_state_exam_score)')</script>
That seems to be retrieving the values from the various DB fields correctly, as the javascript routine is evaluating each value to ensure it's at least 410. But that's as far as it goes...
Here's the javascript routine code:
function gedCheck(read,wri,math,sci,soc) {
if( read < 0 && read > 1000 )
read = 0;
if( wri < 0 && wri > 1000 )
wri = 0;
if( math < 0 && math > 1000 )
math = 0;
if( sci < 0 && read > 1000 )
read = 0;
if( soc < 0 && soc > 1000 )
soc = 0;
if ( (read >= 410) && (wri >= 410) && (math >= 410) && (sci >= 410) && (soc >= 410) ) {
if( read+wri+math+sci+soc >= 2250 )
document.write( "PASSED" )
}
else
document.write( "NOT PASSED" )
}
It is supposed to be checking that every score in the GED tests is at least 410, and that the sum of all scores should be at least 2250. However, it's not getting as far as the last part. It's returning "PASSED" if all the scores are over 410.
I tried this but it, also, doesn't work.
function gedCheck(read,wri,math,sci,soc) {
if( read < 0 && read > 1000 )
read = 0;
if( wri < 0 && wri > 1000 )
wri = 0;
if( math < 0 && math > 1000 )
math = 0;
if( sci < 0 && read > 1000 )
read = 0;
if( soc < 0 && soc > 1000 )
soc = 0;
if ( (read >= 410) && (wri >= 410) && (math >= 410) && (sci >= 410) && (soc >= 410) ) {
if( read+wri+math+sci+soc/5 >= 450 )
document.write( "PASSED" )
}
else
document.write( "NOT PASSED" )
}
Would somebody please help me work this out so it either averages all 5 numbers and returns "PASSED" only if the average is 450, OR simply adds all 5 numbers and returns "PASSED" only if the total sum is 2250 or greater?
To get the average, you'll want to do this:
(((read + wri + math + sci + soc) / 5) > 450)
The parenthesis around the addition ensures that you divide the sum of all scores by 5. The way that you have it now, you are only dividing the soc score by 5.
Edit (Rewriting the entire method):
function gedCheck(read, wri, math, sci, soc) {
// As was said before, these should all be ORs
// If the score is less than 0, OR greater than 1000
if( read < 0 || read > 1000 ) {
read = 0;
}
if( wri < 0 || wri > 1000 ) { // I prefer to put the braces around all if/else statements just for absolute clarity
wri = 0;
}
if( math < 0 || math > 1000 ) {
math = 0;
}
if( sci < 0 || read > 1000 ) {
read = 0;
}
if( soc < 0 || soc > 1000 ) {
soc = 0;
}
if ( read >= 410 && // Doing this will only pass the student
wri >= 410 && // if ALL of the conditions are met.
math >= 410 &&
sci >= 410 &&
soc >= 410 &&
( (read + wri + math + sci + soc) >= 2250 || // Separated more for clarity
((read + wri + math + sci + soc) / 5) > 450) ) {
// Either all scores total over 2250
// Or the average of all 5 are over 450 to pass
document.write( "PASSED" )
}
else
document.write( "NOT PASSED" )
}
What about
if ((read >= 410) &&
(wri >= 410) &&
(math >= 410) &&
(sci >= 410) &&
(soc >= 410) &&
(read+wri+math+sci+soc >= 2250)) {
document.write( "PASSED" )
} else {
document.write( "NOT PASSED" )
}
function gedCheck(read, wri, math, sci, soc) {
if( read < 0 || read > 1000 )
read = 0;
if( wri < 0 || wri > 1000 )
wri = 0;
if( math < 0 && math > 1000 )
math = 0;
if( sci < 0 && read > 1000 )
read = 0;
if( soc < 0 && soc > 1000 )
soc = 0;
var total = read + wri + math + sci + soc;
if (read >= 410 && wri >= 410 && math >= 410 && sci >= 410 && soc >= 410 && total >= 2250) {
document.write("PASSED");
} else {
document.write("NOT PASSED");
}
}
That whole first section was impossible code. It was checking to see if a number was BOTH less than zero and greater than 1000. Obviously impossible, so I changed it to use OR.
I also created a total variable, which you can check in the same way as everything else.
Using an array here will help you reduce the amount of duplicated code
function gedCheck(read, wri, math, sci, soc) {
var subjects, totalScore, averageScore;
subjects = [read, wri, math, sci, soc];
totalScore = 0;
averageScore = 0;
for (var i = 0; i < subjects.length; i++) {
if (subjects[i] < 0 || subjects[i] > 1000) {
subjects[i] = 0;
}
totalScore += subjects[i];
};
averageScore = totalScore / subjects.length;
if (averageScore >= 450 || totalScore >= 2250) {
document.write("PASSED");
} else {
document.write("NOT PASSED");
}
}
The first loop iterates through each subject and sets it to zero if necessary, and then adds it to the total score variable.
Then the total score is averaged by the number of subjects.
Then if the average score is equal to or greater than 450, or equal to or greater than 2250, it passes.

Error in JavaScript return code?

Here is the javascript code:
There is an error in code where nightSurcharges is added to total cost even if pickUptime is less than 20.
function TaxiFare() {
var baseFare = 2;
var costPerMile = 0.50;
var nightSurcharge = 0.50; // 8pm to 6am, every night //its flat 0.50 and not per mile
var milesTravelled = Number(document.getElementById("miles").value) || 0;
if ((milesTravelled < 1) || (milesTravelled > 200)) {
alert("You must enter 1 - 200 miles");
document.getElementById("miles").focus();
return false;
}
var pickupTime = Number(document.getElementById("putime").value) || 0;
if ((pickupTime == "") || (pickupTime < 0) || (pickupTime > 23)) {
alert("The time must be 0-23 hours");
document.getElementById("putime").focus();
return false;
}
var cost = baseFare + (costPerMile * milesTravelled);
// add the nightSurcharge to the cost if it is after
// 8pm or before 6am
if (pickupTime >= 20 || pickupTime < 6) {
cost += nightSurcharge;
}
alert("Your taxi fare is $" + cost.toFixed(2));
}
I want nightSurcharge to be added only when pickupTime is >=20, but that's not working right now.
Any help is appreciated. Thanks
This seems obvious to me.
if (pickupTime >= 20 || pickupTime < 6) {
cost += nightSurcharge;
}
This code right here adds nightSurcharge to the cost if pickupTime is greater than or equal to 20, OR less than 6. So of course it's added if it's less than 6.
if (pickupTime >= 20) {
cost += nightSurcharge;
}
Now it will only add to it if it's greater or equal to 20.
your code is:
if (pickupTime >= 20 || pickupTime < 6)
so if pickupTime is less then 6 it'll enter the if as well
http://jsfiddle.net/7rdzC/

Categories

Resources