現在、私はこのコード スニペットを持っています。これは、私が望むことを行っています。いくつかのオブジェクトを指定すると、それらの間で可能なすべての組み合わせが作成されます。
この例では、4 つのオブジェクト (0、1、2、3) があると想定し、4 つのオブジェクトの可能な組み合わせ (0、1、2、3、01 (0 と 1 の組み合わせ)、02、 03、12、13、23、012、013、023、123、0123)。
2^4 - 1 = 15 通りの組み合わせがあり、通常は 2^オブジェクト数 - 1 通りの組み合わせがあることに注意してください。
このコードで作成されるオブジェクトの順序は、0 -> 01 -> 012 -> 0123 -> 013 -> 02 -> 023 -> 03 -> 1 -> 12 -> 123 -> 13 -> 2 -> です。 23 -> 3
初期オブジェクトとその数を取得する方法は、コードの別の場所で定義されています。
int count = 4; //this is gotten elsewhere
int currPos = 0;
var objects = new Object[(2^count)-1];
for (int i = 0; i < count; i++) //loop that creates combinations of only one object
{
Object obj = new Object(...);
objects[currPos] = obj;
currPos += 1;
for (int j = i + 1; j < count; j++) //loop that creates combinations of two objects
{
Object obj = new Object(...);
objects[currPos] = obj;
currPos += 1;
for (int k = j + 1; k < count; k++) //loop that creates combinations of three objects
{
Object obj = new Object(...);
objects[currPos] = obj;
currPos += 1;
for (int l = k + 1; l < count; l++) //loop that creates combinations of four objects
{
Object obj = new Object(...);
objects[currPos] = obj;
currPos += 1;
}
}
}
}
正しい結果が得られたにもかかわらず、これはハードコーディングされているため、オブジェクトの数 (最大の組み合わせも決定します。この例では 4 つ) で、再帰関数に変更する方法を探しています (ただし、その機能は維持されます)。パラメータとして渡します。
以下のコードのようなことをしようとしましたが、結果がありません。これは主に、必要に応じて「前の」ループに移動できないように見えるためです。たとえば、0123 から 013 に移動します。
int count = 4;
int currPos = 0;
var objects = new Object[(2^count)-1];
combinations(count, 0, currPos, objects); //called elsewhere
private void combinations(int numberOfObjects, int j, int count, int currPos, Object[] objects)
{
if (numberOfObjects == count)
{
for (int k = j; k < count; k++)
{
Object obj = new Object(...);
objects[currPos] = obj;
currPos += 1;
generateCombinations(numberOfObjects - 1, j + 1, count, currPos, objects);
}
}
if (numberOfObjects < count)
{
for (int l = j; l < count; l++)
{
Object obj = new Object(...);
objects[currPos] = obj;
currPos += 1;
(...)
generateCombinations(..., ..., count, currPos, objects);
}
}
}