• Log in or sign up for an account here: https://www.sythe.org/login

Permutation Generator

Xeox

Forum Addict

Banned
Joined
Jun 17, 2010
Sythe Gold
0
Messages
357
Location
United States
Permutation Generator
I recently made this Permutation Generator to test out recursion in coding, and I thought you guys might want to take a look at it or try it out for yourselves! All you need to do is write in the word (for my computer up to 10 characters) into:
PermutationGenerator generator = new PermutationGenerator("Exponentia");

Replace Exponentia with whatever you want, but dont forget to leave the ""'s!!

This is found in the PermutationGeneratorDemo class. I know in bluej, a 5 character max is required to see all the permutations of the given string.

PermutationGeneratorDemo:
Code:
/**
 * Write a description of class PermutationGeneratorDemo here.
 * 
 * @author (Mike Perugini) 
 * @version (13_tutorial_2)
 */
import java.util.ArrayList;

public class PermutationGeneratorDemo
{
    public static void main(String[] args)
    {
        PermutationGenerator generator = new PermutationGenerator("Exponentia");
        ArrayList<String> permutations = generator.getPermutations();
        for (String s : permutations)
        {
            System.out.println(s);
        }
    }
}

PermutationGenerator:
Code:
/**
 * Write a description of class PermutationGenerator here.
 * 
 * @author (Mike Perugini) 
 * @version (13_tutorial_2)
 */
import java.util.ArrayList;

public class PermutationGenerator
{
    private String word;
    
    /**
     * Constructs a permutation generator.
     * @param aWord the word to permute
     */
    public PermutationGenerator(String aWord)
    {
        word = aWord;
    }
    /**
     * Gets all permutations of a given word.
     */
    public ArrayList<String> getPermutations()
    {
        ArrayList<String> result = new ArrayList<String>();
        
        //The empty string has a single permutation: itself
        if (word.length() == 0)
        {
            result.add(word);
            return result;
        }
        //Loop through all character positions
        for (int i = 0; i < word.length(); i++)
        {
            //Form a simpler word by removing the ith character
            String shorterWord = word.substring(0, i) + word.substring(i + 1);
            
            //Generate all permutations of the simpler word
            PermutationGenerator shorterPermutationGenerator = new PermutationGenerator(shorterWord);
            ArrayList<String> shorterWordPermutations = shorterPermutationGenerator.getPermutations();
            
            //Add the removed character to the front of each permutation of the simpler word
            for (String s : shorterWordPermutations)
            {
                result.add(word.charAt(i) + s);
            }
        }
        //Return all permutations
        return result;
    }
}
 
Runescape Gamblingrunescape gambling
Back
Top