Note that there are some explanatory texts on larger screens.

plurals
  1. POJava permutations 2
    text
    copied!<p>I asked a question on helping me with this question about a week ago </p> <h2><a href="https://stackoverflow.com/questions/4340897/java-permutations">Java permutations</a></h2> <p>, with a problem in the print permutation method. I have tidied up my code and have a working example that now works although if 5 is in the 5th position in the array it doesn't print it. Any help would be really appreciated.</p> <pre><code> package permutation; public class Permutation { static int DEFAULT = 100; public static void main(String[] args) { int n = DEFAULT; if (args.length &gt; 0) n = Integer.parseInt(args[0]); int[] OA = new int[n]; for (int i = 0; i &lt; n; i++) OA[i] = i + 1; System.out.println("The original array is:"); for (int i = 0; i &lt; OA.length; i++) System.out.print(OA[i] + " "); System.out.println(); System.out.println("A permutation of the original array is:"); OA = generateRandomPermutation(n); printArray(OA); printPermutation(OA); } static int[] generateRandomPermutation(int n)// (a) { int[] A = new int[n]; for (int i = 0; i &lt; n; i++) A[i] = i + 1; for (int i = 0; i &lt; n; i++) { int r = (int) (Math.random() * (n)); int swap = A[r]; A[r] = A[i]; A[i] = swap; } return A; } static void printArray(int A[]) { for (int i = 0; i &lt; A.length; i++) System.out.print(A[i] + " "); System.out.println(); } static void printPermutation(int[] p) { int n = p.length-1; int j = 0; int m; int f = 0; System.out.print("("); while (f &lt; n) { m = p[j]; if (m == 0) { do f++; while (p[f] == 0 &amp;&amp; f &lt; n); j = f; if (f != n) System.out.print(")("); } else { System.out.print(" " + m); p[j] = 0; j = m - 1; } } System.out.print(" )"); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload