1
14
15 package com.liferay.portlet.words.util;
16
17 import com.liferay.portlet.words.ScramblerException;
18 import com.liferay.portlet.words.util.comparator.WordComparator;
19
20 import java.util.Set;
21 import java.util.TreeSet;
22
23
28 public class Scrambler {
29
30 public Scrambler(String word) throws ScramblerException {
31 if (word == null || word.length() < 3) {
32 throw new ScramblerException();
33 }
34
35 _word = word;
36 _words = new TreeSet<String>(new WordComparator());
37 }
38
39 public String[] scramble() {
40 if (_word == null) {
41 return new String[0];
42 }
43
44 _scramble(0, _word.length(), _word.toCharArray());
45
46 return _words.toArray(new String[_words.size()]);
47 }
48
49 private void _rotate(char[] charArray, int start) {
50 char temp = charArray[start];
51
52 for (int i = charArray.length - start -1; i > 0; i--) {
53 charArray[start] = charArray[++start];
54 }
55
56 charArray[start] = temp;
57 }
58
59 private void _scramble(int start, int length, char[] charArray) {
60 if (length == 0) {
61 String word = new String(charArray);
62
63 for (int i = 3; i <= charArray.length; i++) {
64 _words.add(word.substring(0, i));
65 }
66 }
67 else {
68 for (int i = 0; i < length; i++) {
69 _scramble(start + 1, length - 1, charArray);
70 _rotate(charArray, start);
71 }
72 }
73 }
74
75 private String _word;
76 private Set<String> _words;
77
78 }