Reduce Hamming distance by swapping two characters | Javascript code to decrease hamming distance using swap . ; Function to return the swapped indexes to get minimum hamming distance . ; Find the initial hamming distance ; Case - I : To decrease distance by two ; ASCII values of present character . ; If two same letters appear in different positions print their indexes ; Store the index of letters which is in wrong position ; Case : II ; If misplaced letter is found , print its original index and its new index ; Store the index of letters in wrong position ; Case - III ; Driver code
let MAX = 26 ; function Swap ( s , t , n ) { let dp = new Array ( MAX ) ; for ( let i = 0 ; i < MAX ; i ++ ) { dp [ i ] = new Array ( MAX ) ; for ( let j = 0 ; j < MAX ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } let tot = 0 ; for ( let i = 0 ; i < n ; i ++ ) if ( s [ i ] != t [ i ] ) tot ++ ; for ( let i = 0 ; i < n ; i ++ ) { let a = s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; let b = t [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; if ( a == b ) continue ; if ( dp [ a ] [ b ] != - 1 ) { document . write ( i + 1 + " " + ( dp [ a ] [ b ] + 1 ) + " " ) ; return ; } dp [ b ] [ a ] = i ; } let A = new Array ( MAX ) , B = new Array ( MAX ) ; for ( let i = 0 ; i < MAX ; i ++ ) { A [ i ] = - 1 ; B [ i ] = - 1 ; } for ( let i = 0 ; i < n ; i ++ ) { let a = s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; let b = t [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; if ( a == b ) continue ; if ( A [ b ] != - 1 ) { document . write ( i + 1 + " " + ( A [ b ] + 1 ) + " " ) ; return ; } if ( B [ a ] != - 1 ) { document . write ( i + 1 + " " + ( B [ a ] + 1 ) + " " ) ; return ; } A [ a ] = i ; B [ b ] = i ; } document . write ( - 1 ) ; } let S = " " ; let T = " " ; let n = S . length ; if ( S == " " T == " " ) document . write ( " " ) ; else Swap ( S , T , n ) ;