给定长度值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 小时前
java和kotlin 可以同时运行吗
android·java·开发语言·kotlin·同时运行
滴水成冰-2 天前
Kotlin-Flow学习笔记
笔记·学习·kotlin
_Shirley3 天前
android.view.InflateException: Binary XML file line #7: Error inflating class
android·xml·java·ide·kotlin·android studio
ChinaDragonDreamer3 天前
Kotlin:1.9.0 的新特性
android·开发语言·kotlin
帅次4 天前
Android Studio:驱动高效开发的全方位智能平台
android·ide·flutter·kotlin·gradle·android studio·android jetpack
深海呐5 天前
Android 用线程池实现一个简单的任务队列(Kotlin)
android·kotlin·线程池·延时任务队列·线程池延时任务
我命由我123456 天前
Kotlin 极简小抄 P2(插值表达式、运算符、选择结构赋值)
android·java·开发语言·后端·kotlin·安卓
宝杰X76 天前
Compose Multiplatform+kotlin Multiplatfrom第三弹
android·开发语言·kotlin
jiet_h7 天前
Kotlin 中的 `flatMap` 方法详解
开发语言·微信·kotlin
jiet_h7 天前
Android Kotlin 中的 `groupBy` 方法详解
android·开发语言·kotlin