forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStrings.java
More file actions
101 lines (78 loc) · 2.66 KB
/
Copy pathStrings.java
File metadata and controls
101 lines (78 loc) · 2.66 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
101
package modern.challenge;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public final class Strings {
private Strings() {
throw new AssertionError("Cannot be instantiated");
}
public static void permuteAndPrint(String str) {
if (str == null || str.isBlank()) {
// or throw IllegalArgumentException
return;
}
permuteAndPrint("", str);
}
private static void permuteAndPrint(String prefix, String str) {
int n = str.length();
if (n == 0) {
System.out.print(prefix + " ");
} else {
for (int i = 0; i < n; i++) {
permuteAndPrint(prefix + str.charAt(i),
str.substring(i + 1, n) + str.substring(0, i));
}
}
}
public static Set<String> permuteAndStore(String str) {
if (str == null || str.isBlank()) {
// or throw IllegalArgumentException
return Collections.emptySet();
}
return permuteAndStore("", str);
}
private static Set<String> permuteAndStore(String prefix, String str) {
Set<String> permutations = new HashSet<>();
int n = str.length();
if (n == 0) {
permutations.add(prefix);
} else {
for (int i = 0; i < n; i++) {
permutations.addAll(permuteAndStore(prefix + str.charAt(i),
str.substring(i + 1, n) + str.substring(0, i)));
}
}
return permutations;
}
public static void permuteAndPrintStream(String str) {
if (str == null || str.isBlank()) {
// or throw IllegalArgumentException
return;
}
permuteAndPrintStream("", str);
}
private static void permuteAndPrintStream(String prefix, String str) {
int n = str.length();
if (n == 0) {
System.out.print(prefix + " ");
} else {
IntStream.range(0, n)
.parallel()
.forEach(i -> permuteAndPrintStream(prefix + str.charAt(i),
str.substring(i + 1, n) + str.substring(0, i)));
}
}
public static Stream<String> permuteAndReturnStream(String str) {
if (str == null || str.isBlank()) {
return Stream.of("");
}
return IntStream.range(0, str.length())
.parallel()
.boxed()
.flatMap(i -> permuteAndReturnStream(str.substring(0, i) + str.substring(i + 1))
.map(c -> str.charAt(i) + c)
);
}
}