#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DIGIT_COUNT 4
#define MAX_DIGIT 10
void shuffleArray(int *arr, int length) {
for (int i = 0; i < length; ++i) {
int randomIndex = rand() % length;
// Swap elements at i and randomIndex
int temp = arr[i];
arr[i] = arr[randomIndex];
arr[randomIndex] = temp;
}
}
void generateRandomNumbers(int *numbers) {
int comp[MAX_DIGIT] = {0}; // Initialize array with all zeros
// Fill comp array with 1 at randomly selected indices
for (int i = 0; i < DIGIT_COUNT; ++i) {
int randomIndex;
do {
randomIndex = rand() % MAX_DIGIT;
} while (comp[randomIndex] == 1);
comp[randomIndex] = 1;
}
// Select numbers from comp array (indices with value 1)
int index = 0;
for (int i = 0; i < MAX_DIGIT; ++i) {
if (comp[i] == 1) {
numbers[index++] = i;
}
}
// Shuffle the array to randomize the order
shuffleArray(numbers, DIGIT_COUNT);
}
int contains(int *arr, int length, int num) {
for (int i = 0; i < length; ++i) {
if (arr[i] == num) {
return 1; // True
}
}
return 0; // False
}
void getPlayerInput(int *numbers) {
printf("Enter %d single-digit numbers separated by space: ", DIGIT_COUNT);
for (int i = 0; i < DIGIT_COUNT; ++i) {
int input;
while (1) {
if (scanf("%d", &input) == 1 && input >= 0 && input < MAX_DIGIT && !contains(numbers, i, input)) {
numbers[i] = input;
break;
} else {
printf("Invalid input. Please enter single-digit numbers that are not repeated.\n");
while (getchar() != '\n'); // Clear the input buffer
}
}
}
}
void evaluateGuess(int *computerNumbers, int *playerNumbers, int *strikes, int *balls) {
*strikes = 0;
*balls = 0;
for (int i = 0; i < DIGIT_COUNT; ++i) {
if (computerNumbers[i] == playerNumbers[i]) {
(*strikes)++;
} else if (contains(computerNumbers, DIGIT_COUNT, playerNumbers[i])) {
(*balls)++;
}
}
}
int main(void) {
int computerNumbers[DIGIT_COUNT];
int playerNumbers[DIGIT_COUNT];
int strikes, balls;
srand((unsigned int)time(NULL)); // Move srand to the beginning of the main function
generateRandomNumbers(computerNumbers);
for(int i=0;i<4;i++){
printf("%d ",computerNumbers[i]);
}
while (1) {
getPlayerInput(playerNumbers);
evaluateGuess(computerNumbers, playerNumbers, &strikes, &balls);
printf("Strikes: %d, Balls: %d\n", strikes, balls);
if (strikes == DIGIT_COUNT) {
printf("Congratulations! You've guessed the numbers.\n");
printf("Starting a new game.\n");
} else {
printf("Try again.\n");
}
printf("Enter -1 to exit or any other number to continue: ");
int choice;
scanf("%d", &choice);
if (choice == -1) {
printf("Exiting the game.\n");
break;
}
}
return 0;
}