给定长度值length,把列表切分成每段长度为length的N段列表,Kotlin

给定长度值length,把列表切分成每段长度为length的N段列表,Kotlin

Kotlin 复制代码
import kotlin.random.Random

fun main(args: Array<String>) {
    var source = mutableListOf<String>()
    val end = Random.nextInt(30) + 1
    for (i in 0 until end) {
        source.add(i.toString())
    }
    println(source)
    val length = Random.nextInt(source.size) + 1

    var segment = source.size / length
    if (source.size % length != 0) {
        segment++
    }
    println("总长度:${source.size} 随机生成每段长度:$length 算出段数:$segment ")

    var fromIndex = 0
    var toIndex = 0
    for (i in 0 until segment) {
        fromIndex = i * length
        toIndex = Math.min(fromIndex + length, source.size)
        println(source.subList(fromIndex, toIndex))
    }
}

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21

总长度:22 随机生成每段长度:4 算出段数:6

0, 1, 2, 3

4, 5, 6, 7

8, 9, 10, 11

12, 13, 14, 15

16, 17, 18, 19

20, 21

https://blog.csdn.net/zhangphil/category_12220817.htmlhttps://blog.csdn.net/zhangphil/category_12220817.html

相关推荐
alexhilton17 小时前
Jetpack Compose中的阴影艺术
android·kotlin·android jetpack
Tom4i20 小时前
Kotlin 中的 inline 和 reified 关键字
android·开发语言·kotlin
无知的前端1 天前
一文读懂-Jetpack与AndroidX
android·kotlin·android jetpack
用户69371750013841 天前
Kotlin 函数详解:命名参数与默认参数值
android·后端·kotlin
Jeled1 天前
RecyclerView ViewHolder 复用机制详解(含常见错乱问题与优化方案)
android·学习·面试·kotlin
柯南二号1 天前
【大前端】【Android】 Kotlin 语法超详细解析(2025 最新)
android·kotlin
Ya-Jun2 天前
项目实战Now in Android:项目模块说明
android·架构·kotlin
消失的旧时光-19432 天前
Kotlinx.serialization 使用指南
android·kotlin·json
消失的旧时光-19432 天前
Kotlinx.serialization 项目集成
android·kotlin·json
彭同学学习日志2 天前
解决 Android Navigation 组件导航栏配置崩溃:从错误到实现的完整指南
android·kotlin