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

相关推荐
划水哥~1 天前
Kotlin函数式API
java·开发语言·kotlin
zhangphil4 天前
Android createScaledBitmap与Canvas通过RectF drawBitmap生成马赛克/高斯模糊(毛玻璃)对比,Kotlin
android·kotlin
刘争Stanley4 天前
Kotlin开发(六):Kotlin 数据类,密封类与枚举类
android·开发语言·kotlin
划水哥~4 天前
Kotlin判空辅助工具
开发语言·kotlin
Channing Lewis5 天前
kotlin 简介
android·开发语言·kotlin
闲暇部落7 天前
kotlin内联函数——runCatching
android·开发语言·kotlin
闲暇部落7 天前
kotlin内联函数——takeIf和takeUnless
android·kotlin
张云瀚7 天前
《Kotlin核心编程》下篇
kotlin·kotlin核心编程
命运之手7 天前
[ Spring ] Spring Cloud Gateway 2025 Comprehensive Overview
java·kotlin·gateway·spring-cloud
程序员江同学7 天前
Kotlin 技术月报 | 2025 年 1 月
android·kotlin