Skip to content

Instantly share code, notes, and snippets.

@kousen
Last active June 14, 2020 18:50
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 kousen/f653fe1e040827aed4e894ee86643300 to your computer and use it in GitHub Desktop.
Save kousen/f653fe1e040827aed4e894ee86643300 to your computer and use it in GitHub Desktop.
Jumble solver in Groovy
import groovy.transform.CompileStatic
@CompileStatic
class Jumble {
// dictionary words avail on Mac (or any Un*x system based on BSD)
private List wordList =
new File('/usr/share/dict/words').readLines()
.findAll { it.size() == 5 || it.size() == 6 }
String solve(String clue) {
List<String> letters = clue.split('').toList()
letters.permutations()
.collect { it.join('') }
.find { wordList.contains(it) }
}
}
@CompileStatic
class Jumble2 {
private Map<String, List<String>> wordMap =
new File('/usr/share/dict/words').readLines()
.findAll {it.size() == 5 || it.size() == 6 }
.groupBy { it.toList().sort().join('') }
String solve(String clue) {
def key = clue.toList().sort().join('')
wordMap[key].head()
}
}
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class JumbleJ {
private final Map<String, List<String>> wordMap;
public JumbleJ() {
try {
wordMap = Files.lines(Paths.get("src/main/resources/dict/words"))
.filter(word -> word.length() == 5 || word.length() == 6)
.collect(Collectors.groupingBy(this::word2key));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private String word2key(String word) {
return Arrays.stream(word.split(""))
.sorted()
.collect(Collectors.joining());
}
public String solve(String clue) {
return wordMap.getOrDefault(word2key(clue),
Collections.singletonList("")).get(0);
}
public List<String> parallelSolve(String... clues) {
return Arrays.stream(clues)
.parallel()
.map(this::solve)
.collect(Collectors.toList());
}
}
import spock.lang.Specification
import spock.lang.Unroll
class JumbleSpec extends Specification {
@Unroll
void "unscramble #scrambled to get #word"() {
given:
Jumble jumble = new Jumble()
expect:
jumble.solve(scrambled) == word
where:
scrambled || word
'cautla' || 'actual'
'agileo' || 'goalie'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment