Ruby - 将图形邻接矩阵转换为变量

时间:2014-06-02 18:13:04

标签: ruby arrays string algorithm

我正在尝试编辑找到here的算法。

我希望从文件加载邻接矩阵(文件的格式对我来说无关紧要,它可以像[0,1,1,0]一样,或只是0110G = file.read().split("\n")

然而,我收到错误no implicit conversion of Fixnum into String (TypeError) 我已经知道我需要将此字符串转换为整数,但如何正确地执行此操作以避免丢失此DFS方法所需的格式?

我想这很简单,但我是Ruby(和图表:v)中的一个初学者,并且无法让它工作......

编辑: 所以我用来从文件读取到数组数组的代码是:

def read_array(file_path)
  File.foreach(file_path).with_object([]) do |line, result|
    result << line.split.map(&:to_i)
  end
end

我从文件中获得的结果(例如)

01101010
01010101
01010110
10101011
01011111

就是这样:

=> [[[1101010], [1010101], [1010110], [10101011], [1011111]]]

然而,我需要的是:

=> [[[1,1,0,1,0,1,0], [1,0,1,0,1,0,1], [1,0,1,0,1,1,0], [1,0,1,0,1,0,1,1], [1,0,1,1,1,1,1]]]

这样它就可以使用我帖子第一行中提到的算法(我会在这里复制它,如果它需要太多的地方我可以删除它并只保留链接):

G = [0,1,1,0,0,1,1], # A
[1,0,0,0,0,0,0],
[1,0,0,0,0,0,0],
[0,0,0,0,1,1,0],
[0,0,0,1,0,1,1],
[1,0,0,1,1,0,0],
[1,0,0,0,1,0,0] # G

LABLES = %w(A B C D E F G)

def dfs(vertex)

  print "#{LABLES[vertex]} " # visited

  edge = 0
  while edge < G.size
    G[vertex][edge] = 0
    edge += 1
  end

  edge = 0
  while edge < G.size
    if ( G[edge][vertex] != 0 && edge != vertex)
      dfs(edge)
    end
    edge += 1
  end
end

dfs(0)

1 个答案:

答案 0 :(得分:0)

split的默认分隔符是一个空格。为了让它分割出你需要明确说出的每个字符:

'01101101'.split.map(&:to_i)
# => [ 1101101 ]
'01101101'.split('').map(&:to_i)
# => [ 0, 1, 1, 0, 1, 1, 0, 1 ]

您也可以使用chars执行相同的工作:

'01101101'.chars.map(&:to_i)
# => [ 0, 1, 1, 0, 1, 1, 0, 1 ]

我不知道您的read_array是如何使用的,但可以简化为:

def read_array(file_path)
  File.foreach(file_path).map do |line|
    line.chomp.chars.map(&:to_i)
  end
end

read_array('my_file.txt')
# => [[1, 1, 0, 1, 0, 1, 0], [1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 1, 0], [1, 0, 1, 0, 1, 0, 1, 1], [1, 0, 1, 1, 1, 1, 1]]

如果您仍然获得额外的[,则可以只选择第一项:

my_array[0]

或者(如果超级数组有多个项目) - 使用flat_map

uber_array = [[[1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 1, 0], [1, 0, 1, 0, 1, 0, 1, 1]],
             [[1, 0, 1, 0, 1, 0, 1, 1], [1, 0, 1, 1, 1, 1, 1]]]

uber_array.flat_map { |a| a }
# => [[1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 1, 0], [1, 0, 1, 0, 1, 0, 1, 1], [1, 0, 1, 0, 1, 0, 1, 1], [1, 0, 1, 1, 1, 1, 1]]
相关问题