gpt4 book ai didi

algorithm - 如何缩短此 Scala 代码?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:44:09 25 4
gpt4 key购买 nike

我是 Scala 新手。我尝试了土耳其公民身份号码验证算法。

如何实现和优化此 Scala 代码?

您可以通过此链接找到我的 Java 版本 https://gist.github.com/hasanozgan/5601623

trait TurkishCitizenshipNumberValidator {

private def odd(tckn: String): Int = {
tckn.zipWithIndex.foldLeft(0) {
(total, x) =>
x match {
case i if ((i._2 % 2 == 0 && i._2 < 10)) => ((i._1.asDigit) + total)
case _ => total
}
}
}

private def even(tckn: String): Int = {
tckn.zipWithIndex.foldLeft(0) {
(total, x) =>
x match {
case i if ((i._2 % 2 == 1) && i._2 < 9) => ((i._1.asDigit) + total)
case _ => total
}
}
}

private def total(tckn: String): Int = {
tckn.zipWithIndex.foldLeft(0) {
(total, x) =>
x match {
case i if (i._2 < 10) => ((i._1.asDigit) + total)
case _ => total
}
}
}

def turkishCitizenshipNumberValidator(t: String): Boolean = {
val digit10 = total(t) % 10
val digit9 = ((odd(t) * 7) - even(t)) % 10

((t(9).asDigit == digit9) && t(10).asDigit == digit10)
}
}

object test extends TurkishCitizenshipNumberValidator {
// http://tckimliknouretici.appspot.com/
turkishCitizenshipNumberValidator("29419391592")
//> res0: Boolean = true
}

最佳答案

如果你想要它既紧凑又清晰,并且需要基本的输入验证(正确的长度,东西是数字),我会

def turkishCitizenshipNumberValidator(t: String): Boolean = {
if (t.length != 11 || !t.forall(_.isDigit)) false
else {
val n = t.map(_.asDigit)
val evens = n.grouped(2).take(5).map(_(0)).sum
val odds = n.grouped(2).take(4).map(_(1)).sum
n(10) == (n.take(10).sum % 10) && n(9) == ((odds*7 - evens) % 10)
}
}

此处的键使用分组将字符串分成偶数对和奇数对,并将数字映射到开头的数字,因此使用它们不会太麻烦。


编辑:如果您想混淆您的代码,试试这个!

def tCNV(t: String) = t.map(_.asDigit).foldLeft(Seq(0,0,0)){ (v,n) => v(2) match {
case 10 => Seq(v(0)-n,v(1),0); case 9 => Seq(v(0)+n,v(1)-n,10)
case i => Seq(v(0)+n, v(1)+n*(7*(i%2)+(i%2-1)), i+1)
}}.take(2).map(_%10).forall(_ == 0)

关于algorithm - 如何缩短此 Scala 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16617003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com