27 lines
526 B
Scala
27 lines
526 B
Scala
package main
|
|
|
|
import scala.collection.mutable
|
|
|
|
/**
|
|
* Created by claudio on 02/10/16.
|
|
*/
|
|
class ChecksumAccumulator {
|
|
private var sum = 0
|
|
def add(b: Byte): Unit = sum+=b
|
|
def checksum(): Int = ~(sum & 0xFF) + 1
|
|
}
|
|
|
|
object ChecksumAccumulator {
|
|
private val cache = mutable.Map.empty[String, Int]
|
|
def calculate(s: String): Int ={
|
|
if(cache.contains(s)){
|
|
cache(s)
|
|
}
|
|
val ca = new ChecksumAccumulator
|
|
for(cs <- s)
|
|
ca.add(cs.toByte)
|
|
val cs = ca.checksum()
|
|
cache += (s -> cs)
|
|
cs
|
|
}
|
|
} |