module PersonPin # Simple random CNP generator for romanian sitizens class Cnp def self.valid?(cnp) (cnp.length == 13) && (calculate_check_sum(cnp[0..11]) == cnp[12].to_i) end def self.random gender = rand(1..2) year = rand(1800..(Time.now.year - 18)) month = rand(1..12) day = rand(1..28) county_code = rand(1..52) daily(gender, year, month, day, county_code)[rand(0..999)] end def self.daily(gender, year, month, day, county_code) gender_s = gender.to_s year_s = (year % 100).to_s.rjust(2, '0') month_s = month.to_s.rjust(2, '0') day_s = day.to_s.rjust(2, '0') county_code_s = (county_code % 100).to_s.rjust(2, '0') base = gender_s + year_s + month_s + day_s + county_code_s results = [] 1000.times do |sequence| cnp = base + sequence.to_s.rjust(3, '0') cnp[12] = calculate_check_sum(cnp).to_s results << cnp end results end def self.calculate_check_sum(cnp) weights = [2, 7, 9, 1, 4, 6, 3, 5, 8, 2, 7, 9] sum = 0 cnp.split('').each_with_index do |digit, index| sum += digit.to_i * weights[index] end control_digit = sum % 11 control_digit == 10 ? 1 : control_digit end end end