Skip to content

Instantly share code, notes, and snippets.

@fumokmm
Created May 17, 2010 19:58
Show Gist options
  • Save fumokmm/404162 to your computer and use it in GitHub Desktop.
Save fumokmm/404162 to your computer and use it in GitHub Desktop.
Groovyで切符問題を解いてみた http://groovy.g.hatena.ne.jp/fumokmm/20100515/1273935489
// 2, 5, 6, 8の式の組み合わせを生成
def rslt = []
combiAll('+', '-', '*').collect { opes ->
combi(2, 5, 6, 8).collect { nums ->
rslt << [nums, opes + [null]].transpose().flatten()[0..-2]
}
}
// 答えが10になるリストを出力
rslt.collect { toExp(it) }.findAll{ it.ans == 10 }.each {
println "${it} = ${it.simplify} = ${it.ans}"
}
//-----------------------------------------------------------------------------
/** ユニークな組み合わせ */
def combi(Object... list) {
combiAll(list).findAll{ lst -> lst.every{ lst.count(it) == 1 } }
}
/** 全組み合わせ */
def combiAll(Object... list) {
([list] * list.size()).combinations()
}
/** 数式に変換する */
def toExp(exp) {
def temp = new Exp(l:exp[0], op:exp[1], r:exp[2])
(3..exp.size() - 1).step(2) { i ->
temp = new Exp(l:temp, op:exp[i], r:exp[i + 1])
}
temp
}
/** 数式を表現するクラス */
class Exp {
/** 左辺、右辺、オペレータ */
def l, r, op
/** 数式の文字列表現 */
String toString() { "($l $op $r)" }
/** 答え */
int getAns() { Eval.me(toString()) }
/** シンプル化 */
String getSimplify(){
def result = '' << ''
def calc = { num ->
try {
if (opLevel(num.op) <= opLevel(op)) result << num.simplify
else result << "(${num.simplify})"
} catch(e) { result << num }
}
calc(l)
result << " ${op} "
calc(r)
}
/** オペレータの優先度 */
static opLevel(op) { op in ['*'] ? 1 : 2 }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment