Skip to content

Instantly share code, notes, and snippets.

@iaintshine
Created August 13, 2014 18:33
Show Gist options
  • Save iaintshine/5f6686ac882a0e611ed4 to your computer and use it in GitHub Desktop.
Save iaintshine/5f6686ac882a0e611ed4 to your computer and use it in GitHub Desktop.
A Ruby program which checks if two strings are anagrams of each other using two methods: sorting and frequency counting
#!/usr/bin/env ruby
# anagram.rb
module Anagram
ASCII_COUNT = 256
def sort
self.chars.sort.join
end
# worst case O(n^2)
def anagram?(other)
return false if self.length != other.length
self.sort == other.sort
end
# O(n)
def anagram2?(other)
return false if self.length != other.length
histogram = Array.new ASCII_COUNT, 0
self.length.times do |i|
histogram[[i].ord] += 1
histogram[other[i].ord] -= 1
end
histogram.any? { |count| count != 0 }
end
end
class String
include Anagram
end
if __FILE__ == $0
filename = ARGV[0]
lines = IO.readlines(filename).map &:chomp
puts %Q{Sorting: "#{lines[0]}" and "#{lines[1]}" are #{ lines[0].anagram?(lines[1]) ? '' : 'not' } anagrams}
puts %Q{Histogram: "#{lines[0]}" and "#{lines[1]}" are #{ lines[0].anagram?(lines[1]) ? '' : 'not' } anagrams}
end
ipod lover
poor devil
ruby anagram.rb anagrams.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment