Distributed Averaging Dynamics And Optimization Over Random Networks