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

后端 未结 24 2094
逝去的感伤
逝去的感伤 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:03

    The question: do something (and something happens to be call rand()) a bunch of times without using a loop. Implied is, and without just repeating the source. None of the above answers actually answer this. They either repeat the source, or hide the looping. Here is a general approach that mitigates the repetition and does not hide looping (by implementing it using computed goto, or a regex, or recursion, etc). I call this approach "managed repetition."

    100 has four prime factors: 2*2*5*5 == 100. So we need two repetition managers, five and two:

    sub two{ my $y=shift; ($y->(), $y->()) }
    sub five{my $y=shift; ($y->(), $y->(), $y->(), $y->(), $y->()) } 
    

    then call them -- we're not recursing, because the recursion degenerate case constitutes a loop test -- just calling them:

    my @array = five(sub{five(sub{two(sub{two(sub{rand()})})})});
    

    There you are, a general way to call something a predetermined number of times without using a loop, rather, by delegating the repetition in an efficient and controlled way.

    Discussion question: which order should the fives and twos be in and why?

提交回复
热议问题