I have a case where I’m provided with one UL, and an unknown number of LIs. I’m looking to use JS to split the LIs into 2 ULs (I’m using jQuery). I’m able to split the ULs evenly by number of LIs, but I’d like to split it based on the height of each LI as well, so that both ULs are close to the same height.
Any help with this would be appreciated, I don’t feel like I’m getting anywhere with the approach I started with.
Thanks.
EDIT: JS code I currently have. The HTML is just a straight UL/LI, each LI can be of varying height.
var $sections = $('div.subsection');
$sections.each(function(){
var $section = $(this);
var $list = $section.children('ul');
var $items = $list.children('li');
var itemCount = $items.size();
var leftover = itemCount % 2;
var itemsPerColumn = Math.floor(itemCount / 2);
var $newList = $('<ul />');
$items.each(function(){
var $this = $(this);
var index = $items.index($this);
if (index >= (itemsPerColumn + leftover)) {
$this.remove().appendTo($newList);
}
});
$list.after($newList);
_equalizeListHeights();
function _equalizeListHeights(){
var listHeight = $list.height();
var newListHeight = $newList.height();
if (listHeight > newListHeight){
var $lastItem = $list.children('li:last');
var lastItemHeight = $lastItem.height();
if (listHeight - lastItemHeight > newListHeight + lastItemHeight){
$lastItem.remove().prependTo($newList);
_equalizeListHeights();
}
}
}
});
I think I can at least see the approach here:
total), and store all the individual heightstotal / 2)heightsto come as as possible tototal / 2, without exceeding it.Step 3 is the tricky bit. It’s related to the Subset Sum Problem.
EDIT
Here’s a brute-force algorithm which solves your problem. It doesn’t run on
window.resize, because that would be silly. If you want to see it change, resize the result window, then push run.