#include "stdio.h"
#include <time.h>
#include <stdlib.h>
#include <string.h>
//this program's file name is Game.cpp
//this program is designed by 200624101101杨振平 on NOV 21th,2008
//define a mem struct
typedef struct mem
{
int score;
char name[20];
}mem;
//define the array
mem a[100];
//define a buf array to implement the itoa function
static char buf[12];
//main function
void main()
{
//define a variable x to store the number of game players
//define a variable winner to store the infomation of game winner
int x,winner;
//call the srand function to generate the random number
srand((unsigned)time(NULL));
//define a function which convert a integer to a string
char *itoa(int i);
//define the Game function
int Game(mem r[],int n);
//print the information for user to input
printf("Enter the number of game players:");
scanf("%d",&x);
//initial the random array
for(int i=0;i<x;i++)
{
a[i].score=60+rand()%40;
strcpy(a[i].name,"mem");//strcat("mem",(char *)i)
strcat(a[i].name,itoa(i));
}
putchar('/n');
//print the initial the random array information of game players
for(i=0;i<x;i++)
printf("%s:%d/t",a[i].name,a[i].score);
putchar('/n');putchar('/n');
//call Game function to get the information of the last winner
winner=Game(a,x);
//print the result
printf("/nthe last winner is %s: %d/n",a[0].name,winner);
}
//implement of Comp function
bool Comp(int mem1,int mem2)
{
if(mem1>mem2)return 1;
else return 0;
}
//implement of Game function
int Game(mem r[],int n)
{
int i=n;
while(i>1)
{
i=i/2;
for(int j=0;j<i;j++)
if(Comp(r[j+i].score,r[j].score))
{
printf("%s win %s/n",r[j+i].name,r[j].name);
r[j].score=r[j+i].score;
strcpy(r[j].name,r[j+i].name);
}
}
return r[0].score;
}
//implement of itoa function
char *itoa(int i)
{
/* 10 digits + 1 sign + 1 trailing nul */
char *pos = buf + sizeof(buf) - 1;
unsigned int u;
int negative = 0;
if (i < 0) {
negative = 1;
u = ((unsigned int)(-(1+i))) + 1;
}
else {
u = i;
}
*pos = 0;
do {
*--pos = '0' + (u % 10);
u /= 10;
} while (u);
if (negative) {
*--pos = '-';
}
return pos;
}