Last active
December 2, 2016 05:30
-
-
Save mariastenquist/75d9698b3425e8c728735609255ea316 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
num = gets.chomp | |
splits = num.split(//) | |
card_number = [] | |
card_number << splits[-2] | |
card_number << splits[-4] | |
card_number << splits[-6] | |
card_number << splits[-8] | |
card_number << splits[-10] | |
card_number << splits[-12] | |
card_number << splits[-14] | |
card_number << splits[-16] | |
card_number.reverse! | |
doubles = card_number.map do |num| | |
num.to_i*2 | |
end | |
doubled_digits = doubles.map do |num| | |
if num > 9 | |
num - 9 | |
else num < 9 | |
num | |
end | |
end | |
undoubled = [] | |
undoubled << splits[-1] | |
undoubled << splits[-3] | |
undoubled << splits[-5] | |
undoubled << splits[-7] | |
undoubled << splits[-9] | |
undoubled << splits[-11] | |
undoubled << splits[-13] | |
undoubled << splits[-15] | |
undoubled.reverse! | |
untouched_digits = undoubled | |
remainder_digits = untouched_digits.map do |num| | |
num.to_i | |
end | |
sum_1 = remainder_digits.reduce(:+) | |
sum_2 = doubled_digits.reduce(:+) | |
summed_digits = sum_1 + sum_2 | |
if summed_digits % 10 == 0 | |
puts "This number is valid" | |
else | |
puts "This number is not valid" | |
end | |
# Valid: 5541808923795240, 4024007136512380, 6011797668867828 Ran these numbers, and they are valid | |
# Invalid: 5541801923795240, 4024007106512380, 6011797668868728 Ran these, and they are invalid | |
# Tested a credit card and it was valid! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment