1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
| require 'benchmark'
LOCATION_CODE = {
'A' => [1, 0], 'B' => [1, 1], 'C' => [1, 2], 'D' => [1, 3], 'E' => [1, 4], 'F' => [1, 5], 'G' => [1, 6], 'H' => [1, 7], 'I' => [3, 4],
'J' => [1, 8], 'K' => [1, 9], 'L' => [2, 0], 'M' => [2, 1], 'N' => [2, 2], 'O' => [3, 5], 'P' => [2, 3], 'Q' => [2, 4], 'R' => [2, 5],
'S' => [2, 6], 'T' => [2, 7], 'U' => [2, 8], 'V' => [2, 9], 'W' => [3, 2], 'X' => [3, 0], 'Y' => [3, 1], 'Z' => [3, 3]
}
MULTIPLIER = [1, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1]
def id_card_validate(id)
return false unless id =~ /\A[A-Z](1|2)\d{8}\z/
chars = id.chars
numbers = LOCATION_CODE[chars.shift] + chars.map(&:to_i)
sum = numbers.zip(MULTIPLIER).map{ |a, b| a * b }.reduce(:+)
# sum, i = 0, 0
# while i <= 10
# sum += numbers[i] * MULTIPLIER[i]
# i += 1
# end
(sum % 10).zero?
end
n = 100000
Benchmark.bmbm do |x|
x.report('leonji'){ n.times{ id_card_validate('A123456789') } }
end
# Rehearsal ------------------------------------------
# leonji 0.770000 0.010000 0.780000 ( 0.796012)
# --------------------------------- total: 0.780000sec
# user system total real
# leonji 0.770000 0.000000 0.770000 ( 0.792737)
|