Depth Array

2

I have an a1 Array

a1=[a2[a3[a4[]],a5]]

I need to know the depth of the array in this case is 3 because in the array a1 has the array a2 and inside of a2 has a3 and inside a3 has a4, that is 3 levels deep.

The depth changes from array to array. a1 is the title of example

    
asked by anonymous 30.05.2014 / 00:04

1 answer

6

If you understand your question well, you can use a recursive function that increments one counter each time it encounters one vector within another.

See an example:

public class ProfundidadeArray {

    public static void main(String[] args) {
        //a1=[a2[a3[a4[]],a5]]
        Object[] a5 = null;
        Object[] a4 = { };
        Object[] a3 = {a4};
        Object[] a2 = {a3};
        Object[] a1 = {a2, a5};

        int depth = depth(a1, 0);
        System.out.println(depth);
    }

    public static int depth(Object[] array, int currentDepth) {
        if (array != null && array.length > 0) {
            int result = 0;
            //itera sobre os elementos do array
            for (Object item : array) {
                //verifica se o item é um array
                if (item != null && item.getClass().isArray()) {
                    //chama o método recursivamente, incrementando a "profundidade"
                    int d = depth((Object[]) item, currentDepth + 1);
                    //somente retorna a maior profundidade
                    if (d > result) {
                        result = d;
                    }
                }
            }
            //retorna a maior profundidade encontrada
            return result;
        }
        return currentDepth;
    }

}
    
30.05.2014 / 00:33