lundi 30 novembre 2015

Boolean algorithm producing true output when output should be false

Basically i am trying to create an algorithm that will test whether a given string is a cover string for a list of strings. A string is a cover string if it contains the characters for every string in the list in a way that maintains the left to right order of the listed strings. For example, for the two strings "cat" and "dog", "cadhpotg" would be a cover string, but "ctadhpog" would not be one.

I have created an algorithm however it is producing the output true when the output should be false, as the given string is a cover String for Strings list1 and list2, but not for list3.

Any help into why this algorithm is producing the wrong output would be highly appreciated.

public class StringProcessing2 {

//ArrayList created and 3 fields added.
public static ArrayList<String> stringList = new ArrayList<>();
public static String list1 = "phillip";
public static String list2 = "micky";  
public static String list3 = "fad"; 

//Algorithm to check whether given String is a cover string.
public static boolean isCover(String coverString){
    int matchedWords = 0;
    stringList.add(list1);
    stringList.add(list2);
    stringList.add(list3);

    //for-loops to iterate through each character of every word in stringList to test whether they appear in
    //coverString in left to right order.
    for(int i = 0; i < stringList.size(); i++){
    int countLetters = 1;
        for(int n = 0; n < (stringList.get(i).length())-1; n++){
            if(coverString.indexOf(stringList.get(i).charAt(n)) <= (coverString.indexOf((stringList.get(i).charAt(n+1)), 
                    coverString.indexOf((stringList.get(i).charAt(n)))))){
                countLetters++;
                if(countLetters == stringList.get(i).length()){
                matchedWords++;                     
                }                                  
            }               
        }
    }
if(matchedWords == stringList.size()){
    return true;
}
else
    return false;   
}

public static void main(String[] args) {
System.out.println(isCover("phillmickyp"));

}


}

Aucun commentaire:

Enregistrer un commentaire