递归数组有什么用? [英] What are recursive arrays good for?

查看:25
本文介绍了递归数组有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 支持递归数组(即自包含数组):

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?

推荐答案

A 有向图 with未区分的边可以将每个顶点简单地表示为从该顶点可到达的顶点数组.如果图形有循环,你就会有一个递归数组",特别是如果一条边可以回到同一个顶点.

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:

...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.

这篇关于递归数组有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