Convert graph relation from array to hash


Question
Suppose you have below graph, it is bidirectional graph.

graph of question

So you can create an array to depict relationship of nodes in graph, let say array is “a”, with values below:

a[0]=1; a[1]=2; a[2]=1; a[3]=1; a[4]=3; a[5]=3

and you are supposed to convert graph relation into hash. So the expected hash is given below

expected_hash = {0 => [1], 1 => [0,2,3], 2=>[1], 3 => [1,4,5], 4=> [3], 5=> [3]}

Solution


a=[]; h={}
a[0]=1; a[1]=2; a[2]=1; a[3]=1; a[4]=3; a[5]=3
a.each_with_index do |v, i|
 h[i].nil? ? h[i] = [v] : ( h[i] << v unless h[i].include?(v))
 h[v].nil? ?  h[v] = [i] : (h[v] << i  unless h[v].include?(i)) 
end

Answer:

 h = {0=>[1], 1=>[0, 2, 3], 2=>[1], 3=>[1, 4, 5], 4=>[3], 5=>[3]}
Advertisements

I am Senior Software Engineer. I love reading, writing, sharing,developing, hiking, movies, trips, mountains, brooks, hills etc.

Tagged with: ,
Posted in Algorithm, Interview questions, Ruby

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

StackOverFlow
Categories
Archives
%d bloggers like this: