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

相关推荐
糖猫猫cc6 小时前
Kite:填充处理器
kotlin·orm·kite
Kapaseker12 小时前
一杯美式深入理解 data class
android·kotlin
alexhilton3 天前
端侧RAG实战指南
android·kotlin·android jetpack
Kapaseker4 天前
2026年,我们还该不该学编程?
android·kotlin
Kapaseker5 天前
一杯美式搞懂 Any、Unit、Nothing
android·kotlin
Kapaseker6 天前
一杯美式搞定 Kotlin 空安全
android·kotlin
FunnySaltyFish6 天前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
Kapaseker7 天前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
Kapaseker7 天前
实战 Compose 中的 IntrinsicSize
android·kotlin
A0微声z9 天前
Kotlin Multiplatform (KMP) 中使用 Protobuf
kotlin