Assume that I have an array like 1 2 3 4 5, I want to rotate it to the left by n and get a new one.

For example the 2 rotation of the above array will result in 3 4 5 1 2. I didn't found any extension function to do that.

推荐答案

您可以在Array<T>上编写自己的扩展函数

fun <T> Array<T>.leftShift(d: Int): Array<T> {
    val newList = this.copyOf()
    var shift = d
    if (shift > size) shift %= size
    forEachIndexed { index, value ->
        val newIndex = (index + (size - shift)) % size
        newList[newIndex] = value
    }
    return newList
}

Kotlin相关问答推荐

如何接受任何派生类KClass

我需要后台工作才能使用卡夫卡的消息吗?

Kotlin Coroutine()是如何工作的?S阻止了.

如何在不基于数据 map 的情况下将图例添加到lets plot kotlin

房间数据库操作中的协程取消

generic 类实例列表 - 调用采用 T 的函数

为什么记得不将 StateFlow 转换为特定类型?

Kotlin 协程按顺序执行,但仅在生产机器上执行

Jetpack Compose:当状态从另一个活动改变时强制重组

is return inside function definition 也是 kotlin 中的表达式

compareBy 如何使用布尔表达式在 kotlin 中工作

如何在 kotlin 中通过反射设置委托属性值?

Moshi:解析单个对象或对象列表(kotlin)

禁用 Android 12 默认启动画面

模拟异常 - 没有找到答案

Kotlin 语言是如何用 Kotlin 编写的?

从代码块执行和返回(在 Elvis 运算符之后)

片段内的 Kotlin 按钮 onClickListener 事件

Kotlin中的测试无法访问受保护(protected)的方法

ObjectAnimator.ofFloat 不能直接在kotlin中取Int作为参数