Program entering in a infinite loop only with a specific value

Samir Salmen :

I just started with java and while was doing an exercise about permutations (the exercise asked to create a permutation of N elements using an array a[] meeting the requirement that no a[i] is equal to i.) I've created the following code. While testing it, I realized that it entered in a infinite loop sometimes when N = 6 specifically. Any thoughts on where is the problem?

public class GoodPerm {
    public static void main(String arg[]) {
        int n = Integer.parseInt(arg[0]);

        int[] guests = new int[n];
        for (int i = 0; i < n; i++) {
            guests[i] = i;
        }
        for (int i = 0; i < n; i++) {
            int r = i + (int) (Math.random() * (n - i));
            int q = guests[r];
            guests[r] = guests[i];
            guests[i] = q;
            if(guests[i] == i){
                i --;
            }
        }
        for(int q : guests){
            System.out.println(q);
        }
    }
}

Maybe the code enters in a inf-loop in another values, but I didn't found any others.

Islingre :

This code can always enter an inf-loop. As I understand the code, you try to do some random switches to achieve your needed result. But if the last element of your array has never been switched, it won't be possible to switch it to any "later/higher" position (because there are no more). In the "last" iteration of your second for-loop (so i + 1 == n holds at the beginning) r will always evaluate to i thus no real switch happens. If the last element is still in place, you gonna repeat this forever.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=165138&siteId=1