재귀를 활용한 문자열 조합과, 소수 판별은 언젠가 또 이용될 거 같으니 꼭 다시 복습하기!
HashSet
사용하여 중복 제거HashSet
안에 담긴 숫자들에 대해 소수를 판별하여 카운팅재귀 메서드의 매개변수로 조합된 문자열과, 남은 문자열을 전달하며 모든 문자열이 반복되도록 한다.
public void recursive(String comb, String others) {
if (!comb.equals("")) { // 첫 로직 실행 시 빈 문자열이므로 이를 넘기기 위함
numbersSet.add(Integer.valueOf(comb));
}
for (int i = 0; i < others.length(); i++) {
recursive(comb + others.charAt(i),
others.substring(0,i) + others.substring(i + 1));
}
}
for (int i = 0; i < others.length(); i++) {
recursive(comb + others.charAt(i),
subsString
을 활용하여 조합에 사용된 해당 문자의 앞 부분
과 뒷 부분
을 자른다.recursive(comb + others.charAt(i),
others.substring(0,i) + others.substring(i + 1));
private static boolean isPrime(int index) {
if (index == 1 || index == 0) {
return false;
}
int lim = (int)Math.sqrt(index);
for (int i = 2; i <= lim; i++) {
if (index % i == 0) {
return false;
}
}
return true;
}
lim
이란 변수에 Math.sqrt()
한 값을 넣어 활용한다. (루트 연산한 값)ArrayList, HashSet과 같은 컬렉션을 반복하는 데 사용할 수 있는 객체.
Iterator<Integer> it = numbersSet.iterator();
처럼 선언하며 hasNext()
와 같이 활용한다.