首页 > 解决方案 > 如何在包装到头部时找到跳过某些值的项目的索引

问题描述

我有一个布尔列表

val stacks = List(True, True, False, True, False)

我需要一个带索引的函数,并返回下一个不为假的索引,在达到长度后返回 0。

def nextInvolvedAfter(after: Int): Int = ???

例如:

nextInvolvedAfter(0) // 1
nextInvolvedAfter(1) // 3
nextInvolvedAfter(2) // 3
nextInvolvedAfter(3) // 0

我正在考虑迭代这样的列表:

stacks.drop(after + 1) ++ stacks indexWhere(_)

标签: scala

解决方案


这似乎有效:

(stacks.zipWithIndex.drop(after + 1) ++ stacks.zipWithIndex).find(_._1).get._2

推荐阅读