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

相关推荐
ai2work2 天前
ch23 综合复刻:从零做一个最小可用版本(capstone)
kotlin
ai2work2 天前
ch21 签名、校验与发版
kotlin
JMchen2 天前
属性动画原理与高级动画实现
android·kotlin·canvas
Android打工仔2 天前
Kotlin 协程源码解析:协程是如何切换线程的?
android·kotlin
ai2work2 天前
附录 D 速查索引与阅读指南
kotlin
ai2work2 天前
ch22 诊断方法论:三个真实事故的根因分析
kotlin
Kapaseker2 天前
你有搞明白 Volatile 什么意思吗?
android·kotlin
alexhilton3 天前
藏在设备上的秘密,终究藏不住
android·kotlin·android jetpack
ai2work3 天前
ch15 加载模型与初始化上下文
kotlin
hai_android3 天前
Kotlin / Android 常用函数使用示例手册
android·java·kotlin