2016-09-08 22 views
0

私は任意の数のリストを取り、要素の組み合わせのリストを返すが、各リストから1つの要素のみを結合したい。私が持っているのはどこから始めるべきかわからないので、sudoのコードだけです。いくつかのリストの要素を組み合わせる

私はCombining the elements of 2 listsの質問でこのプログラムの解決策を見つけましたが、私はそのスカラコードを理解していません。私はTclに自分のプログラムを書いていますが、もしあなたが私のJavaやPython、擬似コードなど何でも自由に答えを書いてくれるのを助けてくれれば助かります。誰でも私に人生に次の擬似コードを持たせることができますか?例えば

:ここ

# example: {a b} {c} {d e} 
    # returns: {a c d} {a c e} {b c d} {b c e} 
    # how? 
    # example: {a b} {c} {d e} 
    # iters: 0  0 0 
    #   0  0  1 
    #    1 0 0 
    #    1 0  1 
    # 
    # 
    # set done false 
    # 
    # while {!done} { 
    # 
    # list append combination_of_list due to iteration counts 
    # 
    # foreach list $lists { 
    #  increment the correct count (specifically {0->1} {0->0} {0->1}) } 
    #  reset the approapraite counts to 0 
    # } 
    # 
    # if all the counts in all the lists are at or above their max { 
    #  set done true 
    # } 
    # } 

答えて

1

様々なTclのソリューションは、このページで説明されていますこのように実行すると、結果が表示されます。

% product {a b} {c} {d e} 
{a c d} {a c e} {b c d} {b c e} 

ドキュメント: foreachlappendlistprocreturnset{*} (syntax)

+0

Donal Fellowsはアメリカ人の英雄です。 –

+0

ドナル・フェローズは、強烈な目を持つアルゴリズムの男です。 –

1

すべての組み合わせを生成するアルゴリズムを説明する擬似コードである。

list_of_lists = {{a b}{c}{d e}} 

def copy(list): 
    copy = {} 
    for element in list: 
     copy.add(element) 
    return copy; 
def combine(list1, list2): 
    combinations = {} 
    for item1 in list1: 
     for item2 in list2: 
      combination = copy(item1) 
      combination.add(item2) 
      combinations.add(combination) 
    return combinations 

results = {{}} 
while list_of_lists.length>0: 
    results = combine(results, list_of_lists[0]) 
    list_of_lists.remove(0) 

それと組み合わされる{{a} {b}}を生成{a b c}{{}}を組み合わせることによって開始します{c}を生成し、次の反復時に{{a c} {b c}}を生成する。

更新: Javascriptのバージョン:

proc product args { 
    set xs {{}} 
    foreach ys $args { 
     set result {} 
     foreach x $xs { 
      foreach y $ys { 
       lappend result [list {*}$x $y] 
      } 
     } 
     set xs $result 
    } 
    return $xs 
} 

Cartesian product of a list of lists

ドナル・フェローズは、ページの最後に、この変化を提示:

var list_of_lists = [["a", "b"],["c"],["d", "e"]]; 

function copy(list) { 
    var copy = []; 
    for (element of list) { 
     copy.push(element); 
    } 
    return copy; 
} 

function combine(list1, list2) { 
    var combinations = []; 
    for (let item1 of list1) { 
     var combination = copy(item1); 
     for (let item2 of list2){ 
      combination.push(item2); 
      combinations.push(combination); 
     } 

    } 
    return combinations; 
} 

results = [[]] 
while (list_of_lists.length>0) { 
    results = combine(results, list_of_lists[0]); 
    list_of_lists.splice(0,1); 
} 
console.log(results); 
+0

私はこの権利を実装願っています。よく分かりません。私が得た最終的な出力は正しくありませんでした: '{a c d} {a c d e} {a b c d} {a b c d e} 'ですが、コードを見て、正しく実装しているかどうかを確認します。 –

+0

私は擬似コードを2行反転させて更新しました –

関連する問題