How to write an algorithm for your coding problems

How to write an algorithm for your coding problems

A simple framework for turning problems into code

Since i started coding i've approached problem solving in a rather disorganized way. I'd simply open vscode and start looking at my file willing the solution to appear

2 hours later i have a messy file, my hair in my hands and me wondering where i forgot to add a semicolon (amongst other worthier bugs that i generate)

Chances are, you've experienced this too

So it wasn't until i picked up this book by Brain Hogan; Excercises for Programmers that i learnt how to solve coding problems properly by writing algorithms

In this article, you'll learn how to create algorithms for your projects to enable you write cleaner, less buggy and maintanable code

Now for the uninitiated...

What is an Algorithm?

An algorithm is a step-by-step set of operations that need to be performed to solve programming problems. If you take an algorithm and write code to perform those operations, you end up with a computer program.

Simply put an algorithm is an outline for listing all the steps a program will take to solve a problem

Just like architects draw up housing blueprints, an algorithm is used to guide you while you code

Screenshot 2022-10-11 114451 1.png

Now you might be wondering why you need to write out what your program should do instead of just coding it directly

Why you should write an algorithm

If you're surprised when you read what i'm about to say, know that i was practically bouncing on my seat when i read it

Now why you should write an algorithm? Simple, separation of concerns. It is during the process of writing the program that you do the actual problem solving, not while coding.

I was shocked when i realized this but it makes a lot of sense. Writing an algorithm helps you focus on the logical meat of the problem (instead of finding a semicolon like you're Nemo's Dad)

