Mobile Numeric Keypad Problem | Return count of all possible numbers of length n in a given numeric keyboard ; left , up , right , down move from current location ; Taking n + 1 for simplicity - count [ i ] [ j ] will store number count starting with digit i and length j ; count numbers starting with digit i and of lengths 0 and 1 ; Bottom up - Get number count of length 2 , 3 , 4 , ... , n ; Loop on keypad row ; Loop on keypad column ; Process for 0 to 9 digits ; Here we are counting the numbers starting with digit keypad [ i ] [ j ] and of length k keypad [ i ] [ j ] will become 1 st digit , and we need to look for ( k - 1 ) more digits ; Move left , up , right , down from current location and if new location is valid , then get number count of length ( k - 1 ) from that new digit and add in count we found so far ; Get count of all possible numbers of length " n " starting with digit 0 , 1 , 2 , ... , 9 ; Driver Code
function getCount ( keypad , n ) { if ( keypad == null n <= 0 ) return 0 ; if ( n == 1 ) return 10 ; let row = [ 0 , 0 , - 1 , 0 , 1 ] ; let col = [ 0 , - 1 , 0 , 1 , 0 ] ; let count = new Array ( 10 ) ; for ( let i = 0 ; i < 10 ; i ++ ) { count [ i ] = new Array ( n + 1 ) ; for ( let j = 0 ; j < n + 1 ; j ++ ) { count [ i ] [ j ] = 0 ; } } let i = 0 , j = 0 , k = 0 , move = 0 , ro = 0 , co = 0 , num = 0 ; let nextNum = 0 , totalCount = 0 ; for ( i = 0 ; i <= 9 ; i ++ ) { count [ i ] [ 0 ] = 0 ; count [ i ] [ 1 ] = 1 ; } for ( k = 2 ; k <= n ; k ++ ) { for ( i = 0 ; i < 4 ; i ++ ) { for ( j = 0 ; j < 3 ; j ++ ) { if ( keypad [ i ] [ j ] != ' ' && keypad [ i ] [ j ] != ' ' ) { num = keypad [ i ] [ j ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; count [ num ] [ k ] = 0 ; for ( move = 0 ; move < 5 ; move ++ ) { ro = i + row [ move ] ; co = j + col [ move ] ; if ( ro >= 0 && ro <= 3 && co >= 0 && co <= 2 && keypad [ ro ] [ co ] != ' ' && keypad [ ro ] [ co ] != ' ' ) { nextNum = keypad [ ro ] [ co ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; count [ num ] [ k ] += count [ nextNum ] [ k - 1 ] ; } } } } } } totalCount = 0 ; for ( i = 0 ; i <= 9 ; i ++ ) totalCount += count [ i ] [ n ] ; return totalCount ; } let keypad = [ [ ' ' , ' ' , ' ' ] , [ ' ' , ' ' , ' ' ] , [ ' ' , ' ' , ' ' ] , [ ' ' , ' ' , ' ' ] ] ; document . write ( " " + 1 + " " + getCount ( keypad , 1 ) + " " ) document . write ( " " + 2 + " " + getCount ( keypad , 2 ) + " " ) document . write ( " " + 3 + " " + getCount ( keypad , 3 ) + " " ) document . write ( " " + 4 + " " + getCount ( keypad , 4 ) + " " ) document . write ( " " + 5 + " " + getCount ( keypad , 5 ) + " " )