How to generate an array with random values, without using a loop?

后端 未结 24 2097
逝去的感伤
逝去的感伤 2020-12-13 19:23

How can I generate an array in Perl with 100 random values, without using a loop?

I have to avoid all kind of loops, like \"for\", foreach\", while. This is my exerc

相关标签:
24条回答
  • 2020-12-13 20:11
    my $u;
    
    open(URAND, "/dev/urandom") || die $!;
    
    read(URAND, $u, 100);
    
    close URAND;
    
    my @array = split(/ */, $u);
    
    0 讨论(0)
  • 2020-12-13 20:14

    As per requests from the listeners, a non-pure-regex solution:

    $s="D" x 100; 
    $s=~s/D/rand()." "/ge; 
    @s=split(/ /,$s);
    
    0 讨论(0)
  • 2020-12-13 20:15
    @foo = (rand(), rand(), rand(), ... rand());
    
    0 讨论(0)
  • 2020-12-13 20:16

    Since the task seems to be either to get you to use recursion or to learn how to write an easy loop in a not-so-easy form, humbly I submit the following FULLY EXECUTABLE Perl programs:

    Camel:

    #!/usr/bin/perl
                                          ''=~('('.'?'
               .'{'.(                   '`'|'%').("\["^
            '-').('`'|                '!').('`'|',').'"'
     .'\\'.'$'.  ("\`"|              ',').('`'|')').('`'|
    '-').'='.('^'^("\`"|            '/')).('^'^('`'|'.')).
    ('^'^('`'|'.')).';'.(          '!'^'+').('`'|'&').('`'
      |'/').('['^')').'('        .'\\'.'$'.'='.'='.(('^')^(
           '`'|'/')).';'.      '\\'.'$'.'='.'<'.'='.'\\'.'$'
          .('`'|(',')).(     '`'|')').('`'|'-').';'.'+'."\+".
         '\\'.'$'.('=').   ')'.'\\'.'{'.('['^'+').('['^"\.").(
        '['^'(').("\`"|   '(').('{'^'[').'\\'.'@'.'='.','.("\{"^
        '[').('['^')').  ('`'|'!').('`'|'.').('`'|'$').'\\'.'}'.(
        '!'^'+').'\\'.  '$'.'='.'='.('^'^('`'|'/')).';'.('!'^'+')
        .('`'|('&')).(  '`'|'/').('['^')').('{'^'[').'('.'\\'.'@'.
        '='.')'.('{'^'[').'\\'.'{'.('!'^'+').('*'^'#').('['^'+').(
        '['^')').('`'|')').('`'|'.').('['^'/').('{'^'[').'\\'.'"'.(
         '['^')').('`'|'!').('`'|'.').('`'|'$').('{'^'[').'\\'.'$'.
         '='.('{'^'[').('`'|'/').('`'|'&').('{'^'[').'\\'.'$'.("\`"|
          ',').('`'|')').('`'|'-').'='.'\\'.'$'.'_'.'\\'.'\\'.(('`')|
           '.').'\\'.'"'.';'.('!'^'+').('*'^'#').'\\'.'$'.'='.'+'.'+'
            .';'.('!'^'+').('*'^'#').'\\'.'}'.'"'.'}'.')');$:='.' ^((
             '~'));$~='@'|'(';$^=')'^'[';$/='`'|'.';$,='('^"\}";  $\=
              '`'|'!';$:=')'^'}';$~='*'|'`';$^='+'^'_'; $/="\&"|  '@'
                ;$,='['&'~';$\=','^'|';$:='.'^"\~";$~=  '@'|'('   ;$^
                 =')'^ '[';$/='`'|'.';$,='('^"\}";$\=   '`'|'!'   ;$:
                       =')'^'}';$~='*'|'`';$^=('+')^    '_';$/=   '&'
                       |'@';$,=    '['&'~';$\ ="\,"^     '|';$:   =(
                       ('.'))^     "\~";$~=   ('@')|     '(';$^  =(
                       (')'))^     "\[";$/=   "\`"|       "\.";  (
                       ($,))=      '('^'}';   ($\)         ='`'
                       |"\!";     $:=(')')^   '}';         ($~)
                        ='*'|     "\`";$^=    '+'^         '_';
                        ($/)=     '&'|'@'     ;$,=         '['&
                        '~';     $\=','       ^'|'         ;$:=
                        '.'^     '~'          ;$~=         '@'|
                        '(';      $^=         ')'          ^((
                        '['        ));       $/=           '`'
                        |((         '.'     ));            $,=
                        '('          ^((   '}'              ))
                        ;(             ($\))=               ((
                        ((              '`'))               ))
                        |+             "\!";$:=             ((
                       ')'            ))^+ "\}";            $~
                      =((           '*'))|  '`';           $^=
                     '+'^         "\_";$/=   '&'          |'@'
                   ;($,)=                                ('[')&
                 "\~";$\=                               ','^'|'
    

    Martini:

    #!/usr/bin/perl
                                                      ''=~('(?{'.
                                                      ('`'|'%').(
                                                      '['^"\-").(
                                                      '`'|"\!").(
                                                      '`'|(',')).
                                                      '"\\$'.('`'
                                                        |',').(
                                                        '`'|')'
                                                        ).('`'|
                                                        ('-')).
                                                        ('=').(
                                                       '^'^('`'|
                                                       ('/'))).(
                                                       '^'^('`'|
                                                       ('.'))).(
                                                      '^'^(('`')|
                                                      '.')).';'.(
                                                     '!'^'+').('`'
                                                     |'&').(('`')|
                                                    '/').('['^')').
                                                    '(\\$=='.('^'^(
                                                   '`'|'/')).';\\$='
                                                  .'<=\\$'.('`'|',').
                                                 ('`'|')').('`'|"\-").
                                                ';++\\$=)\\{'.('['^'+')
                                               .('['^'.').('['^'(').('`'
                                              |'(').('{'^'[').'\\@'.('`'|
                                              '!').('['^')').('['^"\)").(
                                              '`'|'!').('['^'"').','.('{'
                                              ^'[').('['^')').('`'|'!').(
                                              '`'|'.').('`'|"\$").'\\}'.(
    '!'^'+').'\\$'.('`'|')').'='.("\^"^(      '`'|'/')).';'.('!'^('+')).(
     '`'|'&').('`'|'/').('['^')').('{'^       '[').'(\\@'.('`'|'!').('['^
       ')').('['^')').('`'|'!').('['^         '"').')'.('{'^"\[").'\\{'.(
        '!'^'+').('*'^'#').('['^'+')          .('['^')').('`'|')').("\`"|
          '.').('['^'/').('{'^'[')            .'\\"'.('['^')').('`'|'!').
           ('`'|'.').('`'|"\$").(             '{'^'[').'\\$'.('`'|"\)").(
             '{'^'[').('`'|'/')               .('`'|'&').('{'^'[').'\\$'.
              ('`'|',').("\`"|                ')').('`'|'-').'=\\$_\\\\'.
                ('`'|('.')).                  '\\";'.('!'^'+').('*'^'#').
                 '\\$'.('`'                   |')').'++;'.('!'^'+').('*'^
                   "\#").                     '\\}"})');$:='.'^'~';$~='@'
                    |'('                      ;$^=')'^'[';$/='`'|"\.";$,=
                    '('^                      '}';$\='`'|'!';$:=')'^"\}";
                    ($~)                      ='*'|'`';$^='+'^'_';$/='&'|
                    '@';                      $,='['&'~';$\=','^('|');$:=
                    '.'^                      '~';$~='@'|'(';$^=')'^"\[";
                    ($/)                      ='`'|'.';$,='('^'}';$\='`'|
                    '!';                      $:=')'^'}';$~='*'|('`');$^=
                    '+'^                      '_';$/='&'|'@';$,='['&"\~";
                    ($\)                      =','^'|';$:='.'^'~';$~='@'|
                    '(';                      $^=')'^'[';$/='`'|('.');$,=
                    '('^                      '}';$\='`'|'!';$:=')'^"\}";
                    ($~)                      ='*'|'`';$^='+'^'_';$/='&'|
    '@';$,='['&'~';$\=','^'|';$:='.'^'~'      ;$~='@'|'(';$^=')'^"\[";$/=
    '`'|'.';$,='('^'}';$\='`'|'!';$:=')'      ^'}';$~='*'|'`';$^='+'^'_';
    

    For the Holidays, snowflakes with recursion rather than iteration inside:

    #!/usr/bin/perl
               '?'                          =~(
             '('.'?'                      ."\{".(
            '`'   |'%'  ).('['^"\-").(  '`'|   '!'
             ).('`'|',').    '"'.    '\\'.('$').(
             '`'|(',')).(    '`'|    ')').(('`')|
            ((  '-')   )).    +(    '`'   |')'  ).
           (((    '['   ))^+  ((  '/')   )).    '='
          .('^'^   ('`'|'/')) .( '^'^("\`"|   '.')).
         +(     '^'^('`'|'.')).';'.('!'^"\+").     ((
     '\\')).'$'.('`'|'#').('`'|'/').('['^'.').('`'|'.').(
    '['^  '/').'='.  (('^')^(    '`'|'/')  ).(';').(  '!'^
    '+'    ).('['^    '(').(      ('[')^    "\.").(    '`'
    |'"'  ).(('{')^  ('[')).(    '['^'+')  .('['^'.'  ).+(
     '['^'(').('`'|'(').'_'.('['^')').('`'|'!').('`'|'.')
         .(     '`'|'$').('{'^'[').'\\'."\{".(     ((
          '!'))^   '+').('{'^ (( ('[')))).(   ('{')^
           '['    ).(   '{'^  ((  '[')   )).    (((
            ((  '{')   )))    ^+    '['   ).+(  ((
             '['))^')').(    '`'|    '%').(('[')^
             '/').(('[')^    '.')    .('['^')').(
            '`'   |'.'  ).('{'^"\[").(  '`'|   ')'
             ).('`'|                      "\&").(
               '{'                          ^((
               '['                          )))
             .'\\'.+                      '$'.'#'
            .+(   '`'|  '!').('['^')')  .''.   (((
             '['))^')').(    '`'|    '!').(('[')^
             '"').('_').(    '`'|    '/').(('`')|
            ((  '&')   )).    ((    '_'   )).(  ((
           '['    ))^   ')')  .(  '`'|   '!'    ).(
          ('`')|   '.').('`'| (( ('$')))).(   ('[')^
         ((     '('))).'>'.'\\'.'$'.('`'|',').     +(
     '`'|')').('`'|'-').('`'|')').('['^'/').';'.('!'^'+')
    .''.  ('{'^'[')  .(('{')^    ('[')).(  '{'^'[').  ('{'
    ^((    '['))).    ("\["^      '+').(    '['^'.'    ).(
    '['^  '(').('`'  |"\(").(    '{'^'[')  .'\\'.'@'  .''.
     ('`'|'!').('['^')').('['^')').('`'|'!').('['^('"')).
         ((     '_')).('`'|'/').('`'|'&').'_'.     +(
          ('[')^   ')').('`'| (( ('!')))).(   ('`')|
           '.'    ).(   '`'|  ((  '$')   )).    (((
            ((  '[')   )))    ^+    '('   ).((  ((
             ',')))).('{'    ^'['    ).('['^')').
             ('`'|"\!").(    '`'|    '.').(('`')|
            '$'   ).((  ';')).('!'^'+'  ).+(   '{'
             ^'[').(                      '{'^'['
               ).(                          '{'
               ^((                          '['
             ))).''.                      (('{')^
            '['   ).+(  '['^'+').('['^  '.')   .+(
             '['^('(')).(    '`'|    '(').('_').(
             '['^(')')).(    '`'|    '!').(('`')|
            ((  '.')   )).    +(    '`'   |'$'  ).
           '('    .((   ')')  ).  ';'.   (((    '!'
          ))^'+'   ).'\\'.'}' .( '!'^'+').(   ('!')^
         ((     '+'))).('!'^'+').('['^('(')).(     ((
     '['))^'.').('`'|'"').('{'^'[').('['^'+').('['^')').(
    '`'|  ')').('`'  |"\.").(    '['^'/')  .'_'.('['  ^')'
    ).(    '`'|'%'    ).('`'      |'#').    (('[')^    '.'
    ).+(  '['^')').  ('['^'('    ).("\`"|  ')').('['  ^'-'
     ).('`'|'%').('{'^'[').'\\'.'{'.('!'^'+').('{'^'[').(
         ((     '{'))^'[').('{'^'[').('{'^'[')     .+
          '\\'.+   '$'.("\["^ (( '/'))).'='   .('['^
           '+'    ).(   '`'|  ((  '/')   )).    (((
            ((  '[')   )))    ^+    '+'   ).+(  ((
             '{'))^"\[").    '\\'    .'@'.'_'.';'
             .('!'^'+').(    '*'^    '#').(('[')^
            '+'   ).+(  '['^')').('`'|  ')')   .+(
             '`'|'.'                      ).('['^
               '/'                          ).(
               '{'                          ^((
             '['))).                      ('\\').
            '"'   .''.  ('['^')').('`'  |'!'   ).(
             '`'|('.')).(    '`'|    '$').(('{')^
             '[').('\\').    '$'.    ('`'|"\#").(
            ((  '`')   )|+    ((    '/'   ))).  +(
           '['    ^((   '.')  ))  .''.   (((    '`'
          ))|'.'   ).('['^'/' ). ('{'^'[').   ("\`"|
         ((     '/'))).('`'|'&').('{'^'[').''.     ((
     '\\')).'$'.('`'|',').('`'|')').('`'|'-').('`'|')').(
    '['^  '/').'='.  '\\'.'$'    .(('[')^  '/').'\\'  .''.
    (((    '\\')))    .('`'|      "\.").    ('\\').    '"'
    .';'  .('!'^'+'  ).("\*"^    '#').''.  '\\'.'$'.  ('`'
     |'#').('`'|'/').('['^'.').('`'|'.').('['^'/').('+').
         ((     '+')).';'.('!'^'+').('*'^'#').     +(
          ('[')^   '+').('['^ (( (')')))).(   ('`')|
           ')'    ).(   '`'|  ((  '.')   )).    (((
            ((  '[')   )))    ^+    '/'   ).((  ((
             '_')))).('['    ^')'    ).('`'|'%').
             ('`'|"\#").(    '['^    '.').(('[')^
            ')'   ).+(  '['^'(').('`'|  ')')   .+(
             '['^'-'                      ).('`'|
               '%'                          ).+
               '('                          .((
             '\\')).                      '@'.'_'
            .((   ')')  ).('{'^"\[").(  '`'|   ')'
             ).('`'|'&').    ('{'    ^'[').('(').
             '\\'.'@'.'_'    .')'    .';'.(('!')^
            ((  '+')   )).    ((    (((   '\\'  ))
           )))    .((   '}')  ).  ('!'   ^((    '+'
          ))).+(   '!'^'+').( (( '['))^'+')   .('['^
         ((     '.'))).('['^'(').('`'|'(').'_'     .(
     '['^')').('`'|'!').('`'|'.').('`'|'$').'('.')'.';'.(
    '['^  '+').('['  ^"\)").(    '`'|')')  .('`'|'.'  ).+(
    '['    ^"\/").    "\_".(      ('[')^    "\)").(    '`'
    |'%'  ).(('`')|  ('#')).(    '['^'.')  .('['^')'  ).+(
     '['^'(').('`'|')').('['^'-').('`'|'%').'('.'\\'.'@'.
         +(     '`'|'!').('['^')').('['^')').(     ((
          '`'))|   '!').('['^ (( '"'))).'_'   .('`'|
           '/'    ).(   '`'|  ((  '&')   )).    '_'
            .(  '['^   ')'    ).    (((   '`')  )|
             '!').(('`')|    '.')    .('`'|'$').(
             '['^'(').')'    .';'    .'"'.'}'.')'
            );(   $:)=  '.'^'~';$~='@'  |'('   ;$^
             =(')')^                      '[';#;#
               ;#;                          #;#
    

    In each case, the output is something like this:

    rand 1 of 100=0.625268682212667
    rand 2 of 100=0.30160434879096
    ...
    rand 100 of 100=0.584811321826528
    

    If you want to see the loops or recursion embedded within, you can use perl -MO=Deparse martini.pl or perl -MO=Deparse camel.pl etc.

    Only with Perl, right???

    If you want to generate these lovely things -- check out Acme::Eyedrops

    0 讨论(0)
  • 2020-12-13 20:17

    Too bad most of the solutions focused on the non-looping part and neglected the random numbers part:

    use LWP::Simple;
    
    my @numbers = split /\s+/, #/ Stackoverflow syntax highlighting bug 
        get( 'http://www.random.org/integers/?num=100&min=1&max=100&col=1&base=10&format=plain&rnd=new' );
    

    Here's the insanity that Tom was waiting to see, but I make it slightly more insane. This solution reduces the problem to a rand call:

    my @numbers = rand( undef, 100 ); # fetch 100 numbers
    

    Normal rand normally takes 0 or 1 arguments. I've given it a new prototype that allows a second argument to note how many numbers to return.

    Notice some differences to the real rand though. This isn't continuous, so this has far fewer available numbers, and it's inclusive on the upper bound. Also, since this one takes two arguments, it's not compatible with programs expecting the real one since a statement like this would parse differently in each:

     my @array = rand 5, 5;
    

    However, there's nothing particularly special about CORE::GLOBAL::rand() here. You don't have to replace the built-in. It's just a bit sick that you can.

    I've left some print statements in there so you can watch it work:

    BEGIN {
        my @buffer;
    
        my $add_to_buffer = sub {
            my $fetch = shift;
            $fetch ||= 100;
            $fetch = 100 if $fetch < 100;
            require LWP::Simple;
            push @buffer, split /\s+/, #/ Stackoverflow syntax highlighting bug
              LWP::Simple::get(
                "http://www.random.org/integers/?num=$fetch&min=1&max=100&col=1&base=10&format=plain&rnd=new"
                );
            };
    
        my $many = sub ($) {
            print "Fetching $_[0] numbers\n";
            $add_to_buffer->($_[0]) if @buffer < $_[0];
            my @fetched = splice @buffer, 0, $_[0], ();
            my $count = @fetched;
            print "Fetched [$count] @fetched\n";
            @fetched
            };
    
        *CORE::GLOBAL::rand = sub (;$$) {
            my $max = $_[0] || 1; # even 0 is 1, just like in the real one
            my $fetch = $_[1] || ( wantarray ? 10 : 1 );
            my @fetched = map { $max * $_ / 100 } $many->( $fetch );
            wantarray ? @fetched : $fetched[-1];
            };
        }
    
    my @rand = rand(undef, 5);
    print "Numbers are @rand\n\n";
    
    @rand = rand(87);
    print "Numbers are @rand\n\n";
    
    $rand = rand(undef, 4);
    print "Numbers are $rand\n\n";
    
    $rand = rand();
    print "Numbers are $rand\n\n";
    
    $rand = rand(undef, 200);
    print "Numbers are $rand\n\n";
    

    My source of random numbers isn't important for this technique though. You could read from /dev/random or /dev/urandom to fill the buffer if you like.

    0 讨论(0)
  • 2020-12-13 20:18

    Recursion:

    sub fill_rand {
     my ($array, $count) = @_;
       if ($count >= 1) {
       unshift @$array, rand();
       fill_rand ($array, --$count);
     }
    }
    
    my @array;
    fill_rand (\@array, 100);
    

    "Tail-call optimised" version:

    sub fill_rand {
        my $array = shift;
        my $count = shift;
        unshift @$array, rand();
        if ($count > 1) {
           $count--;
           @_ = ($array, $count);
           goto &fill_rand;
        }
    }
    
    my @array;
    fill_rand(\@array, 100);
    

    Using eval:

    my @array;
    eval("\@array = (" . ("rand(), " x 100) . ");");
    

    If you assume that my perl is random (not an unwarranted assumption), you could use the perl file itself as a source of random data:

    open FILE, __FILE__ or die "Can't open " . __FILE__ . "\n";
    my $string;
    read FILE, $string, 100;
    close FILE;
    my @array = map { ord } split //, $string;
    

    Of course, you'll get the same results every time, but this is useful for testing.

    0 讨论(0)
提交回复
热议问题