tsounakis

Character Shuffling

Jul 3rd, 2023 (edited)
1,377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.07 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. #define MAP_SIZE 26
  6.  
  7. void createRandomMap(char map[MAP_SIZE]) {
  8.     int i;
  9.     for (i = 0; i < MAP_SIZE; i++) {
  10.         map[i] = 'A' + i;
  11.     }
  12.  
  13.     // Fisher - Yates algorithm
  14.     for (i = MAP_SIZE - 1; i > 0; i--) {
  15.         int j = rand() % (i + 1);
  16.         char temp = map[i];
  17.         map[i] = map[j];
  18.         map[j] = temp;
  19.     }
  20. }
  21.  
  22. void applyMapping(char *j, int count, char charMap[MAP_SIZE], int reverse) {
  23.     int i;
  24.     for (i = 0; i < count; i++) {
  25.         if (j[i] >= 'A' && j[i] <= 'Z') {
  26.             if (reverse) {
  27.                 char mappedChar = 'A';
  28.                 while (charMap[mappedChar - 'A'] != j[i]) {
  29.                     mappedChar++;
  30.                 }
  31.                 j[i] = mappedChar;
  32.             } else {
  33.                 j[i] = charMap[j[i] - 'A'];
  34.             }
  35.         }
  36.     }
  37. }
  38.  
  39. int main() {
  40.     srand(time(NULL));
  41.  
  42.     char charMap[MAP_SIZE];
  43.     createRandomMap(charMap);
  44.  
  45.     char *j = malloc(sizeof(char));
  46.     char input;
  47.     int count;
  48.     int reverseMapping = 0;
  49.  
  50.     while (1) {
  51.         printf("Enter capital letters (terminate with '$', or 'q' to quit): ");
  52.  
  53.         count = 0;
  54.         while (1) {
  55.             scanf(" %c", &input);
  56.             if (input == '$') {
  57.                 break;
  58.             } else if (input == 'q') {
  59.                 free(j);
  60.                 return 0;
  61.             }
  62.  
  63.             if (input >= 'A' && input <= 'Z') {
  64.                 j = realloc(j, (count + 1) * sizeof(char));
  65.                 j[count] = input;
  66.                 count++;
  67.             }
  68.         }
  69.  
  70.         printf("Original characters:\n");
  71.         int i;
  72.         for (i = 0; i < count; i++) {
  73.             printf("%c", j[i]);
  74.         }
  75.         printf("\n");
  76.  
  77.         applyMapping(j, count, charMap, reverseMapping);
  78.  
  79.         printf("Mapped characters:\n");
  80.         for (i = 0; i < count; i++) {
  81.             printf("%c", j[i]);
  82.         }
  83.         printf("\n\n");
  84.  
  85.         reverseMapping = !reverseMapping;
  86.     }
  87.  
  88.     free(j);
  89.  
  90.     return 0;
  91. }
  92.  
Advertisement
Add Comment
Please, Sign In to add comment