wrote a sampling function to replace double loop