Note that there are some explanatory texts on larger screens.

plurals
  1. POJava permutations
    primarykey
    data
    text
    <p>I am trying to run my code so it prints cyclic permutations, though I can only get it to do the first one at the moment. It runs correctly up to the point which I have marked but I can't see what is going wrong. I think it has no break in the while loop, but I'm not sure. Really could do with some help here.</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); printPemutation(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 printPemutation(int p[])// (b) { System.out .println("The permutation is represented by the cyclic notation:"); int[] B = new int[p.length]; int m = 0; while (m &lt; p.length)// this is the point at which my code screws up { if (!check(B, m)) { B = parenthesis(p, m); printParenthesis(B); m++; } else m++; }// if not there are then repeat } static int[] parenthesis(int p[], int i) { int[] B = new int[p.length]; for (int a = p[i], j = 0; a != B[0]; a = p[a - 1], j++) { B[j] = a; } return B; } static void printParenthesis(int B[]) { System.out.print("( "); for (int i = 0; i &lt; B.length &amp;&amp; B[i] != 0; i++) System.out.print(B[i] + " "); System.out.print(")"); } static boolean check(int B[], int m) { int i = 0; boolean a = false; while (i &lt; B.length || !a) { if ((ispresent(m, B, i))){ a = true; break; } else i++; } return a; } static boolean ispresent(int m, int B[], int i) { return m == B[i] &amp;&amp; m &lt; B.length; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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