jeudi 4 mars 2021

How to replace characters matching a specific condition on a 2d matrix in c?

So i have a code that loads a textfile into a 2d array. The textfile contains a grid of this form:

+---------+    +------+
|..........####.......| 
|.........|    |......|
+----------    +______+

Now what i want my code to do is to check if there is any spot on the grid with the character '.' and randomly replace it with the character '*'. But the thing is that, I'm not replacing all the '.' characters. I can replace any number of them and they have to be randomly selected. So for instance, supposing I want to replace 5 random spots on the grid, this would be my expected output:

+---------+    +------+
|...*......####.....*.| 
|*.....*..|    |.*....|
+----------    +______+

This is what I tried but it didn't work as expected. I would be glad if anybody could point me in the right direction.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>

typedef struct grid {
    char **gridArray;
    size_t row;
    size_t col;
} grid_t;

grid_t *
grid_new(size_t length, size_t height)
{
    grid_t *grid = malloc(sizeof(grid_t));
    assert(grid != NULL);
    char ** a = malloc(sizeof(char *) * length);
    assert(a != NULL);
    grid->gridArray = a;
    grid->row = length;
    grid->col = height;

    for (size_t n = 0; n < length; n++){
        grid->gridArray[n] = malloc(sizeof(char) * height);
        assert(grid->gridArray[n] != NULL);
    }

    return grid;
}

bool
emptySpot(grid_t * map, int x, int y);

int main(int argc, char * argv[]){
    grid_t *grid = grid_new(r, rowCol);
    /* replace 7 '.' spots with '*' */
    for (int m = 0; m < 7; m++){
        while (1){
            int randNumRow = (rand() % (grid->row + 1));  // generates random x value between 0 and max number of rows
            int randNumCol = (rand() % (grid->col + 1));  // generates random y value between 0 and max number of cols
            if (emptySpot(grid, randNumRow, randNumCol)){
                grid->gridArray[randNumRow][randNumCol] = '*';  // drop '*' in empty spot on grid
                break;
            }
        }
    }

    return 1;
}


bool
emptySpot(grid_t *map, int x, int y)
{
    if (map->gridArray[x][y] == '.'){  // if spot on grid is empty, return true
        return true;
    }
    else{
        return false;
    }
}



Aucun commentaire:

Enregistrer un commentaire