Same code ( what is this, Lisp? ), reformatted to be more readable and do a sanity check for the zero-columns case.
Note that it doesn't seem to do exactly what the questioner asked - see the 22/7 case:
#!/usr/bin/perl -w
use strict;
while (<DATA> ) {
my ( $items, $cols ) = split;
print "Spread for $items, $cols = ",
spread( $items, $cols ),
"\n";
}
sub spread {
my ($a, $cols) = @_;
$a ||= 0;
return unless $cols > 0; # avoid nasty surprises
return $a if $cols == 1; #trivial case
if ( $a % $cols) {
return join '-', ( (int( $a / ($cols - 1) )) x ( $cols - 1)
+, ( $a % ($cols - 1)));
} else {
return join '-', (int ( $a / $cols)) x $cols;
}
}
__DATA__
19 3
20 5
22 7
2 47
0 9
899 0
Results:
Spread for 19, 3 = 9-9-1
Spread for 20, 5 = 4-4-4-4-4
Spread for 22, 7 = 3-3-3-3-3-3-4
Spread for 2, 47 = 0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0
+-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-2
Spread for 0, 9 = 0-0-0-0-0-0-0-0-0
Spread for 899, 0 =
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.