Skip to content

Instantly share code, notes, and snippets.

@dizzi
Created March 17, 2011 18:45
Show Gist options
  • Save dizzi/874887 to your computer and use it in GitHub Desktop.
Save dizzi/874887 to your computer and use it in GitHub Desktop.
kred...
card = "446157xxxxxx3246"
firstx = card.indexOf('x')
lastx = card.lastIndexOf('x')
firstnum = card[0..firstx-1]
lastnum = card[lastx+1..-1]
xlen = lastx-firstx+1
def luhn(cardNum){
total = 0
cardNum.eachWithIndex(){num, i ->
if(i%2==0) {
((num.toInteger()*2).toString().each(){snum -> total += snum.toInteger()})
} else {
total += num.toInteger()
}
}
if(total%10==0)return 0
else return 10 - (total%10)
}
grandtotal = 0
limit = (10**xlen)-1
for (x in 0..limit){
candidate = firstnum+String.format("%0${xlen}d", x)+lastnum
if (luhn(candidate[0..-2]).toString()==candidate[-1]){
grandtotal++
//println candidate
}
}
println "Cards found: "+grandtotal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment