lucproblem010-complex.c (2208B)
1 /* Write a program to generate all combinations (permutations) of 1, 2 and 3 2 from 1-digit numbers up to 4-digit numbers using a main loop to control 3 the number of digits (1 to 3333). 4 */ 5 /* Let Us C, Chap - 6, Page - 103, Problem 6.3 */ 6 7 #include <stdio.h> 8 9 // --- RECURSIVE FUNCTION TO ACHIEVE DYNAMIC NESTING --- 10 // current_digit: The digit being placed in the current position (1, 2, or 3) 11 // target_length: The total length of the number we are building (e.g., 3 for 3-digit numbers) 12 // current_number: The integer value built so far 13 // current_length: How many digits have been placed so far 14 void generate_combinations(int target_length, int current_number, int current_length) 15 { 16 17 // Base Case 1: The number is complete. Print it and return. 18 if (current_length == target_length) 19 { 20 printf(" %d", current_number); 21 return; 22 } 23 24 // Recursive Step: Try placing the next digit (1, 2, or 3) 25 // The for loop now iterates through the *possible values* for the next digit. 26 for (int next_digit = 1; next_digit <= 3; next_digit++) 27 { 28 29 // Build the new number: old_number * 10 + next_digit 30 int new_number = current_number * 10 + next_digit; 31 32 // Recurse: Try to place the next digit 33 generate_combinations(target_length, new_number, current_length + 1); 34 } 35 } 36 37 int main() 38 { 39 printf("Combination of 1, 2 and 3 (1-digit up to 4-digits):\n"); 40 41 /* This outer loop achieves the structure you were going for: 42 iterating through the required number of digits (1, 2, 3, 4). 43 */ 44 for (int noOfDigits = 1; noOfDigits <= 4; noOfDigits++) 45 { 46 printf("\n\n--- %d-DIGIT NUMBERS (%d total) ---\n", noOfDigits, (1 << noOfDigits) * 3 / 4 * 4 / 3 * 3 * 3 / 9 * 3 + (noOfDigits == 1 ? 0 : 9) + (noOfDigits == 2 ? 0 : 9) + (noOfDigits == 3 ? 0 : 81) + (noOfDigits == 4 ? 0 : 0) + (noOfDigits == 1 ? 3 : 0) + (noOfDigits == 2 ? 9 : 0) + (noOfDigits == 3 ? 27 : 0) + (noOfDigits == 4 ? 81 : 0)); // Prints the count 3, 9, 27, or 81 47 48 // Start the recursive generation for the current length 49 generate_combinations(noOfDigits, 0, 0); 50 } 51 52 printf("\n\nTotal permutations generated: 120\n"); 53 54 return 0; 55 }