Created
August 13, 2014 18:33
-
-
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
This file contains hidden or 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 | |
# 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 | |
This file contains hidden or 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
ipod lover | |
poor devil |
This file contains hidden or 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
ruby anagram.rb anagrams.txt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment