Download Introduction/Computer Science - Computers and Computations | COSC 102 and more Study notes Computer Science in PDF only on Docsity!
Opposite page: Mars Rover.
Photo courtesy of NASA/JPL Caltech
Computers & Computation Home computers are being called upon to perform many new functions, including the consumption of homework formerly eaten by the dog. Doug Larson Computer Science is no more about computers than astronomy is about telescopes. Edsger W. Dijkstra What is the central core of computer science? My answer is simple—it is the art of programming a computer. It is the art of designing efficient and elegant methods of getting a computer to solve problems, theoretical or practical, small or large, simple or complex. It is the art of translating this design into an effective and accurate computer program. C.A.R. Hoare Opposite page: The XO Laptop Photo courtesy of OLPC Project (www.olpc.org)
Computers & Computation
you are reading this, that the ploy worked! But remember that the reason you
are holding a robot of your own in your hand is also because of computers.
Your robot itself is a computer. Whether it was a ploy or not you have
assimilated many key ideas in computing and computer science. In this
chapter, we will make some of these ideas more explicit and also give you a
flavor for what computer science is really all about. As Dijkstra puts it,
computer science is no more about computers than astronomy is about
telescopes.
Computers are dumb
Say you are hosting an international exchange student in your home. Soon
after her arrival you teach her the virtues of PB&J (Peanut Butter & Jelly)
sandwiches. After keenly listening to you, her mouth starts to water and she
politely asks you if you can share the recipe with her. You write it down on a
piece of paper and hand it to her.
Do This: Go ahead; write down the recipe to make a PB&J sandwich.
Seriously, do try to write it down. We insist!
OK, now you have a recipe for making PB&J sandwiches.
Do This: Go ahead, use your recipe from above to make yourself a PB&J
sandwich. Try to follow the instructions exactly as literally as you can. If you
successfully managed to make a PB&J sandwich, congratulations! Go ahead
and enjoy it. Do you think your friend will be able to follow your recipe and
enjoy PB&J sandwiches?
You have to agree, writing a recipe for PB&J sandwiches seemed trivial at
first, but when you sit down to write it you have no choice but to question
several assumptions: does she know what peanut butter is? Should I
recommend a specific brand? Ditto for jelly? By the way, did you forget to
mention it was grape jelly? What kind of bread to use? Will it be pre-sliced?
If not, you need a knife for slicing the loaf? Did you specify how thick the
Chapter 1 1
slices should be? Should she use the same knife for spreading the peanut
butter and the jelly? Etc. The thing is, at such a level of detail you can go on
and on...does your friend know how to use a knife to spread butter or jelly on
a slice? Suddenly, a seemingly trivial task becomes a daunting exercise. In
reality, in writing down your recipe, you make several assumptions: she
knows what a sandwich is, it involves slices of bread, spreading things on the
slices, and slapping them together. There, you have a sandwich!
Think of the number of recipes that have been published in cookbooks all
over the world. Most good cookbook authors start with a dish, write down a
recipe, try it a number of times and refine it in different ways. Prior to
publication, the recipe is tested by others. After all, the recipe is for others to
follow and recreate a dish. The recipe is revised and adjusted based on
feedback by recipe testers. The assumption that cookbook authors make is that
you will have the competence to follow the recipe and recreate the dish to
your satisfaction. It may never result in the same dish that the author prepared.
But it will give you a base to improvise upon. Wouldn't it be nice if there was
an exact way of following a recipe so that you end up with the exact same
result as the cookbook author every time you made that dish? Would it? That
may depend on your own tastes and preferences. Just for fun, here is a recipe
for some yummy Saffron Chicken Kabobs.
Saffron Chicken Kabobs
Ingredients
1 lb boneless chicken breast, cubed into 1-2 inch pieces
1 medium onion, sliced
1 tsp saffron threads
1 lime
1 tbsp olive oil
Salt and black pepper to taste
Chapter 1 1
void wiggle(double speed, double waitTime) { robot.motors(-speed, speed); wait(waitTime); robot.motors(speed, - speed); wait(waitTime); robot.stop(); } // The main dance program int main() { connect(); cout << "Running the dance routine..." << endl; yoyo(0.5, 0.5); wiggle(0.5, 0.5); yoyo(1, 1); wiggle(1, 1); cout << "...Done" << endl; disconnect(); }
In many ways, this program above is like a recipe:
To do a robot dance
Ingredients
1 function yoyo for the robot to go back and forth at a given speed
1 function wiggle that enables the robot to wiggle at a given speed
Preparation
1. yoyo at speed 0.5, wait 0.
2. wiggle at speed 0.5, wait 0.
3. yoyo at speed 1, wait 1
4. wiggle at speed 1, wait 1
Further, you could similarly specify the steps involved in doing the yoyo and
wiggle motions as a recipe. This may seem like a trivial example, but it
makes two very important points: a computer program is like a recipe in that it
Computers & Computation
lays out the list of ingredients and a method or steps for accomplishing the
given task; and, like a recipe, its ingredients and the steps require careful pre-
planning and thought. Importantly, computer programs are different from
recipes in one aspect: they are designed to be followed by a computer!
A computer is a dumb device designed to follow instructions/recipes. We will
save the technical details of how a computer does what it does for a later
course. But it is almost common knowledge that everything inside is
represented as 0's and 1's. Starting from 0's and 1's one can design encoding
schemes to represent numbers, letters of the alphabet, documents, images,
movies, music, etc. and whatever other abstract entities you would like to
manipulate using a computer. A computer program is ultimately also
represented as a sequence of 0's and 1's and it is in this form that most
computers like to follow recipes. However limiting or degenerate this might
sound it is the key to the power of computers. Especially when you realize
that it is this simplification that enables a computer to manipulate hundreds of
millions of pieces of information every second. The price we have to pay for
all this power is that we have to specify our recipes as computer programs in a
rather formal and precise manner. So much so that there is no room for
improvisation: no pinch of salt vagaries, as in cooking recipes, is acceptable.
This is where programming languages come in. Computer scientists specify
their computational recipes using programming languages. You have been
using the programming language C++ to write your robot programs. Other
examples of programming languages are Java, Python, and C# (pron.: sea
sharp). There are well over 2000 programming languages in existence!
Do This: Can you find out how many programming languages there are?
What are the ten most commonly used programming languages?
Prior to the existence of programming languages computers were
programmed using long sequences of 0's and 1's. Needless to say it drove
several people crazy! Programming languages, like C++, enable a friendlier
way for programmers to write programs. Programming languages provide
easy access to encodings that represent the kinds of things we, humans, relate
to. For example, the C++ statement:
Computers & Computation
This is further refined into specific steps, perhaps even some variables are
identified and named, etc. Once you convince yourself that you have a way of
solving the problem, what you have is an algorithm
The idea of an algorithm is central to computer science so we will spend some
time here developing this notion. Perhaps the best way to relate to it is by an
example. Assume that a robot goes into a
grocery store to buy a dozen fresh eggs.
Assuming it is capable of doing this, how
will it ensure that it has selected the freshest
eggs available?
Your personal robot is probably not up to
this kind of task but imagine that it was.
Better yet, leave the mechanics aside, let us
figure out how you would go and buy the
freshest eggs. Well, you would somehow need to know what today's date is.
Assume it is September 15, 2007 (why this date? it'll become clear soon!).
Now you also know that egg cartons typically carry a freshness date on them.
In fact, USDA (the United States Department of Agriculture) offers voluntary,
no cost, certification programs for egg farms.
An egg farmer can volunteer to participate in
USDA's egg certification program whereby the
USDA does regular inspections and also
provides help in categorizing eggs by various
sizes. For example, eggs are generally
classified as Grade AA, Grade A, or Grade B.
Most grocery stores carry Grade A eggs. They
can also come in various sizes: Extra Large,
Large, Small, etc. What is more interesting is
that the carton labeling system has some very
useful information encoded on it.
Every USDA certified egg carton has at least
three pieces of information (see picture on the
Egg Carton Labeling
Chapter 1 1
right): a "sell by" date (or a "use by date" or a "best by" date), a code
identifying the specific farm the eggs came from, and a date on which the
eggs were packed in that carton. Most people buy eggs by looking at the "sell
by" date or the "best by" date. However the freshness information is really
encoded in the packed on date. To make things more confusing, this date is
encoded as the day of the year.
For example, take a look at the top carton shown on the previous page. Its
"sell by" date is October 4. "P1107" is the farm code. This carton was packed
on the 248th day of the year. Further, USDA requires that all certified eggs be
packed within 7 days of being laid. Thus, the eggs in the top carton were laid
somewhere between day 241 and day 248 of 2007. What dates correspond to
those dates?
Next, look at the bottom carton. Those eggs have a later "sell by" date
(October 18) but an earlier packed date: 233. That is those eggs were laid
somewhere between day 226 and day 233 of 2007.
Which eggs are fresher?
Even though the "sell by" date on the second carton is two weeks later, the
first carton contains fresher eggs. In fact, the eggs in the upper carton were
laid at least two weeks later!
The packed on date is encoded as a 3-digit number. Thus eggs packed on
January 1 will be labeled: 001; eggs packed on December 31, 2007 will be
labeled: 365.
Do This: Go to the USDA web site (www.usda.gov) and see if you can find
out which farm the two eggs cartons came from.
For a robot, the problem of buying the freshest eggs becomes that of figuring
out, given a packed on date, what the date was when the eggs were packed?
Chapter 1 1
Input
3 - digit packed on date encoding
Current year
Output
Date the eggs were packed
Example:
Input: 248, 2007
Output: The eggs were packed on September 5, 2007
Any ideas as to how you would solve this problem? It always helps to try and
do it yourself, with pencil and paper. Take the example above, and see how
you would arrive at the output date. While you are working it out, try to write
down your problem solving process. Your algorithm or recipe will be very
similar.
Suppose we are trying to decode the input 248, 2007. If you were to do this by
hand, using a pen and paper, the process might go something like this:
The date is not in January because it has 31 days and 248 is much larger than 31. Lets us subtract 31 out of 248: 248 - 31 = 217 217 is also larger than 28, the number of days in February,
So, let us subtract 28 from 217: 217 - 28 = 189 189 is larger than 31, the number of days in March. Subtract 31 from 189: 189 - 31 = 158 158 is larger than 30, the number of days in April. So: 158 - 30 = 128 128 is larger than 31, the number of days in May. Hence: 128 - 31 = 97 97 is larger than 30, the number of days in June.
Computers & Computation
67 is larger than 31, the number of days in July. 67 - 31 = 36 36 is larger than the number of days in August (31). 36 - 31 = 5 5 is smaller than the number of days in September. Therefore it must be the 5th day of September. The answer is: 248th day of 2007 is September 5, 2007.
That was obviously too repetitious and tedious. But that is where computers
come in. Take a look at the process above and see if there is a pattern to the
steps performed. Sometimes, it is helpful to try another example.
Do This: Suppose the input day and year are: 56, 2007. What is the date?
When you look at the sample computations you have performed, you will see
many patterns. Identifying these is the key to designing an algorithm.
Sometimes, in order to make this easier, it is helpful to identify or name the
key pieces of information being manipulated. Generally, this begins with the
inputs and outputs identified in the problem specification. For example, in this
problem, the inputs are: day of the year, current year. Begin by assigning
these values to specific variable names. That is, let us assign the name day to
represent the day of the year (248 in this example), and year as the name to
store the current year (2007). Notice that we didn't choose to name any of
these variables timbuktu or meaningOfLife!
Also, notice that you have to repeatedly subtract the number of days in a
month, starting from January. Let us assign a variable named, month to keep
track of the month under consideration.
Next, you can substitute the names day and year in the sample computation:
Computers & Computation
day (= 36) is larger than the # of days in month = 8. day = day – 31 ; // next month month = 9 ; day (= 5) is smaller than the # of days in month = 9. Therefore it must be the 5th day of September. The answer is: 9/5/
Notice now how repetitious the above process is. The repetition can be
expressed more concisely as shown below:
Input: day year // start with month = 1, for January month = 1 ; repeat if day is less than number of days in month day = day – number of days in month; // next month month = month + 1 ; else done; Output: day/month/year
It is now starting to look like a recipe or an algorithm. Go ahead and try it
with the sample inputs from above and ensure that you get correct results.
Additionally, make sure that this algorithm will work for boundary cases: 001,
Thirty days hath September
We can refine the algorithm above further: one thing we have left unspecified
above is the computation of the number of days in a month. This information
has to be made explicit for a computer to be able to follow the recipe. So, how
Chapter 1 1
do we compute the number of days in a month? The answer may seem simple.
Many of you may remember the following poem:
Thirty days hath September
April, June, and November
All the rest have thirty-one
Except for February alone
Which hath twenty-eight days clear
And twenty-nine in each leap year
From a design perspective, we can assume that we have an ingredient, a
function in this case, called daysInMonth that, given a month and a year will
compute and return the number of days in the month. That is, we can refine
our algorithm above to the following:
Ingredients: 1 integer function daysInMotnh(int m, int y): returns the number of days in month m and in year y. Input: an integer, day an intger, year // start with month = 1, for January month = 1 ; repeat if day is less than number of days in month day = day - daysInMonth(month, year); // next month month = month + 1 ; else done; Output: day/month/year (integers)
Now, we do have to solve the secondary problem:
Chapter 1 1
Ingredients: 1 function bool leapYear(int y) returns true if y is a leap year, false otherwise Input: int m, y; if m is April(4), June(6), September(9), or November(11) days = 30 ; else if m is February (2) if (leapYear(y)) days = 29 ; else days = 28 ; else /* m is January, March, May, July, August, October, December */ days = 31 ; Output: days (an integer)
Most of us have been taught that a leap year is a year that is divisible by 4.
That is the year 2007 is not a leap year, since 2007 is not divisible by 4, but
2008 is a leap year, since it is divisible by 4.
Do This: How do you determine if something is divisible by 4? Try your
solution on the year 1996, 2000, 1900, 2006.
Leap Years: Papal Bull
To design a recipe or an algorithm that determines if a number corresponding
to a year is a leap year or not is straightforward if you accept the definition
from the last section. Thus, we can write:
Input: int y, a year Output: true if y is a leap year, false otherwise
Computers & Computation
Method
if y is divisible by 4 it is a leap year, or true else it is not a leap year, or false
However, this is not the complete story. The western calendar that we follow
is called the Gregorian Calendar which was adopted in 1582 by a Papal Bull
issued by Pope Gregory XIII. The Gregorian Calendar defines a leap year, by
adding an extra day, every fourth year. However, there is a 100-year
correction applied to it that makes the situation a little more complicated:
Century years are not leap years except when they are divisible by 400. That
is the years 1700, 1800, 1900, 2100 are not leap years even though they are
divisible by 4. However, the years 1600, 2000, 2400 are leap years. For more
information on this, see the exercises at the end of the chapter. Our algorithm
for determining if a year is a leap year can be refined as shown below:
Input: int y, a year if y is divisible by 400 it is a leap year, or true else if y is divisible by 100 it is not a leap year, or false else if y is divisible by 4 it is a leap year, or true else it is not a leap year, or false
Finally, we have managed to design all the algorithms or recipes required to
solve the problem. You may have noticed that we used some familiar
constructs to elaborate our recipes or algorithms. Next, let us take a quick
look at the essential constructs that are used in expressing algorithms.