Also, an algorithm is language-agnostic (fancy fancy for it doesn't rely on any programming language) so you can take an attempt at a problem on a scrap of paper and show other developers for some feedback and they will understand it

When you actually get down to code, you'll feel more relaxed because you have done the hard work of solving the problem with an algorithm and you can just turn it into code in your preferred language

Now...

How to write an algorithm

Just like there are many ways to solve a problem, there are many ways to write an algorithm. But the method outlined in the book i mentioned at the beginning is the most bullet-proof i've found

1. Craft a problem statement

Quoting Brian the author,

To understand a problem, You need to figure out what features a program will have by coming up with a few questions to get a clearer picture of what the client wants. Once you have the answers to your questions, try writing out a problem statement that explains exactly what you’re building.

For example, let's say i ask you to build a tip calculator. Judging by the lack of details you might ask me questions like:

  • What formula do you want to use?
  • What is the tip percentage?
  • What should the program display on the screen when it starts?

After getting your answers, you can write out a problem statement for the tip calculator like so:

Create a simple tip calculator. The program should prompt for a bill amount and a tip rate. The program must compute the tip and then display both the tip and the total amount of the bill.

If you're dealing with a large program don't worry, these programs can be broken down into smaller ones that are easier to manage and solve for

Once you've got your problem statement down, let’s take this tip calculator example and go through a simple process that will help you understand what you’re supposed to build

2. Discover Inputs, Processes, and Outputs

To ensure that small and large programs work well, you should clearly state what it's Inputs, Processes and Outputs are

An easy way to do this if you have a clear problem statement is to look at the nouns and verbs in that statement. The nouns become inputs and outputs while the verbs become your processes

Let's look at the problem statement for our tip calculator to determine the nouns:

  • bill amount
  • tip rate
  • tip
  • total amount

And the verbs:

  • prompt
  • compute
  • display

Of course, the problem statement won’t always be clear but with experience you'll learn fill in the gaps and read between the lines to know what to build.

Now we determine that our inputs, processes, and outputs for this program look like this:

  • Inputs: bill amount, tip rate
  • Processes: calculate the tip
  • Outputs: tip amount, total amount

But we are not ready to code yet, we have to...

3. Write tests

One of the best ways to design and develop software is to think about the result you want right from the start by writing tests that test the output of your program(s). This will help you think about the problems your program might need to solve

Many professional developers use Test-Driven Development (TDD) in which you write bits of code that test the outputs of your program or the outputs of the individual programs that make up a larger program

TDD does require some experience because you have to use language specific testing software but if you are a beginner you can still create simple test plans that test the output of your program

A test plan looks like this

Inputs:
Expected result:
Actual result:

When you create and run your program, you compare the result with the one expected and make any changes to your code if it fails

Let's go back to our tip calculator and define how we want things to work by creating a test plan.

Inputs: 
    bill amount: 10
    tip rate: 15
Expected result: 
    Tip: $1.50 
    Total: $11.50

This test plan tells us a couple of things:

  • First it tells us we'll take in 2 inputs
  • And we'll need to convert the inputs to decimal numbers when we do the math
  • It also tells us we need to format the results as currency

Now one test isn't enough though, what if we entered "11.25"? If you check using a calculator you'd get "1.6875"

But that isn't realistic, so we'll need to round the results of our computation up to the nearest cent and create another test plan like so

Input: 
    bill amount: 11.25 
    tip rate: 15
Expected result: 
    Tip: $1.69 
    Total: $12.94

Develop as much tests as you can and think of as many scenarios as you can for how people might break the program. This will improve the quality of the code and prevent buggy undocumented code from going into production

If you're and experienced developer, check out the book and use the programs there to get acquainted with the testing libraries and tools your favorite language has to offer.

Now that we have a clearer picture of the features our program will require, we can start putting together the algorithm for the program.

4. Write the algorithm

An algorithm helps you think about the logic without battling syntax, when you sit down to code you will only be concerned with syntax if you flesh out the algorithm well

Also there's no right way to write an algorithm, just write it in a fast an easy way you'll understand it and Brian recommends you do it in psuedocode so you can get to solving problems faster. By writing pseudocode, you will create something you can show to another developer to get feedback, and it didn’t take long to throw it together

Here's what the algorithm for our tip calculator would look like

Start 
    Initialize billAmount to 0 
    Initialize tip to 0 
    Initialize tipRate to 0 
    Initialize total to 0 

    Prompt for billAmount with "What is the bill amount?"
    Prompt for tipRate with "What is the tip rate?" 

    convert billAmount to a number 
    convert tipRate to a number 

    tip = billAmount * (tipRate / 100) 
    round tip up to nearest cent 
    total = billAmount + tip 

    Display "Tip: $" + tip 
    Display "Total: $" + total 
End

Although for simple programs like this one it's enough to use psuedocode, but for larger programs especially those that include repetition and decision making logic, it will be more efficient to create a flowchart

A flowchart is a pictorial representation of pseudocode. It's easier to read and helps to understand logic and repetition as you can see how the program flows.

If you've never drawn a flowchart before, watch some Youtube videos to learn how to draw one.

Now you can code

Once you have your algorithm setup, you can open up your editor and create code to perform those operations

Frankly the algorithm we created in not the best way to implement our calculator but that's not the point, an algorithm is for guiding us as we code. When we decide to implement we can do it any way we like including breaking the program into functions

Best of all, we can use this as a blueprint to code this up in any programming language. Notice that our pseudocode makes no assumptions about the language we might end up using, but it does guide us as to what the variable names will be and what the output to the end user will look like

Another added benefit is that we can use this algorithm as documentation for our code when we submit it for reviews or worse when we are looking at a codebase 10 years later

Once you have your pseudocode/flowchart down write your initial version of the program and get it working, after that you can tweak your code to improve it.

Conclusion

That's all for this article

While this process is a bit long, you won't have to use it every time but i recommend you build up discipline writing out algorithms before actually coding

When you start reaping the benefits of developing software like this, you'll wonder how you ever coded without it

I hope this article inspires you start writing algorithms, as they have improved my problem solving skills and i believe they will improve yours.

Thanks for reading

If you liked this article, leave a like or comment below so other developers can find it.

Connect me on twitter @jeffreyon_