Class: Bijective::Instance

Inherits:
Object
  • Object
show all
Defined in:
lib/bijective.rb

Instance Method Summary collapse

Constructor Details

#initialize(sequence) ⇒ Instance

Constructor initialises instance variables @sequence and @base.

Parameters:

  • sequence (String)

    set instance object variable @sequence

Raises:



12
13
14
15
16
17
18
19
20
21
# File 'lib/bijective.rb', line 12

def initialize sequence
  dublicate = sequence.split(//).uniq.join

  if dublicate.length != sequence.length
    raise(InitializationError, 'Sequence string must contain only unique charaters.')
  end

  @sequence = sequence
  @base = @sequence.length
end

Instance Method Details

#decode(s) ⇒ Integer

Decodes the given string

Parameters:

  • s (String)

    the string to decode

Returns:

  • (Integer)

    the decoded integer



41
42
43
44
45
# File 'lib/bijective.rb', line 41

def decode s
  i = 0
  s.each_char { |c| i = i * @base + @sequence.index(c) }
  i
end

#encode(i) ⇒ String

Encodes the given integer

Parameters:

  • i (Integer)

    the integer to encode

Returns:

  • (String)

    the encoded string



27
28
29
30
31
32
33
34
35
# File 'lib/bijective.rb', line 27

def encode i
  return @sequence[0,1] if i == 0
  s = ''
  while i > 0
    s << @sequence[i.modulo(@base)]
    i /= @base
  end
  s.reverse
end