James got hold of a love letter that his friend Harry has written for his girlfriend. Being the prankster that James is, he decides to meddle with it. He changes all the words in the letter into palindromes.
While modifying the letters of the word, he follows 2 rules:
(a) He always reduces the value of a letter, e.g. he changes 'd' to 'c', but he does not change 'c' to 'd'. (b) If he has to repeatedly reduce the value of a letter, he can do it until the letter becomes 'a'. Once a letter has been changed to 'a', it can no longer be changed.
Each reduction in the value of any letter is counted as a single operation. Find the minimum number of operations he carries out to convert a given string into a palindrome.
The challange can be found here.
The first line contains an integer \$T\$, i.e., the number of test cases. The next \$T\$ lines will contain a string each.
A single line containing the number of minimum operations corresponding to each test case.
- \$1 ≤ T ≤ 10\$
- \$1 ≤\$ length of string \$≤ 104\$
All characters are lower cased English alphabets.
3 abc abcba abcd
2 0 4
- For the first test case, abc → abb → aba.
- For the second test case, abcba is a palindromic string.
- For the third test case, abcd → abcc → abcb → abca = abca → abba.
T = gets.chomp.to_i result =  def difference x,y (x.ord - y.ord).abs end T.times do string = gets.chomp i,j = 0, -1 n = 0 loop do n = n + difference(string[i], string[j]) i += 1 j -= 1 break if string.length % 2 == 0 ? i == (string.length/2) : i + j == -1 && string[i] == string[j] && i == string.length/2 end result << n end puts result