Created
August 21, 2015 13:20
-
-
Save jan-matthis/b5619427cf9a785d7206 to your computer and use it in GitHub Desktop.
JS to find connected regions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* JS to find connected regions */ | |
var findConnectedRegions = function(arr) { | |
var distinct = []; | |
var durations = []; | |
var labels = []; | |
var idx = 0; | |
var calcCumSum = function(arr) { | |
var calc = function(acc, n) { | |
var lastNum = acc.length > 0 ? acc[acc.length-1] : 0; | |
acc.push(lastNum + n); | |
return acc; | |
}; | |
return _.reduce(arr, calc, []); | |
} | |
for(i=0; i<arr.length; i++) { | |
if(_.indexOf(distinct, arr[i]) == -1) { | |
distinct.push(arr[i]); | |
} | |
if(_.isEmpty(durations) && _.isEmpty(labels)) { | |
durations.push(1); | |
labels.push(arr[i]); | |
continue; | |
} | |
if(labels[idx] === arr[i]) { | |
durations[idx] = durations[idx]+1; | |
} else { | |
labels.push(arr[i]); | |
durations.push(1); | |
idx++; | |
} | |
} | |
return { | |
durations: durations, | |
cumDurations: calcCumSum(durations), | |
labels: labels, | |
distinct: distinct | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment