Answer to Question #25167 in C for gene
2013-02-25T12:18:41-05:00
Write a c program using a recursive solution that reads a single positive integer, N, and prints out all possible distinct lists that include each positive integer from 1 to N. So, for example, if N is three, your output should be the following 6 lines:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
1
2013-02-27T04:41:35-0500
#include <stdio.h> #include <string.h> #include <stdlib.h> void print_list(int N, int* line, int lineLength, char* numbersUsed) { int n; for (n = 1; n <= N; n++) if (!numbersUsed[n - 1]) { line[lineLength] = n; if (lineLength + 1 == N) { int k; for (k = 0; k < N; k++) printf("%5d", line[k]); putchar('\n'); } else { numbersUsed[n - 1] = 1; print_list(N, line, lineLength + 1, numbersUsed); numbersUsed[n - 1] = 0; } } } int main() { int N; int* line; char* numbersUsed; printf("Enter N: "); scanf("%d", &N); line = (int*)malloc(N * sizeof(int)); numbersUsed = (char*)malloc(N * sizeof(char)); memset(numbersUsed, 0, N * sizeof(char)); print_list(N, line, 0, numbersUsed); free(numbersUsed); free(line); return 0; }
Need a fast expert's response?
Submit order
and get a quick answer at the best price
for any assignment or question with DETAILED EXPLANATIONS !
Learn more about our help with Assignments:
C
Comments
Leave a comment