我的网站有2个容器,每个容器都有一堆相关的内容。组织什么内容在什么容器中是重要的,但不像容器在高度上尽可能接近那样重要。
<button>Click to add more boxes</button>
<div id="wrapper" align="center">
<div id="container1">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div id="container2">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
您会在添加更多项目后看到,有时只有一个容器的内容明显多于另一个容器,但它确实会发生。
当发生这种情况时,我想把剩下的物品放在较大的容器中,然后将它们分配到容器中,使每个容器的高度尽可能接近彼此。
我怎么能这样做呢?
答案 0 :(得分:0)
有一个标准算法Subset Sum Problem
可以解决这个问题。
问题说
You have n integers. Divide n integers into two sets such that |Set1| - |Set2| is minimum. where |Set(i)| represents the sum of elements in ith set.
我发现你在这里有类似的问题。假设您的容器为两个集合,每个框高度为整数,该整数将放入该集合中。问题是我们必须以两个容器的高度保持最小的方式划分整数(方框)。
相关链接:
Geeks for Geeks tutorial - Good One
答案 1 :(得分:0)
我发布了使用的理想算法。仍然可以进行一些粗略的计算以使容器看起来整洁。
JS代码
var $container1 = $('#container1');
var $container2 = $('#container2');
$('.box').each(function(){
$(this).height(100 * Math.random());
});
var move = $container1.outerWidth();
$container2.css("margin-left",move + 10);
// Let us try to minimize the height difference
var h1 = $container1.height();
var h2 = $container2.height();
var diff = 20;
var currentDiff = h1-h2;
if (currentDiff > diff) {
alert('1 is bigger than 2');
reArrange($container1, $container2, Math.abs(currentDiff), diff);
}
if (currentDiff < -diff) {
alert('2nd is bigger than 1st');
reArrange($container2, $container1, Math.abs(currentDiff), diff);
}
// Logic: Send the minium height box to smaller container
function reArrange(largeC, smallC, currentDiff, diff) {
var minHeightBox = null;
var minH = 10000000000;
$('.box', largeC).each(function(){
if ($(this).height() < minH)
minHeightBox = this;
minH = $(this).height();
});
// If transfering this to other reduces the difference, transfer this otherwise returh false
if (minHeightBox !== null) {
var newDiff = (largeC.height() - minH) - (smallC.height() + minH);
newDiff = Math.abs(newDiff);
console.log(newDiff);
if (newDiff < currentDiff) {
smallC.append(minHeightBox);
currentDiff = largeC.height() - smallC.height();
//Recursively call the method
if (currentDiff > diff)
reArrange(largeC, smallC, currentDiff, diff);
}
}
}