본문 바로가기

알고리즘

자바 순열

package test01;

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

public class Test순열2 {

	static boolean[] used;
	static String[] cards;
	static String[] result;
	static ArrayList<String> str = new ArrayList<>();
	static ArrayList<String[]> str2 = new ArrayList<>();

	static void perm(int idx) {
		if (idx == result.length) {
			str.add(Arrays.toString(result));
			str2.add(result); // 잘못된 코드 -> static 변수는 고정된 주소값을 갖고 있기 때문에 같은 주소만 add하고 있음
			// 해결방법 -> Arrays.copyOf(result, result.length);
			return;
		}

		for (int i = 0; i < cards.length; i++) {
			if (used[i] == true) {
				continue;
			}

			result[idx] = cards[i];
			used[i] = true;
			perm(idx + 1);
			used[i] = false;
		}

	}

	public static void main(String[] args) {
		cards = new String[4];
		result = new String[4];
		used = new boolean[4];
		cards[0] = "A";
		cards[1] = "B";
		cards[2] = "C";
		cards[3] = "D";
		perm(0);

		for (int i = 0; i < str.size(); i++) {
			System.out.println(str.get(i));
		}
		System.out.println();

		// 잘못된 코드 -> 위에서 static 변수의 고정된 주소값을 저장했기 때문에, 똑같은 주소의 값만 보여줌
		for (int i = 0; i < str.size(); i++) {
			String[] temp = str2.get(i);
			for (int j = 0; j < temp.length; j++) {
				System.out.print(temp[j] + " ");
			}
			System.out.println();
		}
	}

}

 

정상 출력 화면 (str1)
비정상 출력 화면 (str2)

 

'알고리즘' 카테고리의 다른 글

슬라이딩 윈도우  (0) 2022.08.05
자바 조합  (0) 2022.08.03
자바 부분 집합  (0) 2022.08.03
자바 입/출력 처리  (0) 2022.08.01