Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
Pre každý index i
v reťazci s
skontroluj, či je výsledok tejto rovnice vždy rovnaký.
$$|s_{i} – s_{i+1}| – |s_{length(s)-i-2} – s_{length(s)-i-1}|$$
Vytvoril som riešenie v týchto programovacích jazykoch:
Všetky riešenia sú dostupné aj na mojom GitHub profile.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import java.util.Scanner; public class FunnyString { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = Integer.parseInt(stdin.nextLine()); for(int i = 0; i < tests; i++) { String s = stdin.nextLine(); if(isFunny(s)) { System.out.println("Funny"); } else { System.out.println("Not Funny"); } } stdin.close(); } private static boolean isFunny(String s) { for(int j = 0; j < s.length() - 1; j++) { if(Math.abs(Character.codePointAt(s, j + 1) - Character.codePointAt(s, j)) != Math.abs(Character.codePointAt(s, s.length() - j - 2) - Character.codePointAt(s, s.length() - j - 1))) { return false; } } return true; } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
function processData(input) { var lines = input.split('\n'); for(var i = 1; i < lines.length; i++) { if(isFunny(lines[i])) { console.log("Funny"); } else { console.log("Not Funny"); } } } function isFunny(s) { for(var j = 0; j < s.length - 1; j++) { if(Math.abs(s.charCodeAt(j + 1) - s.charCodeAt(j)) !== Math.abs(s.charCodeAt(s.length - j - 2) - s.charCodeAt(s.length - j - 1))) { return false; } } return true; } 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 FunnyString extends App { val lines = Source.stdin.getLines().drop(1) val funnies = lines.map(funny).map(toText) println(funnies.mkString("\n")) def funny(s: String): Boolean = { val l = s.length s.indices.take(l - 1).forall(i => (s.charAt(i) - s.charAt(i + 1)).abs == (s.charAt(l - i - 2) - s.charAt(l - i - 1)).abs) } def toText(b: Boolean): String = { if(b) "Funny" else "Not Funny" } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
def funny?(s) for i in 0...s.length() - 1 return false if((s[i].ord - s[i + 1].ord).abs != (s[s.length() - i - 2].ord - s[s.length() - i - 1].ord).abs) end return true end tests = gets.to_i tests.times do s = gets.to_s.strip if funny?(s) puts "Funny" else puts "Not Funny" end end |