Created
March 9, 2017 17:08
-
-
Save DNA/a6844f1b05fafced12b6c93544099e8e to your computer and use it in GitHub Desktop.
Generate random valid CPFs
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
#! /usr/bin/env ruby | |
# Setup initial variables | |
number = Random.new | |
cpf = [] | |
vd1 = 0 | |
vd2 = 0 | |
# Generate the 9 first numbers | |
1.upto(9) do |i| | |
n = number.rand(0..9) | |
cpf << n | |
# start calculating the Verification Digits (VD) | |
vd1 += n * (11 - i) | |
vd2 += n * (12 - i) | |
end | |
# Calculate the first VD | |
vd1 = vd1 % 11 | |
vd1 = vd1 < 2 ? 0 : 11 - vd1 | |
# Add first VD to second VD | |
vd2 += vd1 * 2 | |
# Calculate second VD | |
vd2 = vd2 % 11 | |
vd2 = vd2 < 2 ? 0 : 11 - vd2 | |
# Add VDs to CPF | |
cpf << vd1 | |
cpf << vd2 | |
# Print the new cpf | |
puts cpf.join |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment