nombres aléatoires sans doublon c++ builder
Bonjour,
J'aimerais générer une liste de nombres aléatoires (de 0à 104) sans doublons et j'ai trouvé le code ci-dessous.
Le compilateur trouve une erreur dans cette ligne : int* resultat=malloc((taille)*sizeof (int)); // Impossible de convertir 'void *' en 'int *'
Quelqu'un a t-il une solution ? (j'ai trouvé un code semblable, même erreur)
Merci d'avance
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| int rand_a_b(int a, int b)
{
return rand()%(b-a);
}
int* init_sans_doublons(int a, int b)
{
int taille = b-a; // entier = malloc (sizeof (*entier));
int* resultat=malloc((taille)*sizeof (int)); // Impossible de convertir 'void *' en 'int *'
int i=0;
// On remplit le tableau de manière à ce qu'il soit trié
for(i = 0; i< taille; i++)
{
resultat[i]=i+a;
}
return resultat;
}
void melanger(int* tableau, int taille)
{
int i=0;
int nombre_tire=0;
int temp=0;
for(i = 0; i< taille;i++){
nombre_tire=rand_a_b(0,taille);
// On échange les contenus des cases i et nombre_tire
temp = tableau[i];
tableau[i] = tableau[nombre_tire];
tableau[nombre_tire]=temp;
}
}
int main(){
// A ne pas oublier !
srand(time(NULL));
int a=0;
int b=0;
int i =0;
int* t=NULL; // Va contenir le tableau de nombres
do{
printf("Rentrez le premier nombre : ");
scanf("%d",&a);
printf("Rentrez le second, plus grand que le premier : ");
scanf("%d",&b);
}while(b<=a);
// On commence pour de vrai ici :
t=init_sans_doublons(a,b);
melanger(t,b-a);
printf("La suite aléatoire est : ");
for(i=0; i<b-a; i++){
printf("%d ",t[i]);
}
printf("\n");
// Ne pas oublier de libérer le tableau
free(t);
return 0;
} |
A moins qu'il y ait plus simple avec randomize : randomize(); for(i=0; i<104; i++) {j= random(104);ListBox1->Items->Add(IntToStr(j)); }. Ca marche mais il y a des doublons.