Problem Statement
A description of the problem can be found on Hackerrank.
Solution
For an element at index i
create sum of differences between an ordinal number of character at index length(s)-i-1
and an ordinal number of the character at index i
.
I created solution in:
All solutions are also available on my GitHub.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.Scanner; public class LoveLetterMystery { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = stdin.nextInt(); for(int i = 0; i < tests; i++) { String s = stdin.next(); int diff = 0; for(int j = 0; j < s.length() / 2; j++) { diff += Math.abs(Character.codePointAt(s, j) - Character.codePointAt(s, s.length() - j - 1)); } System.out.println(diff); } stdin.close(); } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 |
tests = gets.chomp.to_i tests.times do input = gets.chomp changes = 0 for i in 0...input.length / 2 char_front = input[i] char_back = input[input.length - 1 - i] diff = (char_front.ord - char_back.ord).abs changes += diff end puts changes end |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
function processData(input) { var lines = input.split('\n'); for(var i = 1; i < lines.length; i++) { var diff = 0; for(var j = 0; j < lines[i].length / 2; j++) { diff += Math.abs(lines[i].charCodeAt(j) - lines[i].charCodeAt(lines[i].length - j - 1)); } console.log(diff); } } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); |
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import scala.io.Source object TheLoveLetterMystery extends App { val lines = Source.stdin.getLines().drop(1) val diffs = lines.map(changes) println(diffs.mkString("\n")) def changes(s: String): Int = { val halves = s.splitAt(s.length / 2) val reverted2 = halves._2.reverse halves._1.indices.map(i => ordinalDiff(halves._1.charAt(i), reverted2.charAt(i))).sum } def ordinalDiff(ch1: Char, ch2: Char): Int = { (ch2 - ch1).abs } } |