Skip to content

Instantly share code, notes, and snippets.

@ttm
Last active April 2, 2017 00:05
Show Gist options
  • Save ttm/73019d8a8051652334d3f3af9f1a3993 to your computer and use it in GitHub Desktop.
Save ttm/73019d8a8051652334d3f3af9f1a3993 to your computer and use it in GitHub Desktop.
a solution to the challenge of the Helikar Lab GSoC2017
function gridLayout() {}
gridLayout.calculate = function(nodes, edges, size) {
var degrees = Array(nodes.length).fill(0);
edges.forEach(function(e) {
degrees[e.source.index] += 1;
degrees[e.target.index] += 1;
});
//getting the order of nodes from highest to lowest degrees
var mapped = degrees.map(function(el, i) {
return { index: i, value: el };
});
mapped.sort(function(a, b) {
return +(a.value < b.value) || +(a.value === b.value) - 1;
});
//illustrating how one would sort 'degrees' by 'mapped'
//result = mapped.map(function(el){
// return degrees[el.index];
//});
//positions should spiral around the center:
var spiral = makeSpiral(nodes.length, Math.floor(size/2));
mapped.forEach(function(e, i){
aindex = e.index;
nodes[aindex].x = spiral[i][0];
nodes[aindex].y = spiral[i][1];
});
}
function makeSpiral(n, center){
//(di, dj) is a vector - direction in which we move right now
var di = 1;
var dj = 0;
//length of current segment
var segment_length = 1;
//current position (i, j) and how much of current segment we passed
var i = center;
var j = center;
var segment_passed = 0;
var positions = [[i, j]];
var abuffer = 0;
for (k = 0; k < n-1; ++k) {
//make a step, add 'direction' vector (di, dj) to current position (i, j)
i += di;
j += dj;
++segment_passed;
positions.push([i, j]);
if (segment_passed == segment_length) {
//done with current segment
segment_passed = 0;
//'rotate' directions
abuffer = di;
di = -dj;
dj = abuffer;
//increase segment length if necessary
if (dj == 0) {
++segment_length;
}
}
}
return positions;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment