In mathematics, the notion of permutation is used with several slightly different meanings, all related to the act of permuting (rearranging) objects or values. Informally, a permutation of a set of objects is an arrangement of those objects into a particular order. For example, there are six permutations of the set {1,2,3}, namely (1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2), and (3,2,1).
Here is a quick simple Algorithm which computes all Permutations of a String Object in Java.
- First take out the first char from String and permute the remaining chars
- If String = “123”
- First char = 1 and remaining chars permutations are 23 and 32.
- Now we can insert first char in the available positions in the permutations.
- 23 -> 123, 213, 231
- 22 -> 132, 312, 321
package com.crunchify.tutorials; import java.util.HashSet; import java.util.Set; /** * @author Crunchify.com * */ public class CrunchifyMarmutationExample { public static void main(String[] args) { String s = "ABC"; String s1 = "EBAY"; String s2 = "Yahoo"; System.out.println("\nString " + s + ":\nPermutations: " + crunchifyPermutation(s)); System.out.println("\nString " + s1 + ":\nPermutations: " + crunchifyPermutation(s1)); System.out.println("\nString " + s2 + ":\nPermutations: " + crunchifyPermutation(s2)); } public static Set<String> crunchifyPermutation(String str) { Set<String> crunchifyResult = new HashSet<String>(); if (str == null) { return null; } else if (str.length() == 0) { crunchifyResult.add(""); return crunchifyResult; } char firstChar = str.charAt(0); String rem = str.substring(1); Set<String> words = crunchifyPermutation(rem); for (String newString : words) { for (int i = 0; i <= newString.length(); i++) { crunchifyResult.add(crunchifyCharAdd(newString, firstChar, i)); } } return crunchifyResult; } public static String crunchifyCharAdd(String str, char c, int j) { String first = str.substring(0, j); String last = str.substring(j); return first + c + last; } }
String ABC: Permutations: [ACB, ABC, BCA, CBA, CAB, BAC] String EBAY: Permutations: [YBEA, EYAB, EBYA, YABE, YAEB, BYEA, EYBA, BAEY, AYBE, ABYE, AEYB, AYEB, ABEY, BEYA, YBAE, EBAY, EAYB, BYAE, AEBY, YEAB, YEBA, BEAY, EABY, BAYE] String Yahoo: Permutations: [hYaoo, ooahY, oYoha, hooaY, aoYho, Yooha, ahooY, oaoYh, Yhoao, haYoo, hoaoY, ohoYa, haoYo, haooY, oaYoh, ooYah, oohaY, aYhoo, aoYoh, hooYa, aYooh, Yaoho, ohaoY, Yhooa, Yohao, Yohoa, hoYao, oahoY, aooYh, hoYoa, oYaoh, ohaYo, ohYoa, hYoao, Yahoo, oYoah, Yoaoh, aohYo, hoaYo, ahYoo, ahoYo, ooYha, ohYao, aoohY, oYaho, oohYa, aYoho, Yhaoo, ooaYh, oYhoa, Yoaho, Yooah, oahYo, hYooa, oaohY, ohoaY, Yaooh, oYhao, aohoY, oaYho]
List of all Java Web Development Tutorials.