Advertisement
kraxor

7. kotprog, "tisztitott" verzio

Nov 23rd, 2011
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define INPUT_FILE      "be.txt"
  6. #define OUTPUT_FILE     "ki.txt"
  7. #define MAX_WORD_SIZE   200
  8.  
  9. char *encode(const char *str, const int *key, int cols);
  10. char *decode(const char *str, const int *key, int cols);
  11.  
  12. int main() {
  13.     FILE *in = fopen(INPUT_FILE, "r");
  14.    
  15.     int func, cols;
  16.     fscanf(in, "%d %d", &func, &cols);
  17.  
  18.     int key[10];
  19.     int i;
  20.     for (i = 0; i < cols; i++) {
  21.         fscanf(in, "%d", &key[i]);
  22.     }
  23.    
  24.     char *str = (char *) malloc(sizeof(char) * MAX_WORD_SIZE + 1);
  25.     fscanf(in, "%s", str);
  26.    
  27.     if (func == 1) {
  28.         str = encode(str, key, cols);
  29.     } else {
  30.         str = decode(str, key, cols);
  31.     }
  32.  
  33.     FILE *out = fopen(OUTPUT_FILE, "w");
  34.     fprintf(out, "%s\n", str);
  35.     fclose(out);
  36. }
  37.  
  38. char *encode(const char *str, const int *key, int cols) {
  39.     int rows = strlen(str) / cols;
  40.     char **table = (char **) malloc(sizeof(char *) * rows);
  41.  
  42.     int i, j;
  43.     for (i = 0; i < rows; i++) {
  44.         table[i] = (char *) malloc(sizeof(char) * cols);
  45.         for (j = 0; j < cols; j++) {
  46.             table[i][j] = str[i * cols + j];
  47.         }
  48.     }
  49.  
  50.     char *coded = (char *) malloc(sizeof(char) * strlen(str) + 1);
  51.     for (i = 0; i < cols; i++) {
  52.         for (j = 0; j < rows; j++) {
  53.             coded[i * rows + j] = table[j][key[i] - 1];
  54.         }
  55.     }
  56.     coded[strlen(str)] = '\0';
  57.     return coded;
  58. }
  59.  
  60. char *decode(const char *str, const int *key, int cols) {
  61.     int rows = strlen(str) / cols;
  62.     char **table = (char **) malloc(sizeof(char *) * cols);
  63.  
  64.     int i, j;
  65.     for (i = 0; i < cols; i++) {
  66.         table[key[i]] = (char *) malloc(sizeof(char) * rows + 1);
  67.         for (j = 0; j < rows; j++) {
  68.             table[key[i]][j] = str[i * rows + j];
  69.         }
  70.     }
  71.  
  72.     char *decoded = (char *) malloc(sizeof(char) * strlen(str) + 1);
  73.     for (j = 0; j < rows; j++) {
  74.         for (i = 1; i <= cols; i++) {
  75.             decoded[j * cols + i - 1] = table[i][j];
  76.         }
  77.     }
  78.     decoded[strlen(str)] = '\0';
  79.    
  80.     return decoded;
  81. }
  82.  
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement