0

I've got a method that generates random strings:

def generate_letters(length)
    chars = 'ABCDEFGHJKLMNOPQRSTUVWXYZ'
    letters = ''
    length.times { |i| letters << chars[rand(chars.length)] }
    letters
  end

I want to map values to generated strings, e.g.(1): A = 1, B = 2, C = 3 , e.g.(2): if I generate ACB it equals to 132. Any suggestions?

lukaszkups
  • 5,790
  • 9
  • 47
  • 85
  • Sorry, how do you mean 'map'? Do you want to get number `132` base on generated string `'ACB'` or you need smth else? – KL-7 Dec 27 '11 at 16:19
  • yes - basing on that example, if my method generate `'BAC'` string I want to recognize it as `213` – lukaszkups Dec 27 '11 at 16:22

2 Answers2

1

You can use that for concatenating these values:

s = 'ACB'
puts s.chars.map{ |c| c.ord - 'A'.ord + 10 }.join.to_i
# => 101211

and to sum them instead use Enumerable#inject method (see docs, there are some nice examples):

s.chars.inject(0) { |r, c| r + (c.ord - 'A'.ord + 10) } # => 33

or Enumerable#sum if you're doing it inside Rails:

s.chars.sum { |c| c.ord - 'A'.ord + 10 } # => 33
KL-7
  • 46,000
  • 9
  • 87
  • 74
  • it works! thanks, but could You describe, what each thing in Your code means? I want to understand it :) – lukaszkups Dec 27 '11 at 16:25
  • ok, but wait! it doesn't work for all letters - e.g. K is 11th letter but it equals 1 :/ btw. if You can write that it will start counting from 10 (A = 10, B = 11, ... , Z = 35) it will be awesome! – lukaszkups Dec 27 '11 at 16:30
  • 1
    Sorry, my mistake. What should, for example, `KZ` be converted to? `2035`? – KL-7 Dec 27 '11 at 16:35
  • Updated the answer. Is that what you need now? – KL-7 Dec 27 '11 at 16:57
  • nothing - I've found description of methods which You've used, thanks! – lukaszkups Dec 27 '11 at 17:10
1

How would you deal with the ambiguity for leters above 10 (J) ? For example, how would you differentiate between BKC=2113 and BAAC=2113?

Disregarding this problem you can do this:

def string_to_funny_number(str)
    number=''
    str.each_byte{|char_value| number << (1 + char_value - 'A'.ord).to_s}
    return number.to_i
end

This function will generate a correct int by concatenating each letter value (A=1,B=2,...) Beware that this function doesn't sanitize input, as i am assuming you are using it with output from other function.

polvoazul
  • 2,208
  • 2
  • 19
  • 25
  • differentiate is not required in my case :) I want to add these numbers - e.g ABC = 1 + 2 + 3, AABA = 1 + 1 + 2 + 1 etc. during this transformation – lukaszkups Dec 27 '11 at 16:58