February 13, 2008

command line quizzes part 1

When I wanted to learn about bash and the unix command line tools, I looked for some easy quizzes and challenges but could not find any. Here's two for a start. (edit: part two can be found here)
Q: Find the most common 4-letter word in the following text.


Ruby is a pink to blood red gemstone, a variety of the mineral corundum (aluminium oxide). The common red color is caused mainly by the element chromium. Its name comes from ruber, Latin for red. Other varieties of gem-quality corundum are called sapphires. It is considered one of the four precious stones, together with the sapphire, the emerald and the diamond. Improvements used include color alteration, improving transparency by dissolving rutile inclusions, healing of fractures (cracks) or even completely filling them.

Prices of rubies are primarily determined by color (the brightest and best "red" called Pigeon Blood Red, command a huge premium over other rubies of similar quality). After color follows clarity: similar to diamonds, a clear stone will command a premium, but a ruby without any needle-like rutile inclusions will indicate the stone has been treated one way or another. Cut and carat (size) will also determine the price.

Rubies have a hardness of 9.0 on the Mohs scale of mineral hardness. Among the natural gems only diamond is harder, with a Mohs 10.0 by definition.

Here's a solution.

#!/bin/bash
#a script to find the most common 4-letter word in a text file
sed 's/ /\n/g' text.txt | grep -E '^\w{4}$' | sort | uniq -c | sort -r | head -1

Giving the following output. The most common 4-letter word is 'will' with 3 occurrences.
3 will



Q: Write a 10x10 matrix with random integers from 0 to 9 to standard output.

Here's a solution.

#/bin/bash
#a script to generate a 10x10 matrix with random numbers from 0 to 9
for i in `seq 1 10`; do
for i in `seq 1 10`; do expr $RANDOM % 10; done | xargs
done

Giving the following output.
3 1 0 3 8 5 7 7 0 8
4 5 1 8 8 0 8 7 5 4
6 1 1 3 6 4 8 8 0 9
6 6 1 8 6 9 9 6 3 4
5 1 7 2 1 4 5 4 8 5
7 5 8 7 9 9 5 4 2 1
7 0 8 2 9 4 6 2 7 8
8 6 8 6 9 9 6 3 2 3
8 1 9 3 9 6 7 3 5 8
8 5 9 8 9 0 7 1 0 3

0 comments: