Jump to content

Organize words so you can fit the most number of words in a given length


abstrakone

Recommended Posts

I'm looking for a way to do the following.

 

I have a list of words of various char lengths. I have a limited number of chars I can use in a given strings size. I'd like to organize the words to fit as many of them as I can in a given string without going over the limit or cutting any of the words off.

 

Bobby

Sally

Joe

Sue

Mark

Eric

Jason

Billy

Michael

Jeremy

Jacob

... etc

 

I have a limit of 140 characters to fit them all in, including spaces. If I have more names than space avail in that string, I'd like to generate another string using the same function as described above until all the names in the list are used.

 

Any ideas?

  :shrug:

maybe something like:

$names = array('Bobby', 'Sally', 'Joe', 'Sue', 'Mark', 'Eric', 'Jason', 
                             'Billy', 'Michael', 'Jeremy', 'Jacob');
$maxLen = 140;

$list = array();

$line = '';
foreach ($names as $name) {
if ((strlen($line) + strlen($name) + 1) > $maxLen) {	// +1 for the space
	$list[] = $line;
	$line = '';
}
$line .= (strlen($line)>0 ? ' ' : '') . $name;
}
if (strlen($line) > 0) $list[] = $line; // pickup the last line

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.