001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portlet.words.util;
016    
017    import com.liferay.portlet.words.ScramblerException;
018    import com.liferay.portlet.words.util.comparator.WordComparator;
019    
020    import java.util.Set;
021    import java.util.TreeSet;
022    
023    /**
024     * @author Brian Wing Shun Chan
025     */
026    public class Scrambler {
027    
028            public Scrambler(String word) throws ScramblerException {
029                    if (word == null || word.length() < 3) {
030                            throw new ScramblerException();
031                    }
032    
033                    _word = word;
034                    _words = new TreeSet<String>(new WordComparator());
035            }
036    
037            public String[] scramble() {
038                    if (_word == null) {
039                            return new String[0];
040                    }
041    
042                    _scramble(0, _word.length(), _word.toCharArray());
043    
044                    return _words.toArray(new String[_words.size()]);
045            }
046    
047            private void _rotate(char[] charArray, int start) {
048                    char temp = charArray[start];
049    
050                    for (int i = charArray.length - start -1; i > 0; i--) {
051                            charArray[start] = charArray[++start];
052                    }
053    
054                    charArray[start] = temp;
055            }
056    
057            private void _scramble(int start, int length, char[] charArray) {
058                    if (length == 0) {
059                            String word = new String(charArray);
060    
061                            for (int i = 3; i <= charArray.length; i++) {
062                                    _words.add(word.substring(0, i));
063                            }
064                    }
065                    else {
066                            for (int i = 0; i < length; i++) {
067                                    _scramble(start + 1, length - 1, charArray);
068                                    _rotate(charArray, start);
069                            }
070                    }
071            }
072    
073            private String _word;
074            private Set<String> _words;
075    
076    }