Created
September 19, 2012 10:14
-
-
Save Frost/3748841 to your computer and use it in GitHub Desktop.
Implementation of CodeKata#6 http://codekata.pragprog.com/2007/01/kata_six_anagra.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Anagrams | |
def self.process(word_list) | |
word_list.group_by {|word| word.strip.downcase.chars.sort.join }. | |
values.map {|v| v.map(&:strip).join(" ")} | |
end | |
end | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'minitest/spec' | |
require 'minitest/autorun' | |
require 'minitest/pride' | |
require 'anagrams' | |
describe Anagrams do | |
it "finds a simple anagram" do | |
words = %w[ink kin] | |
output = Anagrams.process(words) | |
output.count.must_equal 1 | |
output.must_equal ["ink kin"] | |
end | |
it "groups anagrams on separate lines" do | |
words = %w[arrest foo ink kin rarest] | |
output = Anagrams.process(words) | |
output.count.must_equal 3 | |
output.must_equal ["arrest rarest", "foo","ink kin"] | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require_relative 'anagrams.rb' | |
USAGE = "run_anagrams.rb <wordlist> | |
Will output a list of all words in the wordlist, with anagrams on the same line. | |
I used http://spacebar.org/ifcd/wordlist.txt as a sample wordlist. | |
Example: | |
Given this input file: | |
foo | |
ink | |
kin | |
The output will be: | |
$ ./anagrams.rb input_file.txt | |
foo | |
ink kin | |
" | |
unless ARGV.length > 0 | |
$stderr.puts USAGE | |
exit 1 | |
end | |
puts Anagrams.process(IO.readlines(ARGV[0])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment