#include "common.h"
#include <time.h>

void PrintVotes(unsigned long *votes,  unsigned long number) {
	for (unsigned long i=0; i<number; ++i) {
        printf("%d,", votes[i]);
    }
	printf("\n");
}

void OneVote(unsigned long candidateNumber, unsigned long quota, unsigned long *votes) {
	ZeroArray(votes, candidateNumber);
	
	unsigned long _quota = quota;
    while (_quota > 0) {
	
        unsigned long selected = rand() % (candidateNumber);
        if (votes[selected] == 0) {
            votes[selected] = 1;
            _quota--;
        }
    }
}

void Vote(unsigned long candidateNumber, unsigned long quota, unsigned long judgerNumber, unsigned long *votes) {

	ZeroArray(votes, candidateNumber);
	
	for (unsigned long i=0; i<judgerNumber; ++i) {
		unsigned long oneVotes[MAX_CANDIDATE_NUMBER];
		OneVote(candidateNumber, quota, oneVotes);
		
		for (unsigned long j=0; j<candidateNumber; ++j) {
			votes[j] += oneVotes[j];
		}
		
	}
	
}

void Usage(void) {
	printf("vote.exe 候选人数(1..%d) 名额(1..%d) 评委数(1..%d) [模拟次数(10..%d)=10000]\n",
		MAX_CANDIDATE_NUMBER, MAX_QUOTA, MAX_JUDGER_NUMBER, MAX_SIMULATION_TIMES); 
}

int main(int argc, const char* argv[]) {

    srand(time(NULL));
	
	if (argc == 4 || argc == 5) {
		unsigned long candidateNumber = atoi(argv[1]);
		unsigned long quota = atoi(argv[2]);
		unsigned long judgerNumber = atoi(argv[3]);
		unsigned long simulationTimes = argc == 5 ? atoi(argv[4]) : 10000;
		
		if (1 <= candidateNumber && candidateNumber <= MAX_CANDIDATE_NUMBER && 
			1 <= quota && quota <= MAX_QUOTA &&
			1 <= judgerNumber && judgerNumber <= MAX_JUDGER_NUMBER && 
			10 <= simulationTimes && simulationTimes <= MAX_SIMULATION_TIMES) {
			
			printf("%d,%d,%d,%d\n", candidateNumber, quota, judgerNumber, simulationTimes);
			
			for (unsigned long i=0; i<simulationTimes; ++i) {
				unsigned long votes[MAX_CANDIDATE_NUMBER];
				Vote(candidateNumber, quota, judgerNumber, votes);
				PrintVotes(votes, candidateNumber);
			}
		
		} else {
			Usage();
		}
		
	} else {
		Usage();
	}
    
    return 0;
}


