迴圈實現從一個陣列中按順序任意擷取幾個字元。

Yuki_NNNN發表於2015-04-22
百度有人提出一個問題 在一個陣列中任意提取幾個元素組成一個新陣列。用迴圈遊標陣列的方式實現了一下。
<span style="font-family: Arial, Helvetica, sans-serif;">public class TestArray {</span>
	public static void main(String[] args) {
		int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		ergodicArray(a, 5);
	}
	
	public static void ergodicArray(int[] a,int length){
		if(length>a.length)
			throw new RuntimeException("長度錯誤");
		else{
			int[] b=new int[length];
			for(int i=0;i<length;i++)
				b[i]=i;
			ergodicArray(a,b);
		}
	}

	public static void ergodicArray(int[] a, int[] b) {

		while (b[0] < (a.length - b.length)) {
			if (b[b.length - 1] < a.length) {
				for (int i = 0; i < b.length; i++) {
					System.out.print(a[b[i]]);
					if(i<b.length-1)
					    System.out.print(',');
				}
				System.out.println();
				++b[b.length - 1];
			} else {
				int j = b.length - 1;
				while (j >= 0) {
					if (b[j] != a.length - (b.length - j) + 1) {
						// j--;
						break;
					} else
						j--;
				}
				if ((b[0] == (a.length - b.length - 1) || b[j] <= (a.length - b.length + j))) {
					int t = 0;
					for (int i = j; i < b.length; i++) {
						if (i == j) {
							b[i]++;
						} else {
							b[i] = b[i - 1] + 1;
						}
					}
				}
			}
		}

	}

}

相關文章