Harder!
import java.util.ArrayList;
/**
*
* @author Nader Sl.
*/
public class PermsAndCombs {
private static ArrayList<String> perms, combs;
static {
combs = new ArrayList<String>();
perms = new ArrayList<String>();
}
public static void main(String[] args) {
//generate and display perms:
generatePerms("Nader");
displayPerms();
//generate and display combs:
generateCombs("Nader");
displayCombs();
}
public static void generatePerms(String s) {
perms.clear();
noRepetitionPerm(s);
}
public static void generateCombs(String s) {
combs.clear();
noRepetitionComb(s);
}
private static void display(ArrayList<String> l) {
for (String s : l) {
System.out.println(s);
}
}
public static void displayPerms() {
System.out.println();
System.out.println("Permutations : length = " + perms.size());
System.out.println("-----------------");
display(perms);
}
public static void displayCombs() {
System.out.println();
System.out.println("Combinations : length = " + combs.size());
System.out.println("-----------------");
display(combs);
}
//----------------------------- Permutations -------------------------------/
//Helper
public static void noRepetitionPerm(String s) {
noRepetitionPerm(s, "");
}
private static void noRepetitionPerm(String s, String sub) {
int l = s.length();
if (l == 0) {
perms.add(sub);
return;
}
for (int i = 0; i < l; ++i) {
noRepetitionPerm(s.substring(0, i) + s.substring(i + 1, l), sub + s.charAt(i));
}
}
//----------------------------- Combinations -------------------------------/
//Helper
public static void noRepetitionComb(String s) {
noRepetitionComb(s, "");
}
private static void noRepetitionComb(String s, String sub) {
combs.add(sub);
for (int i = 0; i < s.length(); ++i) {
noRepetitionComb(s.substring(i + 1), sub + s.charAt(i));
}
}
}
Output :
run:
Permutations : length = 120
-----------------
Nader
Nadre
Naedr
Naerd
Narde
Nared
Ndaer
Ndare
Ndear
Ndera
Ndrae
Ndrea
Neadr
Neard
Nedar
Nedra
Nerad
Nerda
Nrade
Nraed
Nrdae
Nrdea
Nread
Nreda
aNder
aNdre
aNedr
aNerd
aNrde
aNred
adNer
adNre
adeNr
aderN
adrNe
adreN
aeNdr
aeNrd
aedNr
aedrN
aerNd
aerdN
arNde
arNed
ardNe
ardeN
areNd
aredN
dNaer
dNare
dNear
dNera
dNrae
dNrea
daNer
daNre
daeNr
daerN
darNe
dareN
deNar
deNra
deaNr
dearN
derNa
deraN
drNae
drNea
draNe
draeN
dreNa
dreaN
eNadr
eNard
eNdar
eNdra
eNrad
eNrda
eaNdr
eaNrd
eadNr
eadrN
earNd
eardN
edNar
edNra
edaNr
edarN
edrNa
edraN
erNad
erNda
eraNd
eradN
erdNa
erdaN
rNade
rNaed
rNdae
rNdea
rNead
rNeda
raNde
raNed
radNe
radeN
raeNd
raedN
rdNae
rdNea
rdaNe
rdaeN
rdeNa
rdeaN
reNad
reNda
reaNd
readN
redNa
redaN
Combinations : length = 32
-----------------
N
Na
Nad
Nade
Nader
Nadr
Nae
Naer
Nar
Nd
Nde
Nder
Ndr
Ne
Ner
Nr
a
ad
ade
ader
adr
ae
aer
ar
d
de
der
dr
e
er
r
BUILD SUCCESSFUL (total time: 0 seconds)