class Cdigits::Luhn::RandomTable

Attributes

previsous[RW]

Public Class Methods

new(modulus:) click to toggle source
# File lib/cdigits/luhn/random_table.rb, line 8
def initialize(modulus:)
  @modulus = modulus
  @previsous = nil
end

Public Instance Methods

pick(exclude: []) click to toggle source

pick from number table @param exclude [Array<Intger>] exclude numbers @return [Integer]

# File lib/cdigits/luhn/random_table.rb, line 22
def pick(exclude: [])
  table(exclude).sample
end
pick_non_zero() click to toggle source

pick from number table exclude 0 @return [Integer]

# File lib/cdigits/luhn/random_table.rb, line 15
def pick_non_zero
  pick(exclude: [0])
end

Private Instance Methods

build_next_numbers_to_avoid() click to toggle source
# File lib/cdigits/luhn/random_table.rb, line 47
def build_next_numbers_to_avoid
  defaults = { 0 => max, max => 0 }
  return defaults unless occure_twin_error?

  defaults.merge(twin_error_values)
end
max() click to toggle source
# File lib/cdigits/luhn/random_table.rb, line 32
def max
  @modulus - 1
end
next_numbers_to_avoid() click to toggle source
# File lib/cdigits/luhn/random_table.rb, line 43
def next_numbers_to_avoid
  @next_numbers_to_avoid ||= build_next_numbers_to_avoid
end
numbers() click to toggle source
# File lib/cdigits/luhn/random_table.rb, line 28
def numbers
  @numbers ||= (0..max).to_a.freeze
end
occure_twin_error?() click to toggle source
# File lib/cdigits/luhn/random_table.rb, line 80
def occure_twin_error?
  (max % 3).zero?
end
table(exclude) click to toggle source

@return [Array<Integer>]

# File lib/cdigits/luhn/random_table.rb, line 37
def table(exclude)
  exclude << next_numbers_to_avoid[@previsous]
  table = numbers - exclude.compact
  table.empty? ? numbers : table
end
twin_error_values() click to toggle source

@note

modulus = 10
twin | doubled value
---- | -------------
00 | 0
11 | 3
22 | 6
33 | 9
44 | 12
55 | 6
66 | 9
77 | 12
88 | 15
99 | 18

@example

# when @modulus = 10
twin_error_values # => { 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 7 }

@return [Hash]

# File lib/cdigits/luhn/random_table.rb, line 72
def twin_error_values
  size = (max / 3).to_i
  start = (@modulus / 2.0).ceil - size
  stop = start + size * 2 - 1
  values = (start..stop).to_a
  values.zip(values).to_h
end