Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int random(int ran[]);
int input(int num,int list[]);
void repeatinput(int list[],int times);
int check(int ran[], int list[], int* correct, int* wrong);
void check2(int correct, int wrong);
int reguess(int times,int list[]);
void retrycount(int* times);
char replay();
void abort();
int random(int ran[])
{
int x,y,z;
srand(time (NULL));
x= rand()%10 ;
do
{
y=rand()%10;
}while(y==x);
do
{
z=rand()%10;
}while(z==x || z==y);
ran[0]=x;
ran[1]=y;
ran[2]=z;
return ran[3];
}
int input(int num,int list[])
{
int x,y,z;
list[0]=0;
list[1]=0;
list[2]=0;
x=num/100;
y=(num - x*100)/10;
z=num - x*100 - y*10;
list[0]=x;
list[1]=y;
list[2]=z;
return list[3];
}
void repeatinput(int list[],int times)
{
int num;
if(list[0]==list[1]||list[1]==list[2]||list[0]==list[2])
{
printf("Invalid number! The digits cannot be repeated. Please re-enter a number.\n");
printf("Guess #%d:",times);
scanf("%d", &num);
input(num,list);
repeatinput(list,times);
}
}
int check(int ran[], int list[], int* correct, int* wrong)
{
int i,c=0,w=0;
for(i=0;i<3;i++)
{
if(ran[i]==list[i])
c++;
}
if(list[0]==ran[1])
w++;
if(list[0]==ran[2])
w++;
if(list[1]==ran[0])
w++;
if(list[1]==ran[2])
w++;
if(list[2]==ran[0])
w++;
if(list[2]==ran[1])
w++;
*correct = c;
*wrong = w;
return (*correct,*wrong);
}
void check2(int correct, int wrong)
{
if(correct!=3)
printf("You have %d correct position, %d wrong position\n",correct,wrong);
}
void retrycount(int* times)
{
int total=1;
total+= *times;
*times = total;
}
int reguess(int times,int list[])
{
int num,ran[3],correct=0,wrong=0;
printf("Guess #%d:",times);
scanf("%d", &num);
input(num,list);
repeatinput(list,times);
return(times,list[3]);
}
int main()
{
int num,list[3],ran[3],times,correct=0,wrong=0;
char ans;
random(ran);
times=1;
printf("This a 3-digit number guessing game\n");
printf("Please enter a non-repeating 3-digit number:\n");
printf("Guess #%d:",times);
scanf("%d", &num);
input(num,list);
repeatinput(list,times);
for(check(ran,list,&correct,&wrong) ; correct!=3 ; reguess(times,list))
{
retrycount(×);
check2(correct,wrong);
}
printf("Congratulations! You have got the number!\n\n");
printf("Play again? (Y/N):");
scanf("%c",&ans);
while(ans!='n'||ans!='N')
replay();
return 0;
}
char replay()
{
int num,list[3],ran[3],times,correct=0,wrong=0;
char ans;
random(ran);
times=1;
printf("Please enter a non-repeating 3-digit number:\n");
printf("Guess #%d:",times);
scanf("%d", &num);
input(num,list);
repeatinput(list,times);
for(check(ran,list,&correct,&wrong) ; correct!=3 ; reguess(times,list))
{
retrycount(×);
check2(correct,wrong);
}
printf("Congratulations! You have got the number!\n\n");
printf("Play again? (Y/N):");
scanf("%c",&ans);
return ans;
}