Here’s the scenario, you are given a string s
that contains a sentence and your task is to write a word reversal function to reverse the order of all words that are longer than n
characters.
Example:
Then the result should be “The kciuq nworb fox”
I always advocate for trying the direct approach before you start doing weird optimizations. So How could we approach this manually? Well first we’d need to split the words, then check each word and reverse it if it is longer than n:
const reverseWord(s,n) => {
const words = s.split(" ")
const reversedArray = words.map(word => {
if (word.length > n){
return word.split("").reverse().join(")
}
return word
})
return reversedArray.join(" ")
}
Code language: JavaScript (javascript)
Great, this accomplishes our goal. So if you’re in an interview, I’d advise starting with this because in an interview your time is limited and it’s much better to submit something that works rather than spend all your time trying and potentially failing to do the best approach.
But, just for fun, let’s see if we can get a better approach.
The first question we need to ask ourselves is what do we know about the problem? We know;
s
whose length is greater than n
This would seem to suggest looping through each word right? Not necessarily. What if we could just get the words that matched our requirements? If only there was some technology that could do that search for us that… oh wait, we do… regex. And even better we have a built-in function that accepts it and replaces the found words. So we can easily solve the same problem as follows
const reverseWord = (s, n) => {
const re = new RegExp(`\\w{${n},}`,"g");
return s.replace(re, word => {
return word.split("").reverse().join("")
})
}
Code language: JavaScript (javascript)
Way smaller right? But there is an argument to be made about whether it’s more or less readable. I know regex isn’t everyone’s favorite technology so it’s up to you.
Fun fact, there is a bug in the code. Can you spot it? I was going to fix it but I thought it would make a nice easter egg. So if you find it, let me know on Twitter, @phoexer.
Till next time, happy coding.
Today I am working on a summation problem made to look like building a tower out of cubic bricks. It’s fun to brute force sometimes.
Coming back to Rust code after a bit of a hiatus with a simple problem… The Two-sum problem. Finding numbers in an array. Yay, fun.
King Pinn: I Salute You. I’m driving halfway across the country and this song is on repeat. Rest in Peace Tonderai Makoni. You were awesome.
After a few weeks off I’m back to business. This is just an update post detailing plans for the rest of the year.
At last we finally have the great reveal, our mystery project was implementing RSA encryption in rust.