False positives while comparing integers in Javascript - javascript

I'm facing a really strange problem comparing integer in Javascript. I have an array of numbers and I want to check if the current number in a loop is smaller than the previous one. To do so, I save the "current" number as "previous", so I can check them in the next loop. The function runs as expected, EXCEPT every time the current and the previous number have a different number of digits: in this case, the code doesn't see the actually smaller number as being smaller than the previous one.
For example:
111 < 120 ? ---> YES!
106 < 111 ? ---> YES!
98 < 106 ? ---> NO!
76 < 98 ? ---> YES!
5 < 76 ? ---> NO!
I'm unable to find anything strange in the code I'm using, as it is quite simple:
for(var j=0;j<arrScores.length;j++)
{
if(arrScores[j][0] < scoreAnt)
{
console.log("Smaller!");
}
scoreAnt = arrScores[j][0];
}
I've tried using parseInt() in both values, but nothing changes... Checking the length of both numbers using scoreAnt.toString().length returns a length of 1, no matter which number it is (100, 34 or 156798), and the same for arrScores[j][0]. I've also logged the whole thing to check that the numbers are the expected ones, and they are (the numbers used in the example are some of the ones I'm using)...
Any clue on what can be happening? I'm really lost with this, becuase it makes no sense for me...
Thanks in advance for your time and effort! :)

You always do scoreAnt = arrScores[j][0]; in the loop; but you should only do that if arrScores[j] is smaller; i.e. inside the inner curly braces.
for(var j=0;j<arrScores.length;j++)
{
if(arrScores[j][0] < scoreAnt)
{
console.log("Smaller!");
scoreAnt = arrScores[j][0];
}
}

Well, don't even know why, but after changing something relating the CORS of the server where these numbers came from (but not modifying the numbers at all), the comparison seems to work as expected... Have no clue about what might have changed! :S However, now it works correctly...

Related

JavaScript script creating a list of three numbers

I’m new here, and so on coding.
I friend of mine suggests me to learn JavaScript and Python, because I love riddles that I can’t solve (so this languages could help me).
Let me explain: I want to create a JS script starting from this real-life problem.
I have a padlock which have a code of three numbers to be unlocked (you have to turn upside down these numbers to obtain the “Open sesame”), the code goes to 000 to 999, obviously.
I need to create a script that lists all the possible numbers and, at the end, also tell me how many different numbers I have (I suppose 1000 if my math isn’t bad as my english).
I started the learning path, but I’m not able to create this script.
I need to check all the different combinations that i have done for unlock the padlock
Can someone help me?
Thank you so much
ps: it could be nice also the same script in bash, which it's more familiar to me
x 0stone0: I have non familarity with JavaScript, I've only done an online course, so I made no attempt, just asking.
For bash, I found right here a "skeleton" of permutation script like this:
for X in {a..z}{a..z}{0..9}{0..9}{0..9}
do echo $X;
done
but I really don't know ho to edit it, cause I don't know hot to save the output of three numbers YYY from 0 to 9
Javascript
let i = 0;
while (i <= 999) {
console.log(String(i).padStart(3, '0'));
i++;
}
Pad a number with leading zeros in JavaScript
Bash
for X in {0..9}{0..9}{0..9}; do
echo $X;
done
Try it online!
Using js, you can do:
let count = 0;
for (let i = 0; i <= 999; i++) {
count++ // count++ is the same as count = count + 1, count is used to count the number of times the loop has run
if (i < 10) { // if i is less than 10 add two zero before it, for it to look like (009)
console.log('00' + i);
} else if (i < 100) { // if i is less than 100 add one zero before it, for it to look like (099)
console.log('0' + i);
} else if (i < 1000) { // if i is less than 1000 add nothing before it, for it to look like (999)
console.log(i);
} else {
console.log(i);
}
}
// then we console.log() the count variable
console.log(`There is ${count} possibilities`);
The program is made to show 3 digits, so if it's 9, it will show 009 and same for 99 => 099

Javascript performance of boolean array counting

platform: Chrome 76.
I was performance testing, when I came across the following. The app runs the attached (and prior sieving) code, repeated millions of times.
t_sieve is a boolean array, at this point has been fully sieved. This code bit is just counting the false into a int array t_match such that at any point the t_match will contain the number of 'false's up to that array index.
For the image attached, the code takes about 30s to complete out of which 25s happens here. Prior to this, the sieving takes about 4s.
Why? How to refactor this for better performance?
Also FYI, I've repeated the performance profiling and consistently this is where it lags.
Immediate following block is an update to comments received. Shows how these array are being instantiated ( a bit higher up than the code block following )
const t_sieve = new Array( M_MAX + 1 ) ;
const t_match = new Array( M_MAX + 1 ) ;
let cum = 0;
for (let i = 1; i < mod_period1; i++) {
if (!t_sieve[i]) {
cum++;
}
t_match[i] = cum;
}
const period_match_count = t_match[mod_period];
One thought I had was based on line 190 taking a significant amount of time. The reason is when you add new elements to an existing array in JS it recreates the entire array again. Thus taking exponentially longer each time a new item is added. Check out the performance screenshots:
Here is code that is very similar to yours. Creates an array of 1 million true/false, then counts them just like yours. The performance shows very similar behavior: Alot of the time is spent on line 21 adding the new elements to the array.
Now check out this restructure:
I replaced line 13 with an instantiation of the array object with a predefined length. Check out how much faster line 21 ran. This is because it already has space and doesn't have to rebuild the entire array the entire time. Granted, there is a trade off. Line 13 took slightly longer, but if you could initialize the size once then you'll make up for it each iteration through the loop.

