]> git.donarmstrong.com Git - biopieces.git/blob - code_ruby/lib/maasha/base36.rb
add comments to ambiguity.rb
[biopieces.git] / code_ruby / lib / maasha / base36.rb
1 # Copyright (C) 2011 Martin A. Hansen.
2
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
7
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16
17 # http://www.gnu.org/copyleft/gpl.html
18
19 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
20
21 # This software is part of the Biopieces framework (www.biopieces.org).
22
23 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
24
25 # Error class for all exceptions to do with Base36.
26 class Base36Error < StandardError; end
27
28 ALPH   = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
29 BASE36 = 36
30
31 # Class containing methods to encode and decode Base 36.
32 # Note that the ALPH is [alph + num] and not [num + alph]
33 # which prevents us from simply using .to_i(36) and .to_s(36).
34 #
35 # http://en.wikipedia.org/wiki/Base_36
36 class Base36
37   # Method that encodes an integer into a base36 string
38   # that is returned.
39   def self.encode(num)
40     raise Base36Error unless num.is_a? Fixnum
41
42     base36 = ""
43
44     while num > 0
45       base36 << ALPH[(num % BASE36)]
46       num /= BASE36
47     end
48
49     base36 << ALPH[0] if num == 0
50
51     base36.reverse
52   end
53
54   # Method that decodes a base36 string and returns an integer.
55   def self.decode(base36)
56     raise Base36Error if base36.empty?
57
58     result = 0
59     pos    = 0
60
61     base36.upcase.reverse.each_char do |char|
62       result += ALPH.index(char) * (BASE36 ** pos)
63       pos    += 1
64     end
65
66     return result;
67   end
68 end
69
70 __END__