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

相关推荐
XiaoLeisj4 小时前
Kotlin Flow:冷流收集、并行订阅、emit 推送、delay 延迟、collect 全量收集与 collectLatest 的实时数据处理
android·kotlin·android jetpack·协程·flow
Android-Flutter5 小时前
android jetpack 详解
android·kotlin
Enaium1 天前
我实现了KMP的SDL绑定并编写了高性能软光追
前端·kotlin
Android打工仔1 天前
Continuation 的链式关系 —— 一个 suspend 函数如何把结果交还给调用者?
android·kotlin
Kapaseker1 天前
小白都看得懂的 Skill 教程 - 初识 Skill
android·kotlin·vibecoding
zhangphil1 天前
Android Coil 3 ImageRequest.Builder error() 和 fallback()异同
android·kotlin
我命由我123452 天前
Android 控件 - CardView(快速实现圆角)
android·java·java-ee·kotlin·android studio·android-studio·android runtime
大黄说说2 天前
Java 与 Kotlin 混合开发避坑指南:老项目平滑迁移 Kotlin 实操手册
java·开发语言·kotlin
我命由我123452 天前
Android Drawable - gradient
android·java·java-ee·kotlin·android studio·android-studio·android runtime
Kapaseker2 天前
AI 时代,读源码还有用吗?从 Kotlin 集合排序说起
android·kotlin