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

相关推荐
传奇开心果编程10 小时前
【Jetpack Compose娓娓道来】第44课:持久化——让数据“关掉App也不丢”
android·kotlin·移动开发·数据持久化·jetpack compose·ui框架·声明式ui
OriginCoding1 天前
一个 JDK 跑起六个分布式挑战:Kotlin 版 Gossip Glomers(一)
分布式·kotlin
alexhilton2 天前
MVI 让屏幕一次只有一个状态
android·kotlin·android jetpack
金銀銅鐵5 天前
一个 4 个常量的枚举,Kotlin 在字节码里生成了什么
jvm·kotlin
Easyhood7 天前
Android 开发入门实践(十四):Compose 副作用入门与四个常用 API
android·开发语言·kotlin·android jetpack·compose
松仔log7 天前
Kotlin中级——callbackFlow
java·前端·kotlin
zh_xuan7 天前
kotlin常见面试题
开发语言·kotlin·面试题
mmsx7 天前
耳切法切带洞多边形:论文能跑通,真实数据为什么崩
android·kotlin
Kapaseker7 天前
Kotlin 又要加语法糖了:这次轮到 if-else
android·kotlin