much more efficient way of calculating rank