Encrypt the given string with the following operations | Javascript implementation of the above approach : ; Function to return the encrypted string ; Reduce x because rotation of length 26 is unnecessary ; Calculate the frequency of characters ; If the frequency of current character is even then increment it by x ; Else decrement it by x ; Return the count ; Driver code
var MAX = 26 ; function encryptStr ( str , n , x ) { x = x % MAX ; var freq = Array ( MAX ) . fill ( 0 ) ; for ( var i = 0 ; i < n ; i ++ ) { freq [ str [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; } for ( var i = 0 ; i < n ; i ++ ) { if ( freq [ str [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] % 2 == 0 ) { var pos = ( str [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) + x ) % MAX ; str [ i ] = String . fromCharCode ( pos + ' ' . charCodeAt ( 0 ) ) ; } else { var pos = ( str [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) - x ) ; if ( pos < 0 ) { pos += MAX ; } str [ i ] = String . fromCharCode ( pos + ' ' . charCodeAt ( 0 ) ) ; } } return str . join ( ' ' ) ; } var s = " " ; var n = s . length ; var x = 3 ; document . write ( encryptStr ( s . split ( ' ' ) , n , x ) ) ;