Skip to content

Instantly share code, notes, and snippets.

@oofnivek
Last active August 23, 2022 14:25
Show Gist options
  • Save oofnivek/0b57ce35eccc6dc0ae212932a05dabb5 to your computer and use it in GitHub Desktop.
Save oofnivek/0b57ce35eccc6dc0ae212932a05dabb5 to your computer and use it in GitHub Desktop.
Luhn algorithm
def random(n)
s = ''
for i in 0..n-1
s += rand(0..9).to_s
end
return s
end
def get_digit(s, i)
output = 0
if(i%2==0) # if we start from position 0, every even number will be multiplied by 2
output = s[i].to_i*2
else # if we start from position 0, every odd number will stay the same
output = s[i].to_i
end
if(output > 9)
# if the outcome of the multiplication greater than 9
# split the number and add them together
output = output.to_s[0].to_i + output.to_s[1].to_i
end
return output
end
def get_checksum(s)
a = Array.new
for i in 0..s.length-1
a.push(get_digit(s, i))
end
total = 0
for i in 0..s.length-1
# calculate the sum of all the numbers
total += a[i]
end
# divide the total by 10 and gets the remainder
remainder = total % 10
output = 0
if(remainder>0) # if the remainder is greater than 0 then take 10 and minus the remainder
output = 10 - remainder
end
return output
end
def get_visa
# fifteen = '%s%s' % [4, str_random(14)]
fifteen = '499233836191683'
return '%s%s' % [fifteen, get_checksum(fifteen)]
end
puts get_visa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment