How to solve the following problem more elegantly:...
# getting-started
c
How to solve the following problem more elegantly: Given a keyword list and a input data list. Iterate through input data list and if the item contains one of the keywords, put it together. (Sample data and my brute force way are in the thread)
Copy code
val targetKeywords = listOf("red", "blue", "yellow", "white", "black")
val inputData = listOf(
    "one blue",
    "two gray",
    "three black",
    "four blue",
    "blue",
    "five yellow",
    "six gray",
    "yellow",
    "seven black",
    "nine gray",
    "ten blue",
    "purple"
)

val resultMap = targetKeywords.associateWith { mutableListOf<String>() }
inputData.forEach { item ->
    targetKeywords.forEach { color ->
        if (item.contains(color)) {
            resultMap[color]!! += item
            return@forEach
        }
    }
}

print(resultMap)
// result: {red=[], blue=[one blue, four blue, blue, ten blue], yellow=[five yellow, yellow], white=[], black=[three black, seven black]}
v
Copy code
val resultMap = targetKeywords.associateWith { color ->
    inputData.filter { item -> color in item }
}
?
🦜 1
👌 2
c
Cool. TIL the 'in' keyword
r
note that it's not exactly the most efficient solution so if your data can get large you want to consider alternatives
v
They asked for elegant way, not fast way. 😁
👍 1