Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.