给定长度值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

相关推荐
louisgeek8 小时前
Kotlin 面试知识点
kotlin
Kapaseker14 小时前
Kotlin泛型精解:类型世界的奇幻之旅
android·kotlin
居然是阿宋19 小时前
Kotlin函数体详解:表达式函数体 vs 代码块函数体——使用场景与最佳实践
java·开发语言·kotlin
划水哥~20 小时前
Kotlin中实现静态
开发语言·kotlin
tangweiguo030519872 天前
Android Kotlin AIDL 完整实现与优化指南
android·kotlin
Lei活在当下2 天前
Kotlin协程浅入浅出
kotlin
alexhilton2 天前
深入理解Jetpack Compose中的函数的执行顺序
android·kotlin·android jetpack
tangweiguo030519872 天前
Kotlin集合全解析:List和Map高频操作手册
kotlin
前行的小黑炭3 天前
Retrofit框架分析(二):注解、反射以及动态代理,Retrofit框架动态代理的源码分析
android·kotlin·retrofit
老码识土3 天前
Kotlin 协程源代码泛读:Continuation 思想实验-2
android·kotlin