[ 3 ,0,1,4, 4 ,0,3,2,1, 3 ,1,2,4 , 3 ,3,4,2, 3 ,0,4,3]
上面数组中的粗体元素表示该元素后面有多少元素属于该块,将这些块划分为数组并将它们存储在多维数组中的最佳方法是什么,其中每行基本上都包含一个块,这样我们就可以了有这样的事情:
int numOfChunks = 5 //Assuming we already know the number of chunks in the array
int[][] array = { {0, 1, 4},
{0, 3, 2, 1},
{1, 2, 4},
{3, 4, 2},
{0, 4, 3} }
提前致谢。
答案 0 :(得分:1)
有一种预先计算数组长度的替代方法 - 使用List来存储int []数组,因为它们被提取。最后将它转换为正确大小的数组:
public static int[][] blockSplitter(int[] data) {
List<int[]> blocks = new ArrayList<int[]>();
for (int i = 0; i < data.length;) {
int blockSize = data[i];
int[] block = Arrays.copyOfRange(data, i + 1, i + blockSize + 1);
blocks.add(block);
i += (blockSize + 1);
}
return (int[][]) blocks.toArray(new int[blocks.size()][]);
}
答案 1 :(得分:1)
我认为你唯一的问题是找出每一行的列大小。请参阅内联评论。
public static int[][] get2DArray(int[] raw){
int max = 0; // Max number of items in a row
int totalRows = 0;
// Get the row with maximum elements and total number of rows
for(int i = 0; i < raw.length;){
if(raw[i] > max){
max = raw[i];
}
totalRows++;
i += raw[i] + 1;
}
// Declare a 2d array with just rows
// Since different rows can have different number of columns,
// we cannot populate the column size yet
int[][] array = new int[totalRows][];
int ctr = 0; // items indices
for(int i = 0; i < totalRows; i++){
// Since now we know the column size for the current row, let's create
array[i] = new int[raw[ctr]];
// Loop from 0 to column size
for(int j = 0; j < raw[ctr]; j++){
// We use the row start + 1 to get the appropriate column value
array[i][j] = raw[j + 1 + ctr];
}
// Let's point the ctr to the start of the next row
ctr += raw[ctr] + 1;
}
return array;
}
测试方法:
int[] raw = {3, 0, 1, 4, 4, 0, 3, 2, 1, 3, 1, 2, 4, 3, 3, 4, 2, 3, 0, 4, 3};
int[][] array = get2DArray(raw);
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[i].length; j++){
System.out.print(array[i][j] + "\t");
}
System.out.println();
}
输出:
0 1 4
0 3 2 1
1 2 4
3 4 2
0 4 3
答案 2 :(得分:0)
首先,您需要确定最大数字,以便您可以创建该数字的多维数组。
让我们在你的例子中说Biggest number是4然后你需要定义4的数组然后安排元素。
如果任何元素不适合要求分配为0,那么结构应遵循4x4
答案 3 :(得分:0)
我的解决方案是故意模糊的,所以不要那么简单地为你编写代码。
两个循环,一个用于计算可提取的部分或块(行)的数量,创建第二个此大小的数组,然后另一个循环以提取第二个数组的第二个维(列)
int i = 0;
int rows = 0; //extractable sections, in this case 5
do //if you know the number of chunks in advance, may not be needed
{
//add value in array[i] to i
//keep track of largest array[i] value
rows++
}while(i<array.length)
//create new array of size 'rows' by the largest array[i] value
int i2 = 0;
do
{
//create an array of the next array[i] numbers
//put in rows[i2] and increment i2
//add value of array[i] to i
}while(i<array.length)
答案 4 :(得分:0)
Google Guava Lists.partition
很棒的图书馆,看看它