Created
December 2, 2016 00:25
-
-
Save cmacaulay/14ec415d84146bde219e403586977c52 to your computer and use it in GitHub Desktop.
Credit Check - Casey Macaulay
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
card_number = "4929735477250543" | |
valid = false | |
# Your Luhn Algorithm Here | |
# From the right most digit [1] moving left, double the value of | |
# every second digit. | |
card_reverse = card_number.reverse | |
card_array = card_reverse.chars | |
doubled_odds = card_array.map.with_index do |number, index| | |
if index.odd? | |
(number.to_i) * 2 | |
else | |
number.to_i | |
end | |
end | |
# If the product of this doubling operation is greater than 9 | |
# then sum the digits of the products | |
def sum_integers(number_to_integer) | |
number_to_integer.map do |digit| | |
digit.to_i | |
end.reduce(:+) | |
end | |
sum_products = doubled_odds.map do |number| | |
if number > 9 | |
sum_integers(number.to_s.chars) | |
else | |
number | |
end | |
end | |
### Take the sum of all digits | |
final_sum = sum_products.reduce(:+) | |
# # Output | |
if final_sum % 10 == 0 | |
## If it is valid, print "The number is valid!" | |
puts "Can you believe it?! The number is valid!" | |
true | |
else | |
## If it is invalid, print "The number is invalid!" | |
puts "Whomp, the number is invalid" | |
false | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment