Refactors the distance metrics for readability and memory efficiency