Home > Back-end >  Comparing string array to a character array
Comparing string array to a character array

Time:10-21

String[] dictionaryArr= new String[]{"mee","go","bat","me","eat","goal","boy","run","go"};

char[] characterArr={'e','o','b','a','m','g','l'};

OR

String[] characterArr= new String[]{"e","o","b","a","m","g","l"};

I want to compare dictionaryArr to characterArr in such a way that it will

output: go, me, goal

Note: it did'nt output "mee" because letter "e" is repeated and there is only one 'e' in characterArr also it shouldn't print "go" twice

Here's what I have so far:

for (int i = 0; i < dictionaryArr.length ; i  ) {
    for (int j = 0; j < characterArr.length ; j  ) {
        if (dictionaryArr[i] == characterArr[j]) {
            System.out.println(dictionaryArr[i]);
        }
    }
}

CodePudding user response:

You're printing the word as soon as you find a matching letter. What you need to do is print it only after there are no missing letters. One way to do that is to create a list and check and remove each character as you iterate:

private static boolean matches(String word, String[] characterArr) {
    List<String> chars = new ArrayList<>(Arrays.asList(characterArr));
    for (String c : word.split("")) {
        if (!chars.remove(c)) {
            return false;
        }
    }
    return true;
}

We can call this in a distinct stream to easily avoid duplicate words:

Arrays.stream(dictionaryArr)
        .distinct()
        .filter(word -> matches(word, characterArr))
        .forEachOrdered(System.out::println);

Ideone Demo

CodePudding user response:

shmosel has already given a pretty god answer using Stream. Here is a more oldschool solution.

List<String> filteredDictionary = new ArrayList<>();
for (String entry: dictionaryArr) {
    // Create a editable collection that contains a copy of the values of characterArr
    List<String> characters = new ArrayList<>();
    for (char c : characterArr) {
        characters.add(c   "");
    }
    boolean print = true;
    for (char c : entry.toCharArray()) {
        // If the character isn't in the characters list characters.remove returns false
        if (!characters.remove(c   "")) {
            print = false;
            break;
        }
    }
    // Check for duplicates with contains.
    if (print && !filteredDictionary.contains(entry)) {
        filteredDictionary.add(entry);
    }
}
filteredDictionary.forEach(System.out::println);
  • Related