This is continuation of my functional programming experiments in JavaScript. This problem is from HackerRank.
The problem
Input is a string and we have to find out whether the letters of word 'hackerrank' are present inside it in the right order. When we say order, there might be some other letters in between the letters of 'hackerrank' the the order should be maintained. More details can be found in the actual problem link.
Traditional solution
If the guy is not from the computer science background, there is 99% chance that the solution will be based on loops where a lot of states might have stored temporarily. But it looks like a familiar situation of email validation where we are expecting chaaracters in specific order.
The RegExp way
Regular expressions are great. There is no doubt on that. Here goes the regular expression way.function checkForhackerrank(input) { if(testForhackerrank(input)) { return 'YES'; } else return 'NO'; } function testForhackerrank(input){ return /h(.)*a(.)*c(.)*k(.)*e(.)*r(.)*r(.)*a(.)*n(.)*k/g.test(input) }
Works great for the word hackerrank. Lets generalize
Generalized version
Below goes the generalized version which can work for any pattern other than 'hackerrank'.function testForhackerrank(input){ return getFindPattern('hackerrank').test(input); } function getFindPattern(stringToSearch) { return getGlobalRegExp(stringToSearch.split('').map(a=> `(.)*${a}`).join('')); } function getGlobalRegExp(pattern){ return new RegExp(pattern,'g'); }
This doesn't need anything special regarding functional paradigm as the magic is done by regular expression. Plnkr is here.
Enjoy coding.
No comments:
Post a Comment