Implementing distance algorithm