2009年11月26日 星期四

stackoverflow Part 2

 
beautiful code 系列:

首先是廣為人知的 Carmack Q3:
float InvSqrt (float x)
{
    float xhalf = 0.5f*x;
    int i = *(int*)&x;
    i = 0x5f3759df - (i>>1);
    x = *(float*)&i;
    x = x*(1.5f - xhalf*x*x);
    return x;
}
Haskell 著名示例:
qsort [] = []
qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)
談最佳化時常提及的 Duff's device,雖然只是 loop unrolling~
void strcpy (to, from, count)
register char *to, *from;
register int count;
{
    int n = (count + 7) / 8;
    switch (count % 8) {
      case 0: do { *to = *from++;
      case 7:      *to = *from++;
      case 6:      *to = *from++;
      case 5:      *to = *from++;
      case 4:      *to = *from++;
      case 3:      *to = *from++;
      case 2:      *to = *from++;
      case 1:      *to = *from++;
    } while (--n > 0);
  }
}
Evil C 裡的另一例:
switch (c&3) while ((c-=4)>=0) {
    foo(); case 3:
    foo(); case 2:
    foo(); case 1:
    foo(); case 0:
}
theycallhimtom post。給定 adjacency matrix,計算各個最短路徑:
for (int i = 0; i < adj.length; i++)
    for (int j = 0; j < adj.length; j++)
        for (int k = 0; k < adj.length; k++)
            adj[j][k] = min (adj[j][k], adj[j][i] + adj[i][k]);
 
位元倒置:
unsigned int reverse (register unsigned int x)
{
    x = ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1);
    x = ((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2);
    x = ((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4);
    x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8);
    return (x >> 16) | (x << 16);
}
ob-C Mandelbrot:
main(){float A,B,P,Q,X,Y,d;int i,D=80,n=3120;for(X=-2.,Y=-1.5,d=6./D;B=2*A
*B+Y,A=P-Q+X,n;((P=A*A)+(Q=B*B)>4||++i>D)&&putchar(*((n--%D?X+=d/2,i<D?i%11
:11:(X=-2.0,Y+=d,12))+"Mandelbrot! \n"))&&(A=B=P=Q=i=0));}
Another one
#include <unistd.h>;
float o=0.075,h=1.5,T,r,O,l,I;int _,L=80,s=3200;main(){for(;s%L||
(h-=o,T= -2),s;4 -(r=O*O)<(l=I*I)|++ _==L&&write(1,(--s%L?_<L?--_
%6:6:7)+"World! \n",1)&&(O=I=l=_=r=0,T+=o /2))O=I*2*O+h,I=l+T-r;}
Ken Perlin 更短的..
main(k){float i,j,r,x,y=-16;while(puts(""),y++<15)for(x
=0;x++<84;putchar(" .:-;!/>)|&IH%*#"[k&15]))for(i=k=r=0;
j=r*r-i*i-2+x/25,i=2*r*i+y/10,j*j+i*i<11&&k++<111;r=j);}

沒有留言:

張貼留言