Thread: User to figure out a random number generated by the system.

1. User to figure out a random number generated by the system.

My code compiles and runs but some parts are not giving the required output. I cannot seem to figure it out. Included are the code and the desired output.

Code:
```#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#defineMAX_QUERIES12
#defineN_DIGITS4

int isvalid(int n)
{
if (n <= 0) {
return 0;
} else
return 1;
}

int choose_n(void)
{
srand(time(0));
int i;
int arr[N_DIGITS];
int num;
for (i = 0; i < N_DIGITS; i++) {
num = (rand() % (9 - 1 + 1)) + 1;
if (isvalid(num)) {
arr = num;
}
}
int n = arr[0] * 1000 + arr[1] * 100 + arr[2] * 10 + arr[3];
return n;
}

int matches(int n, int m)
{
int match;
int n1 = n / 1000;
int n2 = n / 100 % 10;
int n3 = n % 100 / 10;
int n4 = n % 10;
int m1 = m / 1000;
int m2 = m / 100 % 10;
int m3 = m % 100 / 10;
int m4 = m % 10;
if (n1 == m1) {
match++;
}
if (n2 == m2) {
match++;
}
if (n3 == m3) {
match++;
}
if (n4 == m4) {
match++;
}

return match;
}

int hits(int n, int m)
{
int narrayvalue[N_DIGITS] = { 0, 0, 0, 0 };
int marrayvalue[N_DIGITS] = { 0, 0, 0, 0 };
narrayvalue[0] = n / 1000;
narrayvalue[1] = n / 100 % 10;
narrayvalue[2] = n % 100 / 10;
narrayvalue[3] = n % 10;
marrayvalue[0] = m / 1000;
marrayvalue[1] = m / 100 % 10;
marrayvalue[2] = m % 100 / 10;
marrayvalue[3] = m % 10;
int i;
int j;
int hit = 0;
for (i = 0; i < N_DIGITS; i++) {
for (j = 0; j < N_DIGITS; j++) {
if (marrayvalue[j] == narrayvalue) {
if (i == j) {
} else {
hit++;
}
}
}
}

return hit;
}

int main(void)
{
int i;
int m;
int n;
int match;
int hit;
printf("***Welcome to the MATCH and HIT game***\n");
printf("The computer has selected a 4-digit number.\n");
printf("Try to deduce it in 12 round of queries.\n");
n = choose_n();
for (i = 1; i <= MAX_QUERIES; i++) {
printf("round #%d\n", i);
loop:printf("Please enter your query (4 digit) :");
scanf("%d", &m);
if (isvalid(m)) {
match = matches(n, m);
hit = hits(n, m);
printf("-> %d matches and %d hits\n", match, hit);
if (match == N_DIGITS) {
printf("**********************************\n");
printf("CONGRATULATIONS! You won the game!\n");
printf("**********************************\n");
exit(0);
}
} else {
printf("Invalid query. Please try again!\n");
goto loop;
}
match = 0;
hit = 0;
}
printf("*********************************\n");
printf("Sorry, out of queries. Game over!\n");
printf("*********************************\n");
return 0;
}```

Popular pages Recent additions