Minimum replacements such that the difference between the index of the same characters is divisible by 3 | JavaScript program to find minimum replacements such that the difference between the index of the same characters is divisible by 3 Function to count the number of minimal replacements ; Max Integer Value ; Generate all permutations ; Count the replacements ; Return the replacements ; Driver Code
function countMinimalReplacements ( s ) { var n = s . length ; var mini = 2147483647 ; var dup = " " . split ( " " ) ; do { var dif = 0 ; for ( var i = 0 ; i < n ; i ++ ) { if ( s [ i ] !== dup [ i % 3 ] ) { dif ++ ; } } mini = Math . min ( mini , dif ) ; } while ( next_permutation ( dup ) ) ; return mini ; } function next_permutation ( p ) { for ( var a = p . length - 2 ; a >= 0 ; -- a ) { if ( p [ a ] < p [ a + 1 ] ) { for ( var b = p . length - 1 ; ; -- b ) { if ( p [ b ] > p [ a ] ) { var t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; for ( ++ a , b = p . length - 1 ; a < b ; ++ a , -- b ) { t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; } return true ; } } } } return false ; } var s = " " ; document . write ( countMinimalReplacements ( s ) ) ;