Skip to content

Instantly share code, notes, and snippets.

@DNA
Created March 9, 2017 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DNA/a6844f1b05fafced12b6c93544099e8e to your computer and use it in GitHub Desktop.
Save DNA/a6844f1b05fafced12b6c93544099e8e to your computer and use it in GitHub Desktop.
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