0

I'm a newbie in one of a sport programming service and found that winning solutions often use bitwise operators.

Here is an example.

Write a function, which finds a difference between two arrays (consider that they differ by one element).

The solutions are:

let s = x => ~eval(x.join`+`);
let findDiff = (a, b) => s(b) - s(a);

and

let findDiff = (a, b) => eval(a.concat(b).join`^`);

I would like to know:

  1. The explanation of those two examples (bitwise part).
  2. What's the advantage of using bitwise operators on decimal numbers?
  3. Is that faster to operate with bitwise operations rather than normal one?

Update: I didn't fully understand why my question is marked as a duplicate to ~~ vs parseInt. That's good to know, why this operator replaces parseInt and probably helpful for sport programming. But it doesn't answer on my question.

Kris Ku
  • 1,507
  • 1
  • 16
  • 32
  • 1
    Not necessarily faster. They are concise (and usually harder to read, but that's side effect). Code golf isn't focused on bitwise operators, is about code length. You may consider [the relevant community](http://codegolf.stackexchange.com/questions/2682/tips-for-golfing-in-javascript) instead of SO for this type of questions. – Estus Flask Jan 31 '17 at 06:06
  • Possible duplicate of [~~ vs parseInt?](http://stackoverflow.com/questions/10841204/vs-parseint) – Estus Flask Jan 31 '17 at 08:20
  • @estus, where do you see `~~` in my example? – Kris Ku Jan 31 '17 at 09:56
  • @estus your first comment is exactly what I meant! could you add this as an answer. – Kris Ku Jan 31 '17 at 10:08
  • 1
    I explained it in the answer. The one should know vanilla JS really good before he/she approaches 'sport programming'. Learn to walk before you run, figuratively saying. – Estus Flask Jan 31 '17 at 10:38

1 Answers1

1

Code golf isn't focused on bitwise operators, is about code length.

Bitwise operators are not necessary faster, but generally fast enough. They are concise (and usually harder to read, but that's side effect).

~~ is a shorter (and usually more preformant) alternative to parseInt with a considerable number of remarks. In regular (non-golf) code it should be used only if it provides the behaviour that is more desirable than parseInt or in performance-sensitive context.

~a is roughly equal to parseInt(a) * -1 - 1. It can be used as a shorter alternative to ~~a in this particular example, s(b) - s(a), because * -1 - 1 part is eliminated on subtraction (the sign should be taken into account).

Community
  • 1
  • 1
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • yep! and here is the corresponding community http://codegolf.stackexchange.com/questions/2682/tips-for-golfing-in-javascript – Kris Ku Jan 31 '17 at 10:37