Profundidade Array

Asked

Viewed 176 times

2

I have an a1 Array

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

I need to know the depth of the array now in this case is 3 because inside the a1 array has the a2 array and inside the a2 has the A3 and inside the A3 has the A4, ie 3 levels of depth.

the depth changes from array to array the a1 is the example title

1 answer

6

If I understand your question correctly, you can use a recursive function that increments one counter each time you find one vector within another.

Take 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;
    }

}
  • Note: I made a subtle change that I believe has made the algorithm a little simpler.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.