public class RandomSelect {
static void insertWrong(double[] A, double[] B) {
for (int i = 0; i < B.length; i++) {
// rand(a,b) returns rand int r, a <= r <= b
B[i] = A[rand(0,99)];
}
}
static void randomize(int C[]) {
int i;
for (i = 0; i < C.length - 1; i++)
exchange(C, i, rand(i,C.length - 1));
}
static void exchange(int C[], int i, int j) {
int itemp = C[i];
C[i] = C[j];
C[j] = itemp;
}
static void insertRight(double[] A, double[] B) {
int[] C = new int[100];
for (int i = 0; i < C.length; i++)
C[i] = i;
randomize(C);
for (int i = 0; i < B.length; i++)
B[i] = A[C[i]];
}
static void insertRight2(double[] A, double[] B) {
for (int i = 0; i < B.length; i++) {
int index = rand(0, 99-i);
B[i] = A[index];
double temp = A[index];
A[index] = A[99-i];
A[99-i] = temp;
}
}
static int rand(int a, int b) {
return (int)((b - a + 1)*Math.random() + a);
}
| static void sort(double[] X) {
for (int i = 0; i < X.length - 1; i++)
for (int j = 0; j < X.length - 1; j++)
if (X[j] > X[j+1])
exchange(X, j, j+1);
}
static void exchange(double X[],int i,int j){
double temp = X[i];
X[i] = X[j];
X[j] = temp;
}
static void printit(double[] X) {
for (int i = 0; i < X.length; i++) {
System.out.print(X[i] + " ");
if (i%10 == 9) System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
double[] A = new double[100];
// put 100 distinct doubles into A somehow
for (int i = 0; i < A.length; i++)
A[i] = i + 0.5;
double[] B = new double[75];
System.out.println("75 distinct from A");
System.out.println("Wrong way");
insertWrong(A, B);
sort(B);
printit(B);
System.out.println("Right way");
insertRight(A, B);
sort(B);
printit(B);
System.out.println("Second Right way");
System.out.println("Tajchman, Wachter");
insertRight2(A, B);
sort(B);
printit(B);
}
}
|
75 values from A, 50 distinct
Wrong way (red or blue = duplicates)
0.5 2.5 2.5 3.5 5.5 5.5 9.5 9.5 9.5 10.5
13.5 13.5 14.5 14.5 15.5 18.5 18.5 22.5 25.5 25.5
27.5 27.5 27.5 29.5 31.5 32.5 33.5 35.5 35.5 37.5
39.5 39.5 45.5 45.5 46.5 46.5 46.5 47.5 48.5 49.5
49.5 52.5 53.5 55.5 57.5 58.5 58.5 58.5 58.5 60.5
61.5 62.5 62.5 65.5 69.5 70.5 70.5 70.5 73.5 73.5
75.5 75.5 76.5 77.5 78.5 78.5 79.5 81.5 83.5 85.5
89.5 92.5 93.5 97.5 98.5
|
Right way
0.5 1.5 2.5 3.5 5.5 6.5 7.5 8.5 10.5 11.5
13.5 14.5 16.5 18.5 19.5 21.5 22.5 23.5 24.5 25.5
26.5 27.5 28.5 29.5 30.5 31.5 32.5 33.5 34.5 35.5
36.5 37.5 38.5 39.5 43.5 44.5 46.5 48.5 49.5 50.5
52.5 54.5 57.5 59.5 60.5 61.5 62.5 63.5 64.5 65.5
66.5 67.5 68.5 69.5 70.5 71.5 72.5 73.5 74.5 75.5
76.5 77.5 79.5 80.5 82.5 83.5 84.5 85.5 86.5 87.5
88.5 89.5 90.5 96.5 97.5
Second Right way
Tajchman, Wachter
0.5 1.5 2.5 3.5 5.5 6.5 7.5 8.5 9.5 10.5
11.5 12.5 13.5 14.5 17.5 18.5 19.5 20.5 21.5 22.5
24.5 28.5 31.5 32.5 33.5 34.5 35.5 36.5 38.5 40.5
41.5 42.5 43.5 44.5 45.5 46.5 47.5 48.5 49.5 50.5
51.5 52.5 53.5 54.5 55.5 58.5 60.5 61.5 62.5 64.5
65.5 67.5 68.5 70.5 71.5 72.5 76.5 77.5 78.5 79.5
80.5 81.5 82.5 83.5 84.5 85.5 86.5 87.5 88.5 91.5
92.5 95.5 96.5 97.5 99.5
|