find closest piece algorithm