Reputation: 429
I want to generate combinations of a string with iterable multiplication.I am try to get combination of string passed to my function.I am passing numbers and get combination of strings like 1 for abc,2 for def
fun generatexCombinations(valuePassed:String){
val list2 = listOf("A", "B", "C")
val list3 = listOf("D", "E", "F")
val list4 = listOf("G", "H", "I")
val list5 = listOf("J", "K", "L")
val list6 = listOf("M", "N", "O")
val list7 = listOf("P", "Q", "R", "S")
val list8 = listOf("T", "U", "V")
val list9 = listOf("W", "X", "Y", "Z")
val listCombination= mutableListOf<List<String>>()
val charArray= valuePassed.toCharArray()
for (char in charArray){
when(char.toString()){
"2"->listCombination.add(list2)
"3"->listCombination.add(list3)
"4"->listCombination.add(list4)
"5"->listCombination.add(list5)
"6"->listCombination.add(list6)
"7"->listCombination.add(list7)
"8"->listCombination.add(list8)
"9"->listCombination.add(list9)
}
}
//this is example of text "biryani"
val combinationOfStrings= list2 * list4*list7*list9*list2*list6*list4
//i want to generate above list to multiplied
// dynamically accroding to string value passed
}
how can i achieve it?
i am using iterable multiplication ,please refer website below
https://www.kotlinresources.com/library/kotlindiscretemathtoolkit/
Upvotes: 0
Views: 3108
Reputation: 170745
First, let's simplify building listCombination
:
val mapOfLists = mapOf(
'2' to listOf("A", "B", "C"),
'3' to listOf("D", "E", "F"),
...)
val charArray= valuePassed.toCharArray()
val listCombination = charArray.map { mapOfLists[it] }.filterNotNull()
Or charArray.map { mapOfLists[it]!! }
if you are certain charArray
won't contain characters for which you don't have a corresponding list. And then it's just
val combinationOfStrings = listCombination.reduce(List::times)
Upvotes: 1
Reputation: 5397
Variables can't be created dynamically. They have to be known at compile-time.
Depending on the situation, you can use arrays/lists or maps instead.
Here's a solution:
// 0 1 2 3 4 5 6 7 8 9
private val lut = listOf("", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ")
.map(String::toList)
fun generateXCombinations(numericString: String) = numericString
.filter(Char::isDigit)
.map { lut[it - '0'] }
.fold(listOf("")) { acc, list ->
val pairs = acc * list
pairs.map { (str, char) -> str + char }
}
EDIT: I included the library and tested it. This code creates a list of strings. Each string is one possible input on the number keyboard.
Upvotes: 1