我在读一本 Ruby 书时遇到了一个函数 .flatten。因此,顾名思义,它会展平如下所示的数组:
a = [ 1, 2, 3 ] #=> [1, 2, 3]
b = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]]
c = [ a, b, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
c.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
我的问题是我正在尝试实现,看看我是否可以在 Java 中提出一种算法,以便在传递一个数组(可能包含)其他数组时,它会返回一个数组。我不知道是否有更简单的方法来执行此操作,或者可能已经在 Java 中实现了它。无论如何,我知道我今天还没有等到时间试一试 :)
首先是我的算法: 创建一个数组列表。
for each element in array as x,
if x element, add to arrayList
else
do a recurse(pass x as arg)
Once done, create a int array with size = arrayList.
Loop arrayList and add each element
到目前为止,这是我的代码:
public class Flatten {
public static void main(String[] args){
a = [ 1, 2, 3 ]
b = [ 4, 5, 6, [7, 8] ]
c = [ a, b, 9, 10 ]
flatten(c);
}
public static int[] flatten(int[] a){
ArrayList<Integer> ar = new ArrayList<Integer>();
for(int i=0; i<a.; i
Object o = a[i];
if(!obj instanceof Object[])){
arr.add(a[i]);
}
else {
int[] newArray = nR
flatten(nR);
}
}
}
int[] results = new int[ar.size()];
for(int i=0; i<ar.size(); i++){
int x = ar.get(i);
int[i] = x;
}
return results;
}
此算法的棘手部分是检查元素是否为数组。还有一个问题是 Java 中的数组应该用它们的大小来声明。
最佳答案
您可以编写一个方法来展平多种 Object
进入List<Integer>
无论嵌套多深。以下方法适用于 int[]
, int[][]
, Integer
, Integer[]
, Integer[][]
, List<Integer>
, List<List<Integer>>
, List<int[]>
等等(您可以轻松地让它返回 int[]
而不是)。
public static List<Integer> flatten(Object object) {
List<Integer> list = new ArrayList<>();
helper(object, list);
return list;
}
private static void helper(Object object, List<Integer> list) {
if (object instanceof Integer) {
list.add((Integer) object);
} else if (object instanceof int[]) {
for (int a : (int[]) object)
list.add(a);
} else if (object instanceof Object[]) {
for (Object obj : (Object[]) object)
helper(obj, list);
} else if (object instanceof Iterable) {
for (Object obj : (Iterable) object)
helper(obj, list);
} else {
throw new IllegalArgumentException();
}
}
但是,这种事情是非常糟糕的想法。如果你发现自己写了一大堆 instanceof
检查,然后根据结果做不同的事情,你很可能做出了一些糟糕的设计决定。
关于java - 在 Java 中实现的 Ruby 的 flatten() 方法的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27808438/