자바 순열, 조합 구하기 (파이썬 itertools 라이브러리)

2024. 3. 12. 13:21·Java
728x90
  • 자바는 파이썬의 itertools 라이브러리 같은 내장함수로 순열, 조합이 없어 직접 구현해야함
  • n개중에 r개 선택한다는 가정
  • Depth를 r만큼 재귀

 

변수
int n, r : n개 중 r개를 뽑음
 int[] now : 현재 저장한 list값 인덱스
 List<List<String>> result : 결과값
 boolean[] visited : 순열 방문 여부

 

순열

public static void permutation(List<String> list, int depth) {
    if (depth == r) {
        List<String> temp = new ArrayList<>();
        for (int i = 0; i < now.length; i++) {
            temp.add(list.get(now[i]));
        }
        result.add(temp);
        return;
    }

    for (int i = 0; i < n; i++) {
        if (!visited[i]) {
            visited[i] = true;
            now[depth] = i;
            permutation(list, depth + 1);
            visited[i] = false;
        }
    }
}

 

중복 순열

public static void permutationWithRepetition(List<String> list, int depth) {
    if (depth == r) {
        List<String> temp = new ArrayList<>();
        for (int i = 0; i < now.length; i++) {
            temp.add(list.get(now[i]));
        }
        result.add(temp);
        return;
    }
    for (int i = 0; i < n; i++) {
        now[depth] = i;
        permutationWithRepetition(list, depth + 1);
    }
}

 

조합

    public static void combination(List<String> list, int depth, int index, int target) {
        if (depth == r) {
            List<String> temp = new ArrayList<>();
            for (int i = 0; i < now.length; i++) {
                temp.add(list.get(now[i]));
            }
            result.add(temp);
            return;
        }
        if (target == n) return;

        now[index] = target;
        combination(list, depth + 1, index + 1, target + 1);
        combination(list, depth, index, target + 1);
    }

 

중복 조합

public static void combinationWithRepetition(List<String> list, int depth, int index) {
    if (depth == r) {
        List<String> temp = new ArrayList<>();
        for (int i = 0; i < now.length; i++) {
            temp.add(list.get(now[i]));
        }
        result.add(temp);
        return;
    }
    for (int i = index; i < n; i++) {
        now[depth] = i;
        combinationWithRepetition(list, depth + 1, i);
    }
}

 

메인

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {

    public static int n, r;
    private static int[] now;
    private static boolean[] visited;
    private static List<List<String>> result;

    public static void main(String[] args) {

        List<String> list = Arrays.asList("1", "2", "3");

        n = list.size();
        r = 2;
        now = new int[r];
        visited = new boolean[n];
        result = new ArrayList<>();

        combination(list, 0, 0, 0);
        System.out.println(result);

        combinationWithRepetition(list, 0, 0);
        System.out.println(result);

        permutation(list, 0);
        System.out.println(result);

        permutationWithRepetition(list, 0);
        System.out.println(result);

    }

    public static void permutation(List<String> list, int depth) {
        if (depth == r) {
            List<String> temp = new ArrayList<>();
            for (int i = 0; i < now.length; i++) {
                temp.add(list.get(now[i]));
            }
            result.add(temp);
            return;
        }

        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                visited[i] = true;
                now[depth] = i;
                permutation(list, depth + 1);
                visited[i] = false;
            }
        }
    }

    public static void permutationWithRepetition(List<String> list, int depth) {
        if (depth == r) {
            List<String> temp = new ArrayList<>();
            for (int i = 0; i < now.length; i++) {
                temp.add(list.get(now[i]));
            }
            result.add(temp);
            return;
        }
        for (int i = 0; i < n; i++) {
            now[depth] = i;
            permutationWithRepetition(list, depth + 1);
        }
    }
  public static void combination(List<String> list, int depth, int index, int target) {
        if (depth == r) {
            List<String> temp = new ArrayList<>();
            for (int i = 0; i < now.length; i++) {
                temp.add(list.get(now[i]));
            }
            result.add(temp);
            return;
        }
        if (target == n) return;

        now[index] = target;
        combination(list, depth + 1, index + 1, target + 1);
        combination(list, depth, index, target + 1);
    }


    public static void combinationWithRepetition(List<String> list, int depth, int index) {
        if (depth == r) {
            List<String> temp = new ArrayList<>();
            for (int i = 0; i < now.length; i++) {
                temp.add(list.get(now[i]));
            }
            result.add(temp);
            return;
        }
        for (int i = index; i < n; i++) {
            now[depth] = i;
            combinationWithRepetition(list, depth + 1, i);
        }
    }
}

 

 

 

더보기

참고

https://hi-june.github.io/java%20coding%20test/Itertools

 

[자바 코테] java도 itertools가 있었으면 좋겠다..

코딩 테스트용 자바 정리

hi-june.github.io

https://velog.io/@jiwon_choi/%EC%9E%90%EB%B0%94%EC%97%90%EC%84%9C-%EC%88%9C%EC%97%B4%EA%B3%BC-%EC%A1%B0%ED%95%A9-e0utv9d4

 

자바에서 순열과 조합

충격과 경악의 연속인 자바 코테

velog.io

 

728x90
'Java' 카테고리의 다른 글
  • 자바 우선순위큐(PriorityQueue)
  • 자바 스트림(Stream), 람다(Lambda)
  • ProcessBuilder Java 쉘 명령어, 스크립트 실행
  • [Mac OS / Java] 맥 JDK 자바 버전 변경
Karla Ko
Karla Ko
𝘾𝙤𝙣𝙩𝙞𝙣𝙪𝙤𝙪𝙨𝙡𝙮 𝙄𝙢𝙥𝙧𝙤𝙫𝙞𝙣𝙜, 𝘾𝙤𝙣𝙨𝙩𝙖𝙣𝙩𝙡𝙮 𝘿𝙚𝙫𝙚𝙡𝙤𝙥𝙞𝙣𝙜 𝙔𝙚𝙨!
    250x250
  • Karla Ko
    karlaLog
    Karla Ko
  • 전체
    오늘
    어제
    • Total (467)
      • Spring (19)
      • JPA (4)
      • Cloud & Architecture (15)
        • Kubernetes (5)
        • Docker (3)
        • MSA (2)
        • GCP (1)
        • AWS (4)
      • Devops (1)
      • Message Queue (4)
        • Kafka (2)
        • RabbitMQ (2)
      • Git (4)
      • DB (4)
      • Java (9)
      • Python (4)
      • CS (11)
        • OS (8)
        • Network (2)
        • Algorithm (1)
      • Coding Test (392)
        • programmers (156)
        • Graph (43)
        • DP (37)
        • Search (31)
        • Tree (13)
        • Data Structure (26)
        • Combination (12)
        • Implement (18)
        • Geedy (23)
        • Sort (7)
        • Math (21)
        • geometry (2)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    DFS
    그리디
    구현
    프로그래머스
    동적계획법
    최단거리
    BFS
    힙
    DP
    Algorithm
    다익스트라
    구간합
    최대공약수
    자료구조
    재귀
    조합
    큐
    백준
    이분탐색
    최소신장트리
    그래프
    트리
    파이썬
    월간코드챌린지
    덱
    플로이드워셜
    스택
    정렬
    LIS
    알고리즘
  • hELLO· Designed By정상우.v4.10.3
Karla Ko
자바 순열, 조합 구하기 (파이썬 itertools 라이브러리)
상단으로

티스토리툴바