Given a string, how can you efficiently divide the string into x pieces, where each piece has y characters, except for possibly the last, which has between 1 and y characters?

For the love of Perl, please test your solutions before posting them -- if you find a place where your algorithm fails, post THAT along with your attempt, so that people might be able to help you.

Quiz 2 -- Approximate Parts

This is an introduction to greedy algorithms. Greedy algorithms do what is locally best, and, if they are successful, end up doing the right thing.

So you are given a string, and you are asked to split it into x pieces, but can only split on whitespace. And you are asked to make the pieces as close to the same length as possible. Example:

Splitting "would you like some pizza?" into two pieces results in "would you like" and "some pizza?", whereas splitting it into 3 pieces results in "would you", "like some", and "pizza?"

Assume the string is a list of non-whitespace characters joined by single spaces (that is, you'll never have two spaces in a row, and there is only space between words, not at the beginning of end of the string).

You might find it easier to approach the problem for splitting into 2 pieces, and then generalizing from there.

There are multiple ways to get substrings of a string -- substr(), unpack(), a regex...

Quiz 2

You want to split the string as close to the center as possible (for the "split into 2 pieces" approach). So find the whitespace closest to the center, and split the string there. For splitting into n pieces, you want to find the whitespace closest to 1/n way through the string.

I am sure this is not a very -nice- solution. I discovered something about building REs which I didn't know before which is this:

$re = '$a'; $a = "apple"; /$re/ does not then match "apple" which is why I am reassigning the entire regular expression in the loop. Perhaps someone can enlighten me about how to force the variables in an existing string to get interpolated.

The single quotes around $a make it mean the ACTUAL 2-character string $a. When Perl gets to /$b, it interpolates the variable, and it gets expanded to its value, $a. Perl does not then go and interpolate THAT as well.

#!/usr/bin/perl $a="Cooking is also one of the oldest of the arts. Some modern artists would have you believe that so-called ephemeral art is a recent invention, but cooking has always been an ephemeral art.";