Group arrays by linear comparison

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

I start to draw line, x1 = line[0] to x2 = line[1] at y=10

This is x axis with set of lines drawn

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

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

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

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

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

since l1 = [1, 4] is drawn under l2 = [3, 7] // if(l2[0] < l1[1]) somehow need to y+=10 //

changes again: 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]]

Can someone restructure data into lines with sets of line for offsetting y value.

Answers


You can use a recursive function which tests for "overlaps" like this

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;
}

now every time there is an overlap, the following items get pushed down into the next level

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

Need Your Help

Advice on making a youtube video stop when a click event is fired

javascript jquery youtube youtube-api

I have set up some test code that loads in a youtube video and then a jquery click event on a link that I plan to stop the video, at the moment however when I click the link I get the error: Uncaught

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.