Updated distance algorithm