ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Baekjoon] 15650번 N과 M(2) (Java)
    Java/Baekjoon 2022. 8. 28. 01:47

     

     

     

    package Q15650;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Scanner;
    import java.util.Random;
    
    public class Main {
    	public static void main(String[] args) {
    		Scanner scan = new Scanner(System.in);
    		
    		int x = scan.nextInt();
    		int y = scan.nextInt();
    		
    		// 조합 이용
    		Random rand = new Random();
    		HashSet<String> set = pick(rand, x, y);
    		ArrayList<String> al = new ArrayList<>(set);
    		Collections.sort(al);					// HashSet을 ArrayList로 변환해서 정렬
    		for(int i = 0; i < al.size(); i++) {
    			System.out.println(al.get(i));
    		}
    	}
    	
    	public static HashSet<String> pick(Random rand, int x, int y) {
    		int fac = fac(x)/(fac(y)*fac(x-y));			// 뽑을 수 조합 경우의 수
    		
    		HashSet<String> set = new HashSet<String>();				
    		while(set.size() < fac) {				// set을 이용하여 숫자 조합 중복 방지
    			HashSet<Integer> newSet = new HashSet<Integer>();		
    			while(newSet.size() < y) {			// set을 이용하여 숫자 중복 방지
    				int rnd = rand.nextInt(x) + 1;		// 1 ~ x까지 난수
    				newSet.add(rnd);
    			}
    			Iterator it = newSet.iterator();
    			String str = "";
    			while(it.hasNext()) {
    				str += it.next() + " ";
    			}
    			set.add(str);
    		}
    		return set;
    	}
    	
    	public static int fac(int num) {
    		if(num > 0) {
    			return num * fac(num-1);
    		}else {
    			return 1;
    		}
    	}
    }

     

    1. fac메서드를 이용하여 숫자를 뽑을 수 있는 경우의 수를 구함(xCy)

    2. set(HashSet)을 이용하여 숫자 조합이 중복되지 않도록 함 

    3. newSet(HashSet)을 이용하여 숫자 중복이 되지 않도록 함

    4. HashSet을 ArrayList로 변환하여 Collections.sort로 정렬

    728x90
Designed by Tistory.