The elements in the array are created using rand().
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void){
int array[6] = { 0 };
srand(time(NULL));
for(int i = 0; i < 6; i++){
array[i] = rand() % 49 + 1;
}
/*
Code to check for duplicates
if duplicate found
duplicate = rand(49);
*/
for(int i = 0; i<6; i++){
printf("[%d]",array[i]);
}
return 0;
}
I don´t really want to sort the array if it makes it easier to find duplicates because the array is for a lottery ticket. I have tried different methods, but all of them are inefficient and includes a lot of loops. I had different approaches, but all of them didn´t really work, because what if, the newly created number, is yet again a duplicate? Or if the last number in the array is a duplicate. So I came with the following approach: The algorithm will create as many areas, as long no number in the array is a duplicate
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define TRUE 1
int main(void) {
int a[6] = {0};
srand(time(NULL));
while (TRUE) {
int c = 0;
for (int i = 0; i < 6; i++) {
a[i] = rand() % 49 + 1;
}
for (int i = 0; i < 6; i++) {
for (int j = i + 1; j < 6; j++) {
if (a[i] == a[j]) {
c++;
}
}
}
if (c == 0) {
break;
}
}
for (int i = 0; i < 6; i++) {
printf("%d\n", a[i]);
}
return 0;
}
Any Ideas, how to make an easy, efficient, but not so complex algorithm for a beginner?
Thanks :)
Aucun commentaire:
Enregistrer un commentaire