refine the lottery algorithm to reduce its computational complexity

Dependencies:   C12832 mbed

Fork of app_board-Lottery by WuLung Hsu

Files at this revision

API Documentation at this revision

Comitter:
cclljj
Date:
Wed Jul 20 12:52:01 2016 +0000
Parent:
2:254e72dcfb52
Commit message:
refine the lottery part to reduce its computational complexity

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
diff -r 254e72dcfb52 -r d327dd543579 main.cpp
--- 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;