blah blah blah is here! blah blah » Close

up1down
link

Hi everyone

I'm trying to create all possible combinations without repetitions.

I need to create 3 numbers with values from 1-10 with no repetitions.

Ex: 1-2-3
1-3-4
1-2-4
1-3-5
2-3-5
and so on..... I need a loop or something to create all this and fill a 2d array[120,3]

last answered one year ago

2 answers

up1down
link

don't know whether you want a [120,3] array or all possible values, but here's the latter.

List<byte[]> data = new List<byte[]>( );
for ( byte a = 1; a <= 10; ++a ) {
for ( byte b = 1; b <= 10; ++b ) {
for ( byte c = 1; c <= 10; ++c ) {
data.Add( new byte[] { a, b, c } );
}
}
}
byte[][] values = data.ToArray( );

up1down
link

MadHatter's code works but doesn't exclude repetitions.

I've adjusted it below to do that and used ints rather than bytes to avoid casts:

using System;


class Program
{
static void Main()
{
int[][] data = new int[120][];
int index = 0;

for ( int a = 1; a <= 8; ++a )
{
for ( int b = a + 1; b <= 9; ++b )
{
for ( int c = b + 1; c <= 10; ++c )
{
data[index++] = new int[] { a, b, c };
}
}
}

// check it worked
for ( int i = 0; i < 120; ++i )
{
Console.WriteLine("{0:D3} -> {1}-{2}-{3}", i + 1, data[i][0], data[i][1], data[i][2]);
}

Console.ReadKey();
}
}

Feedback