0

I have to read almost 1M of strings with 1's and 0's (i.e. 01111010) with same length and compare their Hamming Distance on C.

My idea is make something like this: Code #1

typedef struct _matrix
{
    unsigned int n_rows;
    unsigned int n_cols;
    char ** mat;
} matrix;

matrix *create_matrix(matrix *mtrx)
{
    //char** mat;
    //matrix* mtrx = malloc(sizeof(matrix));
    int x=10, y=10, i;
    mtrx->mat = calloc(x+1, sizeof(char*));
    for(i = 0;i<y;i++) mtrx->mat[i] = calloc(y+1, sizeof(char));
    mtrx->n_rows = x;
    mtrx->n_cols = y;
    return mtrx;
}

int main()
{
    matrix* mtrx = malloc(sizeof(matrix));
    mtrx = create_matrix(mtrx);
    int i;
    for(i=mtrx->n_rows;i>=0;i--) free(mtrx->mat[i]);
    free(mtrx->mat);
    free(mtrx);

    return 0;
}

This is gonna make a 10x10 matrix of char: 100bytes. Since I'll have binary strings I want to use only a bit for each element on the matrix instead of a byte. I just found about bit-fields but I'm don't understand sure how to use it to make code#1 use 100bits.

Saludos

jevanio
  • 60
  • 2
  • 12

1 Answers1

0

Since I'll have binary strings I want to use only a bit for each element on the matrix instead of a byte. I just found about bit-fields but I'm don't understand sure how to use it to make code#1 use 100bits.

Bit-fields are not suited for this, since they can't be indexed.

We can use one bit for each element, but then we can't access by writing mat[i][j]; we'd rather have to use getter and setter macros or functions, e. g.:

typedef struct _matrix
{
    unsigned int n_rows;
    unsigned int n_cols;
    unsigned char *mat;
} matrix;

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

matrix *create_matrix(matrix *mtrx)
{
    int x=10, y=10;
    mtrx->mat = calloc((x*y+CHAR_BIT-1)/CHAR_BIT, 1);   // one bit per element
    mtrx->n_rows = x;
    mtrx->n_cols = y;
    return mtrx;
}

inline _Bool get_matrix(matrix *mtrx, unsigned row, unsigned col)
{
    unsigned idx = row*mtrx->n_cols+col;
    unsigned byt = idx/CHAR_BIT;
    unsigned bit = idx%CHAR_BIT;
    return mtrx->mat[byt]>>bit&1;
}

inline void set_matrix(matrix *mtrx, unsigned row, unsigned col, _Bool val)
{
    unsigned idx = row*mtrx->n_cols+col;
    unsigned byt = idx/CHAR_BIT;
    unsigned bit = idx%CHAR_BIT;
    mtrx->mat[byt] = mtrx->mat[byt]&~(1<<bit)|val<<bit;
}

print_matrix(matrix *mtrx)
{
    int i, j;
    for (i=0; i<mtrx->n_rows; ++i, puts(""))
    for (j=0; j<mtrx->n_cols; ++j) printf("%d", get_matrix(mtrx, i, j));
}

int main()
{
    matrix mtrx;
    create_matrix(&mtrx);
    set_matrix(&mtrx, 0, 0, 1);
    set_matrix(&mtrx, 9, 9, 1);
    print_matrix(&mtrx);
    free(mtrx.mat);
    return 0;
}
Armali
  • 18,255
  • 14
  • 57
  • 171