Distributed averaging and optimization over random networks