Minimal operations to make a number magical | CPP program to make a number magical ; function to calculate the minimal changes ; maximum digits that can be changed ; nested loops to generate all 6 digit numbers ; counter to count the number of change required ; if first digit is equal ; if 2 nd digit is equal ; if 3 rd digit is equal ; if 4 th digit is equal ; if 5 th digit is equal ; if 6 th digit is equal ; checks if less then the previous calculate changes ; returns the answer ; driver program to test the above function ; number stored in string ; prints the minimum operations
#include " bits / stdc + + . h " NEW_LINE using namespace std ; int calculate ( string s ) { int ans = 6 ; for ( int i = 0 ; i < 10 ; ++ i ) { for ( int j = 0 ; j < 10 ; ++ j ) { for ( int k = 0 ; k < 10 ; ++ k ) { for ( int l = 0 ; l < 10 ; ++ l ) { for ( int m = 0 ; m < 10 ; ++ m ) { for ( int n = 0 ; n < 10 ; ++ n ) { if ( i + j + k == l + m + n ) { int c = 0 ; if ( i != s [ 0 ] - '0' ) c ++ ; if ( j != s [ 1 ] - '0' ) c ++ ; if ( k != s [ 2 ] - '0' ) c ++ ; if ( l != s [ 3 ] - '0' ) c ++ ; if ( m != s [ 4 ] - '0' ) c ++ ; if ( n != s [ 5 ] - '0' ) c ++ ; if ( c < ans ) ans = c ; } } } } } } } return ans ; } int main ( ) { string s = "123456" ; cout << calculate ( s ) ; }