axyd icon

poncareRT-1DArray

axyd | PRO | 12/08/21 12:21:35 AM UTC (Edited) | 0 ⭐ | 890 👁️ | Never ⏰ | []
C |

2.03 KB

|

None

|

0 👍

/

0 👎

#include <stdio.h>          //printf
#include <stdlib.h>         //random
#include <time.h>               //clock, time
#include <unistd.h>         //fork
#include <sys/types.h>  //clock_t type
 
int drawTicket(const int, const int);
void showUrns(int*, const int, const unsigned long long, const int);
 
int main(){
    srand(time(NULL));  //seed randomizer
 
    int finish= 0, balls= 10;
    int urns[balls];
 
    //initialize urn
    for (int i= 0; i < balls; ++i){ urns[i]= 0; }
 
    int ktr1= balls, ticket= 0;
    unsigned long long nrDraws= 0;
 
    do{ 
        ticket= (drawTicket(1,balls)) -1;   //draw a random ticket      
        showUrns(urns,balls,nrDraws,0);
        
        //move respective ball to other urn
        if(urns[ticket] == 0){
            urns[ticket]= 1;
            --ktr1;         
        }   else{
            urns[ticket]= 0;
            ++ktr1;
        }
        
        ++nrDraws;  //track number of draws     
        showUrns(urns,balls,nrDraws,1); //display ball positions
        
        //Finish when balls are all in the first jar
        if(ktr1 == balls) finish= 1;                
    } while(!finish);
 
    printf("\n\tFINISHED, iterations: %llu\n\n", nrDraws);
 
    _exit(0);
}
 
 
/* Purpose: generates random number from range
 *   In : low, upper  bound
 *   Out: random number         */
int drawTicket(const int low, const int high){
    return (low + (rand() % high) ) ;
}
 
 
/* Purpose: displays in which urn a ball is in
 *   In : urn array, nr of balls, nr of draws, show pre(0) or post(1) draw
 *   Out: none                          */
void showUrns(int *arrUrns, const int balls, const unsigned long long draws, const int post){
    int urn, b= balls;
    
    if (!post){ 
        printf("\n  ## Balls location, draws:(%llu) ##", draws+1);
        printf("\n------------------------------------\n");
        printf(" pre-draw  : |");   
            
        for(int i= 0 ; i<balls; ++i){           
            printf("%d|", (arrUrns[i] == 0)? 1: 2);
        }   
    
    }else if (post){        
        printf("\n post-draw : |");
        
        for(int i=0 ; i<balls; ++i){
        printf("%d|", (arrUrns[i] == 0)? 1: 2);
        }
        
        printf("\n------------------------------------\n");
                
    }else{
        printf("\n\t/!\\ ERROR: no pre/post-draw selected /!\\");
    }
}
 
 
 
 
 

Comments