patternjavaMinor
Flattening a 2D array to a 1D array based on indexes
Viewed 0 times
arraybasedindexesflattening
Problem
I am certain there is a better way to flatten the array with an optimized approach for the solution.
Example:
[[1,2,24],[12,1241,122],[3,2],[7]] => 1 12 3 7 2 1241 2 24 122
Example:
[[1,2,24],[12,1241,122],[3,2],[7]] => 1 12 3 7 2 1241 2 24 122
public class flattenArray {
public static void main(String args[]) {
int inputLists[][] = {{1,2,24},{12,1241,122},{3,2},{7}};
flattenList(inputLists);
}
public static void flattenList(int input[][]){
List result = new ArrayList();
Map> elements = new HashMap>();
for(int i=0;i temp = new ArrayList();
if(elements.get(j)!=null) {
temp=elements.get(j);
temp.add(input[i][j]);
elements.put(j, temp);
}
else {
temp.add(input[i][j]);
elements.put(j,temp);
}
}
}
for(int i=0;i<input.length;i++){
if(elements.get(i)!=null)
result.addAll(elements.get(i));
}
for(int i=0;i<result.size();i++){
System.out.println(result.get(i)+" ");
}
}
}Solution
Don't use raw types:
Should be:
If you are using Java8, you could simplify the code of the map creation using the function
In the next loop, you are using the break condition incorrectly.
This is a failed test:
You don't need to use
List result = new ArrayList();Should be:
List result = new ArrayList<>();If you are using Java8, you could simplify the code of the map creation using the function
computeIfAbsent:for (int i = 0; i new ArrayList<>()).add(input[i][j]);
}
}In the next loop, you are using the break condition incorrectly.
for(int i=0;i<input.length;i++){ // input.length is not what you need
if(elements.get(i)!=null)
result.addAll(elements.get(i));
}input.length is the number of arrays in your 2d array. If the length of any array is greater than the number of arrays, the code is skipping values.This is a failed test:
Input: {{1,2,24},{12,1241,122}}
Output: 1 12 2 1241
Expected: 1 12 2 1241 24 122You don't need to use
input in the loop, you have a map with all the elements for each index, so you can make the conversion using only the map:// Use a TreeMap instead of a HashMap to have the elements ordered by index
Map> elements = new TreeMap>();
...
for (List e : elements.values()) {
result.addAll(e);
}Code Snippets
List result = new ArrayList();List<Integer> result = new ArrayList<>();for (int i = 0; i < input.length; i++){
for (int j = 0; j < input[i].length; j++){
elements.computeIfAbsent(j, k -> new ArrayList<>()).add(input[i][j]);
}
}for(int i=0;i<input.length;i++){ // input.length is not what you need
if(elements.get(i)!=null)
result.addAll(elements.get(i));
}Input: {{1,2,24},{12,1241,122}}
Output: 1 12 2 1241
Expected: 1 12 2 1241 24 122Context
StackExchange Code Review Q#139480, answer score: 5
Revisions (0)
No revisions yet.