Skip to content

Commit cde6e83

Browse files
Ram PatraRam Patra
Ram Patra
authored and
Ram Patra
committed
FlattenArray done
1 parent 94bfb85 commit cde6e83

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.rampatra.arrays;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
public class FlattenArray {
7+
8+
/**
9+
* Given a nested array like [[1, 2], 3, [4]], return an array like [1, 2, 3, 4, 5].
10+
*
11+
* @param nestedArray an Object array
12+
* @return a list of all elements in the nestedArray but all at the same level
13+
*/
14+
private static List<Integer> flattenArray(Object[] nestedArray) {
15+
if (nestedArray == null || nestedArray.length == 0) return new ArrayList<>();
16+
17+
List<Integer> flattenedArray = new ArrayList<>();
18+
19+
for (Object obj : nestedArray) {
20+
if (obj instanceof Object[]) {
21+
flattenedArray.addAll(flattenArray((Object[]) obj));
22+
} else if (obj instanceof Integer) {
23+
flattenedArray.add((Integer) obj);
24+
}
25+
}
26+
27+
return flattenedArray;
28+
}
29+
30+
public static void main(String[] args) {
31+
System.out.println(flattenArray(null));
32+
System.out.println(flattenArray(new Object[]{null}));
33+
System.out.println(flattenArray(new Object[]{new Object[]{}}));
34+
System.out.println(flattenArray(new Object[]{new Object[]{1, 2}}));
35+
System.out.println(flattenArray(new Object[]{1, 2, new Object[]{4, 5}, 6}));
36+
System.out.println(flattenArray(new Object[]{new Object[]{4, 5}, 1, 2, 6}));
37+
System.out.println(flattenArray(new Object[]{1, 2, 6, new Object[]{4, 5}}));
38+
}
39+
}

0 commit comments

Comments
 (0)