-4

I am making a game in c which requires a 2D array of size m*n which needs to store alphabets in pairs. It's a memory game where user needs to select 2 slots from the matrix which is hidden. If they both match then they are deleted from the matrix.

for example: for array a[3][4] it should store

a t x e
b a t n 
x b n e
Adarsh
  • 59
  • 6

1 Answers1

0

Although I am sharing the code, please try and type the code yourself. I am giving some steps with this answer, which should help you think through the code if you want to implement it all by yourself.

Here are some steps.

1) Input m and n

int m, n;
scanf("%d%d", &m, &n);

2) Allocate memory to the array

char *arr[m];
for (i = 0; i < n; ++i) {
    arr[i] = malloc(n * sizeof(char));
}

3) Now, since you mentioned in one of your comments, the program should generate random alphabets and not numbers, let me tell you, C allows casting of datatype from int to char. Here is how you will generate random characters.

for (i = 0; i < m; ++i) {
    for (j = 0; j < n; ++j) {
        c = (char) (rand() % 26) + 'a'; // Generate a random character between 'a' and 'z'
        arr[i][j] = c;
    }
}

Here is the complete code:

#include <stdio.h>
#include <stdlib.h>
int main() {
    int m, n, i, j;
    char c;
    scanf("%d%d", &m, &n);

    char *arr[m];
    for (i = 0; i < n; ++i) {
        arr[i] = malloc(n * sizeof(char));
    }

    for (i = 0; i < m; ++i) {
        for (j = 0; j < n; ++j) {
            c = (char) (rand() % 26) + 'a'; // Generate a random character between 'a' and 'z'
            arr[i][j] = c;
            printf("%c ", c);
        }
        printf("\n");
    }
}

Input:

3
4

Output:

n w l r 
b b m q 
b h c d 

I think this is the expected output!

Thanks.

nikhilbalwani
  • 817
  • 7
  • 20
  • 1
    If you want to generate pairs of random numbers, the logic is easy. Generate (m * n) / 2 random numbers and duplicate them in an array, with (m * n) elements in total. Now, insert these elements into random locations in the 2d array! – nikhilbalwani Apr 14 '19 at 08:43
  • You should check the return value from `scanf` – Ed Heal Apr 14 '19 at 08:44
  • 2
    Also in C you should not cast the return value from `malloc` - see https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Ed Heal Apr 14 '19 at 08:45
  • @EdHeal, I have removed the cast from malloc. Can you please be more specific on how to check the return value of scanf? – nikhilbalwani Apr 14 '19 at 08:48
  • 1
    Read the manual page for `scanf` - https://linux.die.net/man/3/scanf - Returns number matched – Ed Heal Apr 14 '19 at 09:00