Permalink
Browse files

Basic generator working - simple sets of passing strings

  • Loading branch information...
1 parent 979299c commit ee2ebcce7a22a8bce08637817762ab8a06a56272 @rorymckinley rorymckinley committed Jul 18, 2010
Showing with 25 additions and 19 deletions.
  1. +24 −8 lib/luhnacy.rb
  2. +1 −11 spec/luhnacy_spec.rb
View
@@ -1,5 +1,28 @@
class Luhnacy
def self.valid?(candidate)
+ calc_modulus(candidate) == 0
+ end
+
+ def self.generate(string_size)
+ output = ''
+ (string_size-1).times do |n|
+ output += rand(10).to_s
+ end
+ output += '0'
+
+ unless calc_modulus(output) == 0
+ output = output[0...-1] + (10 - calc_modulus(output)).to_s
+ end
+
+ output
+ end
+
+ private
+ def self.double_and_fix(number)
+ 2 * number > 9 ? ( (2 * number) % 10 + 1 ) : 2 * number
+ end
+
+ def self.calc_modulus(candidate)
working = candidate.reverse
double_up = false;
sum = 0
@@ -9,14 +32,7 @@ def self.valid?(candidate)
sum += double_up ? double_and_fix(num) : num
double_up = !double_up
end
- sum % 10 == 0
- end
- def self.generate(string_size)
- return "11111"
- end
- private
- def self.double_and_fix(number)
- 2 * number > 9 ? ( (2 * number) % 10 + 1 ) : 2 * number
+ sum % 10
end
end
View
@@ -1,15 +1,6 @@
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "Luhnacy" do
- def luhn?(string)
- working = string.reverse
- double_up = false;
- sum = 0
-
- working.each_char do |ch|
-
- end
- end
it "should be able to identify if a number satisfies Luhn" do
valid_number = '49927398716'
Luhnacy.valid?(valid_number).should be_true
@@ -21,10 +12,9 @@ def luhn?(string)
end
it "should return a string of digits that satisfies Luhn" do
- pending
string_size = 5
candidate = Luhnacy.generate(string_size)
candidate.should match /^\d{#{string_size}}$/
- luhn?(candidate).should be_true
+ Luhnacy.valid?(candidate).should be_true
end
end

0 comments on commit ee2ebcc

Please sign in to comment.