LoginSignup
0
0

[java] int配列から順列を得る方法

Posted at

序論

Javaの勉強中、int配列から順列を得る方法が必要であったので、そのメモ

Code

Permutation
import java.util.ArrayList;

public class Permutation {

	static public ArrayList<ArrayList<Integer>> resultList = new ArrayList<>();

	static ArrayList<ArrayList<Integer>> getPermutation(int[] arr, int[] output, boolean[] visited, int depth, int n, int r) {
		resultList.clear();
		permutation(arr, output, visited, 0, n, r);
		return resultList;
	}

	static void permutation(int[] arr, int[] output, boolean[] visited, int depth, int n, int r) {
		if (depth == r) {
			addToResult(output, r);
			return;
		}

		for (int i = 0; i < n; i++) {
			if (visited[i] != true) {
				visited[i] = true;
				output[depth] = arr[i];
				permutation(arr, output, visited, depth + 1, n, r);
				visited[i] = false;
			}
		}
	}

	static void swap(int[] arr, int depth, int i) {
		int temp = arr[depth];
		arr[depth] = arr[i];
		arr[i] = temp;
	}

	static void addToResult(int[] arr, int r) {

		ArrayList<Integer> temp = new ArrayList<>();

    // なぜかfor文ではないと、List内の順番がすべて一緒になってします。
		for (int i = 0; i < r; i++) {
			temp.add(arr[i]);
		}
		resultList.add(temp);
	}
}
PermutationUse
import java.util.ArrayList;

public class PermutationUse {
	public static void main(String[] args) {
		int n = 3;
		int[] arr = { 1, 2, 3 };
		int[] output = new int[n];
		boolean[] visited = new boolean[n];

		ArrayList<ArrayList<Integer>> permu = new ArrayList<>();
		permu = Permutation.getPermutation(arr, output, visited, 0, n, n);
		System.out.println(permu);

    // [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
	}
}

おわりに

javaの配列は長さの制限があるので、なるべく使用したくないのが正直な感想ではあるが、あまりにも基本的な部分なので、使用しないことも難しさを感じる。
今回はList型で出力をしたが、Array化は簡単であるので、List出力を基本で考えた方が、応用ができそう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0