我是运动编程服务中的新手,发现获胜解决方案通常使用按位运算符。
这是一个例子。
编写一个函数,找出两个数组之间的差异(考虑它们相差一个元素)。
解决方案是:
let s = x => ~eval(x.join`+`); let findDiff = (a, b) => s(b) - s(a);和
let findDiff = (a, b) => eval(a.concat(b).join`^`);我想知道:
这两个例子的解释(按位部分)。 在十进制数上使用按位运算符有什么好处? 使用按位运算而不是正常运算更快吗?更新 :我没有完全理解为什么我的问题被标记为~~ vs parseInt的副本。 很高兴知道,为什么这个运算符取代了parseInt ,可能对运动编程有帮助。 但它没有回答我的问题。
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:
The explanation of those two examples (bitwise part). What's the advantage of using bitwise operators on decimal numbers? 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.
最满意答案
Code golf并不专注于按位运算符,而是关于代码长度。
按位运算符不需要更快,但通常足够快。 它们简洁(通常难以阅读,但这是副作用)。
~~是parseInt一个较短(通常更多的预先形成)的替代品,有相当多的评论 。 在常规(非高尔夫)代码中,只有当它提供比parseInt或性能敏感的上下文更合适的行为时,才应该使用它。
~a大致等于parseInt(a) * -1 - 1 。 在这个特定的例子中,它可以用作~~a的较短替代, s(b) - s(a) ,因为* -1 - 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).
更多推荐
发布评论