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));
}
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.