版本
- JDK 17
- Kotlin 1.8.21
- IDEA 2022.2.5
1-5题
1.题目:有一对兔子,从出生后第3个月起每个月都生一对兔子, 小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死, 问每个月的兔子对数为多少
规律为:1,1,2,3,5,8,13,21...
题解:使用递归函数,从最先的第一个月和第二个月开始相加
package com.silvergravel.basic
import java.util.Scanner
/**
* 古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,
* 小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,
* 问每个月的兔子对数为多少
* @author DawnStar
* @since : 2024/4/8
*/
class RabbitReproduction {
/**
* 计算繁衍数量
*
* @param month
* @return 返回数量
*/
fun calc(month: Int): Int {
if (month < 0) {
return 0
}
if (month == 1 || month == 2) {
return 1
}
return calc(month - 1) + calc(month - 2)
}
}
fun main() {
// in 是 kotlin中的硬关键字
val scanner = Scanner(System.`in`)
print("输入月份:")
val month = scanner.nextInt()
val rabbitReproduction = RabbitReproduction()
println("第${month}月一共有:${rabbitReproduction.calc(month)} 对兔子")
}
2.题目:输出输出斐波那契数列
题解:生成一个二维数组,下三角为斐波那契数列数据,缺点:浪费空间
package com.silvergravel.basic
import java.util.Scanner
/**
* 输出输出斐波那契数列
*
* @author DawnStar
* @since : 2024/4/8
*/
class FibonacciSequence {
/**
* 生成斐波那契数列
*
* @param rows 行数
* @return 返回字符串
*/
fun generateFibonacciSequence(rows: Int): String {
if (rows < 0) {
return ""
}
val arrays = Array(rows) { arrayOfNulls<Int>(rows) }
// 当前Kotlin版本为1.8.21 没有 `0..<month`
arrays[0][0] = 1
arrays[1][0] = 1;arrays[1][1] = 1
for (row in 2 until rows) {
arrays[row][0] = 1
arrays[row][row] = 1
val previewRow = row - 1
for (col in 1 until row) {
// 如果不为空执行加法
arrays[row][col] = arrays[previewRow][col - 1]?.let { arrays[previewRow][col]?.plus(it) }
}
}
var text = ""
for (row in 0 until rows) {
for (index in 0..(rows - row)) {
text += " "
}
for (i in 0..row) {
text += "${arrays[row][i]} "
}
text += "\n"
}
return text
}
}
fun main() {
// in 是 kotlin中的硬关键字
val scanner = Scanner(System.`in`)
print("输入行数:")
val row = scanner.nextInt()
println("斐波那契数列如下:\n${FibonacciSequence().generateFibonacciSequence(row)}")
}
3.题目:判断101-200之间有多少个素数,并输出所有素数
题解:先平方该数,该数的平方根取下整到 2,如果能被它们其中一个整除,则为合数,否则为素数
package com.silvergravel.basic
import java.lang.IllegalArgumentException
import java.util.Scanner
import kotlin.math.sqrt
/**
* 判断素数/质数(只能被1和其自身整除)
*
* @author DawnStar
* @since : 2024/4/8
*/
class PrimeNumber {
fun filterPrimeNumberLet(left: Int, right: Int): List<Int> {
val list = checkAndGenerateList(left, right)
return list.filter {
// let 写法
it.let {
val sqrt = sqrt(it.toDouble()).toInt()
var flag = true
for (i in sqrt downTo 2) {
if (it == 2) {
break
}
if (it.rem(i) == 0) {
flag = false
break
}
}
flag
}
}
}
fun isPrime(number: Int): Boolean {
if (number == 2) {
return true
}
val sqrt = sqrt(number.toDouble()).toInt()
for (i in sqrt downTo 2) {
if (number.rem(i) == 0) {
return false
}
}
return true
}
fun filterPrimeNumberRun(left: Int, right: Int): List<Int> {
val list = checkAndGenerateList(left, right)
return list.filter {
// run 写法
it.run {
isPrime(this)
// val sqrt = sqrt(this.toDouble()).toInt()
// var flag = true
// for (i in sqrt downTo 2) {
// if (this == 2) {
// break
// }
// if (this.rem(i) == 0) {
// flag = false
// break
// }
// }
// flag
}
}
}
/**
* 检查参数并生成自然数据列表
*
* @param left 左边界
* @param right 右边界
* @return
*/
private fun checkAndGenerateList(left: Int, right: Int): List<Int> {
if (left <= 1) {
throw IllegalArgumentException("参数不合法,左边界应为大于1的自然数")
}
if (right <= 1) {
throw IllegalArgumentException("参数不合法,右边界应为大于1的自然数")
}
if (right < left) {
throw IllegalArgumentException("参数不合法,右边界应为大于1的自然数")
}
return mutableListOf<Int>().apply {
for (element in left..right) {
add(element)
}
}
}
}
fun main() {
// in 是 kotlin中的硬关键字
val scanner = Scanner(System.`in`)
print("输入左边界:")
val left = scanner.nextInt()
print("输入右边界:")
val right = scanner.nextInt()
val primeNumber = PrimeNumber()
println("let写法")
val primeNumberLet = primeNumber.filterPrimeNumberLet(left, right)
println("${left}-${right}共有:${primeNumberLet.size}个素数\n$primeNumberLet")
println("run写法")
val primeNumbersRun = primeNumber.filterPrimeNumberRun(left, right)
println("${left}-${right}共有:${primeNumbersRun.size}个素数\n$primeNumbersRun")
}
4.题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身 如:153 = 13+53+33
题解:将数字拆分为3个数,然后分别进行3次方
package com.silvergravel.basic
/**
* 题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身
* <br>如 153 = 1^3+5^3+3^3
*
* @author DawnStar
* @since : 2024/4/9
*/
class NarcissusFlower {
private fun isNarcissusFlower(number: Int): Boolean {
if (number < 100 || number > 999) {
return false
}
val unit = number.rem(100).rem(10)
val decade = number.rem(100).div(10)
val hundred: Int = number.div(100)
val target = unit.times(unit).times(unit) +
decade.times(decade).times(decade) +
hundred.times(hundred).times(hundred)
return target == number
}
fun getNarcissusFlowerList(sourceList: List<Int>): List<Int> {
return sourceList.filter { isNarcissusFlower(it) }
.toList()
}
}
fun main() {
val arrayList = arrayListOf<Int>().apply {
for (i in 100..999) {
add(i)
}
}
val narcissusFlowerList = NarcissusFlower().getNarcissusFlowerList(arrayList)
println(narcissusFlowerList.toString())
}
5.题目:将一个正整数分解质因数。例如:输入90,打印出 90 = 2 * 3 * 3 *5
题解:第一步:找到最小的质数k,如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可
第二步:如果n!=k,但n能被k整除, 则应打印出k的值,并用n除以k的商,作为新的正整数n,重复执行第一步
第三步:如果n不能被k整除,则用k+1作为k的值,重复执行第一步
package com.silvergravel.basic
import java.util.*
/**
* 题目:将一个正整数分解质因数。例如:输入90,打印出 90 = 2 * 3 * 3 *5
*
* @author DawnStar
* @since : 2024/4/9
*/
class PrimeNumberFactor {
fun getPrimeNumberFactorList(number: Int): List<Int> {
var num = number
return mutableListOf(1).apply {
for (i in 2..number) {
while (num.rem(i) == 0 && num != i) {
// Kotlin 1.9.23版本 有 number.divAssign(i)
num /= i
add(i)
}
if (num == i) {
add(i)
}
}
}
}
}
fun main() {
// in 是 kotlin中的硬关键字
val scanner = Scanner(System.`in`)
print("输入数字:")
val number = scanner.nextInt()
val factorList = PrimeNumberFactor().getPrimeNumberFactorList(number)
val joinToString = factorList.joinToString(" * ")
println("$number = $joinToString")
}
6-10题
6.题目:利用条件运算符的嵌套来完成分数等级展示:学习成绩>=90分的同学用A表示, 60-89分之间的用B表示,60分以下的用C表示
题解:使用when关键字解题
package com.silvergravel.basic
import java.util.*
/**
* 题目:利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示<br>
* @author DawnStar
* @since : 2024/4/9
*/
class GradeShow {
fun show(score: Int) {
when (score) {
in 90..100 -> print("$score is A")
in 60..89 -> print("$score is B")
in 0..69 -> print("$score is C")
else -> print("what are you doing baby")
}
}
}
fun main() {
// in 是 kotlin中的硬关键字
val scanner = Scanner(System.`in`)
print("输入分数:")
val score = scanner.nextInt()
GradeShow().show(score)
}
7.题目:输入两个正整数m和n,求其最大公约数和最小公倍数
题解:利用辗除法 欧几里得算法
package com.silvergravel.basic
import java.util.*
/**
* 最大公约数 最小公倍数
* @author DawnStar
* @since : 2024/4/10
*/
class CommonDivisorMultiple {
fun maxMultiple(number1: Int, number2: Int): Int {
check(number1, number2)
if (number1 > number2) {
return gcd(number2, number1.rem(number2))
}
return gcd(number1, number2.rem(number1))
}
private fun gcd(dividend: Int, remainder: Int): Int {
if (remainder == 0) {
return dividend
}
return gcd(remainder, dividend.rem(remainder))
}
private fun check(number1: Int, number2: Int) {
if (number1 < 0 || number2 < 0) {
throw IllegalArgumentException("两个整数都必须为正整数!")
}
}
}
fun main() {
// in 是 kotlin中的硬关键字
val scanner = Scanner(System.`in`)
print("第一个正整数:")
val first = scanner.nextInt()
print("第二个正整数:")
val second = scanner.nextInt()
val maxMultiple = CommonDivisorMultiple().maxMultiple(first, second)
println("$first 与 $second 的最大公约数为:$maxMultiple,最小公倍数为:${first.times(second).div(maxMultiple)}")
}
8.输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数
题解:使用正则表达式
package com.silvergravel.basic
import java.util.*
/**
* 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数<br/>
* @author DawnStar
* @since : 2024/4/10
*/
class StatisticalCharacter {
private val chineseRegex = Regex("[\u4e00-\u9fa5]")
private val englishRegex = Regex("[A-z]")
private val numberRegex = Regex("\\d")
private val spaceRegex = Regex("\\s")
fun handleText(text: String) {
var chineseChars = 0
var englishChars = 0
var numberChars = 0
var spaceChars = 0
var otherChars = 0
for (c in text) {
val character = c.toString()
if (character.matches(chineseRegex)) {
chineseChars++
continue
}
if (character.matches(englishRegex)) {
englishChars++
continue
}
if (character.matches(numberRegex)) {
numberChars++
continue
}
if (character.matches(spaceRegex)) {
spaceChars++
continue
}
otherChars++
}
print("该段文字中文字符:$chineseChars 个,英文字符:$englishChars 个,数字字符:$numberChars 个,空格字符:$spaceChars 个,其他字符:$otherChars 个")
}
}
fun main() {
// in 是 kotlin中的硬关键字
val scanner = Scanner(System.`in`)
print("输入一行字符串:")
val text = scanner.nextLine()
StatisticalCharacter().handleText(text)
}
9.题目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。 例如2+22+222+2222+22222(此时共有5个数相加),几个数相加有键盘控制。
题解:循环计算每一项的值
package com.silvergravel.basic
import java.util.*
/**
* 题目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。
* @author DawnStar
* @since : 2024/4/10
*/
class SameNumberItem {
fun calcSum(number: Int, item: Int): Pair<String, Int> {
if (item <= 0) {
throw IllegalArgumentException("项数不能0或着负数")
}
if (number !in 1..9) {
throw IllegalArgumentException("不支持1-9之外的数字")
}
var sum = 0
var subItemVale = 0
val mutableListOf = mutableListOf<String>()
for (subItem in 0 until item) {
subItemVale = subItemVale.times(10) + number
mutableListOf.add(subItemVale.toString())
sum += subItemVale
}
val text = mutableListOf.joinToString("+")
return Pair(text, sum)
}
}
fun main() {
// in 是 kotlin中的硬关键字
val scanner = Scanner(System.`in`)
print("输入数字:")
val number = scanner.nextInt()
print("输入项数:")
val item = scanner.nextInt()
val (text, calcSum) = SameNumberItem().calcSum(number, item)
print("$text = $calcSum")
}
10.题目:一个数如果恰好等于它的因子之和,这个数就称为"完数"。 例如6=1+2+3.编程找出1000以内的所有完数
题解:平方这个数得到平方根,然后从2循环至平方根 得到两个因子,最后汇总相加
package com.silvergravel.basic
import java.util.*
import kotlin.math.sqrt
/**
* 题目:一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数
* @author DawnStar
* @since 2024/04/11
*/
class PerfectNumber {
fun isPerfectNumber(number: Int): Pair<Boolean, List<Int>> {
val sqrt = sqrt(number.toDouble()).toInt()
val factors = mutableListOf(1).apply {
for (i in 2..sqrt) {
if (number.rem(i) == 0) {
add(i)
add(number.div(i))
}
}
}.sorted()
if (factors.sum() == number) {
return Pair(true, factors)
}
// 非完数返回空避免占用内存
return Pair(false, listOf())
}
}
fun main() {
// in 是 kotlin中的硬关键字
val scanner = Scanner(System.`in`)
print("输入上界正整数:")
val upperNumber = scanner.nextInt()
val perfectNumber = PerfectNumber()
for (number in 0..upperNumber) {
val (condition, factors) = perfectNumber.isPerfectNumber(number)
if (condition) {
println("$number 是一个完数:$number = ${factors.joinToString("+")}")
}
}
}
11-15题
11.题目:一个球从一定高度自由落下,每次落地后反跳回原高度的一半; 再落下,求它在 第N次落地时,共经过多少米?第N次反弹多高
题解:每一次落地弹起都是该高度的3/2
package com.silvergravel.basic
import java.util.*
/**
* 题目:一个球从100米高度自由落下,每次落地后反跳回原高度的一半;
* 再落下,求它在 第10次落地时,共经过多少米?第10次反弹多高
* @author DawnStar
* @since : 2024/4/11
*/
class BallFalling {
/**
* Calc path distance
*
* @param height 当前高度
* @param frequency 落地次数
* @return Pair<Double,Double>
*/
fun calcPathDistance(height: Int, frequency: Int): Pair<Double, Double> {
if (height <= 0 || frequency <= 0) {
throw IllegalArgumentException("高度和落地次数都必须为正整数!")
}
val fold = 0.5
var currentHeight = height.toDouble()
var pathDistance = 0.0
for (i in 1..frequency) {
currentHeight *= fold
pathDistance += currentHeight.times(3)
}
return Pair(currentHeight, pathDistance)
}
}
fun main() {
// in 是 kotlin中的硬关键字
val scanner = Scanner(System.`in`)
print("输入高度:")
val height = scanner.nextInt()
print("数入次数:")
val frequency = scanner.nextInt()
val (currentHeight, distance) = BallFalling().calcPathDistance(height, frequency)
print(
"经过第 $frequency 落地弹起," +
"小球一共经过 $distance 米(包括反弹高度)," +
"第 $frequency 次反弹高度为:$currentHeight 米"
)
}
12.题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少? 题解:三层循环,相同的数字跳过当前循环
package com.silvergravel.basic
/**
* 题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
* @author DawnStar
* @since : 2024/4/11
*/
class DifferentNotRepeatNumber {
fun printCompose() {
val mutableList = mutableListOf<String>()
for (i in 1..4) {
for (j in 1..4) {
if (i == j) {
continue
}
for (k in 1..4) {
if (i == k || j == k) {
continue
}
mutableList.add("$i$j$k")
}
}
}
println("符合条件一共:${mutableList.size} 个")
println(mutableList.toString())
}
}
fun main() {
DifferentNotRepeatNumber().printCompose()
}
13.题目:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
题解:指定上界,在上界内判断这个数
package com.silvergravel.basic
import kotlin.math.sqrt
/**
* 题目:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
* @author DawnStar
* @since : 2024/4/13
*/
class PerfectSquare {
fun multipleNumber(upper: Int): List<String> {
if (upper <= 0) {
throw IllegalArgumentException("参数不合法 ")
}
return arrayListOf<String>().apply {
for (i in 1..upper) {
val second = i.plus(100)
val sqrt1 = sqrt(second.toDouble()).toInt()
if (sqrt1.times(sqrt1) != second) {
continue
}
val third = second.plus(168)
val sqrt2 = sqrt(third.toDouble()).toInt()
if (sqrt2.times(sqrt2) != third) {
continue
}
// 存储这个数
val show =
("$i" +
"与100的和:$second 是完全平方数,平方根为:$sqrt1, " +
"再与168的和:$third 同样是完全平方数,平方根为:$sqrt2")
add(show)
}
}
}
}
fun main() {
val multipleNumbers = PerfectSquare().multipleNumber(1000000)
multipleNumbers.forEach {
println(it)
}
}
14.题目:输入某年某月某日,判断这一天是这一年的第几天?
题解:处理闰年多一天的情况,创建一个每月的天数数组
package com.silvergravel.basic
import java.time.LocalDate
import java.util.*
/**
* 题目:输入某年某月某日,判断这一天是这一年的第几天?
* @author DawnStar
* @since : 2024/4/13
*/
class DetermineNumberDay {
private val monthArray = arrayOf(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
fun judgeDateOfYear(year: Int, month: Int, day: Int): Int {
check(year, month, day)
return LocalDate.of(year, month, day).dayOfYear
}
fun judgeDateInYear(year: Int, month: Int, day: Int): Int {
check(year, month, day)
var dayInYear = 0
for (i in 0 until month) {
dayInYear += monthArray[i]
}
return dayInYear + day
}
private fun check(year: Int, month: Int, day: Int) {
val condition = year < 0 || month <= 0 || month > 12 || day < 0 || day > 31
if (condition) {
throw IllegalArgumentException("非法参数")
}
// 初始化为28
monthArray[2] = 28
if (year.rem(400) == 0 || (year.rem(4) == 0 && year.rem(100) != 0)) {
// 该年是闰年
monthArray[2] = 29
}
val days = monthArray[month]
if (day !in 1..days) {
throw IllegalArgumentException("非法参数")
}
}
}
fun main() {
// in 是 kotlin中的硬关键字
val scanner = Scanner(System.`in`)
print("输入年份:")
val year = scanner.nextInt()
print("输入月份:")
val month = scanner.nextInt()
print("输入天数:")
val day = scanner.nextInt()
val determineNumberDay = DetermineNumberDay()
println("${year}-${month}-${day}是${year}年的第${determineNumberDay.judgeDateInYear(year, month, day)}天")
println("${year}-${month}-${day}是${year}年的第${determineNumberDay.judgeDateOfYear(year, month, day)}天")
}
15.题目:有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数
题解:数组、集合等方法可以使用,方案可以有:1.空间换时间;2.原有的数据结构进行操作
package com.silvergravel.basic
import com.silvergravel.basic.util.ArrayUtil
import java.time.Instant
import java.time.temporal.ChronoUnit
import java.util.*
/**
* 题目:有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数
* @author DawnStar
* @since : 2024/4/19
*/
class ElementMove {
fun moveBySpace(array: Array<Int?>, m: Int): Array<Int?> {
if (array.size < m) {
throw IllegalArgumentException("非法参数")
}
if (array.size == m) {
return array.copyOf()
}
if (array.size - 1 == m) {
for (i in 0 until array.size - 1) {
array[i + 1] = array[i].also {
array[i] = array[i + 1]
}
}
return array.copyOf()
}
val copyOf = array.copyOf()
val apply = arrayOfNulls<Int>(m).apply {
for (index in 0 until m) {
this[index] = copyOf[copyOf.size - m + index]
}
}
for (i in array.size - 1 downTo m) {
copyOf[i - m] = copyOf[i].also {
copyOf[i] = copyOf[i - m]
}
}
for (index in apply.indices) {
copyOf[index] = apply[index]
}
return copyOf
}
fun move(array: Array<Int?>, m: Int, selectHigher: Boolean) {
if (array.size < m) {
throw IllegalArgumentException("非法参数")
}
if (array.size == m) {
return
}
if (selectHigher)
moveRecurveHigher(array, array.size, m)
else {
moveRecurve(array, array.size, m)
}
}
/**
* 循环移动数字
* @param array 目标数组
* @param currentSize 数组长度
* @param m 移动次数
*/
private fun moveRecurve(array: Array<Int?>, currentSize: Int, m: Int) {
if (currentSize <= 0 || m == 0) {
return
}
if (currentSize - 1 == m) {
for (i in 0 until currentSize - 1) {
array[i + 1] = array[i].also {
array[i] = array[i + 1]
}
}
return
}
for (i in currentSize - 1 downTo 1) {
array[i - 1] = array[i].also {
array[i] = array[i - 1]
}
}
moveRecurve(array, currentSize, m - 1)
}
private fun moveRecurveHigher(array: Array<Int?>, currentSize: Int, m: Int) {
if (currentSize <= 0 || m <= 0) {
return
}
// 这里避免 rem=1
if (currentSize - 1 == m) {
for (i in 0 until currentSize - 1) {
array[i + 1] = array[i].also {
array[i] = array[i + 1]
}
}
return
}
// 第二种方式先一次性排好除m个数的其他数字
for (i in currentSize - 1 downTo m) {
array[i - m] = array[i].also {
array[i] = array[i - m]
}
}
// array.forEach { print("$it ") }
// println()
// 弊端:如果rem=1,那么栈深度会非常之高,1万数量级就会出现问题
val rem = currentSize.rem(m)
if (rem == 0) {
return
}
val nextRem = if (rem > m)
rem
else
m - rem
moveRecurveHigher(array, m, nextRem)
}
}
fun main() {
// 注意:递归的栈深度不能过高,默认栈大小为1024MB,1万量级基本出现问题
val sourceArray = ArrayUtil.generateArrayNumber(100 * 200)
sourceArray.forEach { print("$it ") }
// in 是 kotlin中的硬关键字
val scanner = Scanner(System.`in`)
print("\n数组总长:${sourceArray.size} 输入需要数组移动个数:")
val number = scanner.nextInt()
val elementMove = ElementMove()
val array1 = sourceArray.copyOf()
val array2 = sourceArray.copyOf()
val space = Instant.now()
val moveBySpace = elementMove.moveBySpace(sourceArray, number)
val spaceTimeConsuming = ChronoUnit.NANOS.between(space, Instant.now())
println("数组型:${spaceTimeConsuming}ns")
val higher = Instant.now()
elementMove.move(array2, number, true)
val highTimeConsuming = ChronoUnit.NANOS.between(higher, Instant.now())
println("高性能:${highTimeConsuming}ns")
val notHigher = Instant.now()
elementMove.move(array1, number, false)
val notHighConsuming = ChronoUnit.NANOS.between(notHigher, Instant.now())
println("低性能:${notHighConsuming}ns")
println("moveBySpace 与 sourceArray 顺序相同:${moveBySpace.toList() == sourceArray.toList()}")
println("moveBySpace 与 array1 顺序相同:${moveBySpace.toList() == array1.toList()}")
println("moveBySpace 与 array2 顺序相同:${moveBySpace.toList() == array2.toList()}")
// for (i in moveBySpace.indices) {
// if (i == number) {
// break
// }
// print("${moveBySpace[i]} ")
// }
// println()
// moveBySpace.forEach { print("$it ") }
// println()
// array1.forEach { print("$it ") }
// println()
// array2.forEach { print("$it ") }
}
数组工具类
package com.silvergravel.basic.util
import java.util.concurrent.ThreadLocalRandom
/**
*
* @author DawnStar
* @since : 2024/4/19
*/
object ArrayUtil {
private val current: ThreadLocalRandom = ThreadLocalRandom.current()
fun generateArray(): Array<Int?> {
val num = current.nextInt(8, 20)
return generateArrayNumber(num)
}
fun generateArrayNumber(number: Int): Array<Int?> {
if (number <= 0) {
throw IllegalArgumentException("非法参数")
}
val sourceArray = arrayOfNulls<Int>(number).apply {
for (i in 0 until number) {
this[i] = current.nextInt(20, 300)
}
}
return sourceArray
}
fun generateArrayNatureSort(number: Int): Array<Int?> {
if (number <= 0) {
throw IllegalArgumentException("非法参数")
}
return arrayOfNulls<Int>(number).apply {
for (i in 0 until number) {
this[i] = i+1
}
}
}
}
github
kotlin-skill-learn/basic at main · DawnSilverGravel/kotlin-skill-learn · GitHub