[go: up one dir, main page]

Menu

[r320]: / libpetey / randomize.cc  Maximize  Restore  History

Download this file

75 lines (58 with data), 1.6 kB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//provides a simple and uniform interface for random number generation...
#include <sys/timeb.h>
#include "peteys_tmpl_lib.h"
#include "randomize.h"
namespace libpetey {
long libpetey_ran_seed;
gsl_rng *libpetey_ran;
unsigned long seed_from_clock() {
unsigned long seed;
timeb now;
ftime(&now);
seed= (unsigned long) now.time + ((unsigned long) now.millitm) << 7;
//printf("seed = %d\n", seed);
return seed;
}
void ran_init(const gsl_rng_type *rt) {
libpetey_ran=gsl_rng_alloc(rt);
gsl_rng_set(libpetey_ran, seed_from_clock());
}
long *randomize(long n) {
double *flt;
long *ind;
flt=new double[n];
for (long i=0; i<n; i++) {
flt[i]=ranu();
//printf("%g\n", flt[i]);
}
ind=heapsort(flt, n);
delete [] flt;
return ind;
}
//faster version of randomize O(n):
long *randomize_f(long n) {
long *ind;
long *rind;
long sub;
ind=new long[n];
for (long i=0; i<n; i++) ind[i]=i;
rind=new long[n];
for (long i=n; i>0; i--) {
long swp;
sub=i*ranu();
//inclusive or non-inclusive? let's assume inclusive:
if (sub==i) sub=i-1;
rind[n-i]=ind[sub];
swp=ind[i-1];
ind[i-1]=ind[sub];
ind[sub]=swp;
}
delete [] ind;
return rind;
}
//not really necessary, since one should only call "ran_init"
//once in a given program...
void ran_end() {
gsl_rng_free(libpetey_ran);
}
} //end namespace libpetey