从Scala数组中删除每个第N个元素

时间:2016-12-04 01:17:38

标签: scala

我的要求是从Scala数组中删除每个第N个元素(请注意每个第N个元素)。我写下了完成这项工作的方法。因为,我是Scala的新手,我无法避免Java宿醉。是否有更简单或更有效的替代方案?

def DropNthItem(a: Array[String], n: Int): Array[String] = {
 val in = a.indices.filter(_ % n != 0)
 val ab: ArrayBuffer[String] = ArrayBuffer()
 for ( i <- in)
    ab += a(i-1)
 return ab.toArray
}

5 个答案:

答案 0 :(得分:2)

你开了个好头。考虑这种简化。

def DropNthItem(a: Array[String], n: Int): Array[String] =
  a.indices.filter(x => (x+1) % n != 0).map(a).toArray

答案 1 :(得分:2)

这样的事情怎么样?

app.get('/auth/slack',
        passport.authorize('slack'));

app.get('/auth/slack/callback', 
        passport.authorize('slack', { failureRedirect: '/login' }),
        function(req, res) {
            //Successful authentication, redirect home.
            console.log(req.session);
            console.log(req.session.passport);
            res.redirect('/dashboard');
        }
    );

答案 2 :(得分:1)

这将使它成为

def DropNthItem(a: Array[String], n: Int): Array[String] =
   a.zipWithIndex.filter(_._2 % n != 0).map(_._1)

答案 3 :(得分:0)

我会选择这样的东西;

def dropEvery[A](arr: Seq[A], n: Int) = arr.foldLeft((Seq.empty[A], 0)) {
  case ((acc, idx), _) if idx == n - 1 => (acc, 0)
  case ((acc, idx), el) => (acc :+ el, idx + 1)
}._1

// example: dropEvery(1 to 100, 3)
// res0: Seq[Int] = List(1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26, 28, 29, 31, 32, 34, 35, 37, 38, 40, 41, 43, 44, 46, 47, 49, 50, 52, 53, 55, 56, 58, 59, 61, 62, 64, 65, 67, 68, 70, 71, 73, 74, 76, 77, 79, 80, 82, 83, 85, 86, 88, 89, 91, 92, 94, 95, 97, 98, 100)

这是有效的,因为它需要在数组上单次传递并从中删除每个第n个元素 - 我相信很容易看到。 第一种情况与idx == n - 1匹配,忽略该索引处的元素,并传递acc并将计数重置为0以获取下一个元素。 如果第一种情况不匹配,则将元素添加到acc的末尾,并将计数增加1.

由于您愿意摆脱Java 宿醉,您可能希望使用隐式类以非常好的方式使用它:

implicit class MoreFuncs[A](arr: Seq[A]) {
  def dropEvery(n: Int) = arr.foldLeft((Seq.empty[A], 0)) {
    case ((acc, idx), _) if idx == n - 1 => (acc, 0)
    case ((acc, idx), el) => (acc :+ el, idx + 1)
  }._1
}

// example: (1 to 100 dropEvery 1) == Nil (: true)

答案 4 :(得分:0)

如果您正在寻找性能(因为您使用的是ArrayBuffer),您也可以使用var跟踪索引,手动递增它,并使用{{检查它1}}过滤掉多个索引的值。

if

如果我们使用while循环遍历原始数组作为迭代器,它会更快。

def dropNth[A: reflect.ClassTag](arr: Array[A], n: Int): Array[A] = {
    val buf = new scala.collection.mutable.ArrayBuffer[A]
    var i = 0
    for(a <- arr) {
        if((i + 1) % n != 0) buf += a
        i += 1
    }
    buf.toArray
}
相关问题