www.jungol.co.kr/bbs/board.php?bo_table=pbank&wr_id=449&sca=99&sfl=wr_hit&stx=1169
JUNGOL | 주사위 던지기1 > 문제은행
주사위를 던진 횟수 N과 출력형식 M을 입력 받아서 M의 값에 따라 각각 아래와 같이 출력하는 프로그램을 작성하시오. M = 1 : 주사위를 N번 던져서 나올 수 있는 모든 경우 M = 2 : 주사위를 N번 던져
www.jungol.co.kr
문제 :
주사위를 던진 횟수 N과 출력형식 M을 입력 받아서 M의 값에 따라 각각 아래와 같이 출력하는 프로그램을 작성하시오. M = 1 : 주사위를 N번 던져서 나올 수 있는 모든 경우 |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int N, M;
static int[] temp;
static boolean[] mask;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
mask = new boolean[7];
temp = new int[7];
temp[0] = 1;
if(M == 1) {
dice1(1, 0);
} else if(M == 2) {
dice2(1, 0);
} else if(M == 3) {
dice3(1, 0);
}
}
public static void dice1(int start, int depth) {
if(depth == N) {
for(int i=1; i<=depth; i++) {
System.out.print(temp[i] + " ");
}
System.out.println();
return;
}
for(int i=1; i<=6; i++) {
temp[start] = i;
dice1(start+1, depth+1);
}
}
public static void dice2(int start, int depth) {
if(depth == N) {
for(int i=1; i<=depth; i++) {
System.out.print(temp[i] + " ");
}
System.out.println();
return;
}
for(int i=temp[start-1]; i<=6; i++) {
temp[start] = i;
dice2(start+1, depth+1);
}
}
public static void dice3(int start, int depth) {
if(depth == N) {
for(int i=1; i<=depth; i++) {
System.out.print(temp[i] + " ");
}
System.out.println();
return;
}
for(int i=1; i<=6; i++) {
if(mask[i]) continue;
temp[start] = i;
mask[i] = true;
dice4(start+1, depth+1);
mask[i] = false;
}
}
}
추가 > dice4 : 중복을 제외하고 모두 다른 수가 나오도록 뽑기 |
public static void dice4(int start, int depth) {
if(depth == N) {
for(int i=1; i<=depth; i++) {
System.out.print(temp[i] + " ");
}
System.out.println();
return;
}
for(int i=temp[start-1]; i<=6; i++) {
if(mask[i]) continue;
temp[start] = i;
mask[i] = true;
dice3(start+1, depth+1);
mask[i] = false;
}
}
'ALGORITHM > 이론' 카테고리의 다른 글
Bubble Sort. 버블정렬 (0) | 2021.01.05 |
---|---|
Insertion sort. 삽입정렬 (0) | 2021.01.04 |
Selection sort. 선택정렬 (0) | 2021.01.04 |
HashMap(해시테이블) (0) | 2020.11.14 |
ArrayList(선형리스트) (0) | 2020.11.09 |