Average value of set bit count in given Binary string after performing all possible choices of K operations | C ++ program for the above approach ; Function to calculate the average number of Set bits after after given operations ; Stores the average number of set bits after current operation ; Stores the average number of set bits after current operation ; Iterate through the array arr [ ] and update the values of p and q ; Store the value of p and q of the previous state before their updation ; Update average number of set bits after performing the ith operation ; Update average number of off bits after performing the ith operation ; Return Answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double averageSetBits ( int N , int K , int arr [ ] ) { double p = N ; double q = 0 ; for ( int i = 0 ; i < K ; i ++ ) { double _p = p , _q = q ; p = _p - _p * arr [ i ] / N + _q * arr [ i ] / N ; q = _q - _q * arr [ i ] / N + _p * arr [ i ] / N ; } return p ; } int main ( ) { int N = 5 ; int arr [ ] = { 1 , 2 , 3 } ; int K = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << setprecision ( 10 ) << averageSetBits ( N , K , arr ) ; return 0 ; }