0~9까지의 숫자를 한 번씩 사용하여 만든 세 자리 숫자를 맞추는 코드를 작성하시오. 숫자와 자리가 맞으면 S이고 숫자만 맞으면 B입니다.
컴퓨터가 세 자리 숫자를 설정하고 사용자에게 숫자를 입력받아 S와 B의 개수를 알려주십시오. 정답을 맞히면 정답이라고 알려주고 사용자가 숫자를 룰에 어긋나게 입력 시 경고문을 출력하고 다시 숫자를 입력할 수 있게 하십시오.
예) 정답이 123일 때 사용자가 234를 입력 시 0S2B, 사용자가 109를 입력 시 1S0B, 사용자가 327을 입력 시 1S1B입니다.
int num[3] = { 0,};
int random_value[3] = { 0,};
int input_value[3] = { 0,};
char input_str[4];
for (i = 0; i < 3; i++)
random_value[i] = rand() % 10; // random (0~9)
while(1)
{
printf("숫자를 3자리 입력하세요 :");
scanf("%s", input_str); //입력된 숫자를 확인시켜주는 코드
for (i = 0; i < 3; i++)
{
printf("%c", input_str[i]);
input_value[i] = input_str[i] - 0x30; #ascii code 48 --> '0'
}
strike = 0;
ball = 0;
for(j = 0 ; j < 3; j++)
{
for(i = 0; i< 3; i++)
{
if((random_value[j] == input_value[i]) && (i==j))
strike++
else if((random_value[j] == input_value[i]))
ball++;
}
}
print("%dS %B \r\n",strike,ball);
}
2022年08月23日 12:56
#include<iostream>
#include<vector>
#include<cstdlib>
#include<ctime>
using namespace std;
int main() {
// 숫자 야구
int n;
int count = 0;
cout << "자릿수를 입력하시오(3 or 4): ";
cin >> n;
srand(time(0));
vector<int> arr(n);
for (int i = 0; i < n; i++) {
arr[i] = rand() % 10;
for (int j = 0; j < i; j++) {
if (arr[i] == arr[j]) i--; // 중복 방지
}
}
vector<int> user(n); // 사용자 입력 벡터 크기를 n으로 설정
int s = 0, b = 0;
while (s != n) { // 스트라이크 n개가 될 때까지 반복
s = b = 0;
count += 1;
cout << n << "자리 숫자를 입력하세요: ";
for (int i = 0; i < n; i++) cin >> user[i]; // 사용자 입력
// 스트라이크와 볼 계산
for (int i = 0; i < n; i++) {
if (user[i] == arr[i]) s++; // 스트라이크
else if (find(arr.begin(), arr.end(), user[i]) != arr.end()) b++; // 볼
}
cout << s << "S " << b << "B" << endl;
if (s == n) cout << "정답입니다!" << endl;
else cout << "다시 시도하세요." << endl;
}
// 정답 출력
cout << "정답은: ";
for (int i = 0; i < n; i++) cout << arr[i];
cout << endl;
cout << "시도횟수: " << count << endl;
}
풀이 작성