【问题标题】:How I Can Find The Possible Combinations That Form The Given Input我如何找到形成给定输入的可能组合
【发布时间】:2011-10-19 22:17:01
【问题描述】:

我有一个这样的列表,例如列表名称是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]]]

我有这样的输入,比如input 是:

ogodtsneeencs

现在很明显,input 可以由output 组成。我尝试了outputsubsequences() 来找到形成input 的可能组合,但问题是它不适用于所有input

谁能告诉我如何找到等于inputoutput 组合?并且可能存储在一些list 中。

提前致谢。

【问题讨论】:

  • 你说obviously,但问题并不那么明显:-(
  • 所以我们找不到? :( 想删除我的问题?
  • 不是我们找不到……而是我不知道你在问什么。您想从该列表中重新生成ogodtsneeencs 吗?或者你只想生成其他东西?
  • 是的,我想从列表中重新生成ogodtsneeencs。但是有很多方法可以使用output 重新生成它。我想要所有这些方法。我现在清楚了吗?
  • @tim_yates:好吧,我认为subsequences() 会起作用。但问题是它只在某些情况下有效。并非在所有情况下...

标签: groovy jvm-languages


【解决方案1】:

鉴于您提供的这一小部分测试数据,我想出了这个:

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
}

打印出来的:

ogodtsneeencs
tsneeencsogod

没有更多数据,很难判断它是否正确,但它可能是您的一个良好起点

编辑

更新为返回有效令牌的所有排列

【讨论】:

  • @Ant 已更新以返回有效令牌的所有排列
猜你喜欢
  • 1970-01-01
  • 2018-12-07
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-19
相关资源
最近更新 更多