1.取[0-n]的n个随机数存入数组中,要求数据不能重复.
}
1.2
public class homework04_2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入n,将生成n个随机数存入数组array[n]");
int n = sc.nextInt();
int a[] = new int[n];
suiJi(a,n);
}
public static void suiJi(int a[],int n)
{
Random r= new Random();
int c=0;
Outer:while(c
int s=r.nextInt(n);
for(int i=0;i
if(a[i]==s)
continue Outer;
}
a[c]=s;
c++;
}
for(int i=0;i
System.out.println(a[i]);
}
}
}
2. 设计一个方法,将数组中的数据打乱顺序
import java.util.Random;
public class homework05 {
public static void main(String[] args) {
int n = 10;
int a[]=disorder(n);
for(int i=0;i
System.out.println(a[i]);
}
}
public static int[] disorder(int n)
{
Random r = new Random();
int a[] = new int [n];
for(int i=0;i
a[i] = i;
}
for(int i=0;i
int number = r.nextInt(n);
int temp = a[i];
a[i] = a[number];
a[number] = temp;
}
return a;
}
}
3.去除数组{1,3,1,4,2,3,6,1,5}中的重复项,存入一个新的数组,并从大到小排序.
public class homework08 {
public static void main(String[] args) {
int arr[] = { 1, 3, 1, 4, 2, 3, 6, 1, 5 };
int number = 0;
int count = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 1; j < arr.length - i; j++) {
int temp = 0;
if (arr[j] > arr[j - 1]) {
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
}
for (int i = 0; i < arr.length; i++) {
number = arr[i];
boolean s = true;
for (int j = 0; j < i; j++) {
if (number == arr[j]) {
count++;
s=false;
}
}
if (!s) {
arr[i] = -1;
} else {
arr[i] = number;
}
}
int b[] = new int[arr.length - count];
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != -1) {
b[j] = arr[i];
j++;
}
}
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
}
}
4.给定一个含有n个元素的整型数组a 例如{1,1,1,2,4,3,3} ,如果某些元素出现的次数为奇数次,则将其输出:例如1,2,4
public class homework09 {
public static void main(String[] args) {
int a[] = { 1, 1, 1, 2, 4, 3, 3 };
int c[] = new int[a.length];
int number = 0;
int count = 0;
for (int q = 0; q < a.length; q++) {
c[q] = a[q];
// System.out.println(c[q]);
}
for (int i = 0; i < a.length; i++) {
boolean s = true;
number = a[i];
for (int j = 0; j < i; j++) {
if (number == a[j])
s = false;
}
if (!s) {
count++;
a[i] = -1;
} else {
a[i] = number;
}
}
int b[] = new int[a.length - count];
int count1 = 0;
for (int k = 0; k < a.length; k++) {
if (a[k] != -1) {
b[count1] = a[k];
count1++;
}
}
// for(int z=0;z
// {
// System.out.println(b[z]);
// }
for (int m = 0; m < b.length; m++) {
number = b[m];
int count2 = 0;
for (int n = 0; n < c.length; n++) {
if (number == c[n])
count2++;
}
if (count2 % 2 != 0) {
System.out.println(b[m]);
}
}
}
}