今天我們將生成所有可能的數學方程。快速生成字符串組合的方法
給出這樣的語法:[1,0][+,-][2,3]
這意味着我們需要所有具有1或0作爲第一個字符,+或 - 作爲第二個字符,以及2或3作爲第三個字符的字符串。
所以,這8個可能的組合
1+2
1+3
1-2
1-3
0+2
0+3
0-2
0-3
我的方法是有效的,但它會得到稍微大的值相當緩慢。我解析上面的語法併爲每個標記創建一個可能值的數組,並將其放入一個數組中。
equation_set = [];
tokens = [['1','0'],['+','-'],['2','3']]
// Initialize empty equation_set
token = tokens.pop();
foreach symbol in tokens
question_set.add(symbol)
// We now have a question_set = ['1','0']
// and tokens = [['+','-']['2','3']]
//
// Now we need to fill out the rest of the possible equations
foreach token in tokens
new_question_set = []
foreach symbol in token
foreach question in question_set
new_question_set.add(question + symbol)
question_set = new_question_set
我相信應該給我我想要的結果,但所有這些foreach讓我感到緊張。我現在纔想出了這個算法,但我覺得我錯過了一些明顯的東西。我們正在搞亂combinatorics,所以如果它非常慢,我不會感到驚訝,但感覺這並不是什麼特別的東西。
乾杯!
你需要一次生成它們嗎?即,您是否需要能夠同時收集包含所有這些信息的集合。 – Wug