20100416

Intro CS: an experiment

Intro to the intro

At one time in college I briefly considered becoming a computer science high school teacher. I found myself helping people around me quite a lot with CS homework and things, and it was pretty rewarding when it worked out. At another time, I tried to tutor a friend in CS, but I don't think I was patient enough, and didn't really have the right materials. I think I'll try again. This is an experiment.

This is not meant to be a tutorial in learning how to program. There are plenty of sites on the internet that will do that for you, with varying degrees of success. This is supposed to be an introduction to computer science. CS encompasses a few things other than simply programming. It also includes algorithmic thinking and understanding how computers work. Rest assured, learning how to program is an integral part of it. In fact, that will be our starting point with this...lesson. I guess that's the best word for it.

I should mention that I am using some CSE142 courses from the University of Washington for some of my reference and probably for programming problems.

The primary language I want to use in these lessons is Javascript. Javascript (or JScript as I may call it from time to time), is--as the link points out--a misunderstood language. It has a lot of expressive power, but also has a simple syntax with the added benefit of looking quite a bit like C/C++ and Java. In that respect, you could call it a gateway language. Har!

What is a program?

The core thing of interest in CS is a program. A program is just a series of instructions for the computer to do. You are telling the computer what to do, and in what order to do it, and it does it. Computers are hard workers, but fairly stupid, so it's up to you as a programmer to be very explicit about what steps you want it to take. That's what programming is about.

Programs are written in text files. You can use any text editor, like Notepad, to create or edit a text file, and then use that file as a program. But not all text files are programs. For that to happen, the contents of the file has to conform to a language. A language describes how the computer should interpret the contents of your text file as a program. Enough talking; let's see what a program looks like!

WScript.Echo("Hello World");

The conventional first program to write in any language to test it out is one that prints out the text, "Hello World", for some historical reason. If you create a new text file with just that single line in it, save it in c:\hello.js, and run it (on a command prompt) by using the command cscript c:\hello.js, you should see this output:

Hello World

You might be able to kind of sort of read that program as though it were English: echo "Hello World". For "echo", think, "say back to me." Now to clarify the various things that are going on with this program.

I said earlier that a program is a series of instructions. A better term for "instruction" is statement. A program is a series of statements. In this example, the hello world program contains just one statement. A statement is an instruction telling the computer to do something. When you run a Javascript program, the computer goes one line at a time from top to bottom through your file and does each line in order.

Programs also contain expressions. An expression is something that results in a value. Statements in a program can contain expressions that indicate more about what the computer should do, or how to do it.

Before I get into this next sample program, I need to point out one thing. If you see //, it is known as a comment. The computer ignores everything on the line following it. It's used to write additional clarifying information alongside code. Note that this can be used on its own line (the line begins with //, and so the entire line is ignored) or on the end of a line (the line has some code that is executed, and then //, so only things after the // are ignored).

// statement
WScript.Echo("Hello World");

// expression
WScript.Echo("Hello World");

As you see above, the text between the parentheses is an expression. The program is instructing the computer to Echo (that is, print out or output for the user to see) some text. The text to print out is an expression, which has the value "Hello World".

Other miscellanea about this particular example. WScript is not too important right now; just know that it's necessary and will be explained later.

Blank lines do nothing in a Javascript program. You can insert as many blank lines as you want in between any two lines of your program and receive the same result. For example, the following two programs do exactly the same thing.

WScript.Echo("Hi there");
WScript.Echo("Hi again");
WScript.Echo("Hi there");






WScript.Echo("Hi again");

Generally speaking, most statements in Javascript end in a semicolon. This rule and others comprise the syntax of the language. The syntax of a language is the set of rules that you must follow when writing your program so that the computer can interpret what you wrote. In English, if you neglected all punctuation, used the wrong punctuation, or put punctuation in strange places, someone else may have a hard time understanding what you mean. Likewise, if you do not adhere to the syntax of a language, the computer cannot run your program, because it can't understand you. Unlike humans, the computer is fairly unforgiving about syntax errors, and will usually just display an error message when you try to run your program, rather than try to guess your intent.

