in reply to Re^2: Split range 0 to M into N non-overlapping (roughly equal) ranges.
in thread Split range 0 to M into N non-overlapping (roughly equal) ranges.
I know what you mean, that's what prompted yesterday's question, in fact. I took a bit of a break, and then I thought to myself "too bad reduce (from List::Util) doesn't have a version that returns an array, and then double-checked myself. It can get pretty close. Here's yet another version, which is far too ugly, but interesting in its own way:
#!/usr/bin/perl use strict; use warnings; use List::Util qw(reduce); my ($M, $N) = (9999997,5); my $ranges = reduce { ref($a) eq "ARRAY" ? [ @$a, [ $$a[-1][1], $b] ] : [ [ $a, $b ] ] } map { $_*int($M/$N) } 0 .. $N; print join(", ", map { "(" . join("-",@{$_}).")" } @$ranges), "\n"; $ perl 892828_c.pl (0-1999999), (1999999-3999998), (3999998-5999997), (5999997-7999996), +(7999996-9999995)
I like where it's a single statement, but the special-casing for the first element just sucks. Perhaps I should remove the special case and give it a specially-constructed list:
#!/usr/bin/perl use strict; use warnings; use List::Util qw(reduce); my ($M, $N) = (9999997,5); my $ranges = reduce { [ @$a, [ $$a[-1][1], $b] ] } [ [ 0, 1 ] ], map { $_*int($M/$N) } 0 .. $N; print join(", ", map { "(" . join("-",@{$_}).")" } @$ranges), "\n"; $ perl 892828_d.pl Name "main::b" used only once: possible typo at 892828_d.pl line 10. (0-1), (1-0), (0-1999999), (1999999-3999998), (3999998-5999997), (5999 +997-7999996), (7999996-9999995)
Well, it's getting a little better in that it removes the special case code, but it's broken (the first two ranges need to be removed from the result) and it's not very easy to read.
I think I'll give up on it and move on to my electronics project. Thanks for the interesting diversion!
...roboticus
When your only tool is a hammer, all problems look like your thumb.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^4: Split range 0 to M into N non-overlapping (roughly equal) ranges.
by roboticus (Chancellor) on Mar 12, 2011 at 21:31 UTC |