Sha256: 4c0910712b4740e4637d75a2c9000ddc6873b69b2da43ca4d5078215184d2dde

Contents?: true

Size: 665 Bytes

Versions: 168

Compression:

Stored size: 665 Bytes

Contents

object Luhn {

  def valid(numberStr: String): Boolean = {
    val s = numberStr.replace(" ", "")

    s.length > 1 &&
      s.forall(c => c.isDigit) &&
      checksum(s.map(_.asDigit).toList) == 0
  }

  private def checkDigit(number: Long): Int = (number % 10).toInt

  private def addends(digits: List[Int]): List[Int] = {
    val zippedDigits = digits.reverse.zipWithIndex

    zippedDigits.map{case (m, i) => if (isOdd(i)) dbl(m) else m}
  }

  private def checksum(digits: List[Int]): Int = addends(digits).sum % 10

  private def dbl(n: Int) = {
    val dbled = n * 2

    if (dbled < 10) dbled else dbled - 9
  }

  private def isOdd(i: Int) = i % 2 == 1
}

Version data entries

168 entries across 168 versions & 1 rubygems

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