babacan

January 10th, 2009, 03:49 PM

Greetings

I am trying to convert a pseudo code to java(Revolving Door), however I am failing at this.

Here is the pseudo code(I took a shot from my book): http://img243.imageshack.us/img243/1633/03012009700bj4.jpg

Expected output:http://img209.imageshack.us/img209/74/03012009701qv8.jpg

And here is the java code I have written to convert it to java:

class RevolvingDoor{

static int fact(int a){

if(a == 0)

return 1;

else return a * fact(a -1);

}

static int combination(int n,int k){

return fact(n) / ( fact(k) * fact(n-k)) ;

}

static void RevDoor(int n,int k){

int[] t= new int[n];

for(int i=1; i<=n;i++){

t[i]= i;

}

for(int i=0; i<= combination(n,k);i++){

System.out.print(combination(1,i)+" ");

t[k+1]= n + 1;

int j = 1;

while(j<=k && t[j]==j){

j= j+1;

}

if((k-j) % 2 != 0){

if(j==1)

t[1]= t[1] -1;

else

t[j-1] = j;

t[j-2] = j - 1;

}

else{

if(t[j+1] != t[j] + 1){

t[j-1] = t[j];

t[j] = t[j] + 1;

}

else

t[j+1] = t[j];

t[j] = j;

}

}

System.out.println();

}

public static void main(String[] args){

/*System.out.println(fact(3));

System.out.println(combination(3,2));*/

RevDoor(6,1);

}

}

I cant understand what is wrong, I suspect its about pseudo code starts from 1 while for java the array start is 0. Also I didn't get what exactly visit permutation[0...n-1] stands for.

Thanks.

I am trying to convert a pseudo code to java(Revolving Door), however I am failing at this.

Here is the pseudo code(I took a shot from my book): http://img243.imageshack.us/img243/1633/03012009700bj4.jpg

Expected output:http://img209.imageshack.us/img209/74/03012009701qv8.jpg

And here is the java code I have written to convert it to java:

class RevolvingDoor{

static int fact(int a){

if(a == 0)

return 1;

else return a * fact(a -1);

}

static int combination(int n,int k){

return fact(n) / ( fact(k) * fact(n-k)) ;

}

static void RevDoor(int n,int k){

int[] t= new int[n];

for(int i=1; i<=n;i++){

t[i]= i;

}

for(int i=0; i<= combination(n,k);i++){

System.out.print(combination(1,i)+" ");

t[k+1]= n + 1;

int j = 1;

while(j<=k && t[j]==j){

j= j+1;

}

if((k-j) % 2 != 0){

if(j==1)

t[1]= t[1] -1;

else

t[j-1] = j;

t[j-2] = j - 1;

}

else{

if(t[j+1] != t[j] + 1){

t[j-1] = t[j];

t[j] = t[j] + 1;

}

else

t[j+1] = t[j];

t[j] = j;

}

}

System.out.println();

}

public static void main(String[] args){

/*System.out.println(fact(3));

System.out.println(combination(3,2));*/

RevDoor(6,1);

}

}

I cant understand what is wrong, I suspect its about pseudo code starts from 1 while for java the array start is 0. Also I didn't get what exactly visit permutation[0...n-1] stands for.

Thanks.