Created
August 2, 2017 14:29
-
-
Save danielCarlosCE/554c43f6dac93b9dfd7fdaba140cde4c to your computer and use it in GitHub Desktop.
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
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