Last active
February 15, 2019 11:05
-
-
Save marvk/f28bb155462a109ce22021434834c481 to your computer and use it in GitHub Desktop.
Ceasar Cypher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public final class Caesar { | |
private static final int NUM_LETTERS = 26; | |
public static String caesar(final String s, final int shift) { | |
return s.chars() | |
.filter(Caesar::isEnglishLetter) | |
.map(character -> getIntUnaryOperator((char) character, shift)) | |
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) | |
.toString(); | |
} | |
private static boolean isEnglishLetter(final int i) { | |
return (i >= 'A' && i <= 'Z') || (i >= 'a' && i <= 'z'); | |
} | |
private static int getIntUnaryOperator(final char character, final int shift) { | |
if (Character.isUpperCase(character)) { | |
return safeShift(character, shift, 'A'); | |
} | |
if (Character.isLowerCase(character)) { | |
return safeShift(character, shift, 'a'); | |
} | |
throw new IllegalArgumentException("Character has to be an english letter, was " + character); | |
} | |
private static int safeShift(final char character, final int shift, final char startOffset) { | |
return (character - startOffset + NUM_LETTERS + (shift % NUM_LETTERS)) % NUM_LETTERS + startOffset; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.jupiter.api.Test; | |
import static org.junit.jupiter.api.Assertions.assertEquals; | |
class CaesarTest { | |
@Test | |
void caesarTesd() { | |
assertEquals("BCD", Caesar.caesar("ABC", 1)); | |
assertEquals("BCD", Caesar.caesar("ABC", 27)); | |
assertEquals("ZAB", Caesar.caesar("ABC", -1)); | |
assertEquals("ZAB", Caesar.caesar("ABC", -27)); | |
assertEquals("ABC", Caesar.caesar("1A2B3C$#Ä+", 0)); | |
assertEquals("ABC", Caesar.caesar("1A2B3C$#Ä+", 26)); | |
assertEquals("YZA", Caesar.caesar("XYZ", 1)); | |
assertEquals("XYZABCDEFGHIJKLMNOPQRSTUVW", Caesar.caesar("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 23)); | |
assertEquals("bcd", Caesar.caesar("abc", 1)); | |
assertEquals("bcd", Caesar.caesar("abc", 27)); | |
assertEquals("zab", Caesar.caesar("abc", -1)); | |
assertEquals("zab", Caesar.caesar("abc", -27)); | |
assertEquals("abc", Caesar.caesar("1a2b3c$#ä+", 0)); | |
assertEquals("abc", Caesar.caesar("1a2b3c$#ä+", 26)); | |
assertEquals("yza", Caesar.caesar("xyz", 1)); | |
assertEquals("xyzabcdefghijklmnopqrstuvw", Caesar.caesar("abcdefghijklmnopqrstuvwxyz", 23)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment