Sha256: aeddfdf8c69899a50c0d4233517e964b4af7ce41eca040c690e7e5cf1962cb26

Contents?: true

Size: 1.19 KB

Versions: 172

Compression:

Stored size: 1.19 KB

Contents

object CryptoSquare {
  def normalizedPlaintext(text: String): String =
    text.filter(c => c.isLetterOrDigit).toLowerCase

  def squareSize(text: String): Int = Math.ceil(Math.sqrt(text.length)).asInstanceOf[Int]

  def plaintextSegments(text: String): List[String] = {
    val normalized = normalizedPlaintext(text)
    val size = squareSize(normalized)
    size match {
      case 0 => List.empty
      case _ => normalized.grouped(size).toList
    }
  }

  def encoded(text: String): String = {
    val plainSegs = plaintextSegments(text)

    transpose(plainSegs).mkString.filter(c => !c.isWhitespace)
  }

  def ciphertext(text: String): String = {
    val plainSegs = plaintextSegments(text)

    transpose(plainSegs).mkString(" ")
  }

  private def transpose(texts: List[String]): List[String] = {
    if (texts.isEmpty || texts.head.isEmpty) {
      List.empty
    } else {
      val size = texts.head.length
      // Scala's transpose must work on Lists where all elements are same size.
      // So pad the List. Then strip off the padding before return.
      val padded = texts.map(s => s.padTo(size, "\u0000"))
      padded.transpose.map(item => item.mkString.replaceAll("\u0000", " "))
    }
  }
}

Version data entries

172 entries across 172 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.179 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.178 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.177 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.176 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.175 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.174 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.173 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.172 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.171 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.170 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.169 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.167 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.166 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.165 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.164 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.163 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.162 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.161 tracks/scala/exercises/crypto-square/example.scala
trackler-2.2.1.160 tracks/scala/exercises/crypto-square/example.scala