Reputation: 338
I've been trying to create a method that will return true if chars can be used to create a word.
For example, listOf('a', 'b', 'o'), "baobab") -> true
, and it works fine, but with input: listOf('a, 'a', "aa")
it returns false instead of true. Can you please tell me what's wrong?
fun canBuildFrom(chars: List<Char>, word: String): Boolean {
var i = 0
for (item in chars) {
for (char in word) {
if (char.toLowerCase() == item.toLowerCase()) {
i++
}
}
}
return (i == word.length)
}
Upvotes: 1
Views: 402
Reputation: 1681
Here's a simple approach:
fun canBuildFrom(chars: List<Char>, word: String) = word.all { char -> char in chars}
If you want it to be case insensitive:
fun canBuildFrom(chars: List<Char>, word: String) = chars.map(Char::toLowerCase).let { lowerCasedChars ->
word.all { char ->
char.toLowerCase() in lowerCasedChars
}
}
The function can be improved by making it an extension of String
, and accepting broader interfaces that has contains
. i.e. String.canBuildFrom(chars:Collection<Char>)
Why your code didn't work: Your function accepts a list of Chars as an input. For every characters in the string, i
is increased by the number of times the character appears in the list.
Here's some inputs that it might get wrong:
listOf('a', 'a', 'a'), "abb" -> true // should be false
listOf('a', 'b', 'c', 'c'), "abcbcbacbc" -> false // should be true
Upvotes: 2