Other things from our example that are part of the syntax include the fact that pieces of text need to be enclosed in double quotes (""). The fact that blank lines are ignored and that comments (using //) cause the rest of the line to be ignored are also part of the syntax.

Functions, your best friend

Echo above is what is known as a function. A function is a group of statements that are executed together. That group of statements is called the function's body. When you use a function, the computer jumps to the first line of the function's body, does each line in turn until the end of the body, then jumps back to the next line where you were before.

I said, "use a function" in the previous paragraph. The proper term is calling, or invoking. These terms describe instructing the computer to jump to the function's body, run all of the lines in it, and jump back to the next line after the invocation.

In the example program above, you called a function named Echo. The body of that function happens to be in a different file, so you can't see it. Later, you will see functions whose body is visible to you. You should imagine that on the line that says WScript.Echo("Hello World");, the computer jumped to the function body of Echo (not visible to you), did several lines of program there, then jumped back.

One of the most important features of functions is that they can act on different data whenever called. In the following example (a new program), you are calling the same function, but supplying different data.

WScript.Echo("Hello");
WScript.Echo("Goodbye");

On both lines, the function being called is the same: Echo, but on the first line the data supplied is "Hello", whereas on the second line, the data supplied is "Goodbye". The same type of activity will take place on each line--displaying some text--but the specific text being displayed will be different.

I mentioned "supplying data to a function" a few times in the previous paragraphs. The proper term for the data being supplied is argument, or parameter. The more conventional term for "supply" is pass. So instead of "supplying data to a function", we say pass an argument to a function.

Briefly going back to syntax, function call arguments are always enclosed in parentheses, and immediately follow the function name.

Creating your own functions

One of the most important parts of programming is that you can define your own functions. The way you do this is by using the keyword function followed by the name you want to give to your function, the parameters that someone is allowed to pass to the function, and the function body. The body is enclosed in { } (curly braces), which is part of the syntax of the language and tells the computer where the body starts and ends.

Just to quickly review, remember that the parameters are the pieces of data that someone can supply when calling a function. And remember that the function body is the set of statements that are run, in order, when something calls the function.

Here is an example in which I have defined a function named Greet, then called it. You can write or paste this code in a new text file and save it as c:\greet.js. Then you can run it on the command prompt like you did before with hello.js, by using the command cscript c:\greet.js.

function Greet(person)
{
    WScript.Echo("Hello, " + person);
}

Greet("Owen"); // output is: "Hello, Owen"

There are a lot of interesting things about this example. On the very first line, I defined the function, which consists of what I said in the previous paragraph--giving the function's name, parameters, and body.

After the end of the function body, I call the function and pass a parameter to it. The parameter's value is "Owen". At this point, the computer jumps into the function body, to the line that says WScript.Echo("Hello, " + person);. The computer runs this line, which causes "Hello, Owen" to be displayed. Then the computer goes to the next line, but that is the end of the function body, so it jumps back to where it was before--the line after Greet("Owen");. Since this is the last line in the file, the program is done.

There's one crucially important detail here that I need to point out. This is one of the most difficult, fundamental concepts to grasp, so I will try to explain it thoroughly. When you pass an argument to a function, it can be used within the function body. In the example above, the argument "Owen" that you pass to Greet can be referred to within the function body as person. As we will see later, various different things can be passed as arguments to the function. No matter what, the code within the function body can always refer to the value that was passed in using the name person. One simplistic way to think about it for now is that everywhere you see person in the function body, the computer automatically substitutes the data that you passed as the argument.

By the way, You may be able to surmise from the example and code that + here appends one piece of text to another.

As you will discover later, using functions is one of the primary ways of breaking down a large problem into smaller pieces.

More on function definitions

I'd like you to try something with your greet.js example. I'd like to delete the last line, save the file, and run the program again. What do you see? You should see nothing at all, but why is that?

Remember that there were two steps that I explained in the example: defining the function and calling it. By deleting the last line, you removed the function call but not the definition. This should tell you that defining functions has no visible side effect. Just because a function with a certain name, parameters, and body exists doesn't mean that anything really happens. Only when it is called does the contents of its body run. You could define a million different functions; so long as you don't call any of them, your program will basically do nothing.

Variables, a constantly useful construct

Sometimes you need the computer to remember a piece of information. This is the purpose of a variable. A variable is a holding place for a piece of information.

We can use an analogy that a computer is like a building full of storage units. Each storage unit is empty and unused initially, but could be reserved by someone and used to store something. If the computer is the building, a variable is a little bit like a storage unit in the building, and your program is the customer who can reserve rooms.

When you declare a variable, you reserve a place in the computer that can be used to store data and give a name to that place, so that you can refer to it later. In the analogy, declaring a variable is like reserving a storage unit and picking a unique name or number for the room. Now you have an empty space that could be used to store something, and you know the room number so that you can get back to it later.

When you assign to a variable, you store an actual value in it. In the analogy, this is like putting some of your stuff in the storage unit. You use the room number to find the unit, then put something in there, then carry on with your life, knowing that your thing will stay in there until you take it out.

Finally, you can read a variable, which retrieves the value that you stored in it previously. In the analogy, this would be like going to the storage unit (again, using its room number to find it), and looking at what's inside. The analogy breaks down a little, because you don't actually take anything out of the room at this point.

Here is a new program that you can save and run. In it, we declare, assign to, and read a variable. Let's save it in c:\variable.js and run it.

// declare a variable
var someName;

// assign to a variable
someName = "Owen";

// read the variable by using it
WScript.Echo("Nice to see you, " + someName);
// output is: "Nice to see you, Owen"

There are a lot of things going on here that are important to know. The way to declare a variable, according to the syntax of the language, is to use the var keyword, followed by the name you want to use for the variable.

The way to assign to a variable (store something in it) is to use the variable name, followed by =, followed by the thing you want to store in it. In this program, I've stored a piece of text in this variable for later use. After the line reading someName = "Owen"; the value "Owen" will be stored in the variable named someName.

Finally, in the Echo line, we are reading the variable, simply by using its name in an expression. The expression it is used in is "Nice to see you, " + someName. As part of computing the value of that expression, the computer sees the variable named someName and reads its value (what you stored in it before) to substitute into the final piece of text.

More on function arguments

I'm going to combine parts of a greet.js and variable.js into a new program, as follows. Let's save it as c:\greet2.js and run it.

function Greet(person)
{
    WScript.Echo("Hello, " + person);
}

var someName;
someName = "Owen";

Greet(someName); // output is: "Hello, Owen"

There's one very important point that you need to understand here. Notice how when we define Greet, we write person as the name of the parameter, and refer to that data by the name person in the function body. And then notice that we wrote the line Greet(someName);. Well, someName doesn't "match" person... but it doesn't have to!

On the line where we call Greet, the computer determines the value of the parameter before that value is passed to the function body. So by the time the computer gets into the function body (the Echo line), it doesn't matter what we wrote outside of the function. The function body only knows that it was passed an argument that it knows as person.

A simplistic way to think of it for now is that Greet(someName) is automatically transformed by the computer into Greet("Owen") when the program runs.

That's one of the great powers of functions. No matter what expresion you pass to them, the data is available within the function body by referring to the same parameter name within. Similarly, you have freedom to pass any expression to the function as an argument, and the function will be able to handle it, so, for instance, you're not restricted in what you name your variables.

Exercises and solutions

To see whether you've understood any of this, here are a series of sample programs that make use of some of these constructs. If you've understood well, then in the comments where I ask what the expected output is, you should be able to guess exactly what the output should be. Each code block below is a separate, complete program that you could save in a text file and run with cscript, but try to guess the output before resorting to that.

// problem 1

function Func1(text1)
{
    WScript.Echo("Func1 " + text1);
}

Func1("abc"); // what is the output?

Problem 1 solution - click to show or hide

Func1 abc
// problem 2

function Func1(text1)
{
    WScript.Echo("Func1 " + text1);
}

var text = "def";
Func1(text); // what is the output?

Problem 2 solution - click to show or hide

Func1 def
// problem 3

function Func2(text1, text2)
{
    WScript.Echo("Func2 " + text1 + ", " + text2);
}

Func2("aaa", "ddd"); // what is the output?

Problem 3 solution - click to show or hide

Func2 aaa, ddd
// problem 4

function Func2(text1, text2)
{
    WScript.Echo("Func2 " + text1 + ", " + text2);
}

var text1 = "abc";
var text2 = "def";
Func2(text2, text1); // b) what is the output?

Problem 4 solution - click to show or hide

Func2 abc, def
// problem 5
function Func1(text1)
{
    WScript.Echo("Func1 " + text1);
}

function Func3(text1)
{
    Func1(text1);
}

Func3("def"); // what is the output?

Problem 5 solution - click to show or hide

Func1 def
// problem 6

function Func2(text1, text2)
{
    WScript.Echo("Func2 " + text1 + ", " + text2);
}

function Func4(text1)
{
    Func2(text1, text1);
}

var text2 = "rrr";
Func4(text2); // what is the output?

Problem 6 solution - click to show or hide

Func2 rrr, rrr
// problem 7
function Func1(text1)
{
    WScript.Echo("Func1 " + text1);
}

function Func5(text1, text2)
{
    var text3 = text1 + " " + text2;
    Func1(text1);
    Func1(text3);
}

Func5("dep", "ped"); // what is the output?

Problem 7 solution - click to show or hide

Func1 dep
Func1 dep ped
// problem 8
function Func1(text1)
{
    WScript.Echo("Func1 " + text1);
}

Func1(""); // what is the output?

Problem 8 solution - click to show or hide

Func1
// problem 9

function Func1(text1)
{
    WScript.Echo("Func1 " + text1);
}

var text1 = "efg";
text1 = text1 + text1;
Func1(text1); // what is the output?

Problem 9 solution - click to show or hide

Func1 efgefg

20100414

wow autohotkey wow

so I got a new netbook recently, because my old one (acer aspire one) up and died all of a sudden. the new one is a hp mini 210 hd. as far as netbooks go, it’s pretty rad. it has a high resolution screen, which is great until I realized I couldn’t read anything. so I set the computer to high DPI. How ludicrous is that? a netbook running with high dpi.

anyway, the main thing I find wrong with it is some puzzling choices with the keyboard. there are no dedicated page up, page down, home, and end buttons. Instead, to do that, you have to hit the dreaded Fn key plus up, down, left, or right. that would be fine, I guess, if there were an Fn key on both the left and the right. as it is, it’s only on the left, so to do a page down, I have to use both hands. annoying.

Another weird choice is making the key for “printscreen” the same as the key for “insert”, but making it so that the primary function is printscreen and the secondary (Fn) function is insert. I guess I can kind of understand that. I am probably one of the minority who sometimes uses ctrl+insert and shift+insert for copy and paste, respectively.

I found a program called sharpkeys that allows for some limited remapping of keys, apparently using some built-in windows feature having to do with scancodes. I say limited because a big limitation is the inability to map a combination of keys to a single other keystroke. in particular, I am interested in making right-control + up/down do my page up/down for me.

After some searching, I found a program called autohotkey, which does all this and way more. I’m using just the basics right now, but it can do all kinds of stuff, like run arbitrary programs upon receiving a keystroke, scan windows that are open on the system, append to files, and tons of other things.

here’s my script that I’m using for it right now. it’s pretty simple and slick. I no longer need to use sharpkeys either.

AppsKey & Down:: Send {WheelDown}
AppsKey & Up:: Send {WheelUp}

RCtrl & Down:: Send {PgDn}
RCtrl & Up:: Send {PgUp}
RCtrl & Left:: Send {Home}
RCtrl & Right:: Send {End}

PrintScreen::Ins
Ins::PrintScreen

20100408

cuttin on my finger

I managed to cut my left index finger last night while cutting through some english muffins to make breakfast sandwiches. I held the muffin in my left hand and cut with a gigantic bread knife down towards my hand, like an idiot. it cut a little too smoothly by accident, and I ended up slicing the tip of my left index finger.

now I have the opportunity to observe what daily activities I absolutely need that part of my body for. the good news seems to be that I don’t really use it for much that I couldn’t use my left middle finger for instead.

  • pulling the left trigger on my xbox 360 controller. I don’t know how well I’d adjust to doing this with my middle finger. I think that would throw off my grip a lot
  • wiping water out of my eyes. not a critical dependency

hm, nothing else comes to mind right now. I may update later if I think of something.

20100405

richmond science museum

this morning I bumped up against the wall of the shower while having my shower. it was cold, and reminded me of my childhood. when I was in maybe first grade, our class took an overnight field trip to the richmond science museum. the place was utterly magical for me, since it was my first experience at a science museum like that. I remember two specific experiences there.

the first, which is what reminded me of the museum this morning, was an exhibit where a series of metal bars were placed in a row. every other bar was either pretty hot or very cold. when you placed your hand on it, so that it touched several of the bars, you experienced a sensation quite unlike any other, probably led primarily by your body’s confusion at having such conflicting feelings so close to one another.

the other thing I remember was a kind of workshop that we as a class attended. in it, the instructor created something she called simply “goop”. it was a little bit slimy, and oozed like a very thick liquid when poured, but when you squeezed it hard enough it resisted, like a dense piece of clay or something. the instructor insisted that it could be created in our own homes with ingredients as simple as just corn starch and water, but I was totally disbelieving at the time.

20100404

mass effect 2

I started playing mass effect 2 today. it seems to be better in pretty much every way compared to the first one, which I also liked a great deal. I managed to make my main character just a little weird looking, by accident. so yeah, that’s cool I guess.

some people may be annoyed that they removed such fundamental RPG concepts as armor and weapon management, but actually, I’m not really missing it. the loadout system gives me some choice about it while not making me constantly manage my inventory. and face it, if you played through ME1 you are undoubtedly familiar with how much time was spent in inventory management. ugh.

the one other thing that is just downright bad is that the cool “special” armors like the cerberus armor and blood dragon armor have helmets that, while they look cool (I guess), totally obscure your face. the facial animation has gotten even better since ME1. characters raise their eyebrows, avert their eyes, and make faces with their mouths, and I really kind of want to see shepherd doing those things during conversations. furthermore, conversations are a pretty big part of mass effect. apparently there is a thread on the bioware forums clamoring for an option to remove your helmet. I (and 15 pages worth of people in the forum) hope they address that in an update.

currently a level 7 sentinel. exciting! the scene where you first see the new normandy gave me goosebumps. it was really well executed, cinematically and musically.