Last active
March 27, 2022 10:03
-
-
Save Phryxia/7eb1a32824c4e1d20afdb363d511b2c7 to your computer and use it in GitHub Desktop.
TypeScript implementation of finding greatest element in partially ordered set.
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
export type Relation = [string, string] | |
function makeGraph(relations: Relation[]): Record<string, string[]> { | |
const result: Record<string, string[]> = {} | |
relations.forEach(([u, v]) => { | |
(result[u] ??= []).push(v) | |
result[v] ??= [] | |
}) | |
return result | |
} | |
export function findGreatest(relations: Relation[]): string | null { | |
const graph = makeGraph(relations) | |
const nodes = Object.keys(graph) | |
const zeroOutNodes = nodes.filter(u => graph[u].length === 0) | |
if (zeroOutNodes.length !== 1) return null | |
const dup: Record<string, 'analyzing' | 'resolved'> = {} | |
function isLoopExists(node: string): boolean { | |
if (dup[node] === 'analyzing') return true | |
if (dup[node] === 'resolved') return false | |
dup[node] = 'analyzing' | |
const isLoop = graph[node].reduce((isLoop, child) => isLoop || isLoopExists(child), false) | |
dup[node] = 'resolved' | |
return isLoop | |
} | |
if (nodes.reduce((isLoop, node) => isLoop || isLoopExists(node), false)) return null | |
return zeroOutNodes[0] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Find unique greatest element in partially ordered set. If there is no such element, it returns
null
.Example
For example, let's assume some inequalities between variables.
In this example, the maximum variable is
e
.Time Complexity
It's just simple DFS, so O(V + E)