I need to take a multidimensional array and flatten it so that if the array looks like:
[1,2,3]
[4,5,6]
Then it is transformed to:
[1,2,3,4,5,6]
I also need to accommodate 3D arrays and flatten them also.
Here is what I've got so far...
class ArrayOperations {
private int[] postFlattenedArray;
public ArrayOperations {
flattenedArray = new int[arrayDimensions[0]];
// arrayDimesnsions of 3,4 is a a 3x4 array; 3,4,5 is a 3x4x5 array
//set up ints to hold total size and dimensionality of array
int prod = 1
int dimensions = 0;
newArray = new int[prod - 1];
for (int i: arrayDimensions) {
prod = prod * i;
dimensions += 1;
}
int k = 0;
for ( int i: arrayDimensions ){
for ( int j = 0; j <= i; j++ ){
newArray[k++] = flattenedArray[j][0][0]
}
}
}
I know I need to run some nested for loops, but I'm having difficulty grasping how I would do this for different array dimensions. So if the array has dimensions; 3,5,6 then I am not sure how to run a loop so that it iterates like:
[1..4][0][0], [0][1..5][0], [0][0][1..6]
似乎最简单的解决方案是实现递归函数flatten
(可能必须通用才能处理任何数组),如果已经平坦或在所有内部数组上递归调用自身,则它将返回数组本身。连接结果。
Try this.
static void flatten(Object object, List<Integer> list) {
if (object.getClass().isArray())
for (int i = 0; i < Array.getLength(object); ++i)
flatten(Array.get(object, i), list);
else
list.add((int)object);
}
static int[] flatten(Object object) {
List<Integer> list = new ArrayList<>();
flatten(object, list);
int size = list.size();
int[] result = new int[size];
for (int i = 0; i < size; ++i)
result[i] = list.get(i);
return result;
}
and
int[][][] array = {
{{1, 2, 3}, {4, 5}},
{{6}, {7, 8, 9}},
};
System.out.println(Arrays.toString(flatten(array)));
// -> [1, 2, 3, 4, 5, 6, 7, 8, 9]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.