This code generates all permutations of the numbers 0, 1, 2,...., n-1. I am trying to get it to use recursion to do this. I am not compiling. I do not show errors, but I am not getting it to work. Can anyone see where I am going wrong?

``````import java.io.*;
public class NumberPermutationIterator {

public NumberPermutationIterator(int n)
{
a = new int[n];
boolean done = false;
for (int i = 0; i < n; i++) a[i] = i;
}
public int[] nextPermutation()
{
if (a.length <= 1) return a;

for (int i = a.length - 1; i > 0; i--){
if (a[i -1] > a[i])
{
int j = a.length -1;
while (a[i-1] > a[j]) j--;
swap(i-1, j);
reverse(i, a.length -1);
return a;
}
}
return a;
}
public boolean hasMorePermutations()
{
if (a.length <= 1) return false;
for (int i = a.length -1; i > 0; i--)
{
if (a[i-1] < a[i]) return true;
}
return false;
}
public void swap (int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public void reverse (int i, int j)
{
while (i < j) { swap (i, j); i++; j++;}
}
private int[] a;
public class Permutation {
public void main(String args[]) throws IOException {
int n = 3;
char[] a = new char[n];
for (int i = 0; i < n; i++) a[i] = Character.forDigit(i, 10);
permute("", new String(a));
}

public void permute(String beginningString, String endingString) {
if (endingString.length() <= 1)
System.out.println(beginningString + endingString);
else
for (int i = 0; i < endingString.length(); i++) {
try {
String newString = endingString.substring(0, i) + endingString.substring(i + 1);

permute(beginningString + endingString.charAt(i), newString);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
}
}``````
3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by JamesCherrill

I am not getting it to work.

Does it execute? Is there output? Can you copy and paste here the program's output and explain what is wrong with it?

Lines 60-62
In the loop you remove 1 char from endstring with the intention of adding it to begstring on for the call on line 62 line.
Problem is that you remove the char THEN you try to get it by using charAt, but it's too late, you've already removed it!