langs a-z

This commit is contained in:
Ingy döt Net 2013-04-10 22:43:41 -07:00
parent db842d013d
commit d066446780
11389 changed files with 98361 additions and 1020 deletions

View file

@ -0,0 +1,25 @@
let s_of_n_creator n =
let i = ref 0
and sample = ref [| |] in
fun item ->
incr i;
if !i <= n then sample := Array.append [| item |] !sample
else if Random.int !i < n then !sample.(Random.int n) <- item;
!sample
let test n items_set =
let s_of_n = s_of_n_creator n in
Array.fold_left (fun _ v -> s_of_n v) [| |] items_set
let () =
Random.self_init();
let n = 3 in
let num_items = 10 in
let items_set = Array.init num_items (fun i -> i) in
let results = Array.create num_items 0 in
for i = 1 to 100_000 do
let res = test n items_set in
Array.iter (fun j -> results.(j) <- succ results.(j)) res
done;
Array.iter (Printf.printf " %d") results;
print_newline()

View file

@ -0,0 +1,35 @@
#import <Foundation/Foundation.h>
typedef NSArray *(^SOfN)(id);
SOfN s_of_n_creator(int n) {
NSMutableArray *sample = [NSMutableArray arrayWithCapacity:n];
__block int i = 0;
return [[^(id item) {
i++;
if (i <= n) {
[sample addObject:item];
} else if (rand() % i < n) {
[sample replaceObjectAtIndex:rand() % n withObject:item];
}
return sample;
} copy] autorelease];
}
int main(int argc, const char *argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSCountedSet *bin = [[NSCountedSet alloc] init];
for (int trial = 0; trial < 100000; trial++) {
SOfN s_of_n = s_of_n_creator(3);
NSArray *sample;
for (int i = 0; i < 10; i++)
sample = s_of_n([NSNumber numberWithInt:i]);
[bin addObjectsFromArray:sample];
}
NSLog(@"%@", bin);
[bin release];
[pool release];
return 0;
}

View file

@ -0,0 +1,15 @@
KnuthS(v,n)={
my(u=vector(n,i,i));
for(i=n+1,#v,
if(random(i)<n,u[random(n)+1]=i)
);
vecextract(v,u)
};
test()={
my(v=vector(10),t);
for(i=1,1e5,
t=KnuthS([0,1,2,3,4,5,6,7,8,9],3);
v[t[1]+1]++;v[t[2]+1]++;v[t[3]+1]++
);
v
};

View file

@ -0,0 +1,28 @@
sub s_of_n_creator($n) {
my @sample;
my $i = 0;
-> $item {
if ++$i <= $n {
push @sample, $item;
}
elsif $i.rand < $n {
@sample[$n.rand] = $item;
}
@sample;
}
}
my @items = 0..9;
my @bin;
for ^100000 {
my &s_of_n = s_of_n_creator(3);
my @sample;
for @items -> $item {
@sample = s_of_n($item);
}
for @sample -> $s {
@bin[$s]++;
}
}
say @bin;