Hi all,
what is the best way to obtain all the possible 3-items groups out of 8 elements (0-7) with repetitions?
This would be D'8,3 = 8^3 = 512 groups. I want to save them in an array, like
unsigned int array[512][3]; What is the best approach?
Hi all,
what is the best way to obtain all the possible 3-items groups out of 8 elements (0-7) with repetitions?
This would be D'8,3 = 8^3 = 512 groups. I want to save them in an array, like
unsigned int array[512][3]; What is the best approach?
Short answer: if you really want ordered 3‑tuples from 0..7 (8^3 = 512) the simplest safe options are either the usual triple loop or treating the row index as a base‑8 number and extracting digits. As showed, nested loops are perfectly fine; was also right that new is not a C operator.
A compact alternative is to fill the array by converting the linear index into three base‑8 digits. That produces the same ordering as an outer–middle–inner loop (i.e. element0 changes slowest, element2 fastest):
#include <stdint.h>
unsigned int array[512][3];
for (unsigned idx = 0; idx < 512; ++idx) {
array[idx][0] = idx / 64; /* 8^2 */
array[idx][1] = (idx / 8) % 8; /* 8^1 */
array[idx][2] = idx % 8; /* 8^0 */
} Practical tips: store values in uint8_t (or unsigned char) instead of unsigned int if you only need 0..7 — that cuts memory and helps cache locality. For a variable tuple length r and base n, generalize by repeatedly taking idx % n and dividing idx / n to fill digits from least to most significant.
If order does not matter (combinations with repetition), the count is C(8+3-1,3)=120 and you must generate nondecreasing triples (e.g. i <= j <= k) rather than all ordered tuples. For very large search spaces avoid storing all tuples: generate each tuple on the fly and process it immediately.
int array[][]=new int[512][3];
int count=0;
for(int i=0;i<8;i++)
for(int j=0;j<8;j++)
for(int k=0;k<8;k++){
array[count][0]=i;
array[count][1]=j;
array[count][2]=k;
count++;
}
for(int i=0;i<512;i++)
{ System.out.print("array["+i+"]:");
for(int j=0;j<3;j++)
System.out.print(array[i][j]+" ");
System.out.println("");
}
In C:
unsigned int array[][]=new int[512][3];
int count=0;
int i,j,k;
for(i=0;i<8;i++)
for(j=0;j<8;j++)
for(k=0;k<8;k++){
array[count][0]=i;
array[count][1]=j;
array[count][2]=k;
count++;
}
for(i=0;i<512;i++)
{
printf("\n array[%d]:",i);
for(j=0;j<3;j++)
printf("%d",array[i][j]);
} Thanks for the reply biswajit_cs07, very appreciated.
PS: "new" operator doesn't exist in C. :)
Sorry I did not check the code. Just converted it from java to C without compilation.
Ya there is no new operator in C. If you know that you can easily rectify it.
Thanks.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.