[6603] - 로또

Jeongmin Yeo (Ethan)·2021년 1월 11일
3

Algorithm

목록 보기
3/3
post-thumbnail

문제

독일 로또는 {1, 2, ..., 49}에서 수 6개를 고른다.

로또 번호를 선택하는데 사용되는 가장 유명한 전략은 49가지 수 중 k(k>6)개의 수를 골라 집합 S를 만든 다음 그 수만 가지고 번호를 선택하는 것이다.

예를 들어, k=8, S={1,2,3,5,8,13,21,34}인 경우 이 집합 S에서 수를 고를 수 있는 경우의 수는 총 28가지이다. ([1,2,3,5,8,13], [1,2,3,5,8,21], [1,2,3,5,8,34], [1,2,3,5,13,21], ..., [3,5,8,13,21,34])

집합 S와 k가 주어졌을 때, 수를 고르는 모든 방법을 구하는 프로그램을 작성하시오.

코드


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        while (true){
            List<Integer> arrList = new ArrayList<>();
            Map<Integer, Boolean> map = new TreeMap<>();
            int loopCount = scanner.nextInt();

            if(loopCount == 0) break;

            for (int i = 0; i < loopCount ; i++) {
                arrList.add(scanner.nextInt());
            }
            int[] ints = arrList.stream().mapToInt(Integer::intValue).toArray();
            recursive(ints, map, 0);
            System.out.print("\n");
        }
    }

    public static void recursive(int[] arr, Map<Integer, Boolean> map, int startIndex) {
        if(map.size() == 6){
            Set<Integer> set = map.keySet();
            set.forEach(i -> System.out.print(i + " "));
            System.out.print("\n");
            return;
        }

        for (int i = startIndex; i < arr.length ; i++) {
            if(!map.containsKey(arr[i])){
                map.put(arr[i], true);
                recursive(arr,map,i+1);
                map.remove(arr[i]);
            }
        }
    }
}

테스트 코드

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.Map;
import java.util.TreeMap;


class MainTest {
    Map<Integer, Boolean> map = new TreeMap<>();

    @Test
    @DisplayName("6603 TestCase 1")
    void Test1(){
        int[] arr = new int[]{1,2,3,4,5,6,7};
        Main.recursive(arr, map,0);
    }

    @Test
    @DisplayName("6603 TestCase 2")
    void Test2(){
        int[] arr = new int[]{1,2,3,5,8,13,21,34};
        Main.recursive(arr, map,0);
    }
}
profile
좋은 습관을 가지고 싶은 평범한 개발자입니다.

0개의 댓글