在scala中有什么方法可以在不改变相对位置的情况下对整数和字符串列表进行排序吗?就像我有输入
List("xyz",6,4,"ghi",3,5,1,"abc")输出应该是
List("abc",1,3,"ghi",4,5,6,"xyz")整数和字符串的相对位置不变。为此,我将数字和数字的位置分开存储,然后将字符串和整数排序到不同的列表中,并将它们放在各自的位置上。Scala中有什么技术可以更快地完成吗?
发布于 2017-09-13 13:29:22
这是一个有用的代码。可能不是最优的,但它解决了这个问题:
object Test {
def removeElementFromList[T](xs:List[T], t:T):List[T] = xs match {
case h::tail if h == t => tail
case h::tail if h != t => h :: removeElementFromList(tail, t)
case Nil => Nil
}
def updateElement[T](xs:List[T], oldValue:T, newValue:T):List[T] = xs match{
case h::tail if h == oldValue => newValue :: tail
case h::tail if h != oldValue => h :: updateElement(tail, oldValue, newValue)
case Nil => Nil
}
//ascending
def sortRetainingPosition[T](xs:List[(T, Int)])(implicit cmp:Ordering[T]):List[(T, Int)] = {
xs match{
case h :: tail =>{
val minimalElement = xs.minBy(_._1)
if(h == minimalElement) h :: sortRetainingPosition(tail) else{
(minimalElement._1, h._2) :: sortRetainingPosition(updateElement(tail, minimalElement, (h._1, minimalElement._2)))
}
}
case Nil => Nil
}
}
def main(args:Array[String]):Unit = {
val input = List("xyz",6,4,"ghi",3,5,1,"abc")
val positioned = input.zipWithIndex
val strings = positioned.filter(_._1.isInstanceOf[String]).asInstanceOf[List[(String, Int)]]
val ints = positioned.filterNot(_._1.isInstanceOf[String]).asInstanceOf[List[(Int, Int)]]
val partiallySorted = sortRetainingPosition(strings) ++ sortRetainingPosition(ints)
val result = partiallySorted.sortBy(_._2).map(_._1)
println(result)
}
}https://stackoverflow.com/questions/46192987
复制相似问题