Number checking in C -
(what meant do)
while working on "deal or no deal" project, made function check(); check if 2 cases same, , if are, change 1 of them, re check again.
function deal sets random numbers cases prizes, , call on check();
#include <stdio.h> #include <stdlib.h> #include <time.h> void deal(void); void check(void); int cases[22]; int prizes[22]=1,2,3,4,5,6,8,10,15,20,25,35,50,65,85,100,105,135,165,200,250}; int main() { int a=0; deal(); while (a<22){ printf("%d \n",cases[a] ); a++; } return 0; } void deal(void){ srand(time(null)); int r; int n = 1; while (n <= 22){ r = rand() % 21; cases[n] = prizes[r]; n++; }//ends while loop check(); }//ends function void check(void){ int = rand() % 21; int m = 0; int n = 0; srand(time(null)); while(m < 22){//nested while loop while ( n < 22){ if (m == n){ n++; continue; } else { if(cases[m] == cases[n]){ cases[m] = prizes[i]; = rand() % 21; continue; }else{ n++; continue; } } }//end of inside loop m++; n = 0; }//end of nested loop }//end function
however prints out numbers unchecked, or not checked properly. i'm using code-blocks ide
thanks in advance.
you're there, there simple (and quite common) algorithm or doing scramble on array. 1 pass through array can randomise positions of each value without duplicating them. check function isn't necessary due scramble function's operation.
#include <stdio.h> #include <stdlib.h> #include <time.h> void deal(void); void check(void); int cases[22]; int prizes[22] = {1,2,3,4,5,6,8,10,15,20,25,35,50,65,85,100,105,135,165,200,250}; int main() { srand(time(null)); int = 0; deal(); for(a = 0 ; < 22 ; a++) printf("%d \n", cases[a]); return 0; } //this neat algorithm re-ordering array without duplication void scramble(int* array, int length) { int i; int r; int temp; for(i = 0 ; < length ; i++) { //swap element random 1 it's left (or itself) r = rand() % (i + 1); temp = array[r]; array[r] = array[i]; array[i] = temp; } } void deal(void) { int r; int n = 1; //copy prizes across directly for(n = 0 ; n < 22 ; n++) cases[n] = prizes[n]; scramble(cases, 22); }
examine scramble() function in detail , you'll find quite interesting.
edited change algo single pass per suggestion in comments.
Comments
Post a Comment