Change picture:

Choose file:

fannkuch

#{
    The Great Computer Language Shootout
http://shootout.alioth.debian.org/

contributed by Isaac Gouy
#}


routine  fannkuch(  n  :  int)=>int
{
     check  =  0;
     perm  =  [  0  :  n  ];
     perm1  =  [  0  :  n  ];
     count  =  [  0  :  n  ];
     maxPerm  =  [  0  :  n  ];
     maxFlipsCount  =  0;
     m  =  n  -  1;
     r  =  n;
     while(1){
          # write-out the first 30 permutations
          if(check  <  30){
               for(i=0;  i<n;  i++)stdio.print(  perm1[i]  +  1  );
               stdio.println();
               check++;
          }
          while(r  !=  1){  count[r-1]  =  r;  r--;  }
          if(  perm1[0]  &&  perm1[m]  !=  m  ){
               perm[]  =  perm1;
               flipsCount  =  0;
               while(  k  :=  perm[0]){
                    k2  =  (k+1)  >>  1;
                    for(i=0;  i<k2;  i++){
                         temp  =  perm[i];  perm[i]  =  perm[k-i];  perm[k-i]  =  temp;
                    }
                    flipsCount++;
               }

               if(flipsCount  >  maxFlipsCount){
                    maxFlipsCount  =  flipsCount;
                    maxPerm[]  =  perm1;
               }
          }
          # Use incremental change to generate another permutation
          while(1){
               if(r  ==  n)return  maxFlipsCount;
               perm0  =  perm1[0];
               i  =  0;
               while(i  <  r){
                    j  =  i  +  1;
                    perm1[i]  =  perm1[j];
                    i  =  j;
               }
               perm1[r]  =  perm0;
               count[r]  =  count[r]  -  1;
               if(count[r]  >  0)break;
               r++;
          }
     }
     return  maxFlipsCount;
}

routine  main(  n  =  7  )
{
     stdio.printf("Pfannkuchen(%i) = %i\n",  n,  fannkuch(n));
}

view count 550 times
created at 2009-02-20, 16:26 GMT

12 3
456789 10
111213141516 17
181920212223 24
2526272829 30 31

fu: Many thanks (Jul.04,04:29)

klabim: fixed Hi, great, now my test works now :- ). (Jun.30,17:51)

Nightwalker: Few suggestions (Jul.03,14:37)

This site is powered by Dao
Copyright (C) 2009,2010, daovm.net.
Webmaster: admin@daovm.net