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

相关推荐
糖猫猫cc1 小时前
Kite:两种方式实现动态表名
java·kotlin·orm·kite
如此风景6 小时前
kotlin协程学习小计
android·kotlin
Kapaseker10 小时前
你搞得懂这 15 个 Android 架构问题吗
android·kotlin
zh_xuan11 小时前
kotlin 高阶函数用法
开发语言·kotlin
colicode11 小时前
安卓Android语音验证码接口API示例代码:Kotlin/Java版App验证开发
android·java·前端·前端框架·kotlin·语音识别
程序员敲代码吗11 小时前
解析Kotlin中元组的多返回值实现
android·开发语言·kotlin
zh_xuan1 天前
kotlin with函数
开发语言·kotlin
zh_xuan1 天前
kotlin let函数
开发语言·kotlin
Kapaseker1 天前
Kotlin 协程的取消,我觉得设计的不好
android·kotlin
zh_xuan1 天前
kotlin 作用域函数run
开发语言·kotlin