| 1 |
"use strict"; |
| 2 |
|
| 3 |
var _ = require("../lodash"); |
| 4 |
|
| 5 |
module.exports = crossCount; |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
function crossCount(g, layering) { |
| 24 |
var cc = 0; |
| 25 |
for (var i = 1; i < layering.length; ++i) { |
| 26 |
cc += twoLayerCrossCount(g, layering[i-1], layering[i]); |
| 27 |
} |
| 28 |
return cc; |
| 29 |
} |
| 30 |
|
| 31 |
function twoLayerCrossCount(g, northLayer, southLayer) { |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
var southPos = _.zipObject(southLayer, |
| 36 |
_.map(southLayer, function (v, i) { return i; })); |
| 37 |
var southEntries = _.flatten(_.map(northLayer, function(v) { |
| 38 |
return _.sortBy(_.map(g.outEdges(v), function(e) { |
| 39 |
return { pos: southPos[e.w], weight: g.edge(e).weight }; |
| 40 |
}), "pos"); |
| 41 |
}), true); |
| 42 |
|
| 43 |
|
| 44 |
var firstIndex = 1; |
| 45 |
while (firstIndex < southLayer.length) firstIndex <<= 1; |
| 46 |
var treeSize = 2 * firstIndex - 1; |
| 47 |
firstIndex -= 1; |
| 48 |
var tree = _.map(new Array(treeSize), function() { return 0; }); |
| 49 |
|
| 50 |
|
| 51 |
var cc = 0; |
| 52 |
_.forEach(southEntries.forEach(function(entry) { |
| 53 |
var index = entry.pos + firstIndex; |
| 54 |
tree[index] += entry.weight; |
| 55 |
var weightSum = 0; |
| 56 |
while (index > 0) { |
| 57 |
if (index % 2) { |
| 58 |
weightSum += tree[index + 1]; |
| 59 |
} |
| 60 |
index = (index - 1) >> 1; |
| 61 |
tree[index] += entry.weight; |
| 62 |
} |
| 63 |
cc += entry.weight * weightSum; |
| 64 |
})); |
| 65 |
|
| 66 |
return cc; |
| 67 |
} |