JavaScript, finding an array instance with indexOf() and lastIndexOf() methods

I'm reading "Professional JavaScript for Web Developers" (third edition) by Nicholas Zakas in an attempt to teach myself JS. However, I am having difficulty following the Location Methods section of chapter 5 on page 118 (in case you have the book). He explains that "the indexOf() method starts searching from the front of the array (item 0) and continues to the back, whereas lastIndexOf() starts from the last item in the array and continues to the front". Also he explains that "Each of these methods accepts two arguments: the item to look for and an optional index from which to start looking". He then attempts to illustrate this with examples.
As you can see below, to the right of the alert statements, he has listed what the correct output will be for each statement given the supplied argument(s). I do not understand how these outputs are determined. For example, how does alert(numbers.indexOf(4)); produce 3? I was reading this last night and thought I was just too tired to understand, however, I still cannot seem to figure out how this is achieved. I searched the Errata section from the book's companion website for a possible typo, but nothing was listed. I also searched elsewhere but found examples that mostly dealt with strings instead of numbers. Thanks for any help. This is my first post to stack overflow so my apologies if I have done something incorrect in my post.
His examples:
var numbers = [1,2,3,4,5,4,3,2,1];
alert(numbers.indexOf(4)); //3
alert(numbers.lastIndexOf(4)); //5
alert(numbers.indexOf(4, 4)); //5
alert(numbers.lastIndexOf(4, 4)); //3
The way I thought the outcome would be:
alert(numbers.indexOf(4));
//the item in the array with the fourth index, or 5
alert(numbers.lastIndexOf(4));
//5 (this was only one that seemed to make sense to me) by counting back from the last value
alert(numbers.indexOf(4, 4));
//start looking at index 4, or 5, and then count right four places to end up at 1 (last item in array).
alert(numbers.lastIndexOf(4, 4));
//1, counting back to the left from the value with index 4, or 5, to reach the first value in the array.
Any help in determining the outputs based on the required argument and then how to also count from a specified value given the additional optional argument would be much appreciated. Thanks again.
In most of the Programming languages, default indexing start from 0. Therefore, you have an understanding problem. Double consider your example with index starting from 0.
var numbers = [1,2,3,4,5,4,3,2,1];
alert(numbers.indexOf(4)); //3, because 4 is at 3rd index
alert(numbers.lastIndexOf(4)); //5, because last 4 is at 5th index
alert(numbers.indexOf(4, 4)); //5, because searching will start from 4th index
alert(numbers.lastIndexOf(4, 4)); //3, because searching will start from last 3rd element.
JavasScript arrays are zero indexed, in other words, the first item has an index of zero. This is true for almost all programming languages (apart fro XPath for some odd reason!).
The indexOf function returns the index of the first item it finds that equals the supplied argument.
var numbers = [1,2,3,4,5,4,3,2,1];
var index = numbers.indexOf(4); // index is 3
alert(numbers[index]); // outputs 4
In JS or many other languages the index count of array starts with 0 so for,
var numbers = [1,2,3,4,5,4,3,2,1];
numbers[0] = 1
numbers[1] = 2
numbers[2] = 3
numbers[3] = 4
numbers[4] = 5
numbers[5] = 4
numbers[6] = 3
numbers[7] = 2
numbers[8] = 1
It's
indexOf("SearchString");
not
indexOf(indexNumber);
That would be awfully redundant.

Using the stop in a loop with conditionals

