Download code

Jump to: navigation, search

Back to Permutations_with_repetition_(Java)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

PermutationsWithRepetition.java

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Permutations_with_repetition_(Java)?oldid=11971
14 */
15 
16 import java.util.List;
17 import java.util.ArrayList;
18 
19 public class PermutationsWithRepetition {
20 	private String a;
21 	private int n;
22 	public PermutationsWithRepetition(String a, int n) {
23 		this.a = a;
24 		this.n = n;
25 	}
26 	public List<String> getVariations() {
27 		int l = a.length();
28 		int permutations = (int) Math.pow(l, n);
29 		char[][] table = new char[permutations][n];
30 		
31 		for (int x = 0; x < n; x++) {
32 		    int t2 = (int) Math.pow(l, x);
33 		    for (int p1 = 0; p1 < permutations;) {
34 		        for (int al = 0; al < l; al++) {
35 		            for (int p2 = 0; p2 < t2; p2++) {
36 		                table[p1][x] = a.charAt(al);
37 		                p1++;
38 		            }
39 		        }
40 		    }
41 		}
42 
43 		
44 		List<String> result = new ArrayList<String>();
45 		for (char[] permutation : table) {
46 		    result.add(new String(permutation));
47 		}
48 		return result;
49 	}
50 	public static void main(String[] args) {
51 		
52 		PermutationsWithRepetition gen = new PermutationsWithRepetition("abc", 3);
53 		List<String> v = gen.getVariations();
54 		for (String s : v) {
55 		    System.out.println(s);
56 		}
57 	}
58 }


hijacker
hijacker
hijacker
hijacker