Question

Without a for loop, is there any way to see if a value exists in a multidimensional array? I found

 Arrays.asList(*ArrayName*).contains(*itemToFind*)

but that will only search the first dimension of the array, and I need to search 2 dimensions.

Était-ce utile?

La solution

I've created a two-dimensional array that contains 5 rows and 5 columns. The array is an int type and have initialized with a value i*j. Already exists a method that takes a row number and value to search for.

private static Integer[][] myarray = new Integer[5][5];

public static boolean exists(int row, int value) {
    if(row >= myarray.length) return false;
    List<Integer> rowvalues = Arrays.asList(Arrays.asList(myarray).get(row));
    if(rowvalues.contains(value)) return true;
    return exists(row+1, value);
}

Autres conseils

You can do almost anything with recursion if you care to headache your way through the logic of it. In this case it shouldn't be too hard

private boolean checkForValue(int val, int row, int col){
    if(row == numRows && col == numCols) 
        return false;
    else{
        if(values[row][col] == val)
            return true
        else if(col < (numCols - 1))
            checkForValue(val, row, col + 1);
        else
            checkForValue(val, row + 1, 1);
    }
}

However, if you are just wanting to save time I think the for loop really is pretty efficient to start

private boolean checkForValue(int val){
    for(int i = 0; i < numRows; i++){
        for(int j = 0; j < numCols; j++){
            if(values[i][j] == val) return true;
        }
    }
    return false; //it will reach here if return true was not called.
}

Neither is too rough.

Yes.

You can use Bloom filters (http://en.wikipedia.org/wiki/Bloom_filter) or create a tree-based index for the keys of your Array, such as a Trie (http://en.wikipedia.org/wiki/Trie)

Basically you'd need a data structure to look for the values, and not for the keys. It would not cost much space or speed since you could re-use the references of the value objects on both data structures (yours and the one you elect)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top