Skip to content

Instantly share code, notes, and snippets.

@maasg
Created September 8, 2013 00:15
Show Gist options
  • Select an option

  • Save maasg/6480691 to your computer and use it in GitHub Desktop.

Select an option

Save maasg/6480691 to your computer and use it in GitHub Desktop.
Caesar Codex
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