JavaScript: What is the opposite of the logical operator `A && B`? - javascript

In the following code, what is the opposite of the condition (ran1 <= 63 && ran2 <= 18), which should fit in the else portion of the if statement?
Is it both (ran1 <= 63 || ran2 <= 18) and (! (ran1 <= 63 && ran2 <= 18))?
Logically, I suppose that the opposite of A and B is both A or B and neither A nor B. But I'm not sure how to express the neither A nor B bit in JavaScript.
var ran1 = 1 + Math.floor(Math.random() * 100);
var ran2 = 1 + Math.floor(Math.random() * 100);
if (ran1 <= 63 && ran2 <= 18) {
// code
} else {
// code
}

The mathematical negation of A && B is !A || !B, so in your case, it would be
ran1 > 63 || ran2 > 18

Related

JavaScript if/else Statement Input Data [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Please help me, I am studying on my own and need help, I want to create an "JavaScript else if statement" but this doesn't work.
Who wants to make input
// If "x" is greater than or equal to 1 and "x" is less than 10, and "y" is equal to 100, output "+"
// If "x" is greater than or equal to 11 and "x" is less than 100, and "y" is equal to 100, output "++"
// If "x" is greater than or equal to 1 and "x" is less than 10, and "y" is equal to 1, output "+++"
// If "x" is greater than or equal to 10, and "y" is equal to 1, output "++++"
The code that I tried to make, below
<!DOCTYPE html>
<html>
<body>
<p>Please Help:</p>
<input id="numb1" type="text">
<input id="numb2" type="text">
<button type="button" onclick="myFunction()">Submit</button>
<p id="tes"></p>
<script>
function myFunction() {
var x, y, text;
x = document.getElementById("numb1").value;
y = document.getElementById("numb2").value;
if (x > 1 || x < 10 || y == 100) {
text = "+";
} else if (x > 11 || x < 100 || y == 100) {
text = "++";
} else if (x > 1 || x < 10 || y == 1) {
text = "+++";
} else if (x > 10 || y == 1) {
text = "++++";
}
document.getElementById("tes").innerHTML = text;
}
</script>
</body>
</html>
Full Working Code:
<!DOCTYPE html>
<html>
<body>
<p>Please Help:</p>
<input id="numb1" type="text">
<input id="numb2" type="text">
<button type="button" onclick="myFunction()">Submit</button>
<p id="tes"></p>
<script>
function myFunction() {
var x, y, text;
x = document.getElementById("numb1").value;
y = document.getElementById("numb2").value;
if (x >= 1 && x < 10 && y == 100) {
text = "+";
} else if (x >= 11 && x < 100 && y == 100) {
text = "++";
} else if (x >= 1 && x < 10 && y == 1) {
text = "+++";
} else if (x >= 10 && y == 1) {
text = "++++";
}
document.getElementById("tes").innerHTML = text;
}
</script>
</body>
</html>
Explanation:
You were using || which means or in logical statements, where you meant to use && to represent and.
Furthermore, when using logical statements, more than or equal to would be represented by >= and not >.
What you used:
if (x > 1 || x < 10 || y == 100) {
text = "+";
} else if (x > 11 || x < 100 || y == 100) {
text = "++";
} else if (x > 1 || x < 10 || y == 1) {
text = "+++";
} else if (x > 10 || y == 1) {
text = "++++";
}
What you were supposed to use:
if (x >= 1 && x < 10 && y == 100) {
text = "+";
} else if (x >= 11 && x < 100 && y == 100) {
text = "++";
} else if (x >= 1 && x < 10 && y == 1) {
text = "+++";
} else if (x >= 10 && y == 1) {
text = "++++";
}
To learn more about JavaScript Operators and Comparison Logical Operators (i.e. ||, &&, >, >=, == or !=), visit:
https://www.w3schools.com/js/js_comparisons.asp
https://www.w3schools.com/jsref/jsref_operators.asp
Recommended changes to code:
I would strongly recommend adding an else statement to the conditional statement in you code, as then if all other conditions don't apply there will be a back-up, and your code will not error out and print out undefined.
first: the OR - || opartor returns true even if only one of the expression in is both sides are true. the AND - && operator returns true only if both of them are true, and this is what you are looking for.
so you have to replece all the OR opartors with AND operators.
second: to check if a value is greater than or equal to another value, you have to combine both operators > and = together.
if (x >= 1 && x < 10 && y == 100) {
text = "+";
} else if (x >= 11 && x < 100 && y == 100) {
text = "++";
} else if (x >= 1 && x < 10 && y == 1) {
text = "+++";
} else if (x >= 10 && y == 1) {
text = "++++";
}

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

Parse course in textual way from course in degrees?

So im making a compass in node-red, it should have course in degrees (int) as input and string(course) as output:
So i need function that takes in integer and gives me heading in string. How to do it simple and reliable?
I have to convert course 0-360 degrees in string for example: NORTH, NORTH-EAST, EAST......
I tried the following:
var course = parseInt(courseFloatDegrees);
var courseTxt = "";
if (course >= 349 && course <= 11 || course <= 359 && course >= 349 || course === 0) courseTxt = "N";
else if (course >= 11 && course <= 33) courseTxt = "NNE";
else if (course >= 33 && course <= 56) courseTxt = "NE";
else if (course >= 56 && course <= 78) courseTxt = "ENE";
else if (course >= 78 && course <= 101 || course == 90) courseTxt = "E";
else if (course >= 101 && course <= 124) courseTxt = "ESE";
else if (course >= 124 && course <= 146) courseTxt = "SE";
else if (course >= 146 && course <= 168) courseTxt = "SSE";
else if (course >= 168 && course <= 191 || course == 180) courseTxt = "S";
else if (course >= 191 && course <= 214) courseTxt = "SSW";
else if (course >= 214 && course <= 236) courseTxt = "SW";
else if (course >= 236 && course <= 258) courseTxt = "WSW";
else if (course >= 258 && course <= 281 || course == 270) courseTxt = "W";
else if (course >= 281 && course <= 303) courseTxt = "WNW";
else if (course >= 303 && course <= 326) courseTxt = "NW";
else if (course >= 326 && course <= 349) courseTxt = "NNW";
else courseTxt = "INVALID"
But sometimes i get nothing(null-empty string) or "INVALID". Does anybody know fast and simple way to do this without that much else if statements?
There could be ways of doing this more 'simply' in code, but your approach should work. The reason it doesn't is because your if statements are messed up around the 'N' region.
if ((course >= 349 && course <= 11) || (course <= 359 && course >= 349) || (course === 0)) courseTxt = "N";
If you look at the very first two conditions, they are illogical. More than 349 but less than 11? That's never going to happen. If you have a course of 7 degrees, that doesn't meet any of the specified criteria currently.
So the first thing to do is resolve that problem. You need to adjust the line to use OR instead of AND
if(course < 11 || course > 349) courseTxt = "N";
Now your code will be able to handle the settings either side of 360/0 degrees.
That should be enough to get your current code to work, assuming course is always less or equal to 360.
You asked if there is a way to avoid all the if statements. There are probably hundreds of ways to do this, but the simplest, other than if or case statements would probably be to use an array to look up the heading. Here is an example of how it could be done. You could obviously hardcode the step value, but this way you could update your array with any number of more granular headings, and it will still work.e
function getCourse(course)
{
// define our values
var degs = 360;
var strs =
["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];
// make sure course is always within the expected range in case it is incremented past 360
course = course % degs;
// get the step amount based on the number of compass headings we have
var step = degs/strs.length;
// adjust for the last few degrees on the scale which will be north
if(course > degs - (step/2)) course += step/2;
// now just divide the course by the step and read off the relevant heading
var index = Math.floor(course / step);
return strs[index];
}
Nicky,
I used an approach similar to Toby's -- calculating an index into an array of course strings:
var deg = course % 360;
var dirs = ["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW","N"];
var idx = Math.round(deg * (dirs.length-1)/360);
var dir = dirs[idx];
The trick is to repeat the "N" element at the beginning and end of the array, and use Math.round(...) to jump to the closest integer index number.

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);

javascript if value is number to number

Is there any way to check if value is in a number range? Like my example:
if (battery.level == 70 to 100) {
$('#battery').css('background-image', 'url("battery_full.png")');
}
What's the syntax for that? Thanks for help.
if (battery.level >= 70 && battery.level <= 100) {
something like this
if ( value >= 70 && value <= 100)
{
}
You could do this :
function inRange(n, from, to) {
return n >= from && n <= to;
}
if (inRange(battery.levelPercent, 70, 100))
YOU CAN CHECK NUMBER LIKE
if ( battery.level >= 70 && battery.level <= 100)
{
}
NOT A STRING LIKE ('70%' to '100%')
70% is actually not a number. However, you could get rid of the invalidating % by naming your variable battery.levelPercent instead and adding the percent sign whenever it needs to be output.
Then, you could check the number like this:
if (typeof battery.levelPercent === "number") {
if (battery.levelPercent >= 70 && battery.levelPercent <= 100) {
$('#battery').css('background-image', 'url("battery_full.png")');
} // else, not in range
} // else, not a number
You better remove % from battery.level to compare it with number.
Live Demo
level = battery.level.replace('%', '');
if (level >= 70 && level <= 100) {
$('#battery').css('background-image', 'url("battery_full.png")');
}
You can also use parseFloat or parseInt
level = parseFloat(battery.level);
if (level >= 70 && level <= 100) {
$('#battery').css('background-image', 'url("battery_full.png")');
}

Categories

Resources