Skip to content

Instantly share code, notes, and snippets.

@Frost
Created September 19, 2012 10:14
Show Gist options
  • Save Frost/3748841 to your computer and use it in GitHub Desktop.
Save Frost/3748841 to your computer and use it in GitHub Desktop.
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
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
#!/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