I recently came across some awesome piece of codes. I dont understand any of them, but I find it worth sharing here.
1. A c program to solve The Tower of Hanoi problem without using functions, stack etc. and does the task in 6 lines. Moreover, the code looks like a tower as well
.
main(
){int
z,y,n
;scanf(“%d”,&n);
for(y=1;(1<<n)-y
;y<<=z-1,printf(
“disk %i from %i to %i.\n”/**/
,z,(y&y-1)%3,((y|y-1)+1)%3),y
++)for(z=1;!(y&1);z++,y>>=1);}
2. The queen of problems – N queens problem. If you are a computer science student, you must have heard about n queens problem and probably solved that as well. This C program solves the problem very quickly, and for the rest – just have a look at the code.
int v,i,j,k,l,s,a[99];main(){for(scanf(“%d”,&s);*a-s;v=a[j*=v]-a[i],k=i<
s,j+=(v=j<s&&(!k&&!!printf(2+”\n\n%c”-(!l<<!j),” #Q”[l^v?(l^j)&1:2])&&++
l||a[i]<s&&v&&v-i+j&&v+i-j))&&!(l%=s),v||(i==j?a[i+=k]=0:++a[i])>=s*k&&
++a[--i]);printf(“\n\n”);}
3. Prints first 15000 digits of PI.
a[52514],b,c=52514,d,e,f=1e4,g,h;main(){for(;b=c-=14;h=printf(“%04d”,
e+d/f))for(e=d%=f;g=–b*2;d/=g)d=d*b+f*(h?a[b]:f/5),a[b]=d%–g;}
4. An interesting problem -
what is the “condition” such that, this snippet of code prints HelloWorld!!
if condition
printf(“Hello);
else
print(“World!!);
my friend abhilash gave a nice solution for that ..
if ( printf(“Hello”)<0){
printf(“Hello”);
else
printf(“World!!);
5. Another interesting problem -
Write a small C program, which while compiling takes another program
from input terminal, and on running gives the result for the second
program. (NOTE: The key is, think UNIX).
Suppose, the program is answer.c
Then, while compiling
$ cc -o answer answer.c
int main()
{
printf(“Hello World\n”);
}
^D
$ ./answer
Hello World
$
if anybody can solve this problem please let me know by commenting over the post with the solution.
Happy coding.