arrays - Ruby - Graph adjacency matrix into variable -


i trying edit algorithm found here.

i want adjacency matrix loaded file (formatting of file doesn't matter me, can either [0,1,1,0] or 0110) g = file.read().split("\n")

however, error no implicit conversion of fixnum string (typeerror) , know need convert string ints, how not lose formatting required dfs method?

i guess it's pretty easy, i'm begginer in ruby (and graphs :v) , can't work...

edit: code i'm using read file array of arrays is:

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

and result file (for example)

01101010 01010101 01010110 10101011 01011111 

is this:

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

what need, however, is:

=> [[[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]]] 

so work algorithm mentioned in first line of post (i'll copy here, if takes place can delete , leave link only):

g = [0,1,1,0,0,1,1], # [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) 

split's default separator whitespace. make split every char need explicitly it:

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

you can use chars same job:

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

i don't know how read_array used, can simplified to:

def read_array(file_path)   file.foreach(file_path).map |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]] 

if still [, can either take first item:

my_array[0] 

or (if there more 1 item uber-array) - use 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| } # => [[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]] 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -