给定长度值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 天前
Android WebView 设计指南
android·java·kotlin
Kapaseker1 天前
深入理解 Compose 副作用
kotlin
雨白2 天前
深入理解 Kotlin 协程 (八):拾遗补阙,探秘官方框架的调度细节与取消闭环
android·kotlin
GitLqr2 天前
别被“Flutter 传感器延迟 150ms”带偏了:这可能只是你的实现方式错了
flutter·架构·kotlin
我命由我123452 天前
Android 在构建过程中,发现有两个依赖库都包含了相同路径的资源文件
android·java·开发语言·java-ee·kotlin·android-studio·android runtime
Coffeeee2 天前
谷歌的一个优化建议,让我重新学了一遍Android里面如何正确处理位图
android·google·kotlin
Android打工仔4 天前
Continuation 到底是谁创建的?
android·kotlin
Android-Flutter4 天前
android fragment 使用
android·kotlin
alexhilton4 天前
响应式的Android身份验证架构
android·kotlin·android jetpack
zzq77974 天前
Android 16 API 36 升级后 APP 加固兼容性问题解析
android·开发语言·安全·kotlin·安卓·安全架构