-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutator.java
More file actions
68 lines (50 loc) · 1.66 KB
/
Permutator.java
File metadata and controls
68 lines (50 loc) · 1.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
package string.sentence;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
class Permutator {
private List<List<String>> permutations;
public Permutator() {
this.permutations = new ArrayList<>();
}
public List<String> permute( String value ) {
List<List<String>> groups = extractGroups( value );
String template = generateTemplate( value );
List<String> sentences = new ArrayList<>();
for ( List<String> permutations : permute( groups ) ) {
sentences.add( String.format( template, permutations.toArray() ) );
}
return sentences;
}
private List<List<String>> permute( List<List<String>> groups ) {
permutations.clear();
permute( new ArrayList<>(), 0, groups );
return permutations;
}
private void permute( List<String> permutation, int groupIndex, List<List<String>> groups ) {
if ( groupIndex == groups.size() ) {
permutations.add( permutation );
return;
}
for ( String element : groups.get( groupIndex ) ) {
List<String> newPermute = new ArrayList<>( permutation );
newPermute.add( element );
permute( newPermute, groupIndex + 1, groups );
}
}
List<List<String>> extractGroups( String value ) {
List<List<String>> groups = new ArrayList<>();
Matcher matcher = Pattern.compile( "\\{([^\\}]+)" ).matcher( value );
while ( matcher.find() ) {
groups.add( Arrays.stream( matcher.group( 1 ).split( "," ) ).map( s -> s.trim() )
.collect( Collectors.toList() ) );
}
return groups;
}
String generateTemplate( String value ) {
return value.replaceAll( "\\{[^\\}]+\\}", "%s" );
}
}