-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.pm
92 lines (66 loc) · 1.78 KB
/
utils.pm
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package utils;
use strict;
use warnings;
# Similar to map, but operates on runs of adjacent elements.
sub map_nata (&$@){
my ($sub, $width, @array) = @_;
$sub = \&{$sub}; # Verify this is CODE
my @return_values = ();
my ($s, $e) =
my @args = ();
push (@args, shift @array)
for (0..$width - 2);
while (scalar @array) {
push (@args, shift @array);
push (@return_values, $sub->(@args));
shift @args;
}
return @return_values;
}
# Iterates over a list
sub iter {
my ($l, $i) = (\@_, 0);
return sub {
return ($i < scalar @$l) ? $l->[$i++] : ();
}
}
# iterates over a list in blocks of n consecutive (overlapping) elements.
sub iter_nata ($@) {
my ($width, @array) = @_;
my @args = ();
push (@args, shift @array)
for (0..$width - 2);
return sub {
return ()
unless (scalar @array);
push (@args, shift @array);
shift @args if (scalar @args > $width);
return @args;
}
}
# Code from here: http://www.perlmonks.org/?node_id=158490
# Better explanation here: http://www.perlmonks.org/?node_id=1910
# Modified to avoid using a hash unnecessarily.
sub rbiased {
my @biases = @_;
my ($sum, $index, $rand) = (0, 0);
for ( @biases ) {
$rand = $index
if (rand($sum += $_) < $_);
++$index;
}
return $rand;
}
# Gets a random int between $min and $max
sub rint (;$$) {
my ($min, $max) = @_;
return int (rfloat ($min, $max));
}
# Gets a random float between $min and $max
sub rfloat (;$$) {
my ($min, $max) = @_;
if (!defined $min and !defined $max) { ($min, $max) = (0, 1) }
elsif (!defined $max) { ($min, $max) = (0, $min) }
return rand ($max - $min) + $min;
}
1;