Last active
March 4, 2020 22:36
-
-
Save serverhiccups/7b498657b31ee8da2b385c373f5aad79 to your computer and use it in GitHub Desktop.
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
/* Water Flow Simulation Test | |
Key Ideas: | |
The model that describes the network is stored seperately from the model that does the calculations | |
*/ | |
class Network { | |
constructor() { | |
this.network = []; | |
this.builtNetwork = []; | |
this.sources = []; | |
this.sinks = []; | |
} | |
connect(a, b, maxFlow) { | |
this.network.push({ | |
src: a, | |
dest: b, | |
maxFlow: maxFlow | |
}); | |
} | |
disconnect(a, b) { | |
let idx = this.network.findIndex((x) => { | |
return x.src == a && x.dest == b; | |
}); | |
if (idx != -1) this.network.splice(idx, 1); | |
} | |
setSources(sources) { | |
this.sources = sources; | |
/* this.sources = {id: 0, flow: 20}*/ | |
} | |
setSinks(sinks) { | |
this.sinks = sinks; | |
/* this.sinks = {id: 0, flow: 20}*/ | |
} | |
_buildNetwork() { | |
// Figure out the size of the network. | |
let maxNode = 0; | |
this.network.forEach((x) => { | |
if (x.src > maxNode) maxNode = x.src; | |
if (x.dest > maxNode) maxNode = x.dest; | |
}); | |
// Create the adjacency list. | |
this.builtNetwork = Array(maxNode + 3).fill([]); // 1 for the factor there is a 0 node, two for the source and the sink. | |
this.network.forEach((v) => { | |
this.builtNetwork[v.src].push({dest: v.dest, maxFlow: v.maxFlow}); | |
}); | |
// Remove sources and sinks that aren't in the network. | |
let sources = this.sources.filter((x) => { | |
return x >= 0 && x <= maxNodes | |
}); | |
let sinks = this.sinks.filter((x) => { | |
return x >= 0 && x <= maxNodes | |
}); | |
// Stop if there aren't any sources or sinks. | |
if (sources.length == 0) { | |
throw new Error("There are no sources"); | |
} | |
if (sinks.length == 0) { | |
throw new Error("There are no sinks"); | |
} | |
/* Replace the multiple sources with one so that algorithm can work. | |
This is arguably required anyway because in this algorithm all | |
sources and sinks have unlimited flow, so we have to limit the flow | |
using extra vertices anyway. */ | |
this.sourceId = maxNode + 1; | |
this.sinkId = maxNode + 2; | |
sources.forEach((v) => { | |
this.builtNetwork[this.sourceId].push({dest: v.id, maxFlow: v.flow}); | |
}); | |
sinks.forEach((v) => { | |
this.builtNetwork[v.id].push({dest: this.sinkId, maxFlow: v.flow}); | |
}); | |
} | |
_bfs(start, end) { | |
let queue = []; | |
let visited = new Array(this.builtNetwork.length).fill(false); | |
queue.push(start); | |
while(queue.length > 0) { | |
} | |
} | |
calculate() { | |
this._buildNetwork(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment