user3711600
user3711600

Reputation: 873

Map alphabetic sequence to integer

I want to implement an alphabetic code which maps to an integer.

For example:

A = 1
B = 2
C = 3
...
Z = 26
AA = 27
AB = 28
...
BA = 53
...
ZZ = 702

What the best way to do this mapping so that I can easily convert from an alphabetic code into a number and vice versa?

Upvotes: 1

Views: 124

Answers (2)

pkrawat1
pkrawat1

Reputation: 681

You could achieve it like this.

str_num_map = lambda do |val|
    arr = ('A'..'ZZ').to_a
    val.is_a?(String) ? (arr.index(val) + 1) : (arr[val-1])
  end

str_num_map.call(1) # => 'A'
str_num_map.call('ZZ') # => 702

Upvotes: 0

Dan Kohn
Dan Kohn

Reputation: 34337

('A'..'ZZ').to_a[694] # "ZS"
('A'..'ZZ').to_a.index("ZS") # 694

Ruby array indexing starts at 0. If you really want it to start at 1 you can do:

('A'..'ZZ').to_a.unshift(nil)[694] # "ZR"
('A'..'ZZ').to_a.unshift(nil).index("ZR") # 694

Upvotes: 3

Related Questions