in reply to Re^4: Odometer pattern iterator (in C).
in thread Odometer pattern iterator (in C). (Updated.)

Ok, here is the index-based algorithm:

use strict; use warnings; sub first_idx { my( $N, $M ) = @_; return ( $N-$M .. $N-1 ); } sub next_idx { my( $N, $M, @idx ) = @_; return () if $idx[ -1 ] == $M-1; my $i = $M-1; $i-- while $i>0 and $idx[$i]-$idx[$i-1]==1; return ( @idx[0..$i-1], $idx[ $i ]-1, map { $idx[ $i ] + $N - $idx[ $M - $_+ $i ] } $i+1 .. $M-1); } my $N = 5; my $M = 3; my @indices = first_idx( $N, $M ); 1 while print( "@indices\n"), @indices = next_idx( $N, $M, @indices );

Replies are listed 'Best First'.
Re^6: Odometer pattern iterator (in C).
by BrowserUk (Patriarch) on May 29, 2015 at 13:10 UTC

    Cool! It even runs in the same direction as my original example.

    Though I suspect that once the slice and map operations have been unwound in C, it'll look a lot more complicated.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
    In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked

      I have now compared it to the solution you have posted and it probably amounts to almost the same algorithm...

        I attempted to adapt your Perl to C, but I made a mistake somewhere. I don't know if you can see the problem, but I can't and I need to move on:

        U8 *firstIdx( U8 N, U8 M ) { U32 i; U8 *a = malloc( M ); for( i = N - M; i < N; ++i ) a[ i - M + 1 ] = i; return a; } U8 *nextIdx( U8 N, U8 M, U8 *idx ) { U32 i = M - 1, j; if( idx[ i ] == i ) return NULL; while( i > 0 && idx[ i ] - idx[ i - 1 ] == 1 ) i--; --idx[ i ]; for( j = i+1; j < M; ++j ) idx[ i ] += N - idx[ M - j + i ]; return idx; }

        With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
        In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked