Last active
December 27, 2022 20:18
-
-
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.
This file contains hidden or 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
# 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