본문 바로가기
알고리즘/개념

순열

by 도쿠니 2022. 3. 30.

1. 팩토리얼

- 1에서 n까지 모든 자연수의 곱  = n!

        //5!
        int n = 5;
        
        // for문
        int result = 1;
        for (int i = 1; i <= n; i++) {
            result *= i;
        }
        System.out.println(result); // 120

        //IntStream 이용
        int result2 = IntStream.range(2, 6).reduce(1, (x, y) -> x * y);
        System.out.println(result2); // 120
        
        
     // 재귀함수 이용
     public static int factorial(int num) {
        if (num == 1) {
            return 1;
        }
        return num * factorial(num - 1);
    }

 

2. 순열 (Permutation)

- 순서를 정해서 나열

- 서로 다른 n개 중에 r개를 선택하는 경우의 수 ( 순서 O , 중복 X )

 

nPr = n! / (n-r)!  (단 , 0 < r <= n)

        int n = 5;
        int r = 3;

        int nF = IntStream.range(2, n+1).reduce(1, (x, y) -> x * y);
        int rF = IntStream.range(2, n-r+1).reduce(1, (x, y) -> x * y);

        int result1 = nF / rF;

        int result2 = 1;
        for (int i = n; i >= n - r + 1; i--) {
            result2 *= i;
        }
        System.out.println(result1);  // 60
        System.out.println(result2);  // 60

 

3. 중복 순열

- 서로 다른 n개 중에 r개를 선택하는 경우의 수 ( 순서 O, 중복 O )

 

n∏r = n의 r승

        // 서로 다른 4개의 수 중 2개를 뽑는 경우의 수 (중복 허용)
        int n = 4;
        int r = 2;

        int result1 = (int) Math.pow(n, r);
        System.out.println(result1); // 16

        int result2 = 1;
        for (int i = 0; i < r; i++) {
            result2 *= n;
        }
        System.out.println(result2); // 16

 

4. 원 순열

- 원 모양의 테이블에 n개의 원소를 나열하는 경우

 

𝑛! / 𝑛 = (n − 1)! 

        // 원 모양의 테이블에 3명을 앉히는 경우의 수
        int n = 3;

        int result = IntStream.range(2, n).reduce(1, (x, y) -> x * y);
        System.out.println(result);

'알고리즘 > 개념' 카테고리의 다른 글

점화식과 재귀함수  (0) 2022.04.01
조합 (Combination)  (0) 2022.04.01
최대 공약수, 최소 공배수 구하기  (0) 2022.03.30
경우의 수  (0) 2022.03.30
집합 (Set)  (0) 2022.03.30

댓글