通过线性比较分组数组

时间:2013-11-17 13:15:57

标签: javascript data-structures underscore.js

var data = [[1, 4], [8, 10], [12, 14]]
var line = data[i];

我开始在x1 = line[0] to x2 = line[1]

画线y=10

这是带有一组线条的x轴

0 ' ' 3 ' ' 6 ' ' 9 ' ' 12 ' ' 15

  -------       -----    -----
数据更改时


var data = [[1, 4], [3, 7], [8, 10], [12, 14]]

0 ' ' 3 ' ' 6 ' ' 9 ' ' 12 ' ' 15

  -------       -----    -----
      --------

因为在l1 = [1, 4]

下绘制了l2 = [3, 7] // if(l2[0] < l1[1]) somehow need to y+=10 //

再次更改:
var data = [[1, 4], [3, 7], [2, 5], [8, 10], [12, 14]]

0 ' ' 3 ' ' 6 ' ' 9 ' ' 12 ' ' 15

  -------       -----    -----
      --------
    -------

y+=20

var lines = [[line, line, line], [line], [line]]

有人可以datalines重组为line,用y value来抵消{{1}}。

1 个答案:

答案 0 :(得分:0)

你可以使用一个递归函数来测试像这样的“重叠”

function organise(data1) {
    var data2 = [[]], moreWorkNeeded = [],
        i = data1.length, j;
    d1: while (i-->0) { // loop down, later nodes come last
        for (j = 0; j < i; ++j) { // loop up, stop at current
            if (
                    (data1[i][0] >= data1[j][0] && data1[i][0] <= data1[j][1])
                    ||
                    (data1[i][1] >= data1[j][0] && data1[i][1] <= data1[j][1])
                ) {
                    moreWorkNeeded.push(data1[i]);
                    continue d1;
            }
        }
        data2[0].push(data1[i]);
    }
    if (moreWorkNeeded.length)
        data2 = data2.concat(organise(moreWorkNeeded.reverse())); // recurse
    return data2;
}

现在每次重叠时,以下项目都会被推到下一个级别

var data = [[1, 4], [3, 7], [2, 5], [8, 10], [12, 14]];
organise(data);
/* [
    [[12, 14], [8, 10], [1, 4]],
    [[3, 7]],
    [[2, 5]]
]*/