記錄一下做的幾道編程題

1. 輸入一個整數數組,

    實現一個函數來調整該數組中數字的順序,使得所有的奇數位於數組的前半部分,所有的偶數位於位於數組的後半部分,

    並保證奇數和奇數,偶數和偶數之間的相對位置不變。

   public class Test3 {
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
reOrderArray(a);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}


private static void reOrderArray(int[] a) {
int[] b = new int[a.length];
int oddBegin = 0;
int oddCount = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 1) {
oddCount++;
}
}
for (int j = 0; j < a.length; j++) {
if (a[j] % 2 == 1) {
b[oddBegin++] = a[j];
} else {
b[oddCount++] = a[j];
}
}
for (int i = 0; i < a.length; i++) {
a[i] = b[i];
}
}
}


   2.實現一個蛇形矩陣

  /*
   * 輸出一個蛇形矩陣
   * 例如:
   * 輸入:3
   * 輸出:
   * 1 2 3
   * 8 9 4
   * 7 6 5
   * 
   */
  import java.util.Scanner;


  public class Test2 {
private static int i = 0;
private static int j = 0;
private static int[][] b = null;
private static int start = 1;


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] arr = new int[n][n];
arr = generate(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}


private static int[][] generate(int n) {
int max = n * n;
b = new int[n][n];
while (true) {
int p = i;
int q = j;
for (q = j; q < n; q++) {
b[i][q] = start++;
if (start > max) {
return b;
}
}
for (p = i; p < n - 1; p++) {
b[p + 1][n - 1] = start++;
if (start > max) {
return b;
}
}
for (q = n - 2; q >= j; q--) {
b[n - 1][q] = start++;
if (start > max) {
return b;
}
}
for (p = n - 2; p >= i + 1; p--) {
b[p][j] = start++;
if (start > max) {
return b;
}
}
n--;
i++;
j++;
}
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章