I am trying to write a code that shuffles every element at least once and it didn't work for me.
The code I tried is :
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void show(int[],int);
void shuffle(int[],int,int*);
int main (void)
{
int karten[]={1,2,3,4,5,6,7,8,9,10};
int n = sizeof(karten)/sizeof(int);
int s=0;
srand(time(NULL));
printf("Karten vor dem Mischen: \n");
show(karten,n);
shuffle(karten,n,&s);
printf("Karten nach dem Mischen:\n");
show(karten,n);
return 0;
}
void show(int karten[],int n)
{
for(int i=0;i<n;i++)
{
printf("%d,",karten[i]);
}
printf("\n");
}
void shuffle(int karten[],int n,int *s)
{
int i=0;
int d=0;
int vi;
int vd;
int q;
*s=0;
int *v=(int*)malloc(sizeof(int)*n);
q=0;
while(1)
{
i=rand()%10;
d=rand()%10;
vi=karten[i];
vd=karten[d];
karten[d]=vi;
karten[i]=vd;
*s=*s+1;
v[i]=1;
v[d]=1;
for(int b=0;b<=n;b++)
{
if(v[b]==1)
{
q++;
}
}
if(q==n)
{
break;
}
}
printf("Es wurden %d Vertauschungen gemacht\n",*s);
free(v);
}
The error is that the code works some times and it does not work some times. When it works, I think it doesn't work right because the shuffle times are (3) or (4). I tried to make it as simple as possible.