I seem to find myself having to do this more an more frequently, but I've never really come up with a clean way to code it. My current method is:

#! perl -slw use strict; our $N //= 2; our $M //= 1e6; my( $step, $s, @ranges ) = ( int $M / $N, 0 ); push( @ranges, [ $s, $s+$step -1] ), $s+=$step for 1 ..$N; $ranges[ -1][1] = $M; printf "%2d : from %7d to %7d (%7d)\n", $_, @{ $ranges[ $_ ] }, $ranges[ $_ ][ 1 ] - $ranges[ $_ ][ 0 ] + 1 for 0 .. $#ranges; __END__ [15:43:18.51] C:\test>ranges -N=1 -M=9999997 0 : from 0 to 9999997 (9999998) [15:43:29.03] C:\test>ranges -N=2 -M=9999997 0 : from 0 to 4999997 (4999998) 1 : from 4999998 to 9999997 (5000000) [15:43:34.61] C:\test>ranges -N=3 -M=9999997 0 : from 0 to 3333331 (3333332) 1 : from 3333332 to 6666663 (3333332) 2 : from 6666664 to 9999997 (3333334) [15:43:47.64] C:\test>ranges -N=4 -M=9999997 0 : from 0 to 2499998 (2499999) 1 : from 2499999 to 4999997 (2499999) 2 : from 4999998 to 7499996 (2499999) 3 : from 7499997 to 9999997 (2500001) [15:43:57.34] C:\test>ranges -N=5 -M=9999997 0 : from 0 to 1999998 (1999999) 1 : from 1999999 to 3999997 (1999999) 2 : from 3999998 to 5999996 (1999999) 3 : from 5999997 to 7999995 (1999999) 4 : from 7999996 to 9999997 (2000002)

How would you do this?


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".
In the absence of evidence, opinion is indistinguishable from prejudice.

In reply to Split range 0 to M into N non-overlapping (roughly equal) ranges. by BrowserUk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.