Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can use <a href="https://metacpan.org/pod/Algorithm::Combinatorics#variations_with_repetition-data-k" rel="nofollow">variations_with_repetition</a> from <a href="https://metacpan.org/pod/Algorithm::Combinatorics" rel="nofollow">Algorithm::Combinatorics</a> (which also provides an iterator-based interface), but if you just need a list, this is a fairly simple recursive algorithm:</p> <pre><code>sub ordered_combinations { my ($data, $k) = @_; return @$data if $k == 1; my @previous = ordered_combinations($data, $k-1); my @results; for my $letter (@$data) { push @results, map { $letter . $_ } @previous; } return @results; } # end ordered_combinations print "$_\n" for ordered_combinations([qw(a b c)], 3); </code></pre> <p>This is basically the same algorithm the code golfers are using, but I'm using a <code>for</code> loop instead of nesting <code>map</code>. Also, I recurse only once per level (code golf is about minimizing source code, not runtime).</p> <p>Any recursive function can be converted to an iterative one, which usually reduces its overhead. This one is fairly simple:</p> <pre><code>sub ordered_combinations { my ($data, $k) = @_; return if $k &lt; 1; my $results = $data; while (--$k) { my @new; for my $letter (@$data) { push @new, map { $letter . $_ } @$results; } # end for $letter in @$data $results = \@new; } # end while --$k is not 0 return @$results; } # end ordered_combinations </code></pre> <p>This version handles the <code>$k == 0</code> case, which the original did not.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload