Skip to content

Instantly share code, notes, and snippets.

@DNA

DNA/cpf.rb

Created Mar 9, 2017
Embed
What would you like to do?
Generate random valid CPFs
#! /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