Skip to content

Instantly share code, notes, and snippets.

@sagaya
Created May 15, 2017 23:39
Show Gist options
  • Save sagaya/1d1be4c7afbca2f681bb2a7d9cb2c882 to your computer and use it in GitHub Desktop.
Save sagaya/1d1be4c7afbca2f681bb2a7d9cb2c882 to your computer and use it in GitHub Desktop.
Luhn Algorithm for generating random valid credit card numbers with swift
var card_number = ""
func make_random_number(num:Int)->[Int]{
var result = [Int]()
for _ in 0...num {
result.append(Int(arc4random_uniform(9)))
}
return result
}
func luhn_algorithm(){
var random_master_int = make_random_number(num: 12)
//Add random master card numbers here [51,52,53,54]
random_master_int.insert(5, at: 0)
random_master_int.insert(4, at: 1)
print(random_master_int)
for (index,element) in random_master_int.enumerated(){
if index % 2 != 0 {
var r = random_master_int[index] * 2
var characters = String(r).characters.flatMap{Int(String($0))}
var sum = characters.reduce(0, +)
print(sum)
}
}
var sum = random_master_int.reduce(0, +) * 9
random_master_int.append(sum % 10)
var random_master_string = random_master_int.map {String($0)}
random_master_string
var first4 = "\(random_master_string[0...3].flatMap({$0}).joined())"
var second4 = "\(random_master_string[4...7].flatMap({$0}).joined())"
var third4 = "\(random_master_string[8...11].flatMap({$0}).joined())"
var fourth4 = "\(random_master_string[12...15].flatMap({$0}).joined())"
card_number.append(first4)
card_number.append(second4)
card_number.append(third4)
card_number.append(fourth4)
print(card_number)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment