Skip to content

Commit

Permalink
small refactoring of luhn mask method. free memory on digits list
Browse files Browse the repository at this point in the history
  • Loading branch information
gfmurphy authored and George F Murphy committed Nov 21, 2011
1 parent 31910ea commit 2b4d922
Showing 1 changed file with 14 additions and 27 deletions.
41 changes: 14 additions & 27 deletions luhnybin.rb
Original file line number Diff line number Diff line change
@@ -1,20 +1,5 @@
#!/usr/bin/env ruby
require 'set'
require 'forwardable'
class Mask
extend Forwardable
def_delegators :@set, :include?, :empty?

def initialize(range=nil)
@set = Set.new
self << range
end

def <<(range)
range.to_a.each { |n| @set << n }
end
end

class Luhnybin
RANGE = (14..16)
SUMMED_DOUBLES = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9].freeze
Expand All @@ -29,7 +14,7 @@ def text
end

private
def filter(start=0, index=0, digits=[], mask=Mask.new)
def filter(start=0, index=0, digits=[], mask=Set.new)
return mask if index == @text.length

char = @text[index]
Expand All @@ -41,9 +26,11 @@ def filter(start=0, index=0, digits=[], mask=Mask.new)
start += 1 if digits.length > RANGE.max
elsif !separator?(char)
start = index
digits.clear
end

mask = filter(start, index + 1, digits, luhn_mask(start, index, digits, mask))
mask = filter(start, index + 1, digits,
luhn_mask(start, index, digits, mask))
@text[index] = char('X') if mask.include?(index) && digit
return mask
end
Expand All @@ -53,17 +40,17 @@ def luhn_mask(start, index, digits, mask)
length = digits.length
return mask if length < RANGE.min

length.downto(RANGE.min) do |n|
i = -1
sum = digits.inject(0) do |tot, d|
i += 1
tot += i.odd? ? SUMMED_DOUBLES[d] : d
end
i = -1
sum = digits.reduce(0) do |tot, d|
i += 1
tot += i.odd? ? SUMMED_DOUBLES[d] : d
end

if sum % 10 == 0
mask << (start..index)
return mask
end
if sum % 10 == 0
index.downto(start) { |i| mask << i }
return mask
else
luhn_mask(start, index, digits[0, length - 1], mask)
end

return mask
Expand Down

0 comments on commit 2b4d922

Please sign in to comment.