-1

数字の配列/リストがあります。各番号には特定の優先度/重要度があります。

数字のすべての組み合わせを生成するアルゴリズムが必要ですが、最も重要なフォーム番号から始めます。

e.g. [number, priority]: [1,1], [2,3], [3,2]. Highest priority is 1.

組み合わせ:

1, 3, 2, 1 1, 1 3, 3 3, 3 1, 1 2, 3 2, 2 1, 2 2, 1 1 1, 1 1 3, 1 3 1...

これを行う方法はありますか?もちろん、一定数の組み合わせを生成したいと考えています。

4

2 に答える 2

1

すべての順列ではなく、すべての組み合わせを探しているようです(数字のセットが繰り返されていないので、数字のセットだけを気にし、そのセット内の順序は気にしません)。

ここにあなたへのヒントがあります-最初に1からnまでの数字の可能なすべての組み合わせを生成するコードを書き留めてから、それらの数字とあなたが与えられた数字の間で重みを考慮して単純な全単射を行います。

于 2012-05-03T11:57:55.030 に答える
1

回答をサンプルコードに変更しました。この方法では、再帰さえ必要ありません。最初に要素を優先度順に並べ替える必要があります。例は Perl であり、疑似コードからそう遠くない

@numbers = (1, 3, 2, 4);

push(@result, @numbers);
push(@working_list, @numbers);
for ($i = 1; $i < @numbers; $i++) {  # We loop exactly for the length of the array (-1 because the first iteration is already inside)
    my @result_list;
    for $result (@working_list) { # get the result of the last iteration of $i
        for $number (@numbers) { # iterate the numbers
            push (@result_list, "$result $number");  # adding the numbers
        }
    }

    push(@result, @result_list); # push the last result to final result list
    undef @working_list;
    push(@working_list, @result_list); # use the last result as a start point for next $i iteration

}

print join(', ', @result);
于 2012-05-03T12:00:23.937 に答える