Print a couple of characters without repeating [closed]

0

What I have to do is store a randomly selected pair of characters in a matrix and print it like this.

? # ¡ x
x ? # ¡
0 - + *
+ 0 - *

The problem is that I can not find a way to mark the characters that have come out twice, so as not to include them anymore.

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

char a[4][4];
char cartas[]={'#','%','@','0','*','!','<','x'};
int total=sizeof(cartas);

int main()
{
   srand(time(0));

   for (int i=0;i<4;i++)
   {
       for (int j=0;j<4;j++)
       {
           a[i][j]=cartas[rand()%total];
           printf("\t%c",a[i][j]);
       }
     printf("\n\n");
   }
}

Does anyone know any way?

    
asked by cheroky 11.05.2017 в 16:09
source

1 answer

0

I would start by initializing the game matrix. It is not vital but it is important:

char a[4][4] = {'
char* ptr = (char*)a;
'};

Then I would prepare the array to be able to iterate easily through it. The simplest is to linearize the array to work on a dimension. No problem because a[4][4] reserves 16 consecutive memory locations:

for (i=0;i<16;i+=2)
{
  ptr[i]   = cartas[i/2];
  ptr[i+1] = cartas[i/2];
}

Now the array is filled. To not complicate things, we fill it in order: first two copies of the first letter, then two copies of the second ...

for( i=0; i<16; i++ )
{
  j = i;
  while( j == i ) j = rand()%16;

  char temp = ptr[i];
  ptr[i] = ptr[j];
  ptr[j] = temp;
}

Now the cards are shuffled. To do this, the array is iterated once and, for each position, another random position is chosen with which to exchange its cards:

for(  i=0; i<4; i++ )
{
  for(  j=0; j<4; j++ )
    printf("%c ",a[i][j]);
  printf("\n");
}

This sweep could be done two or more times.

And that's it, all the cards mixed, as you can see with a final loop:

char a[4][4] = {'
char* ptr = (char*)a;
'};
    
answered by 11.05.2017 / 18:31
source