2

I am trying to find all permutations of a pin number coming from a scanner. I have got this bit so far which I guess sets an array with custom digits. How can I get this code to show me all the possible options? Bare in mind that I am new to Java so simple explanations would be the best. Thanks

import java.util.Arrays;
import java.util.Scanner;

public class Methods {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int[] arr = new int[3];

        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter first digit: ");
        arr[0] = sc.nextInt();
        System.out.println("Please enter second digit: ");
        arr[1] = sc.nextInt();
        System.out.println("Please enter third digit: ");
        arr[2] = sc.nextInt();
        System.out.println("Please enter fourth digit: ");
        arr[3] = sc.nextInt();

        System.out.println(Arrays.toString(arr));
        }
    }
Stephan Hogenboom
  • 1,543
  • 2
  • 17
  • 29
  • 1
    Make your array one bigger. You need four elements to store four digits. Have you tried anything yet to permutate? So far, I only see code for reading the input. – Roland Weber Feb 14 '19 at 11:54
  • I haven't as I have no clue where to start off. I have tried reading posts of other people but it just makes no sense. I have changed the array now – Patryk Sarnik Feb 14 '19 at 12:06
  • 1
    Try double-indexing. Generate arrays "perm" with all possible permutations of (0,1,2,3). Then instead of printing/reading your input array with indices 0,1,2,3, access it with index perm[0], perm[1], perm[2], perm[3]. As long as all four input digits are unique, you'll get all permutations without duplicates. If some of the input digits are identical, you'll have duplicates though. – Roland Weber Feb 14 '19 at 12:20

1 Answers1

1

Hey you can use the following code to create an array of n length and calculate the permutations:

public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.print("please enter the length of you array: "); // 4 if you want a 4 digit pincode
  int length = sc.nextInt();

  int[] arr = new int[length];

  for (int i = 0; i < length; i++) {
    System.out.printf("Please enter a value for digit #%s: ", i);
    arr[i] = sc.nextInt();
  }

  StringBuilder bldr = new StringBuilder();
  Arrays.stream(arr).forEach(bldr::append);
  permutation(bldr.toString());
}

public static void permutation(String str) {
    permutation("", str);
}

private static void permutation(String prefix, String str) {
  int n = str.length();
  if (n == 0)
    System.out.println(prefix);
  else {
    for (int i = 0; i < n; i++)
      permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n));
  }
}

Also check this question for more info about permutations.

Stephan Hogenboom
  • 1,543
  • 2
  • 17
  • 29