Convert a number to another by dividing by its factor or removing first occurrence of a digit from an array | Function to check if a digit x is present in the number N or not ; Convert N to string ; Traverse the string num ; Return first occurrence of the digit x ; Function to remove the character at a given index from the number ; Convert N to string ; Store the resultant string ; Traverse the string num ; If the number becomes empty after deletion , then return - 1 ; Return the number ; Function to check if A can be reduced to B by performing the operations any number of times ; Create a queue ; Push A into the queue ; Hashmap to check if the element is present in the Queue or not ; Set A as visited ; Iterate while the queue is not empty ; Store the front value of the queue and pop it from it ; If top is equal to B , then return true ; Traverse the array , D [ ] ; Divide top by D [ i ] if it is possible and push the result in q ; If D [ i ] is present at the top ; Remove the first occurrence of D [ i ] from the top and store the new number ; Push newElement into the queue q ; Return false if A can not be reduced to B ; Driver code Given inputs
function isPresent ( n , x ) { let num = ( n ) . toString ( ) ; for ( let i = 0 ; i < num . length ; i ++ ) { if ( ( num [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) == x ) return i ; } return - 1 ; } function removeDigit ( n , index ) { let num = ( n ) . toString ( ) ; let ans = " " ; for ( let i = 0 ; i < num . length ; i ++ ) { if ( i != index ) ans += num [ i ] ; } if ( ans == " " || ( ans . length == 1 && ans [ 0 ] == ' ' ) ) return - 1 ; let x = parseInt ( ans ) ; return x ; } function reduceNtoX ( a , b , d , n ) { let q = [ ] ; q . push ( a ) ; let visited = new Map ( ) ; visited . set ( a , true ) ; while ( q . length != 0 ) { let top = q . shift ( ) ; if ( top < 0 ) continue ; if ( top == b ) return true ; for ( let i = 0 ; i < n ; i ++ ) { if ( ! visited . has ( top / d [ i ] ) ) visited . set ( top / d [ i ] , false ) ; if ( d [ i ] != 0 && top % d [ i ] == 0 && ! visited . get ( top / d [ i ] ) ) { q . push ( top / d [ i ] ) ; visited . set ( top / d [ i ] , true ) ; } let index = isPresent ( top , d [ i ] ) ; if ( index != - 1 ) { let newElement = removeDigit ( top , index ) ; if ( ! visited . has ( newElement ) ) visited . set ( newElement , false ) ; if ( newElement != - 1 && ( ! visited . get ( newElement ) ) ) { q . push ( newElement ) ; visited . set ( newElement , true ) ; } } } } return false ; } let A = 5643 , B = 81 ; let D = [ 3 , 8 , 1 ] ; let N = D . length ; if ( reduceNtoX ( A , B , D , N ) ) document . write ( " " ) ; else document . write ( " " ) ;