Skip to content

Commit

Permalink
Use topological sort to fix the bug
Browse files Browse the repository at this point in the history
  • Loading branch information
igrep committed Jun 7, 2022
1 parent c7d1f27 commit ac3bfb3
Showing 1 changed file with 17 additions and 13 deletions.
30 changes: 17 additions & 13 deletions eval.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
VertexId,
Edge,
} from "./lib";
import { topologicalSort } from "./topological-sort";

type PlugNumber = number;
type JackNumber = number;
Expand Down Expand Up @@ -90,24 +91,27 @@ type CursorVertexLastPosition = CursorVertexForEvaluationCore & {
};

function vertexesForEvaluation(
vertexes: Required<VertonVertexJsObject>[]
vertexes: Required<VertonVertexJsObject>[],
edges: Edge.JsObject[]
): {
plugsCount: number;
jacksCount: number;
plugJackOrdered: VertexForEvaluation[];
mouseVertexes: MouseVertexes;
idOrdered: VertexForEvaluation[];
} {
const vertexes0 = [...vertexes];
vertexes0.sort((a, b) => weight(a) - weight(b) || a._id - b._id);
function weight({ plugs, jacks }: Required<VertonVertexJsObject>): number {
if (plugs.length) {
if (jacks.length) {
return 0; // has both
}
return -1; // has only plugs
}
return 1; // has only jacks. (All vertexes have at least either!)
const vertexesById: Required<VertonVertexJsObject>[] = [];
for (const vertex of vertexes) {
vertexesById[vertex._id] = vertex;
}

const sortedIds = topologicalSort<{ vertexId: VertexId }>(
edges,
(edge) => edge.vertexId
);
const sortedVertexes: Required<VertonVertexJsObject>[] = [];
for (const id of sortedIds) {
sortedVertexes.push(vertexesById[id]);
}

const plugJackOrdered: VertexForEvaluation[] = [];
Expand All @@ -122,7 +126,7 @@ function vertexesForEvaluation(
};
let plugId = 0;
let jackId = 0;
for (const v of vertexes0) {
for (const v of sortedVertexes) {
let v1: VertexForEvaluation;
switch (v.kind) {
case "click":
Expand Down Expand Up @@ -293,7 +297,7 @@ export function evaluate(
plugJackOrdered,
idOrdered,
mouseVertexes,
} = vertexesForEvaluation(vertexes);
} = vertexesForEvaluation(vertexes, edges);
const graph = Graph.build(edges, idOrdered, jacksCount);
const plugState = PlugState.init(plugsCount);

Expand Down

0 comments on commit ac3bfb3

Please sign in to comment.