开发者

How to embed a list into a list in Groovy, given some conditions?

I have a groovy code like this :

main = []
b="ogodt开发者_开发技巧sneeencs"
def input = ["go", "good", "do", "sentences", "tense", "scen"]
(0..(input.size()-1)).each{ Sp(input[it]) }
def Sp(def a)
{
        flag = false
        list = []
        (0..(a.size()-1)).collect { list << a[it] }
        ans = list.permutations().each { temp =  it.join()
                                           if(b.find("$temp"))
                                           {
                                                main << it
                                                flag = true
                                           }
}
        if(flag == false)
                main << null

}
println main

which outputs :

[[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]]

The thing I'm doing here is to find the possible permutations that have occurred in b using the input. And I'm getting the output as needed. But if the output is noticed carefully, for the same input go i.e(input[0]) produces the first two outputs i.e main[0] and main[1]. Since to keep a index kind of way(i.e for which input which output main is produced), how I can change the above code, so that the output returns like this :

[[[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]]

Indicating that the first both outputs is same from same input, in our case it is input[0].

Thanks in advance.


Artur's solution can be further groovified to:

def Sp(a) {
  (a as List).permutations().findAll { s -> b.find( s.join() ) }
}


I've also simplified your code a bit:

b="ogodtsneeencs"
def input = ["go", "good", "do", "sentences", "tense", "scen"]
main = input.collect { Sp(it) }
def Sp(a) {
  def list = a as List
  def result = []
  list.permutations().each {
    if (b.find(it.join())) result << it
  }
  result
}

This would output:

[[[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]]]

If you'd like to have all the singleton sets without the enclosing set (as you wrote in your example, although I find it as a bit impractical), then you can just swap the last line of Sp to:

result.size() == 1 ? result[0] : result 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