Last active
November 23, 2021 09:29
-
-
Save Beaglefoot/ebdca7768fabbedcbf37a309ab81949e to your computer and use it in GitHub Desktop.
algo test
This file contains hidden or 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
/* | |
arr - массив строк вида ["1-3","5-7","2-4","8-12","5-11"] | |
Каждая строка в массиве задает интервал [N,M], где N и M - целые числа, включая края. | |
Необходимо написать функцию сигнатуры string[] => string[], которая получает на вход подобный массив, | |
и возвращает массив строк такого же формата, в котором все перекрывающиеся интервалы оптимально склеены и отсортированы. | |
Например, в данном случае должен получиться массив ["1-4","5-12"]. | |
Необходимо учесть возможные пограничные случаи, включая невалидный формат" | |
*/ | |
function parseInterval(interval: string): { start: number; end: number } { | |
const matches = interval.match(/(\d+)-(\d+)/); | |
if (!matches) { | |
throw new Error("Incorrect input format."); | |
} | |
const start = parseInt(matches[1]); | |
const end = parseInt(matches[2]); | |
if (start > end) throw new Error("Interval start must be a lesser value"); | |
return { start, end }; | |
} | |
function mergeIntervals(intervals: string[]): string[] { | |
interface IMerges { | |
start: number; | |
end: number; | |
} | |
let isUnmodified = true; | |
const merges: IMerges[] = []; | |
for (let interval of intervals) { | |
const { start, end } = parseInterval(interval); | |
let isMerged = false; | |
for (let rInterval of merges) { | |
if ( | |
(start < rInterval.start && end > rInterval.start) || | |
(start > rInterval.start && end < rInterval.end) || | |
(start < rInterval.end && end > rInterval.end) | |
) { | |
rInterval.start = Math.min(start, rInterval.start); | |
rInterval.end = Math.max(end, rInterval.end); | |
isMerged = true; | |
isUnmodified = false; | |
break; | |
} | |
} | |
if (!isMerged) { | |
merges.push({ start, end }); | |
} | |
} | |
const result = merges.map(({ start, end }) => `${start}-${end}`); | |
return isUnmodified ? result : mergeIntervals(result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment