File: dr_permutate

package info (click to toggle)
draai 20131212-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 576 kB
  • ctags: 63
  • sloc: sh: 801; perl: 170; makefile: 30
file content (127 lines) | stat: -rwxr-xr-x 2,138 bytes parent folder | download | duplicates (6)
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#! /usr/bin/perl -w

# This file is maintained at http://git.mdcc.cx/draai
# exec shuf : does the same, for input on stdin

# Copyright: © 2001 Joost van Baal
# This script is in the public domain.

use strict;

#
# permutate - give a random permutation
#
# permutate 3 e.g. could return (0, 2, 1)
#
sub permutate
{
    my $n = shift;

    my %h;

    for my $i (0 .. $n-1) {
        # rand $exp - a random fractional number >= 0, < $exp
        my $r = int rand $n - $i;

        my $k = -1;

        # find r-th undefined key in %h
        for my $j (0 .. $r) {
            # go find the next undefined key after number $k
            $k++;
            while (defined $h{$k}) {
                $k++;
            }
        }

        # and fill it with $i
        $h{$k} = $i;
    }
    return map { $h{$_} } (0 .. $n-1);
}

my @a;
if (@ARGV) {
    @a = map { $ARGV[$_] } &permutate( scalar @ARGV );
    print "@a\n";
} else {
    @a = <>;
    @a = map { $a[$_] } &permutate( scalar @a );
    print @a;
}


__END__

=pod

=head1 NAME

dr_permutate - print randomly permutated arguments or stdin

=head1 SYNOPSIS

B<dr_permutate> I<arguments>
B<dr_permutate>

=head1 DESCRIPTION

When called with arguments, B<dr_permutate> returns its arguments in randomly
permutated order, space separated.  When called without any arguments,
B<dr_permuate> expects a line-oriented file on stdin.  It returns the contents of
this file, with lines randomly permutated.

=head1 EXAMPLE

Running

 $ dr_permutate foo bar baz

could return

 bar foo baz

.  Running

 $ cat <<EOF | dr_permutate
 foo
 bar
 baz

could return

 bar
 foo
 baz

.

=head1 HISTORY

This script was initially written on 2001-05-06.

=head1 BUGS

When called without any arguments, stdin is read in core entirely.

The GNU coreutils utility shuf(1) implements the same functionality in a
better way, you're probably better off using that.

=head1 SEE ALSO

http://packages.debian.org/randomize-lines

unsort(1), by Wessel Dankers.

=head1 COPYRIGHT

Copyright: (c) 2001 Joost van Baal

This script is in the public domain.

=head1 AUTHOR

Joost van Baal <joostvb@mdcc.cx>

=cut