refine the lottery algorithm to reduce its computational complexity
Fork of app_board-Lottery by
Diff: main.cpp
- Revision:
- 3:d327dd543579
- Parent:
- 2:254e72dcfb52
--- a/main.cpp Wed Jul 20 11:59:33 2016 +0000 +++ b/main.cpp Wed Jul 20 12:52:01 2016 +0000 @@ -40,6 +40,7 @@ int main() { int gift[GIFT_MAXCNT]; + int item[MAN_MAXCNT]; lcd.cls(); lcd.locate(0,3); @@ -73,20 +74,19 @@ wait(twait); lcd.locate(0,3); lcd.cls(); + // Generate non-repeat users + for(int i=0;i<MAN_MAXCNT;i++){ + item[i] = i; + } for(int i=0;i<GIFT_MAXCNT;i++){ - while(1){ - int rand_num = rand()%MAN_MAXCNT+1; - int repeat=0; - for(int j=0;j<i;j++){ - if( gift[j] == rand_num ) repeat=1; - } - if(repeat==0){ - gift[i] = rand_num; - break; - } + int rand_num = rand()%(MAN_MAXCNT-i); + gift[i] = item[rand_num] + 1; + if (rand_num != MAN_MAXCNT-i-1) { + item[rand_num] = item[MAN_MAXCNT-i-1]; } } + // Show the results on LCD for(int i=0;i<GIFT_MAXCNT;i++){ int x=(i % 8)*16;