1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   *
13   */
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  /**
24   * <a href="Scrambler.java.html"><b><i>View Source</i></b></a>
25   *
26   * @author Brian Wing Shun Chan
27   */
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  }