Permalink
Browse files

Remove Strands, make Strand 'Hammable'

Strands didn't really give me anything beyond a way to manipulate two
Strand objects. It seemed unecessary if I could have a Strand know how
to do the maniuplation. Like, if I want to add 1 + 2, I don't have an
Integers object that does the math, the Integer object knows how to do
it.

So Strands is gone and there's a new, badly-named Hammable module that
Strand includes. It defines the - method so that I can get the
difference between two Hammable objects.

This makes everything easier to follow, I think.

The - method has a terrible implementation. That's certainly something
to improve. And I could use delegation in Strand for the array methods.
  • Loading branch information...
Ian Whitney
Ian Whitney committed May 26, 2014
1 parent 5db4924 commit abdc637793a6e9f08daa81e4abed644572413fe8
Showing with 10 additions and 33 deletions.
  1. +10 −33 ruby/hamming/hamming.rb
View
@@ -1,57 +1,34 @@
class Hamming
def self.compute(a,b)
Strands.difference(
Strand.parse(a),
Strand.parse(b)
).count
(Strand.parse(a) - Strand.parse(b)).count
end
end
class Strands
def self.difference(*strands)
self.new(strands).difference
end
def initialize(strands)
self.collection = strands
end
def difference
combined.select {|strand_set| strand_set.first != strand_set.last}
end
private
attr_accessor :collection
def combined
sorted[0].zip(sorted[1])
end
def sorted
@sorted ||= collection.sort_by { |strand| strand.length }
module Hammable
def -(other)
sorted = [self,other].sort_by { |x| x.count }
combined = sorted.first.zip(sorted.last)
x = combined.select {|strand_set| strand_set.first != strand_set.last}
self.class.new(x)
end
end
class Strand
include Enumerable
include Hammable
def self.parse(strand_string)
self.new(strand_string.split(//))
end
def initialize(strand_string)
self.collection = Array(strand_string)
def initialize(strand_array)
self.collection = Array(strand_array)
end
def each(&block)
collection.each(&block)
end
def length
collection.count
end
private
attr_accessor :collection

0 comments on commit abdc637

Please sign in to comment.