Hello there I'm finding it difficult to understand some basic JavaScript
I have written a loop that counts down from 10 to 0 and I'm using console.log to print that value to the console. Inside the loop an if statement is used to check if the number is 0, if it is then console.log prints "Blast Off!" instead of a number.
Here is my working code:
for (i=10; i>=0; i--;)
{
if (i === 0)
{
console.log("Blast Off!");
}
else
{
console.log(i);
}
}
However what I'm desperately trying to understand the is the stop of the for loop which is:
i>=0;
Is this effectively saying if i is greater than or equal to zero then progress through the loop decrementing i each time, then stop when zero is reached?
Conversely when I change the for loop code to what is shown below, is this effectively saying if i is less than or equal to zero then progress through the loop decrementing i each time until zero is reached?
What is the reason for the loop not printing, if the stop is changed? Is this because i never holds a value that is less than or equal to zero, meaning the loop will not run?
i<=0;
Any help clearing this up for me would be appreciated massively.
Your understanding sounds correct. When the for statement is executed, the first expression assigns a value to i (in this case, 10). The second expression is a comparison. It will evaluate to true if i is greater than or equal to 0 (which it is, as we just set it to 10). Because the condition evaluates to true, the loop body is executed. After that, the third expression runs, decrementing the value of i, and that process is repeated until the condition evaluates to false (when i reaches 0).
By changing the condition to i <= 0, it will evaluate to false the first time around, so the loop body will never execute.
The exact behaviour is detailed in the ECMAScript specification, in the section on "the for statement".
Imagine a set of stairs, 10 steps.
--
| i = 10
--
| i = 9
--
| i = 8
--
| i = 7
--
| i = 6
--
| i = 5
--
| i = 4
--
| i = 3
--
| i = 2
--
| i = 1
--
| i = 0
Imagine you are climbing down the stairs, in your head, you subconsciously think: "Until I get down to the bottom-most step, I'll keep stepping down".
Similar to the for loop:
for (i=10; i >= 0; i--)
This says, I start from the top-most, the 10th step as depicted in the image, then you climb down one step each time (or iteration) i--, then everytime after you step down, you check, "Am I at the bottom of the stairs already? No? Keep going", that's when you check i >= 0
Hope that helps you out of your desperation ;)
I think your problem is the semicolon extra in the loop:
this is your code:
for (i=10; i>=0; i--;)
try this:
for (i=10; i>=0; i--)
Maybe that's the reason for the loop is not printing.
for (i=10; i>=0; i--) means this:
start with i=10
if not i>=0 then execute. This is the "stop" condition.
after each loop do: i = i-1
On this example you won't enter the loop because the repeat condition fails.
Hello ok first "i=10" and
i>=0
is the condition for the loop. So everytime the i is greater or equal to zero the loop is returning continueing. Since you are using i-- so when i becomes negative less then zero the loop will stop.
if you use
i<=0
the condition for the loop is false so it won't enter the loop to execute the code inside bracket
Yes, if you were to change
for (i=10; i>=0; i--)
to
for (i=10; i<=0; i--)
the first condition check is false, as i is not smaller or equal to 0, so it will not eter the loop.
The condition is checked before entering the block, but after the incrementation. The incrementation is skipped the first interation. The first time the condition is not met, the whole loop will stop completely.
So if you use i<=0, the condition is not met, and the for will stop.
If you want to skip the zero, you should have the condition i>0.
You understand correctly, the i>=0 in your for loop tells to run the loop as long as i is greater than or equal to 0.
The i-- decrements the value of i on each iteration of the loop.

What are the chances that JavaScript Math.Random() will create the same number twice in a row?

Is this correct? using - http://en.wikipedia.org/wiki/Binomial_probability
Looks like values are from .0000000000000000 to .9999999999999999
Probability of happening twice = p^2 = (1/9999999999999999)^2 = 1.0 e-32
I think I am missing something here?
Also, how does being a pseudo random number generator change this calculation?
Thank You.
In an ideal world Math.random() would be absolutely random, with one output being completely independent from another, which (assuming p=the probability of any given number being produced) results in a probably of p^2 for any value being repeated immediately after another (as others have already said).
In practice people want Math.random to be fast which means pseudo-random number generators are used by the engines. There are many different kinds of PRNG but the most basic is a linear congruential generator, which is basically a function along the lines of:
s(n + 1) = some_prime * s(n) + some_value mod some_other_prime
If such a generator is used then you won't see a value repeated until you've called random() some_other_prime times. You're guaranteed of that.
Relatively recently however it's become apparent that this kind of behaviour (coupled with seeding the PRNGs with the current time) could be used for some forms tracking have led to browsers doing a number of things that mean you can't assume anything about subsequent random() calls.
I think the probability of getting two numbers in a row is 1 divided by the range of the generator, assuming that it has a good distribution.
The reason for this is that the first number can be anything, and the second number needs to just be that number again, which means we don't care about the first number at all. The probability of getting the same number twice in a row is the same as the probability of getting any particular number once.
Getting some particular number twice in a row, e.g. two 0.5s in a row, would be p^2; however, if you just care about any number twice in a row, it's just p.
If the numbers were truly random, you'd expect them, indeed, to appear with probability 1/p, so twice that would be 1/p^2.
The value for p is not exactly the one you have though, because the numbers are being represented internally as binary. Figure out how many bits of mantissa the numbers have in javascript and use that for your combinatoric count.
The "pseudorandom" part is more interesting, because the properties of pseudorandom number generators vary. Knuth does some lovely work with that in Seminumerical Algorithms, but basically most usual PN generators have at least some spectral distributiuon. Cryptograp0hic PN generators are generally stronger.
Update: The amount of time shouldn't be significant. Whether it's a millisecond or a year, as long as you don't update the state The probabilities will stay the same.
The probability that you would get 2 given numbers is (1/p)^2, but the probability that you get 2 of same numbers (any) is 1/p. That is because the first number can be anything, and the second just needs to match that.
You can kind of find out, just let it run a few days :)
var last = 0.1;
var count = 0 | 0;
function rand(){
++count;
var num = Math.random();
if(num === last){
console.log('count: '+count+' num: '+num);
}
last = num;
}
while(true) rand();

Categories