凯升L 2017-08-30 07:05 采纳率: 0%
浏览 749

可以帮我看一下吗,这个代码要从手动输入改为电脑自动猜,怎么才能步数少一点呢?

#include
#include
#define M 4 //猜几个数字
//交换
void swap(int*a,int*b)
{
int t=*a;
a=*b;
b=t;
}
//将数组随机打乱
void random_shuffle(int a,int n)
{
int i;
for(i=0;i<n;i++)
{
int x=rand()%n;
int y=rand()%n;
if(x!=y) swap(a+x,a+y);
}
}
//生成数位不重复的M位全部数据,存在数组a中,并打乱,备用
int gen(int a)
{
int count=0,i,j;
int max=1;
for(i=0;i<M;++i,max*=10);
for(i=0;i<max;++i)
{
_Bool flag[10]={0};
int t=i;
for(j=0;j<M;++j)
if(flag[t%10]) break;
else flag[t%10]=1,t/=10;
if(j==M)
a[count++]=i;
}
random_shuffle(a,count);
return count;
}
void test(int answer,int player,int* A,int* B)
{
int i=0,j;
int answer_a[M]={0},player_a[M]={0};
A=*B=0;
while(answer||player)
{
answer_a[i]=answer%10;
player_a[i++]=player%10;
answer/=10;
player/=10;
}
for(i=0;i<M;++i)
for(j=0;j<M;++j)
if(player_a[i]==answer_a[j])
if(i==j) ++*A;
else ++*B;
}
//参数AB是上一轮猜测的反馈,
//如果得到猜中的信息表示下一把的开始
int guess(int A,int B)
{

  • //你的工作在这个函数** int x; 在这里输入代码: return x; } int main() { srand(2); int i; //初始生成数据 int len; for(len=1,i=0;i<M;++i) len*=10-i; int a[len]; gen(a); //开玩 int n=1;//玩n把 int count=0;//总猜测次数 while(n--) { //每把从猜中开始,例如玩4个数,4A0B为猜中, //此时进入下一把,会有新的数供猜测 //printf("%d\n",a[n]); int A=M,B=0; int count_cur=0; do { int player=guess(A,B); ++count_cur; test(a[n],player,&A,&B); printf("%d:%0*d,%dA%dB\n",count_cur,M,player,A,B); }while(A!=M||B); count+=count_cur; } return 0; }
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
    • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
    • ¥30 截图中的mathematics程序转换成matlab
    • ¥15 动力学代码报错,维度不匹配
    • ¥15 Power query添加列问题
    • ¥50 Kubernetes&Fission&Eleasticsearch
    • ¥15 報錯:Person is not mapped,如何解決?
    • ¥15 c++头文件不能识别CDialog
    • ¥15 Excel发现不可读取的内容
    • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题