Middle — Senior
Labeling common segments of multiple sets of segments
livecode
Task condition
There are three different sets of segments. It is necessary to determine all the areas where they intersect, mark such intersections as separate new segments (for example, the intersection of the green and yellow sets is marked as a new segment – see exampleResult4), cut them out of the original sets, and output the sequence of the resulting segments in the range from 0 to 100.
// Segment mnemonics
const Task4 = () => {
type IMnemo = "green" | "yellow" | "red"
// Type for a segment - start and end
interface IInterval {
start: number,
end: number
}
type ISourceIntervals = Record<IMnemo, IInterval[]>
// Response type
interface IExpectedResult extends IInterval {
mnemo: IMnemo[],
}
// Source segments
const sourceData: ISourceIntervals = {
green: [{ start: 0, end: 30 }, { start: 90, end: 100 }],
yellow: [{ start: 20, end: 40 }, { start: 50, end: 70 }],
red: [{ start: 10, end: 50 }, { start: 70, end: 90 }],
}
// Expected result
const expectedResult: IExpectedResult[] = [
{ "mnemo": ["green"], start: 0, end: 10 },
{ "mnemo": ["green", "red"], start: 10, end: 20 },
{ "mnemo": ["green", "yellow", "red"], start: 20, end: 30 },
{ "mnemo": ["yellow", "red"], start: 30, end: 40 },
{ "mnemo": ["red"], start: 40, end: 50 },
{ "mnemo": ["yellow"], start: 50, end: 70 },
{ "mnemo": ["red"], start: 70, end: 90 },
{ "mnemo": ["green"], start: 90, end: 100 },
]
// Implement this function optimally, only one iteration over the source array is allowed!
// Additional arrays/objects can be created.
const getResult = (sourceIntervals: ISourceIntervals): IExpectedResult[] => {
return expectedResult
}
// This will output the result of its work on the right
return { expectedResult: expectedResult, result: getResult(sourceData) }
}
//Helper functions
const showTaskResult =(task: number, taskResult: {result: any, expectedResult: any}) => {
console.log(`---Result of task ${task}---`)
console.log('Expected: ', taskResult.expectedResult)
console.log('From function: ', taskResult.result)
console.log('')
}
showTaskResult(4, Task4())