Create Combinations from Set {1,2,3,4,5} with 'C' Program

  • Thread starter Thread starter gradnu
  • Start date Start date
  • Tags Tags
    Combinations Set
AI Thread Summary
The discussion focuses on generating all unique combinations of three elements from the set {1,2,3,4,5}. A user requests assistance with a C program to achieve this. The suggested approach involves using nested loops with three indexes to ensure combinations are unique. The first loop iterates through the elements, while the second and third loops select subsequent elements, avoiding repetitions. An example code snippet is provided to illustrate how to print each combination. Additionally, an alternative method is mentioned for generating non-unique combinations using a different looping structure. The conversation emphasizes the importance of correctly indexing to avoid duplicates in the output.
gradnu
Messages
21
Reaction score
0
I have a set {1,2,3,4,5} and I need all possible combinations with three elements. Example {1,2,3}, {1,2,4}, {1,2,5} etc.
Can somebody help me with a 'C' program that does this. I want to store {1,2,3} etc. in an array of size three and print out every time a new combination is formed.

Thanks,
gradnu
 
Technology news on Phys.org
Assuming these are to be unique combinations, then an easy way to do this is 3 indexes:

Code:
    for(i = 0; i < 3; i++){
        for(j = i+1, j < 4; j++){
            (for k = j+1, k < 5; j++){
 
Last edited:
You can do loops if they are not supposed to be unique as well.

for (first = 1; first < 5; first++)
for (second = 1; second < 5; second++)
for (third = 1; third < 5; third++)
printf("%d%d%d\n", first, second, third);

Which should print something like "111", "112", "113", "114", "115", "121", "122", "123", ...

k
 
Thanks a lot guys.
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...
Back
Top