Sha256: d003e969f5170659f284cef1d7720cdc0a99d64c82ccd55080a35268ceecfd32

Contents?: true

Size: 978 Bytes

Versions: 396

Compression:

Stored size: 978 Bytes

Contents

import scala.util.Random

case class Cipher(keyOpt: Option[String]) {
  require(keyOpt.isEmpty || keyOpt.get.matches("^[a-z]+$"))

  private val alphabet = ('a' to 'z').toVector
  private lazy val randomKey = Seq.fill(26)((Random.nextInt(25) + 'a').toChar).mkString

  val key = keyOpt.getOrElse(randomKey)

  def encode(s: String): String =
    (for (i <- 0 until s.length) yield encodeChar(s, i)).mkString

  private def encodeChar(plainText: String, index: Int) = {
    var alphaIdx = alphabet.indexOf(plainText(index)) + alphabet.indexOf(key(index))

    if (alphaIdx >= alphabet.length) alphaIdx -= alphabet.length

    alphabet(alphaIdx)
  }

  def decode(s: String): String =
    (for (i <- 0 until s.length) yield decodeChar(s, i)).mkString

  private def decodeChar(cipherText: String, index: Int) = {
    var alphaIdx = alphabet.indexOf(cipherText(index)) - alphabet.indexOf(key(index))

    if (alphaIdx < 0) alphaIdx += alphabet.length

    alphabet(alphaIdx)
  }
}

Version data entries

396 entries across 396 versions & 1 rubygems

Version Path
trackler-2.2.1.139 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.138 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.137 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.136 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.135 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.134 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.133 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.132 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.131 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.130 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.129 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.128 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.127 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.126 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.125 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.124 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.123 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.122 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.121 tracks/scala/exercises/simple-cipher/example.scala
trackler-2.2.1.120 tracks/scala/exercises/simple-cipher/example.scala