문제

So i have this piece of code:

     int* get_lotto_draw() //Returns an array of six random lottery numbers 1-49
{
     int min = 1;
     int max = 49;
     int counter = 0;

     srand(time(NULL));

     int *arrayPointer = malloc(6 * sizeof(int));

     for(counter = 0; counter <= 5; counter++)
     {
                 arrayPointer[counter] = rand()%(max-min)+min;
     }  

     return arrayPointer;
}

This gives me 6 int* but sometimes these int* values can be the same. How can i compare each of them to eachother, so that if they are the same number, it will re-calculate on of the values that are equal ? Thanks for your time.

도움이 되었습니까?

해결책

make a search in the array for same number before storing the number as,

for(counter = 0; counter <= 5; counter++)
     {
        int x1 = 1;
        while(x1)
        {

          int temp = rand()%(max-min)+min;
          for(i = 0; i < counter; i++)
          {
             if(arrayPointer[i] == temp)
             {
                break;
             }
          } 

          if(i == counter)
          {
            x1 = 0;
            arrayPointer[counter] = temp;
          }
        }
     }

다른 팁

The problem is that random-number generators don't know or care about history (at least, not in the sense that you do--software random number generators use recent results to generate future results). So, your choices are generally to...

  • Live with the possibility of duplicates. Obviously, that doesn't help you.
  • Review previous results and discard duplicates by repeating the draw until the value is unique. This has the potential to never end, if your random numbers get stuck in a cycle.
  • Enumerate the possible values, shuffle them, and pick the values off the list as needed. Obviously, that's not sensible if you have an enormous set of possible values.

In your case, I'd pick the third.

  • Create an array (int[]) big enough to hold one of every possible value (1-49).
  • Use a for loop to initialize each array value.
  • Use another for loop to swap each entry with a random index. If you swap a position with itself, that's fine.
  • Use the first few (6) elements of the array.

You can combine the second and third steps, if you want, but splitting them seems more readable and less prone to error to me.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top