An algorithm is simply a set of specific instructions used to solve a problem or accomplish a specific task.
Here are the steps on how to algorithmically solve a problem using programming:
Step 1: Describe the objective in your own words
Take time to read the problem and describe it in your own words. Particularly, pay attention to the problem’s inputs and outputs. If test cases are given, check each one and apply your understanding of the problem to them to determine what the answer is, then check if your answer matches the final answer (No code needed). If you’re answer doesn’t match, you need to spend more time understanding the problem.
Step 2: Write your own test cases
You don’t need to write entire test code. Simply identify the inputs your code should handle and the outputs it should return, then quickly check your work once you’ve written the solution by console logging the result of calling your solution method and comparing it to the answer you expected.
Step 3: Pseudocode
This is just a plain english description of how you would solve a problem in programming. For example, the pseudocode for copying only numbers from one array to another might look like this:
initialize empty array called result
iterate over each item in the input array:
if element is a number:
push item onto result
return result
Step 4: Code
Use your pseudocode as a map to now code your solution.
Step 5: Make it clean and readable
Refactor your code to make it readable by using well named variables and comments where code might not be easily understood. Convert blocks of code to functions and remove any unneeded or redundant code. Here are some things to look for when writing clean code:
Is it easy to read?
- Use indentation correctly
- Use meaningful variable names
- Add comments when your code needs explanation
- Don’t cram everything into one line of code
Does it follow the single responsibility principle?
- Keep functions focused on one specific task
- Create helper functions when needed
Does it have unnecessary lines?
- Review your code for redundant unnecessary lines.
- Avoid unnecessary comments. Use well-named variables and helper functions than adding a comment to every line of code. Good code is its own best documentation.
Is it DRY (Don’t Repeat Yourself)?
- Avoid repeating yourself by writing functions, classes and utilising global and environment variables where appropriate.
Don’t forget to test your code again.
Step 6: Optimize
How long does your code take to run? How much memory does it use? Think about how to optimize your code to use less time and less memory (time and space complexity).