Home > Blockchain >  Kotlin print all combinations of List<Strings>
Kotlin print all combinations of List<Strings>

Time:12-08

I am trying to print all combinations of a List in Kotlin.

My script has a variable message with a encrypted message. What I want is all combinations of that variable (splitted on space). I have managed to split it on space so it becomes a List of Strings.

Example of desired output:

  1. Y2MPyYU4kblEXrEfExry4AIRAjqdke JyQQN50Uj5GuCu5rE66lEzQXB5bE VOlNGRoU06Ny4vh/gzSPFV0mHUrxaaAVt1BwN1WN1HFT7baIejtR5KyG6 JK8yC70CpuPZV610coCiWzdFICcgEtAdQaesScLrg495kxofzG3EGvA=

  2. Y2MPyYU4kblEXrEfExry4AIRAjqdke JyQQN50Uj5GuCu5rE66lEzQXB5bE JK8yC70CpuPZV610coCiWzdFICcgEtAdQaesScLrg495kxofzG3EGvA= VOlNGRoU06Ny4vh/gzSPFV0mHUrxaaAVt1BwN1WN1HFT7baIejtR5KyG6

  3. VOlNGRoU06Ny4vh/gzSPFV0mHUrxaaAVt1BwN1WN1HFT7baIejtR5KyG6 JK8yC70CpuPZV610coCiWzdFICcgEtAdQaesScLrg495kxofzG3EGvA= Y2MPyYU4kblEXrEfExry4AIRAjqdke JyQQN50Uj5GuCu5rE66lEzQXB5bE

etc..

My code:

// Input data
var message: String = "Y2MPyYU4kblEXrEfExry4AIRAjqdke JyQQN50Uj5GuCu5rE66lEzQXB5bE VOlNGRoU06Ny4vh/gzSPFV0mHUrxaaAVt1BwN1WN1HFT7baIejtR5KyG6 JK8yC70CpuPZV610coCiWzdFICcgEtAdQaesScLrg495kxofzG3EGvA="

// Info Message
var messageLength = message.length
println("Message = $message\n")

// Info parts
var messageSplitOnSpace = message.split(" ")
for (part in messageSplitOnSpace) {
    var partLength = part.length
    println("Part = $part\n")
}

// Print all combinations 
var mixSize: Int = messageSplitOnSpace.size*messageSplitOnSpace.size;
for (part in messageSplitOnSpace) {

}

Output:

Message = Y2MPyYU4kblEXrEfExry4AIRAjqdke JyQQN50Uj5GuCu5rE66lEzQXB5bE VOlNGRoU06Ny4vh/gzSPFV0mHUrxaaAVt1BwN1WN1HFT7baIejtR5KyG6 JK8yC70CpuPZV610coCiWzdFICcgEtAdQaesScLrg495kxofzG3EGvA=

Part = Y2MPyYU4kblEXrEfExry4AIRAjqdke JyQQN50Uj5GuCu5rE66lEzQXB5bE

Part = VOlNGRoU06Ny4vh/gzSPFV0mHUrxaaAVt1BwN1WN1HFT7baIejtR5KyG6

Part = JK8yC70CpuPZV610coCiWzdFICcgEtAdQaesScLrg495kxofzG3EGvA=

CodePudding user response:

var message: String = "Y2MPyYU4kblEXrEfExry4AIRAjqdke JyQQN50Uj5GuCu5rE66lEzQXB5bE VOlNGRoU06Ny4vh/gzSPFV0mHUrxaaAVt1BwN1WN1HFT7baIejtR5KyG6 JK8yC70CpuPZV610coCiWzdFICcgEtAdQaesScLrg495kxofzG3EGvA="

var items = message.split(" ")

val result = items
  .flatMap { i1 ->
    items.flatMap { i2 ->
      items.mapNotNull { i3 ->
        val combination = listOf(i1, i2, i3).distinct()
        if (combination.count() == 3) combination else null
      }
    }
  }
  .mapIndexed { index, it -> ""   (index   1)   ". "   it[0]   "\n   "   it[1]   "\n   "   it[2] }

for (item in result) {
  println(item   "\n")
}
  • Related