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);
 }
}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jan 1, 2016 at 15:34
\$\endgroup\$

1 Answer 1

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.

answered Jan 1, 2016 at 16:18
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.