iterating a selection in javascript - javascript

This is a simple code to change the style of even numbered list elements but as a newbie, i really did not understand how the following if statement can be true and false. Because i think that key is always true. However, when i run the code, i see that it is not always true. Can someone explain why?
$(document).ready(
function()
{
$('ul#rubberSoul li').each(
function(key)
{
if (key & 1) {
$(this).addClass('rubberSoulEven');
}
}
);
}
);

& operator does a bitwise AND operation on each of the bits of two 32 bit expression (the operands). If the bit value from both the sides are 1, the result is 1. Otherwise, the result is 0. Bitwise ANDing any number with 0 yields 0
For example , take this expression x & y
x value y value result
-----------------------------
1 1 1
1 0 0
0 1 0
0 0 0
So in your case, it is going to check bit representation of key variable value & bit representation of 1 in your if condition and return the result of that.
operand1(key) operand1-binary operand2 operand2-binary result
------------------------------------------------------------------
1 1 1 1 1
2 10 1 01 0
3 11 1 01 1
4 100 1 001 0

key is index of each and (key & 1) is true for odd indexes.

<ul id="rubberSoul ">
<li class="">One</li> # 0
<li class="">Two</li> # 1
<li class="">Three</li> # 2
</ul>
Your If loop will show true for only the second statement (<li class="">Two</li> # 1) as it validates (if (key & 1))

Related

What is the use of a bitwise and, (&1), in javascript?

From the tutorial here,
function notePressed(event) {
if (event.buttons & 1) {
let dataset = event.target.dataset;
if (!dataset["pressed"]) {
let octave = +dataset["octave"];
oscList[octave][dataset["note"]] = playTone(dataset["frequency"]);
dataset["pressed"] = "yes";
}
}
}
What is the use of event.buttons & 1? Why is a bitwise AND being used?
Here event.buttons returns an integer value, which represents that which mouse button is pressed. According to MDN it returns -
0 : No button or un-initialized
1 : Primary button (usually the left button)
2 : Secondary button (usually the right button)
4 : Auxiliary button (usually the mouse wheel button or middle button)
8 : 4th button (typically the "Browser Back" button)
16 : 5th button (typically the "Browser Forward" button)
So, ultimately what do we get from this event.buttons? An integer value.
Now come to your shared code snippet. What does the line if (event.buttons & 1) mean? Let's check some example of, what does the & 1 do with 32 bits integer.
0 & 1 => 0
1 & 1 => 1
2 & 1 => 0
3 & 1 => 1
23 & 1 => 1
46 & 1 => 0
So, if we perform & 1 with any 32 bits integer number then for Even numbers it returns 0 and for Odd numbers it returns 1. We can easily detect any odd/even numbers by using bitwise AND 1 operation.
Now you know 0 is a falsy value so the if condition never passes if we get 0 from the statement. So, if (event.buttons & 1) checks if the event.buttons gives an Odd number then execute the if block, otherwise not.
I hope I can clear it.

Math.round(Math.random()) combination seems to be generating too many 0's in my javascript programme

I am trying to make a really simple script to generate a 2d array in which every nth array does not contain it's own index as an element but contains a random amount of other randomised index values as their elements and can not be empty. The following is a little code I wrote to attempt to achieve this:
totElList = []
numEls = 1000
for (i=0;i<numEls;i++) {
totElList[i] = []
for (j=0;j<numEls;j++) {
totElList[i][j] = j
}
}
for (i in totElList) {
totsplice = Math.round(Math.random()*(numEls-1))
totElList[i].splice(i,1)
for (j=0;j<totsplice;j++) {
rand = Math.round(Math.random()*totElList[i].length)
while (typeof(totElList[i][rand]) === undefined) {rand = Math.round(Math.random()*totElList[i].length)}
totElList[i].splice(rand,1)
}
}
The problem is when I run this the totElList array seems to contain more 0's than any other number even though I assumed elements would be removed at random. I did a test to confirm this. The amount of 0's is always the maximum out of all possible values for a given numEls. I am guessing this is something to do with the workings of Math.random() and Math.round() but I am unsure. Could somebody please give me some insight? Thank you.
Instead of Math.round, take Math.floor which works better for indices, because it is zero based.
Example with one digit and a factor of 2 as index for an array with length of 2.
As you see, the second half index is moved to the next index of every number, which results into a wrong index and with the greatest random value, you get an index outside of the wanted length.
value round floor comment for round
----- ----- ----- -----------------
0.0 0 0
0.1 0 0
0.2 0 0
0.3 0 0
0.4 0 0
0.5 1 0 wrong index
0.6 1 0 wrong index
0.7 1 0 wrong index
0.8 1 0 wrong index
0.9 1 0 wrong index
1.0 1 1
1.1 1 1
1.2 1 1
1.3 1 1
1.4 1 1
1.5 2 1 wrong index
1.6 2 1 wrong index
1.7 2 1 wrong index
1.8 2 1 wrong index
1.9 2 1 wrong index

I don't understand what is happening with this XOR

I am working on this problem.
"Given an array, find the int that appears an odd number of times.
There will always be only one integer that appears an odd number of times."
I came up with this solution online:
function findOdd(A) {
var n = 0;
for(var i = 0; i < A.length; i++){
n = n^A[i];
}
return n;
}
This works but I am not sure why and i was hoping someone could explain it to me. I just don't understand the line:
n = n^A[i];
Could you please tell me what it is doing in this instance?
Xoring any number with itself will result in 0. If you know that there's only one number that appears an odd number of times, the others will cancel themselves out by self-xoring, and the answer will be the remaining number that appears an odd number of times.
XOR of two same numbers is always zero. That is,
A^A=0
So, if you XOR a particular number with itself repeatedly for even number of times, the result will be zero.
Here, initially the value of n is zero. The number that will be XOR-ed even number of times, will result zero. And the number that is present odd number of times, say 2m+1number of times, will result in zero for 2m occurrences, and that same number for the final one occurrence.
This is how this solution works.
^ is an exor bit wise operator . so when you do
1 ^ 1 is 0
0 ^ 1 is 1
1 ^ 0 is 1
0 ^ 0 is 0
so to find the odd number of 1's the following code does is
initially result is arr[0] is 1 .
so in the arrary 0^ 0 becomes 0 and 2 ^ 2 becomes 0 and there are 3 1's so 1^1 gets 0 and with 0 ^1 we are leftout with the number which repeats odd nubmer of times
var arr=[1,1,1,0,0,2,2];
var result=arr[0];
for(var i=1;i<arr.length;i++)
result=result ^ arr[i];
console.log(result);
Hope it helps
Bitwise operators work on 32 bits numbers. Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number. ^ is a bitwise XOR javascript operator.
Bitwise XOR Operator returns a one in each bit position for which the corresponding bits of either but not both operands are ones.
a XOR b yields 1 if a and b are different. The truth table for the XOR operation is:
a b a XOR b
0 0 0
0 1 1
1 0 1
1 1 0
Explanation for expression n = n^A[i];
let A = [1,2,3,4,5]
for n=0, i=0 => 0 ^ A[0] => 0 ^ 1 => converted to binary 0000 ^ 0001 results to 0001 which is equal to 1
for n=1, i=1 => 1 ^ A[1] => 1 ^ 1 => converted to binary 1111 ^ 0010 results to 1101 which is equal to 13
and so on... Hope this solution helps you to understand the above expression and clear your all doubts.

& 1 JavaScript. How does it work? Clever or good? [duplicate]

This question already has answers here:
Is there a & logical operator in Javascript
(8 answers)
Closed 6 years ago.
I'm looking over the solutions for a CodeWars problem (IQ Test) in which you're given a string of numbers and all the numbers but 1 are either even or odd. You need to return the index plus 1 of the position of the number that's not like the rest of the numbers.
I'm confused about the line that says & 1 in the solution posted below. The code doesn't work w/ && or w/ the & 1 taken away.
function iqTest(numbers){
numbers = numbers.split(' ')
var evens = []
var odds = []
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] & 1) { //PLEASE EXPLAIN THIS LINE!
odds.push(i + 1)
} else {
evens.push(i + 1)
}
}
return evens.length === 1 ? evens[0] : odds[0]
}
Also, would you consider using & 1 to be best practice or is it just "clever" code?
The single & is a 'bitwise' operator. This specific operator (&) is the bitwise AND operator - which returns a one in each bit position for which the corresponding bits of both operands are ones.
The way it's being used here is to test if numbers[i] is an even or odd number. As i loops from 0 to numbers.length, for the first iteration the if statement evaluates 0 & 1 which evaluates to 0, or false. On the next iteration of the loop, the statement will be 1 & 1, which evaluates to 1, or true.
The result - when numbers[i] & 1 evaluates to 0, or false, then numbers[i] is pushed to the odd array. If numbers[i] & 1 evaluates to 1, or true, then numbers[i] is pushed to the even array.
An alternative to the & operator to test for even and odd is to use the modulo operator. numbers[i] % 2 results in the same output. That is, 1 % 2 results in 1, or true as will any odd number, because an odd number divided by 2 results in a remainder of 1. And any even number, like 2 % 2 results in 0 or false because an even number divided by 2 results in a remainder of 0.
As for your second question, is it 'clever or good?'. It's definitely clever. Whether it's good depends on who you ask and what your goal is. Many would say its less logical and harder to read than using num % 2.
Binary number is 0 and 1 and each of them is called bit.
Single & is add operation and it works bitwise.
like
1 = 01
2 = 10
3 = 11
4 = 100
You can see that every last bit of odd number is 1 and even number is 0.
In add operation
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
So only odd number will return 1 and even number will return 0 and in programming only 0 consider falsy.
If we wanna to check 5 is a odd or even
5 = 101
and perform and(&) operation with 1
101
& 001
-----
001
and value of binary 001 is 1 in 10 base number
So it'll perform easy odd even process.

Javascript XOR operation (trying to understand!)

I've been researching the caret (XOR) operator in Javascript, but i'm having a heck of a hard time understanding.
Can someone explain why, for example, 1 ^ 1 = 0?
I have some code someone wrote, and they are doing the following:
if (shouldBeCollapsed ^ 1)
{
//code to collapse section of page.
}
But if the shouldBeCollapsed variable is equal to 1, the condition fails. I'm just trying to understand the logic behind the ^ operator, and it's kind of confusing me!
Thanks!
That is the definition of XOR. X ^ Y is 1 iff X != Y.
Thus, if X and Y are both 1, then XOR is 0.
The truth table is as follows:
X Y X^Y
0 0 0
0 1 1
1 0 1
1 1 0
X ^ Y is logically equivalent to (X && !Y) || (!X && Y)
Let me illustrate with an example:
2 ^ 1 = 3
In binary
10 ^ 01 = 11
At a bitwise level, A^B = 1 if A != B
shouldBeCollapsed looks like a boolean variable in which case you are doing it wrong. What you are looking for is :
if (shouldBeCollapsed) {
// Code to collapse
}

Categories

Resources