0~9까지의 숫자를 한 번씩 사용하여 만든 세 자리 숫자를 맞추는 코드를 작성하시오. 숫자와 자리가 맞으면 S이고 숫자만 맞으면 B입니다.
컴퓨터가 세 자리 숫자를 설정하고 사용자에게 숫자를 입력받아 S와 B의 개수를 알려주십시오. 정답을 맞히면 정답이라고 알려주고 사용자가 숫자를 룰에 어긋나게 입력 시 경고문을 출력하고 다시 숫자를 입력할 수 있게 하십시오.
예) 정답이 123일 때 사용자가 234를 입력 시 0S2B, 사용자가 109를 입력 시 1S0B, 사용자가 327을 입력 시 1S1B입니다.
import random
# 숫자추출
nums=list(range(0,10))
random.shuffle(nums)
while nums[0]==0:
random.shuffle(nums)
answer = str(nums[0]*100+nums[1]*10+nums[2]*1)
print(answer)
# 값 입력받기
while True:
user_num = input("세자리 숫자를 입력하세요 : ")
# 정답 확인
if user_num == answer:
print("정답을 맞추셨습니다. 게임을 종료합니다.")
break
# 입력값 확인
if user_num.isdigit()==False or len(user_num) != 3:
print("잘못된 입력을 하였습니다. 세자리 숫자를 입력하여 주세요.")
continue
#입력값과 정답비교
strike=0
ball=0
for i in range(3):
if answer[i]==user_num[i]:
strike+=1
elif user_num.count(answer[i])>0:
ball+=1
print("{0}S{1}B".format(strike,ball))
2022年07月26日 16:40
# 숫자야구 3자리 숫자
import random as rd
while 1:
real_a = rd.sample(range(10), 3)
real_b = (real_a[0] * 100) + (real_a[1] * 10) + (real_a[2])
if real_b < 100:
continue
else:
break
# print(real_b)
print('숫자야구 게임입니다. 0~9까지의 숫자를 한번씩 사용하여 만든 세자리 숫자를 맞추십시오.')
print('숫자와 자리가 맞으면 \'S\' 숫자만 맞으면 \'B\' 입니다.')
c = 0
while 1:
s = b = 0
input_n = int(input('세자리 숫자를 입력하십시오 : '))
if not 100 <= input_n < 1000:
continue
input_a = [(input_n // 100) % 10, (input_n // 10) % 10, input_n % 10]
if input_a[0] == input_a[1] or input_a[0] == input_a[2] or input_a[1] == input_a[2]:
print('서로다른 세가지의 숫자로 입력해주세요.')
continue
for ii in range(3):
if input_a[ii] == real_a[ii]:
s += 1
elif input_a[ii] in real_a:
b += 1
c += 1
if s == 3:
print('\'{}\'정답입니다. 정답을 \'{}\'번만에 맞추셨습니다. 축하드립니다.'.format(real_b, c))
exit(0)
print('{}S{}B'.format(s, b))
pass
import java.util.Random; // 임의의 수를 입력하기 위한 랜덤 임포트
import java.util.Scanner; // 플레이어 입력을 위한 스캐너 임포트
public class NumGame { // 클래스 이름은 게임명
public static void main(String[] args) { // 메인메서드 시작
Random r = new Random(); // 랜덤메서드 객체 선언
Scanner sc = new Scanner(System.in); // 스캐너메서드 객체 선언
int[] rnums = new int[3]; // 랜덤숫자를 담을 배열 선언
int[] input_nums = { 0, 0, 0 }; // 플레이어 입력 변수를 담을 배열 선언 및 초기화
int times = 0; // 플레이어 문제풀이 횟수를 담을 변수 선언
System.out.println("Line13");
rnums[0] = r.nextInt(1, 9); // 랜덤숫자를 담을 변수 중 첫번째는 바로 입력
System.out.println(rnums[0]);
boolean num123 = (rnums[0] == rnums[1]) || (rnums[0] == rnums[2]) || (rnums[1] == rnums[2]);
// 랜덤숫자가 서로 같은 게 하나라도 있을 경우에 따른 boolean값을 담을 변수
while (true) { // 위 boolean값을 담은 값
rnums[1] = r.nextInt(1, 9); // 두번째 숫자에 랜덤숫자를 다시 대입
rnums[2] = r.nextInt(1, 9); // 세번째 숫자에 랜덤숫자를 다시 대입
if ((rnums[0] == rnums[1]) || (rnums[0] == rnums[2]) || (rnums[1] == rnums[2])) {
continue;
} else {
break;
}
}
System.out.println(rnums[1]);
System.out.println(rnums[2]);
System.out.println("Line21");
while (rnums[0] != input_nums[0] || rnums[1] != input_nums[1] || rnums[2] != input_nums[2]) {
// 랜덤숫자와 플레이어 입력 숫자가 하나라도 틀리면 while문 진입함.
// 반대로, 모두 같으면(정답이면) while문 진입하지 않음.
int strike = 0; // 게임기능 스트라이크를 담을 변수 선언 및 초기화
int ball = 0; // 게임기능 볼을 담을 변수 선언 및 초기화
try {
System.out.print("숫자 >> "); // 입력 안내메시지
input_nums[0] = sc.nextInt(); // 첫번째자리 입력
input_nums[1] = sc.nextInt(); // 두번째자리 입력
input_nums[2] = sc.nextInt(); // 세번째자리 입력
boolean ip0 = (input_nums[0] >= 10) || (input_nums[0] <= 0);
boolean ip1 = (input_nums[1] >= 10) || (input_nums[1] <= 0);
boolean ip2 = (input_nums[2] >= 10) || (input_nums[2] <= 0);
if (ip0 || ip1 || ip2) {
continue;
}
} catch (Exception e) {
System.err.println("잘못된 입력입니다. 다시 입력해주시기 바랍니다.");
continue;
}
times++; // 시도횟수 증감식. 제대로 입력했을 경우에만 증가하도록 함.
for (int i = 0; i < input_nums.length; i++) {
if (rnums[i] == input_nums[i]) {
strike += 1;
} else {
if (i == 0) {
if (rnums[0] == input_nums[1] || rnums[0] == input_nums[2]) {
ball += 1;
}
} else if (i == 1) {
if (rnums[1] == input_nums[0] || rnums[1] == input_nums[2]) {
ball += 1;
}
} else if (i == 2) {
if (rnums[2] == input_nums[1] || rnums[2] == input_nums[0]) {
ball += 1;
}
}
}
}
System.out.printf("%dS %dB\n", strike, ball);
// 게임결과 출력
System.out.println();
// 가독성을 위한 줄바꿈
}
System.out.printf("축하합니다! %d번만에 문제를 맞혔습니다.", times);
}
}
2022年07月30日 12:35
#include<stdio.h>
int main(void) {
int num[3] = { 0, 0, 0 }, i;
for (i = 0; i < 3; i++)
{
num[i] = rand() % 9 + 1; // 랜덤으로 숫자 생성(1~9)
}
int swi = 1;
while (swi == 1) // swi는 스위치
{
char ans[4]; // 입력할 수는 ans
printf("숫자 입력(100의 자리까지) :");
scanf("%s", ans); //입력된 숫자를 확인시켜주는 코드
for (i = 0; i < 3; i++) printf("%c", ans[i]);
printf(" 입력됨\n");
swi = check(num, ans);
}
}
int check(int* pnum, char* pans)
{
int res[2] = { 0, 0 }, i, j; // res[0]은 스트라이크, res[1]은 볼
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
if ((pnum[i] == (int)pans[j] - 48) && (i == j)) // '1'의 정수형은 49
{
res[0]++; // 스트라이크
break;
}
if ((pnum[i] == (int)pans[j]- 48) && (i != j))
{
res[1]++; // 볼
break;
}
}
}
if (res[0] == 3)
{
printf("축하합니다. 3 strikes!\n");
return 0;
}
else
{
printf("%d strikes, %d balls\n", res[0], res[1]);
return 1;
}
}
2022年07月31日 01:21
자바로 작성하였습니다.
package baseball;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int base1 = (int) (Math.random() * 9 + 1);
int base2 = (int) (Math.random() * 9 + 1);
int base3 = (int) (Math.random() * 9 + 1);
//이상 123은 정답 숫자
int s = 0;
int b = 0;
int homerun = 0;
int out = 0;
//3가지 숫자가 겹치지 않게금 해주는 코드
while (true) {
while (base1 == base2) {
base2 = (int) (Math.random() * 9 + 1);
if (base1 != base2) {
}
}
while (base3 == base1 & base3 == base2) {
base3 = (int) (Math.random() * 9 + 1);
if (base3 != base1 & base3 != base2) {
}
}
if (base1 != base2 & base1 != base3 & base2 != base3) {
break;
}
}
//코드 끝
exit: while (true) {
while (out != 3) {
System.out.println("------------");
System.out.println("당신의 카운트" + out);
System.out.println("3이되면 패배합니다.");
System.out.println("------------");
System.out.println("첫번째 숫자를 입력하십시오");
int run1 = sc.nextInt();
System.out.println("두번째 숫자를 입력하십시오");
int run2 = sc.nextInt();
System.out.println("세번째 숫자를 입력하십시오");
int run3 = sc.nextInt();
//이상 유저의 입력을 받는 숫자.
if (run1 == base1) {
s = s + 1;
}
if (run1 == base2) {
b = b + 1;
}
if (run1 == base3) {
b = b + 1;
}
if (run2 == base1) {
b = b + 1;
}
if (run2 == base2) {
s = s + 1;
}
if (run2 == base3) {
b = b + 1;
}
if (run3 == base1) {
b = b + 1;
}
if (run3 == base2) {
b = b + 1;
}
if (run3 == base3) {
s = s + 1;
}
if (s == 3) {
System.out.println("홈런");
homerun = homerun + 1;
}
if (s == 0 & b == 0) {
System.out.println("아웃");
out = out + 1;
} else if (s != 3) {
System.out.println("스트라이크: " + s);
System.out.println("볼: " + b);
}
s = 0;
b = 0;
if (homerun == 1 | out == 3) {
System.out.println("게임종료");
if (homerun == 1) {
System.out.println("승리하였습니다.");
break exit;
} else if (out == 3) {
System.out.println("패배하였습니다.");
break exit;
}
}
}
}
}
}
2022年08月02日 16:15
import java.util.Random;
import java.util.Scanner;
import java.util.stream.IntStream;
public class CountBaseBall {
public static final int DIGIT_NUM = 5; // 숫자야구게임 문제&정답숫자 자릿수
private static String[] digitStr = new String[DIGIT_NUM]; // 정답숫자
private static String[] inputStr = new String[DIGIT_NUM]; // 입력숫자
private static Scanner sc; // 입력객체
public static void main(String[] args) {
int[] num = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 }; // int형 배열
Random r = new Random();
String bf = null;
for (int i = 0; i < digitStr.length; i++) {
int idx = r.nextInt(num.length);
digitStr[i] = num[idx] + "";
num = remove(num, idx);
}
System.out.println(":::::::::::::::::::: BaseBall Game Start ::::::::::::::::::::");
try {
sc = new Scanner(System.in);
while (true) {
System.out.print("[0-9까지] 서로다른 "+DIGIT_NUM+"자리의 값을 입력하시오 : ");
bf = sc.nextLine();
if (bf != null && bf.length() == DIGIT_NUM) {
boolean isNumeric = bf.matches("[+-]?\\d*(\\.\\d+)?"); // 입력된 값 숫자여부 판단
if (isNumeric && dupCheck(bf)) {
bf = bf.substring(0, DIGIT_NUM);
System.out.println("입력한 답 : " + bf);
inputStr = bf.split("");
} else {
// 숫자로 다시입력
continue;
}
int strike = 0;
int ball = 0;
for (int j = 0; j < digitStr.length; j++) {
for (int k = 0; k < inputStr.length; k++) {
if (digitStr[j].equals(inputStr[k])) {
if (j == k) {
strike++;
} else {
ball++;
}
}
}
}
if (strike == digitStr.length) {
System.out.println("정답입니다!! 축하합니다!");
System.out.println(":::::::::::::::::::: BaseBall Game End ::::::::::::::::::::");
break;
} else {
System.out.println("아쉽습니다.. [ " + strike + "S" + ball + "B ] 입니다");
}
}
}
} catch (Exception e) {
// 예외처리
}
}
private static boolean dupCheck(String bf) {
String[] str = bf.split("");
for (int i = 0; i < str.length; i++) {
for (int j = (i+1); j < str.length; j++) {
if ( str[i].equals(str[j])) {
return false;
}
}
}
return true;
}
/**
* 숫자야구게임에서 중복된 숫자를 허용하지 않도록 idx 값 사용 후 제거하는 기능
* @param num int형 숫자배열
* @param idx 삭제할 index 값
* @return 필터링 된 num 값
*/
private static int[] remove(int[] num, int idx) {
return IntStream.range(0, num.length)
.filter(i -> i != idx)
.map(i -> num[i])
.toArray();
}
}
2022年08月09日 23:55
import random
answer = [0,0,0]
answer[0]=str(random.randint(0,9))
i=1
while True: #중복 없는 랜덤값 설정
if i==3:
break
tmp=str(random.randint(0,9))
if tmp in answer:
continue
else:
answer[i]=tmp
i+=1
print(answer)
while True:
input1 = input('맞춰보시오:')
if len(input1) != 3 or input1[0] in input1[1:] or input1[1] == input1[2]: #3자리가 아니거나 중복이면 continue
print('조건에 맞게 입력하시오')
continue
if list(input1) == answer: #정답이면 프로그램 끝냄
print("정답입니다.")
break
scnt=0
bcnt=0
for i in range(3):
if answer[i] == input1[i]:
scnt+=1
elif answer[i]!=input1[i] and input1[i] in answer:
bcnt+=1
print(f'{scnt}S{bcnt}B')
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
def main():
given = input("Enter an integer with three positions")
if len(str(given)) != 3:
raise Exception("Please provide the number in the appropriate format")
answer = 123
# change to string to compare
s_given = given
s_answer = str(answer)
# check S
S = 0
indices = []
for idx, (g, a) in enumerate(zip(s_given, s_answer)):
if g == a:
S += 1
indices.append(idx)
# preparing for checking B
for idx in indices:
s_given = s_given.replace(s_given[idx], '*')
s_answer = s_answer.replace(s_answer[idx], '*')
# check B
B = 0
for c in set(s_given):
try:
int(c)
B += s_answer.count(c)
except:
pass
print(f"{S}S{B}B")
if __name__ == '__main__':
main()
import java.util.HashSet;
import java.util.Scanner;
public class CD_baseball {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a;
int b;
int c;
int ball;
int strike;
while(true) {
a = (int)(Math.random()*10);
b = (int)(Math.random()*10);
c = (int)(Math.random()*10);
HashSet<Integer> p = new HashSet<Integer>();
p.add(a);
p.add(b);
p.add(c);
if(p.size()==3) {
break;
}
}
System.out.println(a*100+b*10+c);
while(true) {
strike = 0;
ball = 0;
System.out.println("1번 숫자 입력");
int s_a = sc.nextInt();
System.out.println("2번 숫자 입력");
int s_b = sc.nextInt();
System.out.println("3번 숫자 입력");
int s_c = sc.nextInt();
if(s_a==a||s_a==b||s_a==c) {
if(s_a==a) {
strike++;
}else {ball++;
}
}
if(s_b==a||s_b==b||s_b==c) {
if(s_b==b) {
strike++;
}else {ball++;
}
}
if(s_c==a||s_c==b||s_c==c) {
if(s_c==c) {
strike++;
}else {ball++;
}
}
System.out.println(strike+"스트라이크,"+ball+"볼");
if(s_a==a&&s_b==b&&s_c==c) {
System.out.println("축하합니다 다 맞추었습니다.");
break;
}
}
sc.close();
}
}
풀이 작성