DEV Community

Discussion on: Daily Challenge #6 - Grandma and her friends

Collapse
 
spaciecat profile image
Spacie • Edited

I'm making the following assumptions, but I think I have a solution:

  • Town X1 is 1 mile from X0, X2 is 2 miles from X0, etc... (otherwise I don't believe there is enough information to come up with a solution)
  • friendTownList uses format C (flattened list)
  • the return trip from the last friend's house back to X0 is included in the total

Could be one (ugly) line if not counting error handling in the case where we don't know where a friend lives, could also be smaller if friendTownList was a hash to start with~

def getDistance(visitOrder, friendTownList)
  townHash = Hash[*friendTownList]
  visitOrder.each {|f| raise "IDK where #{f} lives!" if !townHash.key? f }
  [0, *visitOrder.map(&proc {|f| townHash[f][1 .. -1].to_i }), 0]
    .each_cons(2)
    .map(&proc {|a, b| (a - b).abs })
    .sum
end

getDistance(%w(A2 A1 A3), %w(A1 X1 A2 X2 A3 X3))
# -> 8
# Because (0, 2[2], 1[1], 3[2], 0[3]) -> 2 + 1 + 2 + 3 = 8

I'll update / post another solution if the question is updated with more information!

Collapse
 
coreyja profile image
Corey Alexander

Wow! Love that we are all over here just complaining about not having enough data and you just went for it!

Love it! Keep up the awesome work on these challenges!