0

I'm working through a problem on CodeSignal and trying to understand some of the solutions that other people have submitted. One of the solutions was as follows, and I don't understand what the ampersand is doing.

(a) => a.reduce((p,v,i) => (p[i&1]+=v,p), [0,0])

The problem is:

Several people are standing in a row and need to be divided into two teams. The first person goes into team 1, the second goes into team 2, the third goes into team 1 again, the fourth into team 2, and so on.

You are given an array of positive integers - the weights of the people. Return an array of two integers, where the first element is the total weight of team 1, and the second element is the total weight of team 2 after the division is complete.

Example

For a = [50, 60, 60, 45, 70], the output should be solution(a) = [180, 105].

Tom
  • 7,640
  • 1
  • 23
  • 47
  • 3
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND – OldProgrammer Jan 04 '23 at 21:12
  • Perhaps this [answer](https://stackoverflow.com/a/57023927/20436957) could help. – John Li Jan 04 '23 at 21:18
  • 2
    Good old bitwise operators, aka "black magic" (to me anyway, no Computer Science background). There's something to be said about "clever" solutions like this - if you can't read it, it's maybe not that clever. Code like this is great to demonstrate capabilities of a language (look up Code Golf if you're interested), but when learning, be careful with code like this – Tim Lewis Jan 04 '23 at 21:18

1 Answers1

4

In this solution, the & operator is used to perform a bitwise AND operation. In JavaScript, the & operator compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

In the given solution, the & operator is used to determine whether the index i of the current element in the array is even or odd. If i is even, the result of i & 1 will be 0. If i is odd, the result of i & 1 will be 1.

MorganFreeFarm
  • 3,811
  • 8
  • 23
  • 46