Created
January 7, 2020 17:41
-
-
Save ayinlaaji/8fbd35ca4033712b38b34c4b34b16e7e to your computer and use it in GitHub Desktop.
Validating credit card numbers
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
package main | |
import ( | |
"fmt" | |
"strconv" | |
) | |
func luhnCheck(cardNo int) bool { | |
toStr := strconv.Itoa(cardNo) | |
var cardDigits []int | |
for i := range toStr { | |
x, _ := strconv.Atoi(string(toStr[i])) | |
cardDigits = append(cardDigits, x) | |
} | |
cardLen := len(cardDigits) | |
var reversedDigits []int | |
l := cardLen - 1 | |
for i := l; i > -1; i-- { | |
reversedDigits = append(reversedDigits, cardDigits[i]) | |
} | |
var oddParity int | |
var evenParity int | |
for i := range reversedDigits { | |
if (i+1)%2 > 0 { | |
oddParity += reversedDigits[i] | |
} else { | |
m := reversedDigits[i] * 2 | |
if m > 9 { | |
t := strconv.Itoa(m) | |
g := 0 | |
for i := range t { | |
x, _ := strconv.Atoi(string(t[i])) | |
g += x | |
} | |
evenParity += g | |
} else { | |
evenParity += m | |
} | |
} | |
} | |
total := oddParity + evenParity | |
return total%10 == 0 | |
} | |
func main() { | |
start := "517214" | |
end := "7805" | |
maxNo := 9997 | |
total := 0 | |
cardNos := []int{} | |
for i := 0; i <= maxNo; i++ { | |
//todo bug padd numbers less that 10 | |
sC := start + strconv.Itoa(i) + end | |
cardNo, _ := strconv.Atoi(sC) | |
isValid := luhnCheck(cardNo) | |
if isValid { | |
cardNos = append(cardNos, cardNo) | |
total += 1 | |
} | |
} | |
fmt.Println(cardNos, total) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment