记录一下做的几道编程题

来源:互联网 发布:录音软件免费下载 编辑:程序博客网 时间:2024/06/06 03:57

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++;
}
}
}

0 0
原创粉丝点击