Can't show the input value result as distance

Hi,
This is Lalarukh, I’m seeking community experts help.
Actually I want to show the distance between two entities that is getting as input from User. I’m taking them as simple code. Just want to get the two inputs which are working perfectly and then verify that input value from user is sun & mercury, after verification it should show the distance value as output.
There’s no thing like to sum the distance just want to check the input value & assign the distance between entities.
Here’s the code:

 def main() do
    IO.puts "Find the distance: "
    entity1 = IO.gets "Enter First Entity Name: "
    entity2 = IO.gets "Enter Second Entity Name: "
    if [entity1, entity2] = {"sun", "mercury"} do
      distance = "57909227";
    end
    IO.puts "Difference between #{String.trim(entity1)} & #{String.trim(entity2)} is: #{String.trim(distance)}km"
  end

Sun & Mercury distance is one of example. I want to show the distance of more entities like EARTH & MOON or Sun & Neptune.

Thanks

You could do something like this:

  def main do
    IO.puts("Find the distance: ")
    entity1 = IO.gets("Enter First Entity Name: ") |> String.trim("\n")
    entity2 = IO.gets("Enter Second Entity Name: ") |> String.trim("\n")

    distance = distance(entity1, entity2)

    IO.puts("Difference between #{entity1} & #{entity2} is: #{distance}km")
  end

  defp distance("sun", "mercury"), do: "57909227"
  defp distance("mercury", "sun"), do: "57909227"

You can keep on adding to the private distance/2 function to add more support. and then later on generate logic for the sun → mercury, mercury → sun duplications

2 Likes

Which part is difficult for you? Seems you have it mostly figured out.

Looking at your code, maybe you’re struggling to do pattern matching, maybe?

1 Like

Hey @tomkonidas,
Thanks a lot. It worked the way I wanted It too :heart_eyes:
You helped me out, Thanks again.