Advertisement
sci4me

Permuter

Dec 19th, 2015
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.50 KB | None | 0 0
  1. public final class Permuter
  2. {
  3.     private final String characters;
  4.  
  5.     private List<Character> current;
  6.  
  7.     public Permuter()
  8.     {
  9.         this("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
  10.     }
  11.  
  12.     public Permuter(final String characters)
  13.     {
  14.         this.characters = characters;
  15.  
  16.         this.current = new ArrayList<>();
  17.         this.current.add(characters.charAt(0));
  18.     }
  19.  
  20.     public String next()
  21.     {
  22.         final String result = this.build();
  23.         this.advance();
  24.         return result;
  25.     }
  26.  
  27.     private String build()
  28.     {
  29.         String result = "";
  30.         for (final char c : this.current)
  31.             result += c;
  32.         return result;
  33.     }
  34.  
  35.     private void advance()
  36.     {
  37.         this.advance(0);
  38.     }
  39.  
  40.     private void advance(final int index)
  41.     {
  42.         if (index >= this.current.size())
  43.         {
  44.             this.current.add(this.characters.charAt(0));
  45.         }
  46.         else
  47.         {
  48.             final char current = this.current.get(index);
  49.             final int indexOfCurrent = this.characters.indexOf(current);
  50.             final int indexOfNext = indexOfCurrent + 1;
  51.  
  52.             if (indexOfNext >= this.characters.length())
  53.             {
  54.                 this.current.set(index, this.characters.charAt(0));
  55.                 this.advance(index + 1);
  56.             }
  57.             else
  58.             {
  59.                 this.current.set(index, this.characters.charAt(indexOfNext));
  60.             }
  61.         }
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement