230208 공부내용 정리
주사위 던지는 경우의수 실습
package algo;
import java.util.Arrays;
import java.util.Scanner;
public class Dice {
static int N;
static int [] numbers;
static int totalCnt;
static boolean[] isSelected;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int mode = sc.nextInt();
N = sc.nextInt();
numbers = new int[N];
switch (mode) {
case 1:
dice1(0);
break;
case 2:
isSelected = new boolean[7];
dice2(0);
break;
case 3:
dice3(0,1);
break;
case 4:
dice4(0,1);
break;
}
System.out.println("총 경우의수: "+totalCnt);
}
private static void dice1(int cnt) {
if(cnt ==N) {
System.out.println(Arrays.toString(numbers));
totalCnt++;
return;
}
for(int i=1; i<=6; i++) {
numbers[cnt] =i;
dice1(cnt+1);
}
}
private static void dice2(int cnt) {
if(cnt ==N) {
System.out.println(Arrays.toString(numbers));
totalCnt++;
return;
}
for(int i=1; i<=6; i++) {
if(isSelected[i])continue;
numbers[cnt] =i;
isSelected[i] = true;
dice2(cnt+1);
isSelected[i] = false;
}
}
private static void dice3(int cnt, int start) {
if (cnt==N) {
System.out.println(Arrays.toString(numbers));
totalCnt++;
return;
}
for (int i = start; i <= 6; i++) {
numbers[cnt] = i;
dice3(cnt+1,i);
}
}
private static void dice4(int cnt, int start) {
if (cnt==N) {
System.out.println(Arrays.toString(numbers));
totalCnt++;
return;
}
for (int i = start; i <= 6; i++) {
numbers[cnt] = i;
dice4(cnt+1,i+1);
}
}
}