jeudi 10 décembre 2020

Why dont I get random numbers?

I am wondering why I wont get random numbers. My code is a game in which you roll a dice and then depending on the number you add oder remove smth. That works so far! Now i want to simulate this game like 100 times. But here I always get the same results. I have looked through some "random" Posts and I would assume that I understood how rand works, but couldnt find any solution. Hope you can help me.

#include <stdlib.h>
#include <time.h>
#include <stdbool.h>

int items[] = {10,10,10,10,9};

int roll_dice(){
  return rand() % 6;
}
void pick(int index){
  if(items[index] > 0){
    --items[index];
  }
}
bool won(){
  return items[0] == 0 && items[1] == 0 && items[2] == 0 && items[3] == 0;
}
bool lost(){
  return items[4] == 0;
}
void print_config(){
  printf("%u, %u, %u, %u; %u\n", items[0], items[1], items[2], items[3], items[4]);
}
int fullest_basket(){ // Returns index of fullest basket.
  int fullest_basket = 0;
  int index_basket = 0;
  for(int i = 0; i < 4; i++){
    if(fullest_basket < items[i]){
      fullest_basket = items[i];
      index_basket = i;
    }
  }
  return index_basket;
}
void handle_basket(){
  for(int i = 0; i < 2; ++i){
    int basket =  fullest_basket();
    if(items[basket] > 0){
      --items[basket];
    }
  }
}
int main(){
  srand(time(NULL));
  int won_games = 0, lost_games = 0;
  for(int i = 0; i < 100; i++){
    while(1) {
      int rolled = roll_dice(); // return rand() % 6;
      if(rolled < 5){
        pick(rolled);
      } else if( rolled == 5){
        handle_basket();
      }
      if(won()){
        won_games++;
        //printf("WON!\n");
        break;
      }
      if(lost()){
        lost_games++;
        //printf("LOST!\n");
        break;
      }
    }
    //print_config();
  }
  printf("%u, %u; %.2f", won_games, lost_games, (float)won_games/(won_games+lost_games));
  return 0;
}



Aucun commentaire:

Enregistrer un commentaire