cmatrix

Transforming strings into n * n ascii value matrix


I am currently trying to make a c function to transform a string into an n*n matrix made from the ascii value of the characters of the string.For example the string "Wordsss" should give a matrix such as

87  111 82
100 115 115
115 0   0

The space between the differents values should be tabulations. My current code is :

int matrix_size(int length)
{
    int n = 0;
    double square = sqrt(length);

    if ((int)square % 1 != 0 ){
        n = ((square / 1) - ((int)square % 1)) + 1;
        length = n;
    } else {
        n = square + 1;
        length = n;
    }
}

int key_matrix(int ac, char **av)
{
    int length = strlen(av[2]);
    int i = 0;
    int j = 0;
    int n = matrix_size(length);
    int limit = pow(n, 2);

    while(i < limit){
        if(i % n == 0 && i != 0){
            printf("%d\n", av[2][i]);
            ++i;
        } else if (i > length && i < limit){
            printf("%d\t", 2);
        } else {
            printf("%d\t", av[2][i]);
            ++i;
      }
   }
}

Solution

  • There are a whole bunch of issues here.

    If I want to get the size of the output matrix based on the length of the string, I'll find the floor of the square root. If multiplying that my itself yields the original length, it's fine as-is. This covers numbers like 9 or 16. Otherwise, it'll return that number plus one.

    This neatly handles cases where floating point math says the square root of something like 10000 is 99.999999... rather than 100.

    size_t matrix_dimension(size_t length) {
        size_t s = floor(sqrt((double)length));
    
        if (s * s == length) {
            return s;
        }
        else {
            return s + 1;
        }   
    }
    

    Now, I'll write a function to print a "matrix" for one string. If we need to handle multiples, we can simply write a loop and call this function multiple times.

    Note that I use a width specifier on my format specifier to achieve tabulation rather than tabs.

    void print_matrix(char *str) {
        size_t slen = strlen(str);
        size_t len = matrix_dimension(slen);
    
        for (size_t i = 0; i < len; i++) {
            for (size_t j = 0; j < len; j++) {
                size_t k = i * len + j;
    
                if (k >= slen) {
                    printf("%4d", 0);
                }
                else {
                    printf("%4d", (int)str[k]);
                }
            }
            printf("\n");
        }
    }