Search code examples
groovyjvm-languages

How I Can Find The Possible Combinations That Form The Given Input


I have a list like this, say for example the list name is output which has:

[[[o, g], [g, o]], [[o, g, o, d]], [[o, d]], [[t, s, n, e, e, e, n, c, s]], [[t, s, n, e, e]], [[e, n, c, s]]]

And I have a input like this, say input is:

ogodtsneeencs

Now obviously, the input can be formed from output. I tried the subsequences() of output to find the possible combinations that form the input, but the thing is it wont work for all the input.

Can anyone say me how I can find the combinations of output that will be equal to input? And possibly store in some list.

Thanks in advance.


Solution

  • Given just this small set of test data you have supplied, I came up with this:

    def list = [[['o', 'g'], ['g', 'o']], [['o', 'g', 'o', 'd']], [['o', 'd']], [['t', 's', 'n', 'e', 'e', 'e', 'n', 'c', 's']], [['t', 's', 'n', 'e', 'e']], [['e', 'n', 'c', 's']]]
    
    // For every combination of the lists
    def result = list.combinations().collect { combination ->
      // Join them into strings
      combination*.join().with { stringcombo ->
        // Then find every string in the list
        stringcombo.findAll { word ->
          // Which is not a substring of another string in the list
          (stringcombo - word).every { it.indexOf( word ) == -1 }
        }
      }.permutations()*.join() // Then get every String permutation of these remaining strings
    }.flatten().unique() // and get them into a single unique list
    
    // And print them out
    result.each {
      println it
    }
    

    Which prints out:

    ogodtsneeencs
    tsneeencsogod
    

    Without more data, it's hard to tell if it is correct, but it might be a good starting place for you

    edit

    Updated to return all permutations of the valid tokens