Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing by alphabet, groups letters with few entries together (PHP or JS)

I am working on a Web Application that includes long listings of names. The client originally wanted to have the names split up into divs by letter so it is easy to jump to a particular name on the list.

Now, looking at the list, the client pointed out several letters that have only one or two names associated with them. He now wants to know if we can combine several consecutive letters if there are only a few names in each.

(Note that letters with no names are not displayed at all.)

What I do right now is have the database server return a sorted list, then keep a variable containing the current character. I run through the list of names, incrementing the character and printing the opening and closing div and ul tags as I get to each letter. I know how to adapt this code to combine some letters, however, the one thing I'm not sure about how to handle is whether a particular combination of letters is the best-possible one. In other words, say that I have:

  • A - 12 names
  • B - 2 names
  • C - 1 name
  • D - 1 name
  • E - 1 name
  • F - 23 names

I know how to end up with a group A-C and then have D by itself. What I'm looking for is an efficient way to realize that A should be by itself and then B-D should be together.

I am not really sure where to start looking at this.

If it makes any difference, this code will be used in a Kohana Framework module.


UPDATE 2012-04-04:

Here is a clarification of what I need:

Say the minimum number of items I want in a group is 30. Now say that letter A has 25 items, letters B, C, and D, have 10 items each, and letter E has 32 items. I want to leave A alone because it will be better to combine B+C+D. The simple way to combine them is A+B, C+D+E - which is not what I want.

In other words, I need the best fit that comes closest to the minimum per group.

like image 633
Moshe Katz Avatar asked Nov 05 '22 02:11

Moshe Katz


1 Answers

If a letter contains more than 10 names, or whatever reasonable limit you set, do not combine it with the next one. However, if you start combining letters, you might have it run until 15 or so names are collected if you want, as long as no individual letter has more than 10. That's not a universal solution, but it's how I'd solve it.

like image 52
Sprachprofi Avatar answered Nov 09 '22 14:11

Sprachprofi