I was messing around in python and I found this library called itertools
. It is very useful for challenges you'd come across at at a competition. However only one of three competitions I go to accepts python. They all support mainly java and other various c style languages.
Anyways I wrote this code in python and want to translate it into java.
import itertools
array = [''.join(x) for x in itertools.permutations(input("Enter a word: "))]
print(",".join(array).replace(",", "\n"))
This will print out all permutations of a word that are length of the word.
Examples: hi ---> hi, ih
foo---> foo, foo, ofo, oof, ofo, oof
(Yes there are duplicates disregard them when answering)
Now I am aware of this java code that is similar to what I've made (Don't bother examining it. Just know it does the same task)
public class Permutations {
// print N! permutation of the characters of the string s (in order)
public static void perm1(String s) { perm1("", s); }
private static void perm1(String prefix, String s) {
int N = s.length();
if (N == 0) System.out.println(prefix);
else {
for (int i = 0; i < N; i++)
perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
}
}
// print N! permutation of the elements of array a (not in order)
public static void perm2(String s) {
int N = s.length();
char[] a = new char[N];
for (int i = 0; i < N; i++)
a[i] = s.charAt(i);
perm2(a, N);
}
private static void perm2(char[] a, int n) {
if (n == 1) {
System.out.println(a);
return;
}
for (int i = 0; i < n; i++) {
swap(a, i, n-1);
perm2(a, n-1);
swap(a, i, n-1);
}
}
// swap the characters at indices i and j
private static void swap(char[] a, int i, int j) {
char c;
c = a[i]; a[i] = a[j]; a[j] = c;
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String elements = alphabet.substring(0, N);
perm1(elements);
System.out.println();
perm2(elements);
}
}
Now in the crunch time of a competition I'd really prefer to use my 3 lined code opposed to this but, I can't because of the restrictions. Is anyone aware of a library in java that is similar to python's itertools
?
Guava's Collections2.permutations
might do the job, but as many other people have said, third-party libraries usually aren't fair game for contest programming. (There's nothing for this built into Java.)