code for finding the right weights