从红宝石中的数字数组生成图形路径 [英] Generating graph path from an array with numbers in ruby

查看:72
本文介绍了从红宝石中的数字数组生成图形路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含12个节点的无向​​图.在这种方法中:

I have an undirected graph with 12 nodes. In this method:

def generate_paths
  arr = []
  (1..10).each { arr << [rand(12)].product([rand(12)]) }
  arr
end

我生成一个像这样的数组:arr = [[3, 12], [8, 12], [0, 3], [0, 5], [0, 10], [7, 9], [5, 5], [4, 9], [5, 12], [0, 1]],它代表图形的边缘.

I generate an array like this: arr = [[3, 12], [8, 12], [0, 3], [0, 5], [0, 10], [7, 9], [5, 5], [4, 9], [5, 12], [0, 1]] which represents the graph edges.

我想在图中找到最长的路径,例如每个边最多使用一次.对于给定的示例,它类似于:arr = [[1, 0], [0, 5], [5, 5], [5, 12], [12, 3], [3, 0], [0, 10]]

I would like to find the longest possible path through the graph, such as each edge is used at most once. For given example it would be something like: arr = [[1, 0], [0, 5], [5, 5], [5, 12], [12, 3], [3, 0], [0, 10]]

我通过搜索Euler路径但使用其他编程语言编写的方法在许多来源上看到了解决该问题的方法.我将如何在Ruby中进行处理?

I have seen on a number of sources solutions to this problem by searching the Euler path but written in other programming languages​​. How would I proceed with it in Ruby?

推荐答案

目前尚不清楚目标是什么.

It's unclear at the moment what the goal is.

我猜您正在尝试获取包含随机数的数组的数组,其中任何给定数组的第二个数字等于下一个数组的第一个数字.

I'm going to guess that you're trying to get an array of arrays containing random numbers where the second number of any given array is equal to the first number of the next array.

如果是这种情况,那么您可以使用each_cons轻松实现这一目标,each_cons是每个连续的"的缩写,并采用n的自变量(即项数).

If that's the case, then you can achieve this easily, using each_cons, which is short for "each consecutive" and takes an argument of n (i.e. number of items).

random_numbers = 8.times.map { rand(12) }
# => [1, 0, 5, 5, 12, 3, 0, 10]


random_numbers.each_cons(2).to_a
# => [[1, 0], [0, 5], [5, 5], [5, 12], [12, 3], [3, 0], [0, 10]]

这篇关于从红宝石中的数字数组生成图形路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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