1 package baseCode.math;
2
3 import java.util.Random;
4
5 /***
6 * Fill arrays with random values given a source of values.
7 * <p>
8 * Copyright (c) 2004
9 * </p>
10 * <p>
11 * Institution: Columbia University
12 * </p>
13 *
14 * @author Paul Pavlidis
15 * @version $Id: RandomChooser.java,v 1.8 2005/03/21 18:01:04 pavlidis Exp $
16 */
17 public class RandomChooser {
18
19 private RandomChooser() {
20 }
21
22 private static Random generator = new Random( System.currentTimeMillis() );
23
24 /***
25 * Initialized the random number generator witha given seed.
26 * @param seed
27 */
28 public static void init(long seed) {
29 generator = new Random(seed);
30 }
31
32 /***
33 * Fill randomvals with random things from sourcedata, without replacement.
34 *
35 * @param randomvals answers go here.
36 * @param sourcedata Data to be randomly selected
37 * @param deck an array pre-filled with integers from 0 to max, but they don't have to be in order.
38 * @param max how many values we need.
39 * @param n int
40 */
41 public static void chooserandom( double[] randomvals, double[] sourcedata,
42 int[] deck, int max, int n ) {
43 int rand;
44 int i;
45 int temp;
46 for ( i = 0; i < n; i++ ) {
47 rand = generator.nextInt( max - i ) + i;
48 temp = deck[rand];
49 deck[rand] = deck[i];
50 deck[i] = temp;
51 randomvals[i] = sourcedata[temp];
52 }
53 }
54
55 /***
56 * choose n random integers from 0 to max without repeating
57 *
58 * @param randomnums answers go here.
59 * @param deck an array pre-filled with integers from 0 to max, but they don't have to be in order.
60 * @param max how many values we need.
61 * @param n int
62 */
63 public static void chooserandom( int[] randomnums, int[] deck, int max, int n ) {
64 int rand;
65 int i;
66 for ( i = 0; i < n; i++ ) {
67 rand = generator.nextInt( max - i ) + i;
68 randomnums[i] = deck[rand];
69 deck[rand] = deck[i];
70 deck[i] = randomnums[i];
71 }
72 }
73
74 /***
75 * choose n random integers from 0 to max without repeating
76 *
77 * @param randomnums int[]
78 * @param recLog record of what values are already chosen.
79 * @param max int
80 * @param n int
81 */
82 public static void chooserandom( int[] randomnums, boolean[] recLog,
83 int max, int n ) {
84 int numgot;
85 int i;
86 int newnum;
87
88 numgot = 0;
89
90 while ( numgot < n ) {
91 newnum = generator.nextInt( max );
92 if ( !recLog[newnum] ) {
93 randomnums[numgot] = newnum;
94 recLog[newnum] = true;
95 numgot++;
96 }
97 }
98
99
100 for ( i = 0; i < n; i++ ) {
101 recLog[randomnums[i]] = false;
102 }
103
104 }
105
106 /***
107 * Same as chooserandom, but with replacement -- that is, repeats are allowed.
108 *
109 * @param randomnums int[]
110 * @param max int
111 * @param n int
112 */
113 public static void chooserandomWrep( int[] randomnums, int max, int n ) {
114 for ( int i = 0; i < n; i++ ) {
115 int newnum = ( char ) ( generator.nextInt() % max );
116 randomnums[i] = newnum;
117 }
118 }
119
120 }