7
\$\begingroup\$

I've just written code for generating all permutations of the numbers from 1 to n in Java. It seems to work, but I think it's a bit more complex than it needs to be.

import java.util.*;

public class ProblemFour {
    private static int n;

    private static void printResult(int[] result) {
        Set<Integer> set = new HashSet<>();
        // I am using Hashset<> to avoid repetitions
        Integer[] nums = new Integer[result.length];
        for (int i = 0; i < n; i++) {
            nums[i] = result[i];
        }

        Collections.addAll(set, nums);
        if(set.size() == n) System.out.println(Arrays.toString(nums));
    }

    private static void permute(int[] result, int index) {
        if (index == result.length) {
            printResult(result);
            return;
            // Recursion bottom
        }
        for (int i = 1; i <= n; i++) {
            result[index] = i;
            permute(result, index+1);
        }
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("From 1 to: ");
        n = input.nextInt();

        int[] result = new int[n];

        permute(result, 0);
    }
}
\$\endgroup\$
5
\$\begingroup\$

Single responsibility principle

Think about the possible reuse of your code. More specifically, the permute method. Do you think that the caller will always want to print out the result? Right now storing the permutations in a variable is impossible, so I cannot use this as a building block for bigger programs. What about printResult it does not only print the result, it also takes care of duplicates.

In general each method does many things, even asking for global variables around the class (printResult accesses n)

I would write follow this stub:

public class Permutation extending Array {
    public static Sequence[Sequence[Any]] permutations(Sequence[Any] array) {
        // implementation 
    }
}

public class PermutationUptoApplication {
    public static void main(String[] args) {
        int upperLimit = (new Scanner(System.in)).nextInt()
        System.out.println(Range(1, upperLimit).toArray().permutations().join("\n"));
}

You see that I wrote this in pseudo-code, but the main concept is that now you can import the Permutation class from anywhere and call it and reuse the result.

The application class just handles input and output and generates the range of numbers.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.