Thread: Reordering columns

  1. #1
    Registered User
    Join Date
    Jun 2022
    Posts
    5

    Reordering columns

    Hey my code is intended to take in an encrypted message and key then decrypts it.

    Firstly the lines would have to be read column wise then rearrange based on the reconstruction of the key. So if the message was encrypted with "jmpu" then it has to be decrypted by "jump". The problem I am having is the swapping the columns. i tired sorting the key then trying to swap based on is the current letter in the key is >= the sorted key.
    Code:
    char *transpose(char *message, char *key);
    char *sorting(char *string);
    int main()
    {
        char sentence[100]="Tqkofeibnx-cr--hu-wo";
        char key[100]="jump";
        transpose(sentence, key);
         
       /* how it should be read into a matrix(the key is not read into the matrix):
        J M P U     
        T e - h    
        q i c u     
        k b r -       
        o n - w       
        f x - o    
       
        how it should be arranged
        J U M P           
        T h e - 
        q u i c
        k - b r 
        o w n -
        f o x -
       
        then read row by row
    */
    
        return 0;
    }
    char *transpose(char *message, char *key)
    {
        int i,j,k,index;
        //len of message
        int message_len=strlen(message);
        //column len
        int col_len=strlen(key);
        //give us the number of rows
        int row_len =message_len/col_len;
        if(message_len%col_len)
        {
            row_len++;//increments row_len
        }
        char matrix[row_len][col_len];
        //creat matrix
        k=0;
        for(i=0;i<col_len;i++)
        {
            for(j=0;j<row_len;j++)
            {
                matrix[j][i]= message[k++];
            }
        }
        
        //remove padding
        for(i=0;i<col_len;i++)
        {
            for(j=0;j<row_len;j++)
            {
                if(matrix[j][i]=='-'||matrix[i][j]=='\0')
                {
                    matrix[j][i]=' ';
                }
                
            }
        }
        //print matrix above
        for(i=0;i<row_len;i++)
        {
            for(j=0;j<col_len;j++)
                {
                    printf("%c ",matrix[i][j]);
                }
            printf("\n");
        }
    
    
        //columnuar transpose
        char *dmessage = malloc(sizeof(char)*(row_len*col_len));
        *dmessage ='\0';
        k=0;
        char temp[col_len];
        strcpy(temp,key);
        char *sortedkey= sorting(temp);
        
            //need help at this point
        for(index=0; index<strlen(key);index++)
        {
            for(i=0;i<col_len;i++)
            {
                for (j=0;j<row_len;j++) 
                {
                    if(sortedkey[index]>=key[i])
                    {
                        dmessage[k++]=matrix[j][i];
                    }
                    dmessage[k]='\0';
                }
            }
        }
        
        printf("\nDecrypted message is\n");
        for (i=0;dmessage[i]!='\0';i++) 
        printf("%c",dmessage[i]);
        printf("\n\n");
    
    
    }
    
    
    
    
    char *sorting(char *string)//sort alphabetically 
    {
        
        char temp;
        int i, j;
        int str_len = strlen(string);
        for (i = 0; i < str_len-1; i++) {
            for (j = i+1; j < str_len; j++) {
                if (string[i] > string[j]) {
                        temp = string[i];
                        string[i] = string[j];
                        string[j] = temp;
                }
            }
        }
        
        return string;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Study this -> A development process

    Then this.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    // Use a fixed sized array to test with before
    // adding complications with variable sizes
    #define M_ROWS  50
    #define M_COLS  10
    
    char *transpose(char *message, char *key);
    
    int main()
    {
        char sentence[100]="Tqkofeibnx-cr--hu-wo";
        char key[100]="jump";
        transpose(sentence, key);
         
       /* how it should be read into a matrix(the key is not read into the matrix):
        J M P U     
        T e - h    
        q i c u     
        k b r -       
        o n - w       
        f x - o    
       
        how it should be arranged
        J U M P           
        T h e - 
        q u i c
        k - b r 
        o w n -
        f o x -
       
        then read row by row
    */
    
        return 0;
    }
    
    void fill(char matrix[][M_COLS], const char *message, int col_len, int row_len) {
        int k=0;
        for(int c=0;c<col_len;c++)
        {
            for(int r=0;r<row_len;r++)
            {
                matrix[r][c]= message[k++];
            }
        }
    }
    
    void pad(char matrix[][M_COLS], int col_len, int row_len) {
        for(int c=0;c<col_len;c++)
        {
            for(int r=0;r<row_len;r++)
            {
                if(matrix[r][c]=='-'||matrix[r][c]=='\0')
                {
                    matrix[r][c]=' ';
                }
            }
        }
    }
    
    void print(const char matrix[][M_COLS], int col_len, int row_len) {
        for(int r=0;r<row_len;r++)
        {
            for(int c=0;c<col_len;c++)
            {
                printf("%c ",matrix[r][c]);
            }
            printf("\n");
        }
        printf("-----\n");
    }
    
    void swap(char matrix[][M_COLS], int row_len, int col1, int col2) {
        for(int r=0;r<row_len;r++) {
            char temp = matrix[r][col1];
            matrix[r][col1] = matrix[r][col2];
            matrix[r][col2] = temp;
        }
    }
    
    char *transpose(char *message, char *key)
    {
        int message_len=strlen(message);
        //column len
        int col_len=strlen(key);
        //give us the number of rows
        int row_len =message_len/col_len;
        if(message_len%col_len)
        {
            row_len++;//increments row_len
        }
        char matrix[M_ROWS][M_COLS] = { { 0 } };
    
        //creat matrix
        fill(matrix, message, col_len, row_len);
        
        //remove padding
        pad(matrix, col_len, row_len);
    
        //print matrix above
        print(matrix, col_len, row_len);
    
        //columnuar transpose
        swap(matrix, row_len, 1, 3);
        print(matrix, col_len, row_len);
        swap(matrix, row_len, 2, 3);
        print(matrix, col_len, row_len);
    }

    $ gcc foo.c
    $ ./a.out
    T e h
    q i c u
    k b r
    o n w
    f x o
    -----
    T h e
    q u c i
    k r b
    o w n
    f o x
    -----
    T h e
    q u i c
    k b r
    o w n
    f o x
    -----
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jun 2022
    Posts
    5
    Hey, thank you. But a confusion still lingers, in this code you hard coded the columns and rows when swapping. How can I code it so that it does the calculations to this?

  4. #4
    Registered User
    Join Date
    Jun 2022
    Posts
    5
    so that when the user enters the key, the columns are swapped based on that key.

  5. #5
    Registered User
    Join Date
    Dec 2017
    Posts
    1,633
    It's possible to do this without a 2D array.
    BTW, "columnuar" isn't a word, and "create" has an 'e' at the end (even Thompson agrees ).
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
     
    #define MAX_STRING 1000
    #define MAX_KEY     100
     
    void sort(const char *str, int len, int *pos) {
        for (int i = 0; i < len; ++i)
            pos[i] = i;
        for (int i = 0; i < len; ++i)
            for (int j = i + 1; j < len; ++j)
                if (tolower(str[pos[i]]) > tolower(str[pos[j]])) {
                    int t = pos[i]; pos[i] = pos[j]; pos[j] = t;
                }
    }
     
    void prepare_string(char *str, int len, int cols) {
        // Replace spaces with dashes
        for (int i = 0; i < len; ++i)
            if (str[i] == ' ') str[i] = '-';
        // Pad string with dashes to a multiple of cols
        int i = len;
        for ( ; i % cols != 0; ++i) str[i] = '-';
        str[i] = '\0';
    }
     
    void encode_message(const char *str, int rows, int cols, const int *pos, char *out) {
        int i = 0;
        for (int c = 0; c < cols; ++c)
            for (int r = 0; r < rows; ++r)
                out[i++] = str[pos[c] + r * cols];
        out[i] = '\0';
    }
     
    void decode_message(const char *str, int rows, int cols, const int *pos, char *out) {
        // Determine reverse column-swapping positions 
        int pos2[MAX_KEY] = {0};
        for (int i = 0; i < cols; ++i)
            pos2[pos[i]] = i;
        // Decode message
        int i = 0;
        for (int r = 0; r < rows; ++r)
            for (int c = 0; c < cols; ++c)
                out[i++] = str[r + pos2[c] * rows];
        out[i] = '\0';
    }
     
    int main() {
        char str[MAX_STRING] = "The quick brown fox jumps over the lazy dog";
        // The key cannot have duplicate letters
        const char *key =
            //"sad";
            "jump";
            //"other";
            //"script";
        int len = strlen(str);
        int cols = strlen(key);
        int rows = (len + cols - 1) / cols;
     
        prepare_string(str, len, cols);
        printf("%s\n", str);
     
        // Determine column-swapping positions 
        int pos[MAX_KEY] = {0};
        sort(key, cols, pos);
     
        char str2[MAX_STRING];
        encode_message(str, rows, cols, pos, str2);
        printf("%s\n", str2);
     
        str[0] = '\0';
        decode_message(str2, rows, cols, pos, str);
        printf("%s\n", str);
     
        return 0;
    }
    A little inaccuracy saves tons of explanation. - H.H. Munro

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > in this code you hard coded the columns and rows when swapping.
    That's only to show you how it works.

    > How can I code it so that it does the calculations to this?
    Well where in the code do you know the other half of the key is "J M P U"?
    You get your column swaps by figuring out which pairs of letters you need to swap to turn "J M P U" into "J U M P"
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. reordering bytes in array
    By johnmerlino in forum C Programming
    Replies: 1
    Last Post: 03-25-2014, 06:40 PM
  2. Reordering strings!
    By Monochrome in forum C Programming
    Replies: 4
    Last Post: 11-02-2011, 09:19 AM
  3. aes mix columns
    By zxcv in forum C Programming
    Replies: 8
    Last Post: 01-04-2008, 03:28 PM
  4. Reordering numbers
    By shaheel in forum C Programming
    Replies: 3
    Last Post: 11-22-2007, 08:56 AM
  5. Aligning Columns
    By mike_g in forum C Programming
    Replies: 3
    Last Post: 06-27-2007, 08:27 AM

Tags for this Thread