Untitled
unknown
plain_text
10 months ago
2.2 kB
14
Indexable
#include <stdio.h>
int isValidNum(int n)
{
if(n < 1000 || n > 9999) return 0;
int seen[10] = {0};
for(int i = 0; i < 4; i++)
{
int digit = n % 10;
if(seen[digit] != 0) return 0;
seen[digit]++;
n /= 10;
}
return 1;
}
int is_shot(int num, int guess) // the function returns how many digits are in the same place
{
if(num == 0 || guess == 0) return 0;
return (num%10 == guess%10) + is_shot(num/10, guess/10);
}
int is_hit_helper(int num, int n) // helper function for is_hit()
{
if(num == 0) return 0;
return (num%10 == n) + is_hit_helper(num/10, n);
}
int is_hit(int num, int guess) // the function returns how many simillar digits there are
{
int count = 0;
while(guess != 0)
{
count += is_hit_helper(num, guess%10);
guess /= 10;
}
return count;
}
int get_num(int turn) // the function returns a valid num from the user
{
int num;
do{
printf("Player %d, enter your number: ", turn);
scanf("%d", &num);
} while(!isValidNum(num));
return num;
}
int main()
{
int p1_num, p2_num;
int winner;
int current_guess = 0;
int current_turn = 0;
int turns_counter = 0;
p1_num = get_num(1);
p2_num = get_num(2);
int nums[] = {p1_num, p2_num};
printf("----- TIME FOR GUESSES -----\n");
while((current_turn == 1 && current_guess != p2_num) ||
(current_turn == 0 && current_guess != p1_num))
{
current_guess = get_num(current_turn+1);
printf("Player %d has %d hits and %d shots.\n", current_turn + 1,
is_hit(nums[!current_turn], current_guess),
is_shot(nums[!current_turn], current_guess));
current_turn = !current_turn;
turns_counter++;
}
if(current_guess == p1_num) winner = 2;
else winner = 1;
printf("The GREAT winner is Player %d. Guessed the number by %d turns. ", winner,
turns_counter/2 + current_turn);
return 0;
}Editor is loading...
Leave a Comment