Skip to content

Instantly share code, notes, and snippets.

@danielCarlosCE
Created August 2, 2017 14:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielCarlosCE/554c43f6dac93b9dfd7fdaba140cde4c to your computer and use it in GitHub Desktop.
Save danielCarlosCE/554c43f6dac93b9dfd7fdaba140cde4c to your computer and use it in GitHub Desktop.
import Foundation
/// 9 radom numbers followed by two verifying digits
var randomValidCpf: String {
var cpf = (1...11).map { _ in Int(arc4random_uniform(9)) }
cpf[9] = calcVerifyingDigit(originalValue: cpf, weights: (2...10).map{$0}.reversed())
cpf[10] = calcVerifyingDigit(originalValue: cpf, weights: (2...11).map{$0}.reversed())
return (cpf.map { "\($0)" }).joined(separator:"")
}
/// 1 - Multiply each weight from weights array by a value from originalValue array with the same index
/// 2 - Sums up all the results from previous step
/// 3 - Remainder from the sum divided by 11
/// 4 - If Remainder is less than 2 then digit will be 0, else digit will be (11 - Remainder)
private func calcVerifyingDigit(originalValue: [Int], weights: [Int]) -> Int {
let valuesWeighted = weights.enumerated().map { i, w in originalValue[i] * w }
let weightedSum = valuesWeighted.reduce(0, +)
let rest = weightedSum % 11
return (rest < 2) ? 0 : (11 - rest)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment