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