Created
March 21, 2023 09:23
-
-
Save ajays97/5afed0a0778519556b8d909e2df41aad to your computer and use it in GitHub Desktop.
Find paths to consume all tickets
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
const data: Record<string, Set<string>> = { | |
MUM: new Set(['CHEN']), | |
BLR: new Set(['JAI']), | |
DEL: new Set(['BLR', 'AGRA']), | |
JAI: new Set(['MUM']), | |
AGRA: new Set(['DEL']) | |
}; | |
function findStart(data: Record<string, Set<string>>) { | |
const source: Record<string, number> = {}; | |
const dest: Record<string, number> = {}; | |
const startingPoints: string[] = []; | |
for (let [key, value] of Object.entries(data)) { | |
source[key] = value.size; | |
} | |
for (let destinations of Object.values(data)) { | |
for (let destination of destinations) { | |
if (!dest[destination]) { | |
dest[destination] = 1; | |
} else { | |
dest[destination]++; | |
} | |
} | |
} | |
for (let destination of Object.keys(dest)) { | |
dest[destination] -= source[destination] || 0; | |
if (dest[destination] === -1) { | |
startingPoints.push(destination); | |
} | |
} | |
if (startingPoints.length === 1) { | |
return startingPoints[0]; | |
} else if (startingPoints.length > 1) { | |
return ''; | |
} | |
} | |
function findPath(data: Record<string, Set<string>>, start: string) { | |
const path = []; | |
let currentSource = start; | |
while (currentSource && data[currentSource]) { | |
if (!data[currentSource]) { | |
return path; | |
} | |
if (data[currentSource].size === 0) { | |
return path; | |
} | |
if (data[currentSource].size === 1) { | |
let currentDestination = data[currentSource].values().next().value; | |
path.push([currentSource, currentDestination]); | |
currentSource = currentDestination; | |
} | |
if (data[currentSource] && data[currentSource].size > 1) { | |
for (let destination of data[currentSource].values()) { | |
if (data[destination] && data[destination].has(currentSource)) { | |
data[currentSource].delete(destination); | |
path.push([currentSource, destination]); | |
currentSource = destination; | |
} | |
} | |
} | |
} | |
return path; | |
} | |
const startingPoint = findStart(data); | |
console.log(`Starting point: `, startingPoint); | |
const paths = findPath(data, startingPoint); | |
let result = ''; | |
result += `${paths[0][0]} --> `; | |
for (let path of paths) { | |
result += `${path[1]} --> `; | |
} | |
console.log(result.slice(0, -5)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment