Skip to content

Instantly share code, notes, and snippets.

@MelvIsntNormal
Last active May 15, 2016 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MelvIsntNormal/b77e3e4720d9a050b6ad892d9ccfb668 to your computer and use it in GitHub Desktop.
Save MelvIsntNormal/b77e3e4720d9a050b6ad892d9ccfb668 to your computer and use it in GitHub Desktop.
import "dart:io";
import "dart:convert";
int main() async {
Map<int, List<int>> nodes = {};
int maxNodes = null;
List<int> emptyNode() => new List<int>.filled(maxNodes, 0);
// initialises node if it doesn't yet exist
List<int> node(int i) {
if(nodes[i] == null) nodes[i] = emptyNode();
return nodes[i];
}
List<int> intArray(String line) {
return line.split(" ").map(int.parse).toList();
}
// I store edges in a 2D array just so it's easier for me to
// print the matrix at the end
addEdge(int from, int to) {
node(from)[to - 1] = 1;
node(to)[from - 1] = 1;
}
processEdge(List<int> edge) {
if(maxNodes == null) maxNodes = edge[0];
else addEdge(edge[0], edge[1]);
}
// stdin streams bytes, so they need to be converted
// Not sure if I could convert them to integers directly
Stream nodeStream = stdin
.transform(UTF8.decoder)
.transform(const LineSplitter())
.map(intArray);
await nodeStream.listen(processEdge).asFuture();
StringBuffer matrix = new StringBuffer("\n\nMatrix: \n");
RegExp tokens = new RegExp(r'[\[\],]');
for (int i = 1; i <= maxNodes; i++) {
print("Node $i has a degree of ${node(i).where((edge) => edge == 1).length}");
matrix.writeln(" " + node(i).toString().replaceAll(tokens, ''));
}
print(matrix);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment