r/dailyprogrammer • u/XenophonOfAthens 2 1 • Aug 12 '15
[2015-08-12] Challenge #227 [Intermediate] Contiguous chains
Description:
If something is contiguous, it means it is connected or unbroken. For a chain, this would mean that all parts of the chain are reachable without leaving the chain. So, in this little piece of ASCII-art:
xxxxxxxx
x x
there is only 1 contiguous chain, while in this
xxxx xxxx
x
there are 3 contiguous chains. Note that a single x, unconnected to any other, counts as one chain.
For the purposes of this problems, chains can only be contiguous if they connect horizontally of vertically, not diagonally. So this image
xx
xx
xx
contains three chains.
Your challenge today is to write a program that calculates the number of contiguous chains in a given input.
Formal inputs & outputs
Input:
The first line in the input will consist of two numbers separated by a space, giving the dimensions of the ASCII-field you're supposed to read. The first number gives the number of lines to read, the second the number of columns (all lines have the same number of columns).
After that follows the field itself, consisting of only x's and spaces.
Output:
Output a single number giving the number of contiguous chains.
Sample inputs & outputs
Input 1
2 8
xxxxxxxx
x x
Output 1
1
Input 2
3 9
xxxx xxxx
x
xx
Output 2
3
Challenge inputs:
Input 1
4 9
xxxx xxxx
xxx
x x x
xxxxxxxxx
Input 2
8 11
xx x xx x
x x xx x
xx xx x
xxxxxxxxx x
xx
xxxxxxxxxxx
x x x x x
x x x x
Bonus
/u/Cephian was nice enough to generete a much larger 1000x1000 input which you are welcome to use if you want a little tougher performance test.
Notes
Many thanks to /u/vgbm for suggesting this problem at /r/dailyprogrammer_ideas! For his great contribution, /u/vgbm has been awarded with a gold medal. Do you want to be as cool as /u/vgbm (as if that were possible!)? Go on over to /r/dailyprogrammer_ideas and suggest a problem. If it's good problem, we'll use it.
As a final note, I would just like to observe that "contiguous" is a very interesting word to spell (saying it is no picnic either...)
9
u/Cephian 0 2 Aug 12 '15 edited Aug 12 '15
I thought the inputs given seemed kind of small, so I made some bigger ones [1000 x 1000] to play with! I uploaded them to both MEGA and gist.
The answers for each input txt file are here.
20.txt was generated with a 20% chance of each square being an x, 80.txt was generated with an 80% chance, and so on.
My solution:
Iterated through each point and did a BFS [Breadth First Search] fill on all untouched x's I found. I used BFS instead of a recursive DFS because I wanted to be able to scale to larger problems without stack overflow.
C++
edit: made code better
4
u/skeeto -9 8 Aug 12 '15 edited Aug 12 '15
C, using a disjoint set forest to track connectedness. One of my design goals was to store only two rows in memory at a time so that it could potentially operate on humongous, arbitrarily tall inputs. The disjoint sets are constructed "pointing" down and right so that nodes can be freed as the algorithm progresses, maintaining only two rows at a time.
Code:
Using /u/Cephian's 90.txt (worst case):
2
u/Pantstown Aug 12 '15 edited Aug 12 '15
I'm confused on what counts as a chain.
xa chain, butx xisn't? Ifxxxx xxxxcounts as 2 chains, andxx xxcounts as two chains, doesn't it make sense thatx xcounts as two chains too?7
u/13467 1 1 Aug 12 '15
Haskell. Data.Graph to the rescue!
6
u/glenbolake 2 0 Aug 12 '15
Python 3. Instead of assuming all chains are composed of
x, a chain is any contiguous clump of the name non-space character.So this is two chains:
I iterate over the field, and whenever a non-space character is found, and that character doesn't appear in any already-built chains, build and record a new chain.
Inside building the chain, a set of locations relevant to the chain is created. I then repeatedly iterate over any newly-added elements of the chain, adding any new adjacent cells to the chain.
Code:
4
u/DownloadReddit Aug 12 '15 edited Aug 12 '15
C99
Implemented as a recursive DFS that eliminates the parts of the board that it visits to avoid visiting it again.
Edit: For Cephian's large input:
1
u/Elementoid Aug 20 '15
C++
My clever solution was just to count up all the "end links" of the chains and then divide that number by 2, but it seems that chains can have more than 2 ends, so I ended up just going through the grid, counting and then erasing chains as I found them.
3
u/wizao 1 0 Aug 13 '15 edited Oct 09 '15
Haskell:
1
u/TaohRihze Aug 12 '15
would following be considered a single chain or multiple. All parts are reachable but not traversable without backtracking.
oXo
XXX
XoX
2
u/NoobOfProgramming Aug 12 '15
I just started using Python and made a non-solution that only works with chains that are one x thick
2
u/mdskrzypczyk Aug 12 '15 edited Aug 12 '15
Python 2.7 using BFS search
EDIT: Needed to include challenge outputs: Challenge 1 - 1 chain Challenge 2 - 9 chains
2
u/kirsybuu 0 1 Aug 12 '15
D, using disjoint sets to process line-by-line:
2
u/curtmack Aug 12 '15 edited Aug 12 '15
Haskell
I mainly wanted to learn how to use the ST monad. All of the problems are instantaneous, but I haven't been able to get it to work on the 1000 x 1000 problems /u/Cephian posted - there's a space leak somewhere that I haven't quite been able to track down and it gobbles up like three gigs of RAM if I let it, so I'll have to figure that out at some point. (I've tried various bang patterns, didn't seem to help.)
Edit: Fixed some alignment errors that appeared when I pulled out all the bang patterns.
2
u/Ledrug 0 2 Aug 13 '15
C99. Quite complicated, but fast. It also runs online, meaning it doesn't keep all the input lines, but only the last two rows instead. I think the complexity is O(w*h) for a w by h input. Timing of /u/Cephian's big inputs at the end of post.
Large inputs (bash):
1
u/NoobOfProgramming Aug 12 '15
Ok, i'm pretty sure this works:
As my username implies, help/criticism is appreciated, especially since i'm new to python.
1
u/aukkras Aug 12 '15 edited Aug 12 '15
My solution in Rust
1
u/Godspiral 3 3 Aug 12 '15 edited Aug 12 '15
In J, reusing floodfill code, 'a' is the text matrix. just >@:cutLF
10
1
u/carrutstick Aug 12 '15
Haskell
My approach and goals were very similar to those of /u/curtmack, but I seem to have managed to avoid their space-leaks (by luck rather than experience, no doubt). In any case I got in some good practice with the
STmonad and with mutable arrays.The code crunches through /u/Cephian 's examples in a couple of seconds, which honestly seems longer than it should take. If I get some time later today I'll do some profiling and see what the holdup is.
1
u/Pretentious_Username Aug 12 '15
Python 2.7 It's been quite a while since I did one of these so I felt it was about time I gave one a shot. I'm using numpy to handle large arrays nicely and due to familiarity with it. I loop over all characters in the image and if they're not part of an existing chain I try to build a chain from them, propagating the label through the input. (Note I make the array 2 characters bigger in each dimension to deal with edge effects and yes I should have used "if _name_ == '_main_' and I abuse global scope a bit but for a small script I can live with the abuse)
On the 10.txt 1000x1000 data set the main processing loop takes just over a second. Sample output:
Which gives the correct answer according to here
1
u/altorelievo Aug 12 '15 edited Aug 15 '15
Python 2.7
Edit: Went back and made this a recursive DFS. I was getting a clipboard error because I was just copy and pasting the large inputs instead of parsing them out :) The original would go fine for the first few I pasted in 10, 20, ... 40 but on the larger input files 50.txt, 60.txt, ... things would hang up (the cache might have just filled up by then, not sure) Went from under a second to complete hang up. I reworked the algorithm and the larger inputs complete. With
60.txtin just over 3 sec. (with parsing into memory).Edit 2: Using
resourcesmodule and finding a good window with70.txtI've gotten it to run in a little under 3 seconds. While not in good form just wanted to see how far this bit of code could go.Edit 3: I tested out the first implementation again (BFS) this time with parsing in the files and even without the clipboard error after
40.txtthings would become too slow. I had in mind one line to add to fix this and it works. Nowhere as fast as the disjoint set algorithms but completes all the input files (with out the stackoveflows). The90.txtfinishes in around 7 seconds.recursive DFS
Results:
Non-recursive BFS
Results:
1
u/Trppmdm Aug 12 '15
Classic problem, the implementation part is really hard thoough, BFS is really easy to screw up.
C++
1
u/a_Happy_Tiny_Bunny Aug 12 '15 edited Aug 13 '15
Haskell
I decided to implement a very simple Graph data structure instead of importing a library or using arrays.
It runs /u/Cephian's 1000x1000 input in about 0.34s * for 10.txt, others run slower (40.txt takes about 8 s).
Feedback is appreciated; questions are welcomed.
EDIT: I now see that there are other bonus inputs. I believe the bottleneck for dense inputs is the depth first search that has to check all visited nodes every time. I'll probably come back and keep the visited nodes in an array, or use an annotated graph to keep track of this state.
2nd EDIT: I came back to the problem and decided to go all out and implemented a version of this papers depth first search. It's similar to what I was trying to do before (I mentioned keeping the visited nodes in an array...). It's pretty cool because it actually creates an infinite tree rooted at every vertex of the graph, except that we have to prune this forest (this is where the array comes from). 10.txt takes ~0.20s, and 90.txt takes about 2s.
Here is the code:
1
u/Def_Your_Duck Aug 13 '15
Java
Would someone give me some help? I honestly could not tell you what is wrong with this... At this point all it should do is tell me how many points are in a chain (doing so tells me that it recognizes the whole chain) but it always outputs 1. any advice would be fantastic.
Main class:
Point class:
Chain class:
1
u/ooesili Aug 13 '15 edited Aug 13 '15
Golang written TDD-style with GoConvey.
Edit: remove unneeded
set.has()method; simplify interfacesmain.go
main_test.go
1
u/royxiao Aug 13 '15
c++. any feedback is appreciated.
result for challenge 1 is 1, and challenge 2 is 9.
1
u/veeberz Aug 13 '15 edited Aug 13 '15
Python2
I want to do shenanigans with this one. Here's my implementation:
Explanation: Count number of edges, subtract one edge in each cycle. Subtract the number of vertices from the result. So,
My reasoning is that for connected graphs with no cycles, there are n-1 edges, where n is the number of vertices. So if you have a group of disjoint acyclic graphs, total vertices - total edges = number of disjoint graphs.
1
u/ReckoningReckoner Aug 13 '15
Ruby. Runs /u/Cephian's input in about 1.5 seconds.
1
u/SexmanTaco Aug 13 '15
Python using recursion
1
u/Godspiral 3 3 Aug 13 '15
26 wide sample
1
u/Keyallis Aug 13 '15
import java.io.*;
import java.util.*;
import static java.lang.System.*;
public class ContiguousChains{
}
1
u/Wiggledan Aug 13 '15
C99, kinda late and I think mine is pretty simple.
It finds the beginning of each chain, counts that chain, and then removes it by converting it into spaces.
1
u/ChiefSnoopy Aug 13 '15
I'd never made a submission on here in the form of a Bash script, so I thought I'd throw up a solution. Unfortunately, it's not the prettiest, but it works. I'm not very good in Bash, so please critique if you're looking at this after the fact.
1
u/A_Density_Matrix Aug 13 '15 edited Aug 13 '15
My naive solution in Python 3.4. Feedback is welcome!
I believe that what I have done is called a depth first search.
The program has an array to represent the locations of X'es , as well as an array to keep track of which locations have already been visited. The program walks along the grid until it finds an unvisited x. Then it checks for adjacent unvisited x'es. If there are, program moves to an adjacent x while saving the location of the previous x. This is repeated until no adjacent unvisited x is available, at which points the program walks back along the saved locations, doing a check of adjacent unvisited x's each time. Once it has no adjacent unvisited x'es and no previous locations to check, the program increments the chain counter, and continues walking until it finds a new chain.
The program could not handle inputs 50.txt and higher, as the chains in those were too long making the program exceed maximum recursion depth allowed by the interpreter.
1
u/VilHarvey Aug 13 '15 edited Aug 13 '15
Here's a simple incremental approach in python 2.7. It processes the grid line-by-line without ever having to load the whole grid into memory & uses very little memory (proportional to the width of the grid), so theoretically it would scale perfectly well to a grid trillions of lines long. The runtime is linear with respect to the size of the grid.
The algorithm is based on the observation that we only need to count a group when there's no possible way for it to continue on the current line. I do this by keeping track of the active group labels for each column (the 'roots' array in the code below). A group can be active in multiple columns; it only ends when there's a space in the new line for every column in which it's currently active. For each new line, I build up two sets: the set of groups which may be ending and the set of groups which are continuing. Subtracting one set from the other gives us the set of groups which have definitely ended, so I increment the total group count by the size of that set.
For this to work, group labels have to be consistent: each group has to have one and only one label; and no two distinct groups can have the same label. I guarantee the first property by using the row-major index of the starting grid cell as the group label. The second comes from propagating the minimum labels for existing groups down and across (both left and right) for each step - it doesn't matter if I had two distinct labels on a previous row for what turns out to be the same group now, as long as I have a single consistent label for it when the group ends.
Here's the code:
This processes the 1000x1000 input in just under 0.45 seconds on my machine.
1
u/dunstantom Aug 13 '15
Python 2.7. Similar to /u/NoobOfProgramming, but treated the board as a single list, rather than a grid.
1
u/[deleted] Aug 13 '15 edited Aug 13 '15
Standard solution in C#. Gets all the right answers for the regular, challenge, and x-large inputs.
Explanation:
Code:
Output:
1
u/[deleted] Aug 13 '15 edited Aug 14 '15
Java using DFS.
I didn't try making this OO at all.
I'm reading in each file in an folder named "input".
For each of those files, I'm reading in the first line and generating an array of ints[][] based on those two numbers, then set each to 0 for space or 1 for x.
Then I iterate over each point in the grid. If it's 0, I move on, if it's 1 then I call buildChain (the DFS recursive call) on it. When I return, I know I built a chain, and I won't start making another chain until I find another one.
buildChain sets the node to 1, then gets a list of the neighbors of that node that are one, and visits each of them, adding them to the current chain. As it traverses along, it's flipping nodes to 0 so they don't get re-visited.
Once the stack is empty a full chain was returned, and eventually this finds all the chains.
Changes -- I was thinking about why it was so slow. Initially I was adding each node (as a String i,j) to an ArrayList and checking if that list contained the current node, but that was adding a TON of overhead. I thought it would be much faster to just flip nodes I visited to 0 r and only look at nodes marked as 1, and that wound up going from 80 seconds to run 10.txt to instant, and from well over 40 minutes (before I killed it) to run 40.txt to 2 seconds. =D
Code:
Output:
Output on /largeinputs:
I'll take it.
1
u/shayhtfc Aug 14 '15
Solution in Ruby.
Pretty straight forward..
Returns 80020 for the big file
1
u/minikomi Aug 14 '15 edited Aug 14 '15
Racket (Scheme):
REPL testing challenge inputs:
REPL testing large input:
1
u/Contagion21 Aug 14 '15
C# (meat without input parsing to create an appropriate grid)
Outputs:
1
u/alexandr-nikitin Aug 14 '15
Here's my Scala solution:
1
u/XDtsFsoVZV Aug 15 '15
Python 3
Boy was this hard.
Challenge #1:
Challenge #2:
1
u/__dict__ Aug 16 '15 edited Aug 16 '15
Right, so I wasn't going for efficiency. Neither of these work on the 1000x1000 input but they get the correct answer for the smaller problems.
First, here's a complete Racket scheme solution:
It works by having a set of vertices to represent an "island" (component). Each time you see a vertex you merge all islands which it connected to (with set union). It's not very fast because, well, it does a lot of set union. It can do the easier problems.
Then I decided to try to do this in Prolog, for practice. First I modified my Racket script to convert the input into vertex predicates:
That above script generates a Prolog knowledge base based on the input given in the problem. This can be queried with:
So using
Will give you the answer of the number of components for the vertices knowledge base you have loaded.
1
u/gabyjunior 1 2 Aug 17 '15 edited Aug 17 '15
My cocktail for this one is good old C and union/find structure. Cheers!
Some output:
bonus1 is 1000x1000 10% filled bonus
bonus2 is 1000x1000 90% filled bonus
full is 2000x2000 100% filled own test
1
u/Rubisk Aug 17 '15
Used C++ and very wonky pointers for lots of pointer fun. Felt heckish, but maybe pointers are intended this way. Could someone verify my outputs:
And the code is here:
1
u/mpm_lc Aug 18 '15 edited Aug 18 '15
Ruby recursive solution. For simplicity I read the input from a text file with the ascii field border pre-padded.
1
u/ullerrm Aug 20 '15
C++
1
u/bradyzhou Aug 20 '15
Just a depth first search with a visited array.
O(nm) time (visits each node only once)
O(nm) space (an array of visited nodes)
1
u/linkazoid Aug 25 '15
Python.
1
u/aw_ambir Aug 26 '15
Java
1
u/stinkytofu415 Aug 30 '15
Python 3
1
u/zlli0520 Sep 05 '15
C++ BFS
1
u/gastropner Sep 11 '15 edited Sep 11 '15
Works great on input 1 and 2, as well as the challenges. When I try those large ones I get stack overflow from 70.txt and up (I understand that), but I also get some funky results on the others:
10.txt: 80020 (correct)
20.txt: 121858 (off by 3)
30.txt: 128118 (correct)
40.txt: 106124 (off by 9)
50.txt: 66011 (correct)
60.txt: 25513 (correct)
I cannot for the life of me figure out why. If I output the changed field to a file I can see that there are no x's left. Since some of them give stack overflows, I tried compiling with larger stacks, but the errors persisted. I made sure the changing of starti (which is there for performance enchancement) is not to blame; if I start from 0 every time it takes a shitload longer, but with the same results.
EDIT: The fault was in the initial scanf() trying to remove newline and eating some other whitespace as well. Hooray for C's I/O!
C:
1
u/[deleted] Sep 15 '15
I have a fairly simple semi-solution in Python 2.7.
Sadly this doesn't account for if the rows have a character length of more that asked for. would have to think about it with less wine.
I saved the inputs as .txt but mild modification needed if you wanted it to grab from Cephian's gist page or from a string.
1
u/[deleted] Sep 23 '15
Pretty simple solution in Go, not sure how I could simplify the actual file parsing.
1
u/l4adventure Sep 24 '15
[Ruby] DAYUM finally got it. I'm kind of a novice so this was very hard for me, and I solved it using a really weird convoluted method. Each "cell" in the grid is a Struct with attributes (coordinates, checked?, value (x or " ")). I do a recursive function only on coordinates that haven't been checked and all this modifies the class variable containing these structs. I dunno, I'm probably gonna look at another code with 1 line asnwer that works well, but w/e here it is:
for final challenge (the 8/11 one), output was:
1
u/maligenligen Oct 12 '15 edited Oct 12 '15
code in java
O(n) = xy, space = 2width
example of call:
1
u/[deleted] Aug 12 '15
...
0
u/[deleted] Aug 12 '15
[deleted] — view deleted comment