Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <mm_malloc.h>
  3. #include <memory.h>
  4. #include <stdbool.h>
  5.  
  6. void swap(int* a, int* b) {
  7. int temp = *a;
  8. *a = *b;
  9. *b = temp;
  10. }
  11.  
  12. bool lastPerm(const int* arrayOfPerm, size_t length) {
  13. for (size_t i = 1; i < length; i++) {
  14. if (arrayOfPerm[i] > arrayOfPerm[i - 1]) {
  15. return false;
  16. }
  17. }
  18.  
  19. return true;
  20. }
  21.  
  22. void startAlgorithm(int* arrayOfPerm, size_t length, size_t countOfIterations) {
  23. if (countOfIterations == 0 || lastPerm(arrayOfPerm, length)) {
  24. return;
  25. }
  26.  
  27. int valueBreakingOrder = -1,
  28. indexOfFirst = -1;
  29. for (size_t i = length - 1; i > 0; i--) {
  30. if (arrayOfPerm[i] > arrayOfPerm[i - 1]) {
  31. valueBreakingOrder = arrayOfPerm[i - 1];
  32. indexOfFirst = (int)i - 1;
  33. break;
  34. }
  35. }
  36.  
  37. int indexOfSecond = indexOfFirst + 1;
  38. for (size_t i = (size_t)indexOfFirst + 2; i < length; i++) {
  39. if (arrayOfPerm[i] > valueBreakingOrder && arrayOfPerm[i] < arrayOfPerm[indexOfSecond]) {
  40. indexOfSecond = (int)i;
  41. }
  42. }
  43.  
  44. swap(&arrayOfPerm[indexOfFirst], &arrayOfPerm[indexOfSecond]);
  45. int left = indexOfFirst + 1;
  46. int right = length - 1;
  47. while (left < right) {
  48. swap(&arrayOfPerm[left], &arrayOfPerm[right]);
  49. left++;
  50. right--;
  51. }
  52.  
  53. for (size_t i = 0; i < length; i++) {
  54. printf("%d", arrayOfPerm[i]);
  55. }
  56. printf("\n");
  57. startAlgorithm(arrayOfPerm, length, countOfIterations - 1);
  58. }
  59.  
  60. int main() {
  61. char* currentPerm = (char*)calloc(11, sizeof(char));
  62. if (scanf("%10s", currentPerm) == 0) {
  63. printf("bad input");
  64. free(currentPerm);
  65. return 0;
  66. }
  67.  
  68. size_t countOfIterations;
  69. if (scanf("%zu", &countOfIterations) == 0) {
  70. printf("bad input");
  71. free(currentPerm);
  72. return 0;
  73. }
  74.  
  75. int arrayCheckRepetition[10] = {0};
  76. for (size_t i = 0; i < strlen(currentPerm); i++) {
  77. if (currentPerm[i] < '0' || currentPerm[i] > '9' || arrayCheckRepetition[currentPerm[i] - '0'] == 1) {
  78. printf("bad input");
  79. free(currentPerm);
  80. return 0;
  81. } else {
  82. arrayCheckRepetition[currentPerm[i] - '0']++;
  83. }
  84. }
  85.  
  86. int arrayOfPerm[strlen(currentPerm)];
  87. for (size_t i = 0; i < strlen(currentPerm); i++) {
  88. arrayOfPerm[i] = currentPerm[i] - '0';
  89. }
  90.  
  91. startAlgorithm(arrayOfPerm, strlen(currentPerm), countOfIterations);
  92. free(currentPerm);
  93. return 0;
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement