Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <mm_malloc.h>
- #include <stdbool.h>
- #include <string.h>
- void swap(int* a, int* b) {
- int tmp = *a;
- *a = *b;
- *b = tmp;
- }
- bool lastPerm(const int* arrOfPerm, int length)
- {
- for (int i = 1; i < length; i++)
- {
- if (arrOfPerm[i] > arrOfPerm[i - 1])
- {
- return false;
- }
- }
- return true;
- }
- void permutations(int* arrOfPerm, int length, size_t countOfIterations)
- {
- if (countOfIterations == 0 || lastPerm(arrOfPerm, length))
- {
- return;
- }
- int stop = 0, first = 0;
- for(int i = length -1; i > 0; i--)
- {
- if (arrOfPerm[i] > arrOfPerm[i - 1])
- {
- stop = arrOfPerm[i - 1];
- first = i - 1;
- break;
- }
- }
- int second = first + 1;
- for (int i = first + 2; i < length; i++)
- {
- if (arrOfPerm[i] > stop && arrOfPerm[i] < arrOfPerm[second])
- {
- second = i;
- }
- }
- swap(&arrOfPerm[first], &arrOfPerm[second]);
- int l = first + 1;
- int r = length - 1;
- while (l < r)
- {
- swap(&arrOfPerm[l], &arrOfPerm[r]);
- l++;
- r--;
- }
- for (int i = 0; i < length; i++)
- {
- printf("%d", arrOfPerm[i]);
- }
- printf("\n");
- permutations(arrOfPerm, length, countOfIterations - 1);
- }
- int main() {
- char* in = (char*)calloc(11, sizeof(char));
- if(scanf("%10s", in) == 0)
- {
- printf("bad input");
- free(in);
- return 0;
- }
- size_t countOfIterations;
- if(scanf("%zu", &countOfIterations) == 0)
- {
- printf("bad input");
- free(in);
- return 0;
- }
- int arrRepeat[10] = { 0 };
- for(int i = 0; i < (int)strlen(in); i++)
- {
- if(in[i] < '0' || in[i] > '9' || arrRepeat[in[i] - '0'] == 1)
- {
- printf("bad input");
- free(in);
- return 0;
- }
- else
- {
- arrRepeat[in[i] - '0']++;
- }
- }
- int arrOfPerm[strlen(in)];
- for(int i = 0; i < (int)strlen(in); i++)
- {
- arrOfPerm[i] = in[i] - '0';
- }
- permutations(arrOfPerm, strlen(in), countOfIterations);
- free(in);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement