Exercism v3 launches on Sept 1st 2021. Learn more! ðŸš€ðŸš€ðŸš€

Published at Jul 13 2018
·
0 comments

Instructions

Test suite

Solution

Given a number determine whether or not it is valid per the Luhn formula.

The Luhn algorithm is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers and Canadian Social Insurance Numbers.

The task is to check if a given string is valid.

Strings of length 1 or less are not valid. Spaces are allowed in the input, but they should be stripped before checking. All other non-digit characters are disallowed.

```
4539 1488 0343 6467
```

The first step of the Luhn algorithm is to double every second digit, starting from the right. We will be doubling

```
4_3_ 1_8_ 0_4_ 6_6_
```

If doubling the number results in a number greater than 9 then subtract 9 from the product. The results of our doubling:

```
8569 2478 0383 3437
```

Then sum all of the digits:

```
8+5+6+9+2+4+7+8+0+3+8+3+3+4+3+7 = 80
```

If the sum is evenly divisible by 10, then the number is valid. This number is valid!

```
8273 1232 7352 0569
```

Double the second digits, starting from the right

```
7253 2262 5312 0539
```

Sum the digits

```
7+2+5+3+2+2+6+2+5+3+1+2+0+5+3+9 = 57
```

57 is not evenly divisible by 10, so this number is not valid.

For installation and learning resources, refer to the exercism help page.

For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:

```
gem install minitest
```

If you would like color output, you can `require 'minitest/pride'`

in
the test file, or note the alternative instruction, below, for running
the test file.

Run the tests from the exercise directory using the following command:

```
ruby luhn_test.rb
```

To include color from the command line:

```
ruby -r minitest/pride luhn_test.rb
```

The Luhn Algorithm on Wikipedia http://en.wikipedia.org/wiki/Luhn_algorithm

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

```
require 'minitest/autorun'
require_relative 'luhn'
# Common test data version: 1.0.0 c826372
class LuhnTest < Minitest::Test
def test_single_digit_strings_can_not_be_valid
# skip
refute Luhn.valid?("1")
end
def test_a_single_zero_is_invalid
skip
refute Luhn.valid?("0")
end
def test_a_simple_valid_sin_that_remains_valid_if_reversed
skip
assert Luhn.valid?("059")
end
def test_a_simple_valid_sin_that_becomes_invalid_if_reversed
skip
assert Luhn.valid?("59")
end
def test_a_valid_canadian_sin
skip
assert Luhn.valid?("055 444 285")
end
def test_invalid_canadian_sin
skip
refute Luhn.valid?("055 444 286")
end
def test_invalid_credit_card
skip
refute Luhn.valid?("8273 1232 7352 0569")
end
def test_valid_strings_with_a_non_digit_included_become_invalid
skip
refute Luhn.valid?("055a 444 285")
end
def test_valid_strings_with_punctuation_included_become_invalid
skip
refute Luhn.valid?("055-444-285")
end
def test_valid_strings_with_symbols_included_become_invalid
skip
refute Luhn.valid?("055Â£ 444$ 285")
end
def test_single_zero_with_space_is_invalid
skip
refute Luhn.valid?(" 0")
end
def test_more_than_a_single_zero_is_valid
skip
assert Luhn.valid?("0000 0")
end
def test_input_digit_9_is_correctly_converted_to_output_digit_9
skip
assert Luhn.valid?("091")
end
# Problems in exercism evolve over time, as we find better ways to ask
# questions.
# The version number refers to the version of the problem you solved,
# not your solution.
#
# Define a constant named VERSION inside of the top level BookKeeping
# module, which may be placed near the end of your file.
#
# In your file, it will look like this:
#
# module BookKeeping
# VERSION = 1 # Where the version number matches the one in the test.
# end
#
# If you are curious, read more about constants on RubyDoc:
# http://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/constants.html
def test_bookkeeping
skip
assert_equal 1, BookKeeping::VERSION
end
end
```

```
# Luhn
class Luhn
attr_reader :num
def initialize(num)
@num = num
end
def addends
num.to_s.chars.map(&:to_i) # digits
.reverse
.map.with_index { |digit, index| addend(digit, index) }
.reverse
end
def addend(digit, index)
subtract_nine(double_every_other(digit, index))
end
def checksum
addends.inject(:+)
end
def valid?
checksum % 10 == 0
end
def self.create(num)
(0..9).each do |i|
return "#{num}#{i}".to_i if Luhn.new("#{num}#{i}".to_i).valid?
end
end
private
def double_every_other(digit, index)
index.odd? ? digit * 2 : digit
end
def subtract_nine(digit)
digit > 9 ? digit - 9 : digit
end
end
```

A huge amount can be learned from reading other peopleâ€™s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

- What compromises have been made?
- Are there new concepts here that you could read more about to improve your understanding?

Level up your programming skills with 3,450 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments