2014-01-11 66 views
4

假设我有一个(我认为是默认可变)数组[字符串]从字符串数组中删除第n个元素在斯卡拉

在斯卡拉我怎么能简单地删除第n个元素?

没有简单的方法似乎可用。

希望喜欢的东西(我做这件事):

def dropEle(n: Int): Array[T] 
Selects all elements except the nth one. 

n 
the subscript of the element to drop from this Array. 
Returns an Array consisting of all elements of this Array except the 
nth element, or else the complete Array, if this Array has less than 
n elements. 

非常感谢。

+0

您是否明白t他将需要N次复制(或移动元素),并且不会在O(1)中完成? –

+0

费用不是问题,我宁愿使用另一个更高效的数据结构,但由于相互依赖性很大,我必须坚持这一点,我不喜欢强制 - spasiba bolshoi! –

+0

它是否必须是一个数组?你不可能转换为List,做你需要的一切,然后转换回Array? –

回答

2

DEF dropEle [T](n为中等,在:数组[T]):数组[T] = in.take(N - 1)++ in.drop(N)

8

这就是意见是。

scala> implicit class Foo[T](as: Array[T]) { 
    | def dropping(i: Int) = as.view.take(i) ++ as.view.drop(i+1) 
    | } 
defined class Foo 

scala> (1 to 10 toArray) dropping 3 
warning: there were 1 feature warning(s); re-run with -feature for details 
res9: scala.collection.SeqView[Int,Array[Int]] = SeqViewSA(...) 

scala> .toList 
res10: List[Int] = List(1, 2, 3, 5, 6, 7, 8, 9, 10) 
+0

您能解释一下为什么您在这里选择了“视图”吗? –

+0

@KevinMeredith希望避免中间副本。直到视图被迫,大概你正在处理索引算术。想必。当然,观点会收到很多仇恨邮件。 –

+0

'toIterator'在这里作为'view'的替代品,以防你不想讨厌邮件:) – sourcedelica

5

问题在于您选择的半可变集合,因为数组的元素可能会发生变异,但其大小不能更改。你真的需要一个已经提供了“删除(索引)”方法的缓冲区。

假设你已经有一个阵列,可以很容易将其转换为与从缓冲器以执行此操作

def remove(a: Array[String], i: index): Array[String] = { 
    val b = a.toBuffer 
    b.remove(i) 
    b.toArray 
} 
0

对于nth=0参考阵列中的第一个元素,

def dropEle[T](nth: Int, in: Array[T]): Array[T] = { 
    in.view.zipWithIndex.filter{ e => e._2 != nth }.map{ kv => kv._1 }.toArray 
} 

稍微更简洁的语法包括

def dropEle[T](nth: Int, in: Array[T]): Array[T] = { 
    in.view.zipWithIndex.filter{ _._2 != nth }.map{ _._1 }.toArray 
} 
相关问题