1

Okay, so I'm trying to finish task from codewars which says exactly:

"You get an array of arrays. If you sort the arrays by their length, you will see, that their length-values are consecutive. But one array is missing!

You have to write a method, that return the length of the missing array.

Example: [[1, 2], [4, 5, 1, 1], [1], [5, 6, 7, 8, 9]] --> 3

If the array of arrays is null/nil or empty, the method should return 0.

When an array in the array is null or empty, the method should return 0 too! There will always be a missing element and its length will be always between the given arrays. "

I wrote the code like this:

package codewars;

import java.util.ArrayList;
import java.util.Collections;

public class CodewarsMissingArrays {

static int wynik = 0;

public static int getLengthOfMissingArray(Object[][] arrayOfArrays) 
{   

    if (arrayOfArrays.length == 0) {
        return wynik = 0;
    } else {

    ArrayList<Integer> lista = new ArrayList<Integer>();

    for (int y = 0; y < arrayOfArrays.length; y++) {
        if (arrayOfArrays[y].length == 0){
            return wynik = 0;
        } else {
        lista.add(arrayOfArrays[y].length);
        }
    }

    Collections.sort(lista);

    for ( int x = lista.size() - 1; x >= 0 ; x--) {
        if ( lista.get(x) - lista.get(x - 1) != 1 ) {
            wynik = lista.get(x) - 1;
            return wynik;
        }
    }

    }

    return wynik;
}
}

And testing class:

package codewars;

public class CodewarsTest {

public static void main(String[] args) {
    System.out.println(CodewarsMissingArrays.getLengthOfMissingArray(new Object[][] { new Object[] { 1, 2 }, new Object[] { 4, 5, 1, 1 }, new Object[] { 1 }, new Object[] { 5, 6, 7, 8, 9 }} ));
}

}

And locally it works fine, but Kata returns NullPointerException:

java.lang.NullPointerException
at Kata.getLengthOfMissingArray(Kata.java:13)
at KataTests.BasicTests(KataTests.java:19)

And I have no idea what might be wrong, I assume that it might be something with the arrayOfArrays object, but I have no clue what exactly might be wrong.

Can you help me?

0 Answers0