The fun thing about learning how to code is that you come to realize that there are many solutions to any challenge you are presented with.
Sometimes it can even get a little overwhelming but as you learn more, and know when to implement each solution, you will find that having many options is a very good thing indeed!
Let me give you a simple example:
You have been challenged to create a program, which lets you know whether an array of numbers that are not sorted in any order and are meant to be unique, has a duplicate hiding in its ranks.
Let's try option 1: Brute force.
The basic idea behind ‘brute forcing’ is you are trying to solve the problem no matter the cost. In other words, without taking into consideration run time or memory.
public boolean containsDuplicate(int[] nums) {
for (int a = 0; a < nums.length; a++ ) {
for (int b = a+1; b < nums.length; b++ ) {
if (nums[a] == nums[b]){
return true;
}
}
}
return false;
}
Here we are creating a method, which accepts an array, and loops through it, comparing the first number to the rest, then the second number, etc.
This will solve the problem but is not considered the most ‘ideal’ approach, seeing as it is creating a loop within a loop, which is not as fast as other methods.
Option number 2: Sort method
Although it is nice to be able to solve an issue from scratch, when the goal is efficiency, we definitely want to use all the tools we can to speed up the process and make it less complicated. It is a good thing that Java has many built-in functions, that allow you to simplify the solution. So let’s try solving the problem using the Sort method.
import java.util.Arrays;
public static boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length-1; i++) {
if(nums[i] == nums[i+1]) {
return true;
}
}
return false;
}
The sort method sorts the array so that it is now organized by size, which means that if there is a duplicate, they will be next to each other in the array. The reason this method is faster than the previous one is that instead of comparing each number to the entire array, you can now compare each number to the following number in the array, which requires only one loop.
Note that not all built-in functions are available automatically, and that is why in the first line I had to import the function which would allow me to sort arrays.
Conclusion:
I showed two simple ways to solve the same problem. There are many many more, and this is almost always the case.
Personally, I love the idea that different people would tackle the same challenge using different methods or even programming languages. It's what keeps developers on their toes, and shows us that there is almost always another way.