我有一个随机数字数组例如
[ 1 , 2 , 3 , 6 , 7 , 8 , 24 , 25 , 26 ]
此数组中有3个序列
1. [ 1 , 2 , 3 ]
2. [ 6 , 7 , 8 ]
3. [ 24 , 25 , 26 ]
而且我需要将这些序列放入单独的2D数组中像这样
[ [ 1 , 2 , 3 ] , [ 6 , 7 , 8 ] , [ 24 , 25 , 26 ] ]
这也是我得到的,但是我无法再处理了
val removedPositions = ArrayList<Int>()
// Code ommited where removedPositions are filled
val removedPositionSequence: ArrayList<ArrayList<Int>> = arrayListOf()
var position = 0
var currentSequence = 0
while (position < removedPositions.size) {
if (position + 1 < removedPositions.size) {
var removedPositionCurrent = removedPositions[position]
var removedPositionNext = removedPositions[position + 1]
var foundDif = false
while (!foundDif){
}
if (removedPositionCurrent + 1 == removedPositionNext) {
removedPositionSequence[currentSequence].add(removedPositionCurrent)
position++
} else {
currentSequence++
}
}
}
[如何做到这一点? (首选Kotlin)
我假设您知道结果将是int[3][3]
类型(即,由3个数组组成的数组,每个数组包含3个整数)。
我的回应基于this article,有关在Java中初始化二维数组。
int[] before = {1, 2, 3, 6, 7, 8, 24, 25, 26};
int[][] after = new int[3][3];
// iterate through "after"
for (int i = 0; i < after.length; i++) {
for (int j = 0; j < after[i].length; j++) {
// fill in with the correpsonding value in "before"
after[i][j] = before[i * after.length + j];
}
}
// print output for checking
for (int i = 0; i < after.length; i++) {
for (int j = 0; j < after[i].length; j++) {
System.out.print(after[i][j] + " ");
}
System.out.print("\n");
}
此输出
1 2 3
6 7 8
24 25 26