[Quora] What is the most elegant line of code you've seen?

来源:互联网 发布:阿里云服务器开放3306 编辑:程序博客网 时间:2024/05/23 13:32

@Murtaza Aliakbar:

// Counting # bits set in 'v', Brian Kernighan's wayfor (c = 0; v; c++)    v &= v - 1;
@Joshua Seims:

Euclid's Greatest Common Divisor algorithm (considered the oldest historical algorithm):

function (a, b) { return b ? gcb(b, a % b) : a; }
@Pradeep George Mathias:

Binary Search (The main "elegant" point is in line 3.)

int lo = 0, hi = N;for (int mid = (lo + hi) / 2; hi - lo > 1; mid = (lo + hi) / 2)    (arr[mid] > x ? hi : lo) = mid;return lo;// assuming N < 2^30, else "(lo + hi)" may overflow int// can be worked around using lo + ( hi - lo) / 2

@Ravi Tandon:

Checking whether a (natural number > 1) is a power of two or not

return (!(x & (x - 1)));

@Vinay Bajaj

Swaps A and B:

A = A + B - (B = A);
@Jesse Tov:

while (*s++ = *t++);
(揸枪注:这是复制字符串的代码,在《C程序设计语言》那本书里。)
@Sugavanesh Balasubramanian:

Not exactly a line of code, but this is a terminal command 

(*Disclaimer: Don't ever try this command! - Reference: :(){ :|:& };:)

:(){ :|:& };:
@Chetan bademi:

Inverse square roots are used to compute angles of incidence and reflection for lighting and shading in computer graphics. This code uses integer operations, avoiding computationally expensive floating point operations, which makes it four times faster than normal floating point division. 

float FastInvSqrt(float x) {    float xhalf = 0.5f * x;    int i = *(int*) &x;                 // evil floating point bit level hacking    i = 0x5f3759df - (i >> 1);          // what the fuck?    x = *(float*) &i;    x = x * (1.5f - (xhalf * x * x));    return x;}
@Thomas Le Feuvre:

One line sudoku solver(python)

def r(a):i=a.find('0');~i or exit(a);[m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]from sys import*;r(argv[1])
This is a recursive algorithm for solving a sudoku. I don't think it's incredibly efficient though. It's a fun one to work out what it's doing. If you are wanting to see a deep explanation of it see here:http://stackoverflow.com/questions/201461/shortest-sudoku-solver-in-python-how-does-it-work

@Brien Colwell:

For a 64-bit integer x,

for m in [0xff51afd7ed558ccdL, 0xc4ceb9fe1a85ec53L, 1]: x = (x ^ (x >>> 33)) * m
Applies the MurmurHash3 bit avalanche to generate a near-uniform distribution for x drawn from nearly any input distribution. Useful for uniformly distributing processing and data, much more efficient than md5 and other deep hashes.

@Jiten Thakkar:

while(x-->0) { /* Do something */ }
This gives a feeling of x tends to 0.

暂时就摘录这么多吧。这些都是我相对能看懂的语言写的代码,原文里还有perl和Haskell写的代码,因为我不懂,所以就没有贴出来了。对整个问题的答案有兴趣的朋友可以访问这里。

原创粉丝点击