How to build, sort and print a tree of a sort?

Posted by Tuplanolla on Stack Overflow See other posts from Stack Overflow or by Tuplanolla
Published on 2010-03-18T09:57:17Z Indexed on 2010/03/18 10:11 UTC
Read the original article Hit count: 412

Filed under:
|
|

This is more of an algorithmic dilemma than a language-specific problem, but since I'm currently using Ruby I'll tag this as such. I've already spent over 20 hours on this and I would've never believed it if someone told me writing a LaTeX parser was a walk in the park in comparison.

I have a loop to read hierarchies (that are prefixed with \m) from different files

art.tex: \m{Art}
graphical.tex: \m{Art}{Graphical}
me.tex: \m{About}{Me}
music.tex: \m{Art}{Music}
notes.tex: \m{Art}{Music}{Sheet Music}
site.tex: \m{About}{Site}
something.tex: \m{Something}
whatever.tex: \m{Something}{That}{Does Not}{Matter}

and I need to sort them alphabetically and print them out as a tree

About
    Me (me.tex)
    Site (site.tex)
Art (art.tex)
    Graphical (graphical.tex)
    Music (music.tex)
        Sheet Music (notes.tex)
Something (something.tex)
    That
        Does Not
            Matter (whatever.tex)

in (X)HTML

<ul>
<li>About</li>
<ul>
<li><a href="me.tex">Me</a></li>
<li><a href="site.tex">Site</a></li>
</ul>
<li><a href="art.tex">Art</a></li>
<ul>
<li><a href="graphical.tex">Graphical</a></li>
<li><a href="music.tex">Music</a></li>
<ul>
<li><a href="notes.tex">Sheet Music</a></li>
</ul>
</ul>
<li><a href="something.tex">Something</a></li>
<ul>
<li>That</li>
<ul>
<li>Doesn't</li>
<ul>
<li><a href="whatever.tex">Matter</a></li>
</ul>
</ul>
</ul>
</ul>

using Ruby without Rails, which means that at least Array.sort and Dir.glob are available.

All of my attempts were formed like this (as this part should work just fine).

def fss_brace_array(ss_input)#a concise version of another function; converts {1}{2}...{n} into an array [1, 2, ..., n] or returns an empty array
    ss_output = ss_input[1].scan(%r{\{(.*?)\}})
rescue
    ss_output = []
ensure
    return ss_output
end
#define tree
s_handle = File.join(:content.to_s, "*")
Dir.glob("#{s_handle}.tex").each do |s_handle|
    File.open(s_handle, "r") do |f_handle|
        while s_line = f_handle.gets
            if s_all = s_line.match(%r{\\m\{(\{.*?\})+\}})
                s_all = s_all.to_a
                #do something with tree, fss_brace_array(s_all) and s_handle
                break
            end
        end
    end
end
#do something else with tree

© Stack Overflow or respective owner

Related posts about algorithm

Related posts about ruby