line |
stmt |
bran |
cond |
sub |
pod |
time |
code |
1
|
|
|
|
|
|
|
package Array::Sample::SimpleRandom; |
2
|
|
|
|
|
|
|
|
3
|
1
|
|
|
1
|
|
57515
|
use 5.010001; |
|
1
|
|
|
|
|
12
|
|
4
|
1
|
|
|
1
|
|
5
|
use strict; |
|
1
|
|
|
|
|
2
|
|
|
1
|
|
|
|
|
19
|
|
5
|
1
|
|
|
1
|
|
4
|
use warnings; |
|
1
|
|
|
|
|
2
|
|
|
1
|
|
|
|
|
40
|
|
6
|
|
|
|
|
|
|
|
7
|
1
|
|
|
1
|
|
5
|
use Exporter qw(import); |
|
1
|
|
|
|
|
1
|
|
|
1
|
|
|
|
|
268
|
|
8
|
|
|
|
|
|
|
|
9
|
|
|
|
|
|
|
our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY |
10
|
|
|
|
|
|
|
our $DATE = '2022-05-21'; # DATE |
11
|
|
|
|
|
|
|
our $DIST = 'Array-Sample-SimpleRandom'; # DIST |
12
|
|
|
|
|
|
|
our $VERSION = '0.003'; # VERSION |
13
|
|
|
|
|
|
|
|
14
|
|
|
|
|
|
|
our @EXPORT_OK = qw(sample_simple_random_with_replacement |
15
|
|
|
|
|
|
|
sample_simple_random_no_replacement); |
16
|
|
|
|
|
|
|
|
17
|
|
|
|
|
|
|
sub sample_simple_random_with_replacement { |
18
|
5
|
|
|
5
|
1
|
2149
|
my ($ary, $n, $opts) = @_; |
19
|
5
|
|
50
|
|
|
21
|
$opts //= {}; |
20
|
|
|
|
|
|
|
|
21
|
5
|
100
|
|
|
|
17
|
return () unless @$ary; |
22
|
|
|
|
|
|
|
|
23
|
3
|
|
|
|
|
6
|
my @res; |
24
|
3
|
|
|
|
|
7
|
for my $i (1..$n) { |
25
|
1
|
|
|
|
|
3
|
my $idx = int(rand(@$ary)); |
26
|
1
|
50
|
|
|
|
5
|
push @res, $opts->{pos} ? $idx : $ary->[$idx]; |
27
|
|
|
|
|
|
|
} |
28
|
|
|
|
|
|
|
|
29
|
3
|
|
|
|
|
13
|
@res; |
30
|
|
|
|
|
|
|
} |
31
|
|
|
|
|
|
|
|
32
|
|
|
|
|
|
|
sub sample_simple_random_no_replacement { |
33
|
5
|
|
|
5
|
1
|
1087
|
my ($ary, $n, $opts) = @_; |
34
|
5
|
|
50
|
|
|
23
|
$opts //= {}; |
35
|
|
|
|
|
|
|
|
36
|
5
|
100
|
|
|
|
12
|
$n = @$ary if $n > @$ary; |
37
|
5
|
|
|
|
|
10
|
my @ary_copy = @$ary; |
38
|
5
|
|
|
|
|
11
|
my @pos = 0 .. $#ary_copy; |
39
|
|
|
|
|
|
|
|
40
|
5
|
|
|
|
|
6
|
my @res; |
41
|
5
|
|
|
|
|
12
|
for my $i (1..$n) { |
42
|
1
|
|
|
|
|
30
|
my $idx = int(rand(@ary_copy)); |
43
|
1
|
50
|
|
|
|
8
|
push @res, $opts->{pos} ? $pos[$idx] : $ary_copy[$idx]; |
44
|
1
|
|
|
|
|
2
|
splice @ary_copy, $idx, 1; |
45
|
1
|
|
|
|
|
3
|
splice @pos , $idx, 1; |
46
|
|
|
|
|
|
|
} |
47
|
|
|
|
|
|
|
|
48
|
5
|
|
|
|
|
23
|
@res; |
49
|
|
|
|
|
|
|
} |
50
|
|
|
|
|
|
|
|
51
|
|
|
|
|
|
|
1; |
52
|
|
|
|
|
|
|
# ABSTRACT: Sample elements randomly (with or without replacement) |
53
|
|
|
|
|
|
|
|
54
|
|
|
|
|
|
|
__END__ |