Wednesday, July 3, 2019

Peanut Butter and Jelly as an Algorithm?

When it comes to understanding algorithms and data structures, we first have to understand what algorithms and data structures are. The easiest way of explaining algorithms is to describe an algorithm as a set of instructions. It doesn't have to be computer related though, that's what most people would associate with algorithms. The set of instructions for making a peanut butter and jelly sandwich is the algorithm for making a peanut butter and jelly sandwich. What I'm trying to say is algorithms don't have to be super tricky to understand computer instructions, they can be as simple as using a program to count the number of students in a school. Data structures are the ways of managing data passed to the computers. The data can be stored in various ways like trees and lists.

Pen and paper are your best friend.

If you're ever tasked with creating your own algorithm and data structure, the first step is to write down the tasks that you'll need the program to process. By writing out the steps, you're creating a framework for your algorithm, which will make it easier to program. After your framework is completed, it's time to start writing out your code.

Let's say we've been given a task of taking in user input, maybe a list of countries the user has visited, storing that data in a list, and then retrieving requested data.

Our algorithm would look something like

Take in user information.
Store data in a list
Use list methods like add and remove to edit the list and retrieve information.

After creating a new Array called countries, using the .add() method we can add in the user's data. It may look something like:

countries.add("Canada");
countries.add("Mexico");

The Array holds Canada and Mexico now.

If we wanted to return the whole list to the user we could use a for loop coded like this:

for (String n:countries){
            System.out.println(n);
        }
The code would iterate through the array, regardless of the number of entries the user inputted. Now let's say the user made a mistake on one of the countries that are entered. We can use the .remove() method to pass through the index that needs to be taken out of the array. Then using the for loop again, we can reprint the updated list.

This is a simple example of how to turn a few instructions into an algorithm and how the information can be saved.

Good luck!

No comments:

Post a Comment