Last active
May 15, 2016 17:31
-
-
Save MelvIsntNormal/b77e3e4720d9a050b6ad892d9ccfb668 to your computer and use it in GitHub Desktop.
Dart solution to https://www.reddit.com/r/dailyprogrammer/comments/4ijtrt/20160509_challenge_266_easy_basic_graph/
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
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