Created
September 8, 2013 00:15
-
-
Save maasg/6480691 to your computer and use it in GitHub Desktop.
Caesar Codex
This file contains hidden or 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
| object CaesarCodex { | |
| class CyclicCharRange(start:Char,end:Char) extends PartialFunction[Char,Int=>Char] { | |
| val size = end-start+1 | |
| def isDefinedAt(c:Char) = c>=start && c<=end | |
| def apply(c:Char): Int => Char = { amount => | |
| val rangeAmount = ((amount % size)+size) % size | |
| val shiftedValue = (((c-start)+rangeAmount)%size)+start | |
| shiftedValue.toChar | |
| } | |
| } | |
| class CharIdentity extends PartialFunction[Char,Int=>Char] { | |
| def isDefinedAt(c:Char) = true | |
| def apply(c:Char): Int => Char = x => c | |
| } | |
| val rangeAZ = new CyclicCharRange('A','Z') | |
| val rangeaz = new CyclicCharRange('a','z') | |
| val id = new CharIdentity | |
| def encode(s:String, shift:Int) = { | |
| s.map(c => (rangeAZ orElse rangeaz orElse id)(c) (shift)) | |
| } | |
| def decode(s:String, shift:Int) = encode(s,-shift) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment