001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
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    }