language-agnosticgraphcode-golfrosetta-stone

CodeGolf: Find the Unique Paths


Here's a pretty simple idea, in this pastebin I've posted some pair of numbers. These represent Nodes of a directed graph. The input to stdin will be of the form, (they'll be numbers, i'll be using an example here)

c d
q r
a b
b c
d e
p q

so x y means x is connected to y (not viceversa)

There are 2 paths in that example. a->b->c->d->e and p->q->r.

You need to print all the unique paths from that graph The output should be of the format

a->b->c->d->e
p->q->r

Notes

  1. You can assume the numbers are chosen such that one path doesn't intersect the other (one node belongs to one path)
  2. The pairs are in random order.
  3. They are more than 1 paths, they can be of different lengths.
  4. All numbers are less than 1000.

If you need more details, please leave a comment. I'll amend as required.

Shameless-Plug

For those who enjoy Codegolf, please Commit at Area51 for its very own site:) (for those who don't enjoy it, please support it as well, so we'll stay out of your way...)


Solution

  • Ruby — 132 125 87

    h=Hash[a=[*$<].map(&:split)]
    1000.times{a.map!{|i|i+[h[i[-1]]]-[nil]}}
    puts a.sort_by{|i|-i.size}.uniq(&:last).map{|i|i*'->'}
    

    Took Nas Banov's idea of h.keys-h.values:

    h=Hash[[*$<].map &:split]
    puts (h.keys-h.values).map{|i|s=i
    s+='->'+i=h[i]while h[i];s}