-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberPermutationGenerator.java
More file actions
100 lines (83 loc) · 3.13 KB
/
NumberPermutationGenerator.java
File metadata and controls
100 lines (83 loc) · 3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package fourEqualsTen;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class NumberPermutationGenerator {
public static List<String> generateValidPermutations(String input) {
List<String> permutations = generatePermutations(input);
List<String> validPermutations = new ArrayList<>();
for (String permutation : permutations) {
if (isValid(permutation)) {
validPermutations.add(permutation);
}
}
return validPermutations;
}
public static boolean isValid(String permutation) {
int openParenIndex = permutation.indexOf('(');
int closeParenIndex = permutation.indexOf(')');
if (openParenIndex == -1 || closeParenIndex == -1 || openParenIndex >= closeParenIndex) {
return false;
}
String contents = permutation.substring(openParenIndex + 1, closeParenIndex);
int numCount = 0;
for (char c : contents.toCharArray()) {
if (Character.isDigit(c)) {
numCount++;
}
}
return numCount >= 2 && numCount <= 3;
}
public static List<String> generatePermutations(String input) {
List<String> result = new ArrayList<>();
char[] chars = input.toCharArray();
List<Character> numbers = new ArrayList<>();
int openParenCount = 0;
int closeParenCount = 0;
for (char c : chars) {
if (Character.isDigit(c)) {
numbers.add(c);
} else if (c == '(') {
openParenCount++;
} else if (c == ')') {
closeParenCount++;
}
}
// Check for input validity
if (numbers.size() != 4) {
System.out.println("Error: Input should contain exactly 4 numbers.");
return result;
}
if (openParenCount != 1 || closeParenCount != 1) {
System.out.println("Error: Input should contain exactly one pair of parentheses.");
return result;
}
if (openParenCount != closeParenCount) {
System.out.println("Error: Invalid parentheses (mismatched open and close parentheses).");
return result;
}
if (numbers.size() == 0) {
System.out.println("Error: Input should contain at least one number.");
return result;
}
generatePermutationsHelper(chars, 0, result);
return result;
}
public static void generatePermutationsHelper(char[] chars, int index, List<String> result) {
if (index == chars.length) {
result.add(new String(chars));
return;
}
for (int i = index; i < chars.length; i++) {
swap(chars, index, i);
generatePermutationsHelper(chars, index + 1, result);
swap(chars, index, i);
}
}
public static void swap(char[] chars, int i, int j) {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}