Assignment 1: Warmup
Sample solution by Rebecca Shapiro, Spring 2008.
Problem 1: Exploring Unix
This problem asks you to describe what the following command is doing.
ls -la / | grep ^d | wc -l
Solution
This command consists of three different commands strung together with pipes.
The first command is ls -la / .
ls lists
the contents of a directory. In this case,
the / we see is telling it to
list the contents of the root directory.
ls is being run with two
options selected, l and
a. The l
option is telling ls to print
extra information about the files. Particularly,
it will print out information in the following
order: permissions, number of links to the file
the owner of the file, the group of the file,
the size, the last time the file was modified,
and the name of the file. The a
option is telling ls to print out
all directories,
include those that are hidden (begin with a '.').
The output of ls is piped over to
grep. grep is a program
that searches lines of its input for strings that
match the string or regular expression fed to it.
grep flags a matching line by printing out
the entire line that it found the match in. In this
case, grep is searching its input
for lines that match the regular expression
^d. The ^ symbol
signifies that whatever follows it should be
found at the beginning of the line. In this
case it is searching for the character 'd' at the
beginning of each line, and prints out the line if it
matches.
The output of grep is finally piped to
wc. wc counts the number
of characters, words, and lines in its input. If
it is used with the l option, it will
only output the number of lines.
To summarize, ls is printing detailed information
about all files in the root folder, grep
is searching for lines from ls that begin with
a 'd'. If a line from ls -l begins with a 'd',
it means that that file is a directory. So grep outputs
just the long listings for the directories in the root
folder, one per line. Finally wc counts the number of
lines from grep, resulting in counting the number
of directories living in the root directory.
Problem 2: Compiling Stuff
What does freq.c do?
Solution
freq.c reads in data through standard input, and calculates the frequency at which each character appears. After it receives the EOF symbol, for each character it read in, it prints out the hexadecimal value of the character, the character (or '-' if the character isn't printable), and the number of times that character was seen in its input.
Problem 3: Diamond Programming
Finally, here's an actual programming problem:
Write a program diamond.c that prints
out a "diamond of stars" like this one (of size 7):
* *** ***** ******* ***** *** *
Ideally there's only one place in the program where the size of the pattern is defined, so it should only take a few keystrokes to produce a smaller or larger diamond instead.