我想在Scala中复制两位数字,如下所示:
duplicateDigits(List(1,2,3,4,5,6,7,8,9,10,11,345))
//> res0: List[Long] = List(11, 22, 33, 44, 55, 66, 77, 88, 99, 1010, 1111, 345345)我还必须考虑以下模板:
def duplicateDigits(xs: List[Int]): List[Long]= xs match {
case Nil => Nil
case x::ys =>???
}如果我有一个字符串列表,那就很容易了,因为我只需乘以x乘以2,数字就会被复制,但是由于我处理的是整数值,所以我不能这样做。
我最近得到的答案是:
case x :: ys => (x :: x) :: duplicateDigits(ys)但我发现了一个错误:
价值::不是国际贸易组织的成员
有人知道怎么做吗?
发布于 2016-04-18 04:50:46
使用数字是教授编程的基本任务之一。将数字转换为字符串是可行的,但通常不是学生期望的那样。此外,将数字转换为字符串和返回从性能上来说也是不好的。
这里有两种选择。
使用递归帮助函数将“填充”计算为Long。
def duplicateDigits(xs: List[Int]): List[Long] = {
def padding(x: Int): Long = if (x == 0) 1 else padding(x / 10) * 10
xs match {
case Nil => Nil
case x :: ys =>
(padding(x) * x + x) :: duplicateDigits(ys)
}
}替代,其中“填充”是内联计算,使用scanLeft。不过,看起来有点费解:
def duplicateDigits(xs: List[Int]): List[Long] = xs match {
case Nil => Nil
case x :: ys =>
(Stream.from(0)
.scanLeft((1L, x.toLong)) { case ((i, cX), _) => (i * 10, cX / 10) }
.dropWhile(_._2 > 0).head._1 * x + x) ::
duplicateDigits(ys)
}发布于 2016-04-18 04:40:00
您可以使用zip本身创建一个元组列表,然后将其扁平化,如下所示:
xs.zip(xs).flatMap(pair => List(pair._1,pair._2))或者简单的
def duplicate[A](xs:List[A]):List[A] =
xs match {
case Nil => Nil
case h :: t => h :: h :: duplicate(t)
}我的错,误解了这个问题。在这种情况下,我认为没有什么能打败map(_.toString * 2 toLong)。
发布于 2016-04-18 16:44:28
正如注释中所建议的,您可以在Scala中“乘”一个String,因此:
def duplicateDigits(xs: List[Int]): List[Long]=
xs.map(x => (x.toString * 2).toLong)toLong通常是不安全的(如果字符串不是有效的长号,它会抛出),但是在这种简单的情况下,我们可以忽略这个事实,因为我们是从一个Int派生的。
https://stackoverflow.com/questions/36684490
复制相似问题