对决算法

#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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值