distance algorithm