Skip to content

Instantly share code, notes, and snippets.

@marvk
Last active February 15, 2019 11:05
Show Gist options
  • Save marvk/f28bb155462a109ce22021434834c481 to your computer and use it in GitHub Desktop.
Save marvk/f28bb155462a109ce22021434834c481 to your computer and use it in GitHub Desktop.
Ceasar Cypher
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;
}
}
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