0

I try to resolve some task in code wars. I have to create method, which returns column title(occurring in Excel). The method gets one parameter, it's number. For example:

def get_column_title(n)
//code
end

If n = 1. It should return A.

enter image description here

enter image description here

Test cases:

Test.assert_equals(get_column_title(1), "A")
Test.assert_equals(get_column_title(26), "Z")
Test.assert_equals(get_column_title(52), "AZ")
Test.assert_equals(get_column_title(53), "BA")
Test.assert_equals(get_column_title(702), "ZZ")

What I have:

  def number_values
    {
      1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D', 5 => 'E', 6 => 'F', 7 => 'G',
      8 => 'H', 9 => 'I', 10 => 'J', 11 => 'K', 12 => 'L', 13 => 'M', 14 => 'N',
      15 => 'O', 16 => 'P', 17 => 'Q', 18 => 'R', 19 => 'S', 20 => 'T',
      21 => 'U', 22 => 'V', 23 => 'W', 24 => 'X', 25 => 'Y', 26 => 'Z'
    }
  end

def translate_values
    if @n <= 26
      number_values[@n-26*0]
    elsif @n <= 52
        'A'+ number_values[@n-26*1]
    elsif @n <= 78
        'B' + number_values[@n-26*2]
    end
end

Issue: I don't know how to resolve this task algorithmically. I thought about dividing the number by 26 in a loop. Can you give me some hints how to approach the task?

Source of exercise: codewars.com

1

2 Answers 2

1

You have to convert your number to Base 26 and use A...Z instead of 0...25. The only trick is to subtract one from your number in each step.

Sign up to request clarification or add additional context in comments.

Comments

1
{alphabetCount=26
alphabetOffset=1

for i in 0 .. 1000
    i = i + alphabetOffset
    category=""

    while i>alphabetCount do
        j=i%alphabetCount

        if j==0 then
            j=alphabetCount
        end

        category=(64+j).chr + category
        i=(i-j)/alphabetCount

        if j==0 then
            i=i-1
         end
    end

    category=(64+i).chr + category + "\n"
    puts category
end}

sorry if it is a bit wonky but i am in mobile and could only test via an online compiler :( but it outputs

0=A
...
25=Z
....
702=AAA

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.