Skip to content

Instantly share code, notes, and snippets.

@jkoenig134
Created May 11, 2019 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkoenig134/97006a710beb3fafea9ecaff54b96b1c to your computer and use it in GitHub Desktop.
Save jkoenig134/97006a710beb3fafea9ecaff54b96b1c to your computer and use it in GitHub Desktop.
Permutate a Word and search in dictionary
import org.apache.commons.io.IOUtils;
import java.io.Console;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class Cheat {
private static Set<String> wordsSet;
private static ArrayList<String> alreadyPrinted = new ArrayList<>();
private static void Dictionary() throws IOException {
InputStream stream = Cheat.class.getClassLoader().getResourceAsStream("de.dic");
byte[] readBytes = IOUtils.toByteArray(stream);
String wordListContents = new String(readBytes, StandardCharsets.UTF_8);
String[] words = wordListContents.split("\n");
wordsSet = new HashSet<>();
Collections.addAll(wordsSet, words);
}
public static void main(String[] args) throws IOException {
Dictionary();
System.out.println("Bitte String eingeben:");
boolean close = false;
while (!close) {
Console console = System.console();
String s = console.readLine("Enter word or type [exit]: ");
if (s.equalsIgnoreCase("exit")) {
System.out.println("Bye Bye!");
close = true;
} else {
String[] splitted = s.split("(?!^)");
List<String> toDo = Arrays.asList(splitted);
Cheat.permute(toDo, 0);
}
}
}
private static void permute(List<String> arr, int k) {
for (int i = k; i < arr.size(); i++) {
java.util.Collections.swap(arr, i, k);
permute(arr, k + 1);
java.util.Collections.swap(arr, k, i);
}
if (k == arr.size() - 1) {
StringBuilder out = new StringBuilder();
for (String s : arr) {
out.append(s);
}
if (wordsSet.contains(out.toString()) && !alreadyPrinted.contains(out.toString())) {
System.out.println(out);
alreadyPrinted.add(out.toString());
}
}
alreadyPrinted = new ArrayList<>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment