Advertisement
Guest User

Untitled

a guest
Apr 29th, 2022
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.31 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. void swap(char* num, int i, int j){
  5.     char temp = num[i];
  6.     num[i] = num[j];
  7.     num[j] = temp;
  8. }
  9.  
  10. int find_max_index(char *num, size_t num_size){
  11.     for (int i = num_size - 2; i >= 0; i--) {
  12.         if (num[i] < num[i + 1]) {
  13.             return i;
  14.         }
  15.     }
  16.     return -1;
  17. }
  18.  
  19. int find_index_bigger_element(char *num, size_t num_size, int element){
  20.     for (int i = num_size - 1; i >= 0; i--) {
  21.         if (num[i] > element) {
  22.             return i;
  23.         }
  24.     }
  25.     return -1;
  26. }
  27.  
  28. void reverse_sequence_part(int begin, char* num, size_t num_size){
  29.     int end = num_size - 1;
  30.  
  31.     while (begin < end)
  32.     {
  33.         swap(num, begin, end);
  34.         begin++;
  35.         end--;
  36.     }
  37. }
  38.  
  39. void narajana(int permutation_counter, char *num){
  40.     size_t num_size = strlen(num);
  41.     int index = find_max_index(num, num_size);
  42.     for (; index != -1;) {
  43.         int element = num[index];
  44.         int swapIndex = find_index_bigger_element(num, num_size, element);
  45.         swap(num, index, swapIndex);
  46.         reverse_sequence_part(index, num, num_size);
  47.         printf("%s\n", num);
  48.         index = find_max_index(num, num_size);
  49.     }
  50. }
  51.  
  52. int main(){
  53.     int permutation_counter = 2;
  54.     char *num = "214";
  55.     narajana(permutation_counter, num);
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement