Skip to content

Instantly share code, notes, and snippets.

@mkpoli
Created August 24, 2022 09:18
Show Gist options
  • Select an option

  • Save mkpoli/d8d21117b85f93f7c81bf6185ee6488d to your computer and use it in GitHub Desktop.

Select an option

Save mkpoli/d8d21117b85f93f7c81bf6185ee6488d to your computer and use it in GitHub Desktop.
A simple integer segmentation function
// Input: [10, 11, 12, 15, 17]
// Output: [[10, 12], [15, 15], [17, 17]]
// Input [1, 2, 3, 5]
// Output [[1, 3], [5, 5]]
function segmentate(arr: number[]): number[][] {
const array = [...new Set(arr)].sort((a, b) => a - b);
const result: number[][] = [];
let segment: [start: number, end: number] = [array[0], array[0]];
for (let i = 0; i <= array.length - 1 ; i++) {
const [curr, next] = [array[i], array[i + 1]];
if (curr + 1 === next) {
segment = [segment[0], next];
} else {
result.push(segment);
segment = [next, next];
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment