#!/usr/bin/pugs use v6; class MultiCounter { has @.positions is rw; has @.lengths is rw; submethod BUILD() { @.positions = (0) xx (@.lengths.end + 1); } method inc () returns Bool { @.positions[-1]++; for reverse (0..@.lengths.end - 1) -> $i { if (@.positions[$i + 1] > @.lengths[$i + 1]) { @.positions[$i]++; @.positions[$i + 1] = 0; } } return (@.positions[0] > @.lengths[0]) ?? 0 :: 1; } } class NestedLoops { has @.loops is rw; has MultiCounter $.counter is r; submethod BUILD() { $.counter = MultiCounter.new( :lengths( @.loops.map:{.end } ) ); } method inc () returns Bool { $.counter.inc; } method data () { my @data; for (0..@.loops.end) -> $i { push @data, @.loops[ $i ][$.counter.positions[$i]]; } return @data; }; } my $counter = NestedLoops.new( :loops(['a','b'],[0..2], ['one',2,3]) ); while ($counter.inc) { $counter.data.join(" ").say; }