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:

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.