thraxil.org:

Reply to: A Simple Programming Puzzle Seen Through Three Different Lenses

I’d like to contribute a ruby solution. While the logic of using a “seen” hash is re-used, this is fairly concise due to the ruby libraries’ tendency to allow cascading calls, and the flexibility of specifying the default not-found-key-handler of the Hash object:


#!/usr/bin/ruby

states = %w(alabama alaska arizona arkansas california colorado connecticut delaware florida georgia hawaii idaho illinois indiana iowa kansas kentucky louisiana maine maryland massachusetts michigan minnesota mississippi missouri montana nebraska nevada newhampshire newjersey newmexico newyork northcarolina northdakota ohio oklahoma oregon pennsylvania rhodeisland southcarolina southdakota tennessee texas utah vermont virginia washington westvirginia wisconsin wyoming)

seen = Hash.new {|hash,key| hash[key] = []}

states.each do |s1|
states.reject{|s2| s2 < s1}.each do |s2| sorted = (s1 + s2).split(//).sort.join
seen[sorted] << [s1,s2] p seen[sorted] if seen[sorted].length > 1
end
end


formatting is with Textile syntax. Comments are not displayed until they are approved by a moderator. Moderators will not approve unless the comment contributes value to the discussion.

namerequired
emailrequired
url
remember info?