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

相关推荐
我命由我123451 天前
Kotlin 面向对象 - 匿名内部类、匿名内部类简化
android·java·开发语言·java-ee·kotlin·android studio·android jetpack
悠哉清闲2 天前
Future
java·开发语言·kotlin
hewence12 天前
Kotlin CoroutineScope解密
android·开发语言·kotlin
hewence12 天前
重构千行Callback:Android异步回调无损迁移协程Suspend完全指南
android·重构·kotlin
我命由我123452 天前
Android多进程开发 - AIDL 参数方向、AIDL 传递自定义对象、AIDL 传递自定义对象(参数方向)
android·java·java-ee·kotlin·android studio·android jetpack·android-studio
alexhilton3 天前
使用LoRA微调Gemma实现移动端推理
android·kotlin·android jetpack
hewence13 天前
Kotlin协程启动方式详解
android·开发语言·kotlin
RdoZam3 天前
Android-封装个好用、轻量和通用的原生Adapter基类
android·kotlin
智先森zhi3 天前
实战:将 Android 多Module应用迁移到 kmp+cmp
android·ios·kotlin
hewence13 天前
Kotlin CoroutineContext 详解
android·开发语言·kotlin