2

我有一个有 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>

提琴手


问题:

添加更多项目后,您会看到,有时一个容器的内容会比另一个容器多得多,但确实会发生。

发生这种情况时,我想将剩余的物品放在较大的容器中,并以一种使每个容器的高度尽可能接近的方式将它们分配到容器中。

我怎么能这样做呢?

4

2 回答 2

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);
    }
  }
}
于 2013-06-22T02:32:31.620 回答
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.

我看到你在这里有类似的问题。假设您的容器为两组,每个盒子的高度为将放入该组中的整数。问题是我们必须以使两个容器的高度保持最小的方式来划分整数(框)。

相关链接:

子集和问题 - Wiki

极客极客教程- 好一个

于 2013-06-22T01:44:24.297 回答