user1043911
user1043911

Reputation: 1

How do I compare two strings of different lengths and return false for just 1 invalid char?

public boolean setValidColor(String input, String colors) {
    int exists;
    isValidColor = true;
    char[] colorch = colors.toCharArray();
    Arrays.sort(colorch);
    for(int i = 0; i < input.length(); i++)
    {
        exists = Arrays.binarySearch(colorch, input.charAt(i));
        if(exists == -1)
        {
            isValidColor = false;
            break;
        }
    }  
    return isValidColor;
}

I'm having trouble comparing two strings of different lengths and returning false at just 1 instance of an invalid input..

For example: possible colors are RGOPYB and input colors are YZOR. The 'Z' is not a possibility and I need to code to return false but the code keeps returning true. Where am I going wrong?

edit: There is more to this code than just this (doing OOP), this is just a method that I keep running into trouble on.

Upvotes: 0

Views: 3503

Answers (4)

Mikael Sundberg
Mikael Sundberg

Reputation: 783

You might want to convert it into lists. Then you can use retainAll or removeAll and see if the list is empty/the same.

Something like:

 List validInput=   input.retainAll(colors);
if(validInput.equals(input)) {
 return true;
} 
return false;

Upvotes: 0

Stephen C
Stephen C

Reputation: 718826

I think that Ted Hopp has found your problem.


I'd just like to point out that your current approach (sorting and using binary search) is likely to be significantly slower than a simple O(N^2) algorithm using colors.indexOf(input.charAt(i)). You can improve things by "hoisting" the creation of the sorted array of characters. (Or maybe just require the colors string to be sorted as a precondition.) But even with that change, the indexOf approach will still be faster if the color array is small enough.

The moral of this is that optimization (especially premature optimization) can make things worse if you don't include a realistic characterization of the expected data.

(Now maybe "RGOPYB" is not indicative of the actual number of colors. But if that's the case, you ought to tell us ...)

Upvotes: 0

Udi
Udi

Reputation: 1110

From java.util.Arrays: index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). Means your condition should be:

   if(exists < 0)

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234797

Arrays.binarySearch will only return -1 if the value being searched for should be inserted at position 0. For other values that are not found, it returns other negative values. Test for exist < 0 instead of exists == -1.

Upvotes: 6

Related Questions