Skip to content

Instantly share code, notes, and snippets.

@rogerluan
Last active December 27, 2022 20:18
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 rogerluan/4505f4db122b2bea547efd2187fadfa5 to your computer and use it in GitHub Desktop.
Save rogerluan/4505f4db122b2bea547efd2187fadfa5 to your computer and use it in GitHub Desktop.
Calculates the digits of a CPF, given the first 9 digits of it.
# Usage: `ruby calculate_cpf_digits.rb "123456789"`
cpf = ARGV[0]
cpf_array = cpf.split("").map(&:to_i)
def calculate_digit(base_array:)
# Constants
divisor = 11 # Constant, fixed number
weighted_array = [10, 9, 8, 7, 6, 5, 4, 3, 2] # Digits, starts with 10 and decrements by 1
# Algorithm
weighted_sum = 0
(0...9).each do |index|
weighted_sum += base_array[index] * weighted_array[index]
end
remainder = weighted_sum % divisor
case remainder
when 0, 1
0
else
divisor - remainder
end
end
def calculate_first_digit(cpf_array:)
calculate_digit(base_array: cpf_array)
end
def calculate_second_digit(cpf_array:, first_digit:)
second_digit_array = cpf_array.drop(1) + [first_digit]
calculate_digit(base_array: second_digit_array)
end
first_digit = calculate_first_digit(cpf_array: cpf_array)
second_digit = calculate_second_digit(cpf_array: cpf_array, first_digit: first_digit)
puts("CPF: #{cpf}-#{first_digit}#{second_digit}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment