Home > Software design >  I wonder how (ar1 | ar2 [I]) works in this code
I wonder how (ar1 | ar2 [I]) works in this code

Time:09-03

let n = 6;

let arr1 = [46, 33, 33, 22, 31, 50];
let arr2 = [27, 56, 19, 14, 14, 10];

let answer;

let solution = (n, arr1, arr2) => {
  answer = arr1.map(
    (arr1, i) =>
      (arr1 | arr2[i])
        .toString(2)
        .padStart(n, 0)
        .replace(/0/g, " ")
        .replace(/1/g, "#"),
    console.log(arr2)
  );
  console.log(answer);
};
solution(n, arr1, arr2);

I'm asking because there is something I don't understand in the code above. How did (arr1 | arr2[i]) work? Why are the two arrays combined?

CodePudding user response:

"Bitwise or" is the name of the | operator. JavaScript coerces arr1 and arr2[i] to binary (a set of 0s and/or 1s), then ors them.

For a given set of bits, the bitwise operator evaluates them like this:

(0 | 0) === 0
(0 | 1) === 1
(1 | 0) === 1
(1 | 1) === 1

arr1.map(arr1, i)... creates a locally scoped variable arr1 with the same name as the array it's mapping. So, inside the map function, arr1 refers to the item at array index i. It should be renamed for clarity.

arr2[i] just evaluates to the value from the 2nd array, which is in the same position during the map's loop. So, in this case, for a given index of the loop:

i arr1 arr2[i]
0 46 27
1 33 56
2 33 19
3 22 14
4 31 14
5 50 10

Then the confusing part of your code ((arr1 | arr2[i])) does a bitwise or on the binary values:

arr1 Number(arr1).toString(2) arr2[i] Number(arr2[i]).toString(2) Bitwise Or (binary)
46 101110 27 011011 111111
33 100001 56 111000 111001
33 100001 19 010011 110011
22 010110 14 001110 011110
31 011111 14 001110 011111
50 110010 10 001010 111010

Then your code .toString(2).padStart(n, 0).replace(/0/g, " ").replace(/1/g, "#") just uses the binary values above and replaces zeroes with spaces, and ones with octothorpes: ['######', '### #', '## ##', ' #### ', ' #####', '### # ']

  • Related