Many ways of solving problems
When I am working on programming problems, I tend to fixed to first way to solve that problem that I have on my mind. Sometimes that is ok, and often the easiest way to solve that problem for me. But most time it is not the best and not the only way to do that.
So today I will present three easy problems with three different solutions to show you that there is always a few ways to provide another solution.
1) First Problem: Double Char
Our goal in that exercise is to find a function that takes a string as an argument and return the new string in which it doubles every character.
Let's look at test cases
repeater("Hello") // => "HHeelllloo"
repeater("We've been doubled") // => "WWee''vvee bbeeeenn ddoouubblleedd"
The first way to solve that problem is splitting our input string to an array, and then map elements of that array by using repeat
function.
function repeater(string) {
return string.split("").map(function(char) {
return char.repeat(2);
}).join("");
}
repeater("Hello") // => "HHeelloo"
String.prototype.repeat
is a function that returns copies of string on which is called. These copies are equal to the integer number that was passed on as an argument.
After using repeat our string has elements with doubled string, so we join it to one string.
Another solution can be a solution that uses a for loop and Array.prototype.push
function.
function repeater(string) {
var stringArr = string.split("")
var result = [];
for (var i=0; i < stringArr.length; i++) {
result.push(stringArr[i] + stringArr[i])
}
return result.join("")
}
repeater("Hello") // => "HHeelloo"
Like in the first solution we split input string to an array of characters and then we iterate through that array and for each element we push doubled element to result
array. We return joined result array and we have the expected result.
Last way to solve this is a one-liner.
function repeater(string) {
return string.replace(/./g, "$&$&");
}
repeater("We've been doubled") // => "WWee''vvee bbeeeenn ddoouubblleedd"
When we working with arrays we have regular expressions to our disposal. So here we use String.protorype.replace
which takes a regular expression as a first argument, and as a second argument, it takes a string that replaces regexp specified as the first argument.
According to JavaScript docs $&
pattern inserts the matched substring so we get our expected result.
2) Second Problem: Counting Up
We had strings so let's take some numbers.
Our goal here is to write a function that takes an integer argument, and returns an Array of all integers, in sequence, between 1 and the argument with the assumption that our input is always a valid integer greater than 0.
sequence(5) // [1, 2, 3, 4, 5]
sequence(3) // [1, 2, 3]
As input, we have an integer and as output, we want to have an array. So we have to find ways to create a sequence of elements.
One way to do that is using a loop.
function sequence(integer) {
var i = 1;
var result = [];
while (i <= integer) {
result.push(i);
i++;
}
return result;
}
sequence(5) // [1, 2, 3, 4, 5]
This time we use a while loop. First we create a empty result array and then we set some variable with our iteration value. This variable should be equal to 1 because we want to return sequence from 1 to function input integer.
After that, we used Array.prototype.push
in a loop until iteration value is equal to function input. At the end, we return our result.
In next solution, at first, we create an Array with a proper number of empty elements.
function sequence(number) {
return Array(number).fill(1).map(function(v, i) {
return v + i
});
}
sequence(5) // [1, 2, 3, 4, 5]
To create the empty table we used Array(number)
it creates a number of elements equal to the number value. After that, we using Array.prototype.fill
function. We passed 1 as an input. fill
takes as first argument a value of array element, so we fill our array with 1 in order to map that elements by adding an iteration value to value of the element which is a 1 in our case. So after each iteration, we increment the value by 1.
The third solution can be done with strings.
function sequence(number) {
return "1".repeat(number).split("").map(function(_,i){
return ++i;
});
}
sequence(5) // [1, 2, 3, 4, 5]
That solution first takes random one character string that is repeat number times where the number is our input. Then that string is split by character to an array and then, every element of that array is mapped with the value of an incremented first number of iteration.
3) Third Problem: Name Swapping
In this task, we write a function that takes a first name, a space, and the last name passed as a single String argument, and returns a string that contains the last name, a comma, a space, and the first name.
swapName('Bill Gates') // 'Gates, Bill'
The first way to solve that is simple and with use of a method that we use earlier.
function swapName(string) {
var nameArr = string.split(" ");
return nameArr[1] + ", " + nameArr[0];
}
swapName('Bill Gates') // 'Gates, Bill'
This solution splits string to array of words and then simply return first second element of that string followed by comma followed by first element of splited string.
Second solution used Array.prototype.reverse
function.
function swapName(name) {
return name.split(' ').reverse().join(', ');
}
swapName('Bill Gates') // 'Gates, Bill'
As in the first example, we split the string to words. Because we know that we have only two elements in an array we can reverse it with reverse
function and then join array elements with comma and whitespace as the separator.
The last solution is similar to the first. In this case, we get our array with regular expression and String.protoype.match
function.
function swapName(string) {
var nameArr = string.match(/\w+/g);
return `${nameArr[1]}, ${nameArr[0]}`;
}
swapName('Bill Gates') // 'Gates, Bill'
match
function take a regular expresion as an argument and return an array containing the entire match result. After we received an array we return a string with swapped elemnts of that array like in first example.
To add variety to this example I use a template string a technology from ES6 Standard, which allows us to embedded expressions right into the string.
Summary
That was very simple problems with a very simple solutions, but I hope I show you that even simple problems can have few ways of solving. Often that are ways that can learn us something new.
Top comments (4)
For the name swapping regular expression one, you can make it shorter by using a replace method.
So we have another way :) Great job!
Great Article! It is important to evaluate and think about other ways to solve a problem. Quite often, the first solution is not the best or optimal. By thinking about the problem from another angle, we able to find out edge cases that do not get solved by the initial solution.
Thank you, Roman.
You definitely right, it's a great habit to first take time to understand a problem well.