Problem Statement
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.
Input Format
The first line contains an integer \$T\$, i.e., the number of test cases. The next \$T\$ lines will contain a string each.
Output Format
A single line containing the number of minimum operations corresponding to each test case.
Constraints
- \$1 ≤ T ≤ 10\$
- \$1 ≤\$ length of string \$≤ 104\$
All characters are lower cased English alphabets.
Sample Input
3 abc abcba abcd
Sample Output
2 0 4
Test Cases
- 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.
Solution
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
print sum((abs(ord(s[i]) - ord(s[-i-1]))) for i in range(len(s)/2))
. Basically, you need to go through your list in both direction (and stop at the middle), summing the differences between the two values you are considering. \$\endgroup\$puts (s.length/2).times.inject(0) {|n, i| n += (s[i].ord - s[-1-i].ord).abs}
\$\endgroup\$