代码之家  ›  专栏  ›  技术社区  ›  Elye

上下循环

  •  3
  • Elye  · 技术社区  · 7 年前

    我有下面的代码

    (0..6).forEach { colorized(colors, it) }
    (6 downTo 0).forEach { colorized(colors, it) }
    

    我上下打转的地方。有没有办法在一个循环而不是两个循环中实现它?

    4 回复  |  直到 7 年前
        1
  •  4
  •   s1m0nw1    7 年前

    上的简单扩展 IntRange 可以解决它:

    fun IntRange.forEachUpAndDown(action: (Int) -> Unit) {
        forEach(action)
        reversed().forEach(action)
    }
    
    fun main(args: Array<String>) {
        (0..6).forEachUpAndDown {
            println(it)
        }
    }
    
        2
  •  2
  •   user8959091    7 年前

    这样可以:

    (0..13).forEach { colorized(colors, if (it > 6)  13 - it else it) }
    
        3
  •  1
  •   Geno Chen    7 年前

    您可以尝试将这两个范围添加为一个:

    ((0..6) + (6 downTo 0)).forEach { colorized(colors, it) }

    或者尝试减少参数的数量:

    with (6) { (0..this) + (this downTo 0) }.forEach { colorized(colors, it) }

        4
  •  0
  •   Raymond Arteaga    7 年前

    这是一种简单但难看的仅在一个循环中执行的方式:

    inline fun<T> Iterable<T>.forEachUpDown(action: (T) -> Unit): Unit {
        for (index in 0 until this.count()) {
            action(this.elementAt(index))
            action(this.elementAt(this.count()-index-1))
        }
    }
    

    并致电:

    (0..6).forEachUpDown {
            colorized(colors,it)
        }
    

    由于(0…6)是可迭代的,它只能遍历,并且不能通过索引访问元素。

    一种只在一个循环中执行的更好的性能方法是:

     val max=6
        for (index in 0 until max) {
            colorized(colors, index)
            colorized(colors, max-index-1)
        }
    

    但是,就我个人而言,我觉得你的方法更清楚。