Popis problému
Celý popis zadania sa nacháza – Hackerrank.
Riešenie
Vytvoriť kryptovaciu funkciu, ktoré berie zadaný Cézarov posun. Pre každý znak, treba tiež overiť, či je písmeno. Pre malé písmená platí rovnica:
to_char[ascii_of_char - asci_of_a + shift) % 26 + ascii_of_a]
Pre veľké písmena
to_char[ascii_of_char - asci_of_A + shift) % 26 + ascii_of_A]
.
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 |
import java.util.*; public class CaesarCipher { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int length = stdin.nextInt(); String text = stdin.next(); int shift = stdin.nextInt(); for(int i = 0; i < length; i++) { char c = text.charAt(i); if(c >= 'a' && c <= 'z') { System.out.print((char)(((int)c - (int)'a' + shift) % 26 + (int)'a')); } else if(c >= 'A' && c <= 'Z') { System.out.print((char)(((int)c - (int)'A' + shift) % 26 + (int)'A')); } else { System.out.print(c); } } stdin.close(); } } |
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 |
'use strict'; const processData = input => { let lines = input.split('\n'); let text = lines[1]; let shift = parseInt(lines[2]); let encrypted = ''; for(let i = 0; i < text.length; i++) { if(text.charCodeAt(i) >= 'a'.charCodeAt(0) && text.charCodeAt(i) <= 'z'.charCodeAt(0)) { encrypted += String.fromCharCode((text.charCodeAt(i) - 'a'.charCodeAt(0) + shift) % 26 + 'a'.charCodeAt(0)) } else if(text.charCodeAt(i) >= 'A'.charCodeAt(0) && text.charCodeAt(i) <= 'Z'.charCodeAt(0)) { encrypted += String.fromCharCode((text.charCodeAt(i) - 'A'.charCodeAt(0) + shift) % 26 + 'A'.charCodeAt(0)) } else { encrypted += text.charAt(i); } } console.log(encrypted); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); var _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import scala.io.Source object CaesarCipher extends App { val lines = Source.stdin.getLines().toList val text = lines(1) val encryptionKey = lines(2).toInt val encrypted = text.map(caesarCipher(_, encryptionKey)) println(encrypted) def caesarCipher(c: Char, shift: Int): Char = { if(c >= 'a' && c <= 'z') { return ((c.toInt - 'a'.toInt + shift) % 26 + 'a'.toInt).toChar } if(c>= 'A' && c <= 'Z') { return ((c.toInt - 'A'.toInt + shift) % 26 + 'A'.toInt).toChar } return c } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 |
l = gets.to_i text = gets.to_s shift = gets.to_i text.each_codepoint do |c| if(c >= 'a'.ord && c <= 'z'.ord) print ((c - 'a'.ord + shift) % 26 + 'a'.ord).chr elsif (c >= 'A'.ord && c <= 'Z'.ord) print ((c - 'A'.ord + shift) % 26 + 'A'.ord).chr else print c.chr end end |