# CSE341, Spring 2008, Homework 6 provided code # Put your solutions to problems 1--4 here # A few tests for the trees, not necessarily meant to cover everything def test_tree t1 = Leaf.new "hi" t1a = Leaf.new "there" t2 = NaryNode.new([t1a, (Leaf.new "world")]) t3 = BinaryNode.new(t1,t2) puts t3.concatAll puts t3.firstAlphabetical t3.iterate(lambda { |s| puts s }) puts (BinaryNode.concatAll t3) puts "======" # below here works only after problem 3 t1 = "hi" t1a = "there" t2 = NaryNode.new([t1a, ("world")]) t3 = BinaryNode.new(t1,t2) puts t3.concatAll puts t3.firstAlphabetical end # The rest of the file is for problem 5 class LetterCount attr_reader :hash protected :hash def initialize arg if arg.is_a? String @hash = str_to_count arg elsif arg.is_a? Hash @hash = arg else raise "bad argument" end end def difference other ans = @hash.clone other.hash.each { |letter, value| if value > ans[letter] return nil else ans[letter] -= value end } LetterCount.new ans end def all_zeros @hash.each { |letter,value| if value != 0 : return false end } true end private def str_to_count s h = Hash.new 0 s.split("").each { |c| h[c] += 1 } h end end def anagrams(word,filename) lc = LetterCount.new word file = File.new(filename, "r") file.each_line { |w| w = w.chop wlc = LetterCount.new w d = lc.difference wlc if d && d.all_zeros then puts w end } file.close end