Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

ruby - What are recursive arrays good for?

Ruby supports recursive arrays (that is, self-containing arrays):

a = []
# => [] 
a << a
# => [[...]] 
a.first == a
# => true 

This is intrinsically cool, but what work can you do with it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A directed graph with undifferentiated edges could have each vertex represented simply as an array of the the vertices reachable from that vertex. If the graph had cycles, you would have a 'recursive array', especially if an edge could lead back to the same vertex.

For example, this graph:
directed cyclic graph
...could be represented in code as:

nodes = { a:[], b:[], c:[], d:[] }
nodes[:a] << nodes[:a]
nodes[:a] << nodes[:b]
nodes[:b] << nodes[:a]
nodes[:b] << nodes[:c]
p nodes
#=> {:a=>[[[...], []], [...]], :b=>[[[...], [...]], []], :c=>[], :d=>[]}

Usually the representation of each vertex would be more 'robust' (e.g. a class instance with properties for the name and array of outgoing edges), but it's not impossible to imagine a case where you wanted a very lightweight representation of your data (for very large graphs) and so needed to use a minimal representation like this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...