r/dailyprogrammer • u/nint22 1 2 • Dec 18 '13
[12/18/13] Challenge #140 [Intermediate] Adjacency Matrix
(Intermediate): Adjacency Matrix
In graph theory, an adjacency matrix is a data structure that can represent the edges between nodes for a [graph](http://en.wikipedia.org/wiki/Graph_(mathematics)) in an N x N matrix. The basic idea is that an edge exists between the elements of a row and column if the entry at that point is set to a valid value. This data structure can also represent either a directed graph or an undirected graph.
Your goal is to write a program that takes in a list of edge-node relationships, and print a directed adjacency matrix for it. Our convention will follow that rows point to columns. Follow the examples for clarification of this convention.
Here's a great online directed graph editor written in Javascript to help you visualize the challenge. Feel free to post your own helpful links!
Formal Inputs & Outputs
Input Description
On standard console input, you will be first given a line with two space-delimited integers N and M. N is the number of nodes / vertices in the graph, while M is the number of following lines of edge-node data. A line of edge-node data is a space-delimited set of integers, with the special "->" symbol indicating an edge. This symbol shows the edge-relationship between the set of left-sided integers and the right-sided integers. This symbol will only have one element to its left, or one element to its right. These lines of data will also never have duplicate information; you do not have to handle re-definitions of the same edges.
An example of data that maps the node 1 to the nodes 2 and 3 is as follows:
1 -> 2 3Another example where multiple nodes points to the same node:
3 8 -> 2You can expect input to sometimes create cycles and self-references in the graph. The following is valid:
2 -> 2 3
3 -> 2Note that there is no order in the given integers; thus "1 -> 2 3" is the same as "1 -> 3 2".
Output Description
Print the N x N adjacency matrix as a series of 0's (no-edge) and 1's (edge).
Sample Inputs & Outputs
Sample Input
5 5
0 -> 1
1 -> 2
2 -> 4
3 -> 4
0 -> 3Sample Output
01010
00100
00001
00001
00000
5
u/skyangelisme 0 1 Dec 18 '13 edited Dec 18 '13
Java 1.6+ I can't wait until java has lambdas! Edit to include multiple nodes.
19
u/KompjoeFriek 1 0 Dec 20 '13 edited Dec 20 '13
Made with dogescript, see here for runnable version
Edit: added parseInt for gridsizes with double digits
10
u/thestoicattack Dec 18 '13 edited Dec 18 '13
bash:
7
u/dooglehead Dec 19 '13 edited Dec 19 '13
C: This is my first time doing a challenge.
5
u/dunnowins Dec 18 '13
This is my first time trying an intermediate problem. I'd really appreciate some feedback. I did it in Ruby.
adj_mat.txt:
Output:
5
u/null_terminator Dec 18 '13 edited Dec 18 '13
C
5
u/ponkanpinoy Dec 19 '13 edited Dec 19 '13
Gnarly lisp -- the input parsing code is over half the program. For the purposes of clarity in this submission I put a blank line before the
labelsstatement that forms the body of thelet*statement and is the start of the actual function logic. This is my first intermediate submission, and comments are definitely welcome.Sample problem output:
Instructions are to accept many-to-one and one-to-many relationships -- also works with many-to-many
2
u/[deleted] Dec 18 '13
Totally not getting this adjacency matrix thing.
4
u/winged_scapula Dec 18 '13 edited Dec 18 '13
Python 2.7 :
EDIT: fixed wrong variable names, I can't even node.
4
u/skeeto -9 8 Dec 18 '13
Elisp/Lisp. First it parses into an adjacency graph alist of the connections, then prints the alist.
Usage:
The intermediate alist looks like so,
7
u/[deleted] Dec 19 '13 edited Dec 19 '13
"Enterprise" Java:
AdjacencyMatrix.java
Map.java
AdjacentMatrixDAO.java
FileAdjacentMatrixDAO.java
FileMatrixDAO.java
PrintMatrixController.java
Main.java
Example Input
Output
3
u/jmillikan2 Dec 18 '13 edited Dec 18 '13
Go 1.1.1 since I've been learning it. Input may not be idiomatic. Edit: Same stuff, less lines (When in Rome...)
3
u/OffPiste18 Dec 18 '13
Scala. I'm trying to get towards writing more idiomatic Scala, including following the style guide as closely as possible.
3
u/[deleted] Dec 18 '13 edited Dec 19 '13
Python 3
Pretty sure this is wrong, I mean, it works for the sample input but I think anything else might break it. I've not bothered converting the input but I might get round to it later on.
Input
Output
3
u/Edward_H Dec 18 '13
My COBOL solution:
AdjacencyMatrix.cbl:
SplitNumsIntoTable.cbl:
3
u/thoth7907 0 1 Dec 18 '13 edited Dec 19 '13
Powershell:
Tested on multiple nodes lines, such as:
0 1 2 3 -> 4
0 -> 1 2 3 4
0 1 -> 2 3
and so on, plus the sample.
3
u/skyangelisme 0 1 Dec 19 '13
Clojure 1.5.1
3
u/markus1189 0 1 Dec 19 '13 edited Dec 19 '13
Haskell
3
u/imladris Dec 19 '13 edited Dec 19 '13
My Haskell solution: (One IO line shamelessly copied from the solution of /u/ooesili) Edit: putChar . head -> putStr
Edit: Made an attempt to use more specific types and tried to make everything as clear and concise as possible.
3
u/hardleaningwork Dec 19 '13 edited Dec 19 '13
C#, done with bitmaps to hold the connecting node data. This takes our memory space from potentially O(n2) (which would be a simple NxN array) to O(n/32) worst case (with a little overhead for the dictionary). It also uses bit-wise lookups and sets, which are constant time O(1).
It's O(1) to look up a row (Dictionary lookup), and O(1) to look up any column in that row (bitwise ops). It's O(1) to set any node relationship (bitwise ops). The memory space is O(n/32) based on which rows actually have data, otherwise I don't record them.
5
u/ooesili Dec 18 '13 edited Dec 18 '13
Haskell solution with quite a few comments. Discrete mathematics is so much fun! EDIT: shortened the code and renamed/changed a few functions and types.
4
u/nowne Dec 18 '13 edited Dec 18 '13
Python 2.7
2
u/0x746d616e Dec 18 '13 edited Dec 18 '13
Go:
Edit: fixed bug where
0 -> 1 2and1 2 -> 0would result in identical matrix2
u/BondDotCom Dec 18 '13
VBScript (under WSH). Saving a few lines by creating the array with zeros pre-populated and by converting from an array back to a string before outputting.
Output:
2
u/kirsybuu 0 1 Dec 18 '13
D Language
Example:
2
u/f0rkk Dec 18 '13
Am I doing this right? I think I'm doing this right, but I'm not completely sure. Regardless, it works for the sample.
2
u/demon_ix 1 0 Dec 18 '13
Python 3.
usage:
2
u/TimeCannotErase Dec 18 '13
R Solution:
2
u/thinksInCode Dec 18 '13 edited Dec 18 '13
Java:
Edit: don't compile the pattern every time
2
u/kozko2001 Dec 18 '13
Another python 2.7 --- Hope you like it :)
2
u/AnthonyInsanity Dec 18 '13
python 2.7 - i feel like i'm getting faster at implementing these!
2
u/[deleted] Dec 18 '13
Python 3
Help me clean up the input parsing!
2
u/Steve132 0 1 Dec 18 '13
C++0x
2
u/koloron Dec 18 '13
Python 3
2
u/_Bia Dec 18 '13
C++
2
u/prondose 0 0 Dec 18 '13
Perl:
2
u/conor_fogarty Dec 19 '13
Solution in Go:
2
u/Sakuya_Lv9 Dec 19 '13 edited Dec 19 '13
edit: Forgot there can be "2 3 -> 2". Working on that right now.edit: done.
Lua. One single function. This has been fun.
2
u/rectal_smasher_2000 1 1 Dec 19 '13
c++
2
u/Garth5689 Dec 19 '13
python 2.7
2
u/danohuiginn Dec 19 '13 edited Dec 19 '13
I took this as an excuse to try bit-manipulation in python. Went with the bitarray library. I learnt a lot, including about how fragile efficiency gains can be. For example, at first I initialized the adjacency matrix with:
but this turns out to be very slow compared to:
Anyway, here is the code:
2
u/pbl24 Dec 19 '13
A little Python action. Could probably minimize it a decent amount, but it works nonetheless:
Full program (including input parsing):
2
u/pbl24 Dec 19 '13
Here is some additional input that I tried:
Input:
Output:
2
u/toodim Dec 19 '13
Python 3. I initially tried doing this with a bunch of convoluted list comprehensions but things weren't working quite right so I wrote out some for loops.
2
u/drguildo Dec 19 '13
My solution handles edge-node data of the form "1 2 -> 3 4". The problem description didn't forbid it, it makes the solution easier to read/more concise and it seemed like a useful ability.
Java
2
u/dadosky2010 Dec 19 '13 edited Dec 19 '13
Python 3.2
I didn't test it, but this should also handle 1 2 -> 3 4 cases as well (Thanks to the product function).
2
u/itsthatguy42 Dec 19 '13 edited Dec 19 '13
on #145 easy I went for confusing code; now for the other end of the spectrum (at least, I hope... I do like chaining function calls a bit too much)
solution in javascript, using html5 for file input:
2
u/hamc17 Dec 19 '13 edited Dec 20 '13
This one's in Java.
First time trying an intermediate challenge, nailed it! It takes in inputs that map from single to single, single to multiple, multiple to single and multiple to multiple. Redefinitions of same edges are fine. Took about 2 hours, less than a quarter of which was actually writing the code. I spent most of my time searching for a rogue variable that was messing up the whole lot but I found it!
Critique is welcome, I'm relearning the language by myself to hopefully become a programmer. Formatting is a little off as I'm not bothered to put another 4 spaces on every single line.
Sample input:
10 10
0 -> 5 6 7
3 4 -> 8 9
1 -> 2
3 -> 6
2 -> 4 7 6
8 -> 9
6 -> 1 4 7
5 -> 2
7 -> 3
1 5 2 8 -> 6 4 2
Sample output:
0 0 0 0 0 1 1 1 0 0
0 0 1 0 1 0 1 0 0 0
0 0 1 0 1 0 1 1 0 0
0 0 0 0 0 0 1 0 1 1
0 0 0 0 0 0 0 0 1 1
0 0 1 0 1 0 1 0 0 0
0 1 0 0 1 0 0 1 0 0
0 0 0 1 0 0 0 0 0 0
0 0 1 0 1 0 1 0 0 1
0 0 0 0 0 0 0 0 0 0
Edit: Removed redundant loop.
2
u/harmspam Dec 20 '13
JavaScript:
2
u/benzrf 0 0 Dec 20 '13
Simple Ruby solution:
2
u/VerifiedMyEmail Dec 20 '13 edited Dec 20 '13
Javascript with html
working codepen
feedback is weclome
2
u/Elite6809 1 1 Dec 20 '13
Ruby. Still new to Ruby so excuse me if I use C#-isms rather than Rubyisms:
Note that this will also support n-to-n edges, so an input line like
2 3 -> 4 5 6will still work (thanks to Array::product).2
u/vishbar Dec 20 '13 edited Dec 20 '13
F#. A little wordy, but it gets the job done :)
2
u/cooper6581 Dec 21 '13
Java. (Still learning the language). Thanks for keeping the daily challenges going!
2
u/code508 Dec 21 '13 edited Dec 21 '13
Python 2.7:
2
u/Rhinoceros_Party Dec 21 '13 edited Dec 21 '13
I think this is the first time I was able to solve an intermediate problem. If anyone has any critiques or recommendations for my code, I'd welcome it. Ultimately, this came down to just looping through the input and setting array elements to 1, which didn't feel very complex. Maybe I missed something that would be triggered by a more complex test case? Written in Java.
2
u/i4X-xEsO Dec 21 '13
python:
2
u/ReginaldIII Dec 21 '13
C++ solution using a char array as a bit array to reduce memory for storing the matrix.
2
u/ReasonableCause Dec 22 '13
My Haskell solution, pretty straightforward; I convert the input file to a flat list of edge tuples (from, to) and when building the matrix I check if the coordinate is in the list or not. I am not too happy with the "createMatrix" function; it feels a bit bloated. But I am not sure how to improve it.. any suggestions are welcome!
Haskell:
2
u/tanaqui Dec 22 '13
Java:
I guess I didn't really need the smaller helper methods, but I just dislike looking at nested loops.
2
u/arthurv89 Dec 22 '13
2
u/dongas420 Dec 22 '13
First challenge, let's do this
2
u/[deleted] Dec 22 '13 edited Dec 23 '13
python:
2
u/[deleted] Dec 23 '13
Matrix.java:
Not the prettiest code but it worked the first time I ran it. I tried to add plenty of error-checking (cause it's a good habit to get into) but I didn't extensively test it or anything. Seems to work fine on all inputs I've tried though. Also halfway through I got bored adding error messages on invalid input so it just prompts you for the same input.
2
u/phantomesse Dec 23 '13
My Java solution. I found this one to be particularly easy for an intermediate problem. Am I missing something?
2
u/carnaxcce Dec 24 '13
Python 2.7:
2
u/derekpetey_ Dec 28 '13
Quick and dirty with Python:
2
u/deprecated_reality Jan 09 '14
First post here. Its been a long time since ive touched java (or any OO) and im kinda upset by how hacky this is, nearly didnt even post it.
2
u/altanic Jan 11 '14
I didn't pick up right away that it'd be NxN and started with NxM in mind but anyway, it works... (I think) C#:
2
u/Idra_rage_lulz Jan 11 '14
Kinda late but here's my solution. C++11
2
u/murdockr Jan 21 '14 edited Jan 21 '14
A bit late to the party, but here's my clojure solution
Usage:
2
u/agambrahma Jan 27 '14
C++ solution:
2
u/[deleted] Dec 18 '13 edited Dec 19 '13
Python3 using NumPy, been a long while since I used it, can probably be done much cleaner
1
u/slackertwo Dec 19 '13
Ruby - Feedback on readability would be much appreciated.
Output:
1
u/wildconceits Dec 19 '13
This my first time with an intermediate problem, so any advice is welcome! Answer in Python 2.6 below:
1
u/OldNedder Dec 19 '13
Groovy:
1
u/NarcissusGray Dec 19 '13
Simple Python solution:
1
u/[deleted] Dec 19 '13
Can anyone donate a few more test cases just to be 100% I've got this working?
1
u/Die-Nacht 0 0 Feb 16 '14
Haskell, playing with Lens
1
u/MrFromEurope Feb 18 '14
First time ever posting here using Java.
}
1
u/refucktoring Feb 19 '14
PHP
1
u/deuteros Feb 23 '14
C#
1
u/iomanip1 Apr 08 '14
Python 2.7.4: short but sweet! (and late, but i liked the challenge) import numpy as np;
1
u/Tappity Dec 18 '13 edited Dec 18 '13
Java. I haven't really done this before, but is this efficient?
1
u/hardleaningwork Dec 18 '13 edited Dec 19 '13
C#
1
u/grimcraftman Dec 18 '13 edited Dec 18 '13
In Python 3.3. It works, but it's not a good code. I will improve it later. Open to feedback.
Edit:
Looking at the other Python submissions, my re.match should be replaced with split(sep = '->').
1
u/the_mighty_skeetadon Dec 18 '13
Ruby, half of which is just building the arrays to hold zeros:
Any tips on how I get the matrix up better? This way sucks. Anyway, here's what it looks like with input and output:
1
u/DGChainZ Dec 18 '13 edited Dec 18 '13
C#: Open to suggestions
EDIT: Fixed formatting
-2
u/[deleted] Dec 18 '13
Cool, I'll have a look
0
u/[deleted] Dec 22 '13
[deleted] — view deleted comment