[프로그래머스/완전탐색/2] 소수 찾기 (JAVA)

진문장·2021년 11월 2일
0

출처: 프로그래머스 코딩테스트 모의고사 (완전탐색) 2번째 문제
(https://programmers.co.kr/learn/courses/30/lessons/42839)

문제 설명

한자리 숫자가 적힌 종이 조각이 흩어져있습니다. 흩어진 종이 조각을 붙여 소수를 몇 개 만들 수 있는지 알아내려 합니다.

각 종이 조각에 적힌 숫자가 적힌 문자열 numbers가 주어졌을 때, 종이 조각으로 만들 수 있는 소수가 몇 개인지 return 하도록 solution 함수를 완성해주세요.

제한사항

  1. numbers는 길이 1 이상 7 이하인 문자열입니다.
  2. numbers는 0~9까지 숫자만으로 이루어져 있습니다.
  3. "013"은 0, 1, 3 숫자가 적힌 종이 조각이 흩어져있다는 의미입니다.

풀이 방법

init. 수포자 3명의 패턴을 patterns 배열안에 배열로 넣는다. EX) [[1,2,3],[2,1,3]]
1. patterns 배열을 하나씩 순회하면서 result 배열에 해당 pattern을 기준으로 마킹후 채점한 결과를 넣는다.
2. 채점 결과중 가장 점수가 높은 max를 찾는다.
3. answer 배열에 result 배열에서 최고 점수를 가진 원소의 index+1을 넣는다.
4. answer 배열을 넣는다.

소스 코드

import java.util.HashSet;
class Solution {
	private static int CNT=0;
	private static HashSet<Integer> hashSet = new HashSet<Integer>();
	public int solution(String numbers) {
		int answer = 0;
		String[] n = numbers.split("");
		int[] history = new int[n.length];
		for (int i = 0; i < n.length; i++) history[i] = -1;
		search(n, 0, history, "");
		answer = CNT;
		return answer;
	}

	public void search(String[] n, int idx, int[] history, String sum) {
		if (idx < n.length) {
			int num;
			for (int i = 0; i < n.length; i++) {
				if (promising(n, idx, i, history)) {
					history[idx] = i;
					num = Integer.parseInt(sum+n[i]);
					if(!hashSet.contains(num)) {
						if(isPrime(num)) {
							hashSet.add(num);
							CNT++;
						}
					}
					search(n, idx + 1, history, sum+n[i]);
				}
			}
		}
	}

	public boolean promising(String[] n, int idx1, int idx2, int[] history) {
		boolean check = true;
		for (int j = 0; j < idx1; j++) {
			if (idx2 == history[j]) {
				check = false;
				break;
			}
		}
		return check;
	}

	public boolean isPrime(int num) {
		boolean isPrime = true;
		if(num<2) return false;
        int range =(int)Math.sqrt(num);
		for (int n = 2; n < range+1; n++) {
			if (num % n == 0) {
				isPrime = false;
				break;
			}
		}
		return isPrime;
	}
}

후기

완전 탐색문제이긴 하나 굳이 완전탐색을 쓰지않고 반복문을 통해서도 쉽게 풀려서 그냥 풀었다. 난이도가 어려운 문제는 아닌 것 같다.

0개의 댓글