# HW4 Solution

Here is the solution to the fourth homework, hw4.

## Exercise 1 (perl1): even zero counts!

As you may have noticed counting things is a common occurrence in programming. Variables that keep the number of things you have found are called counters. Here we have five of them:

```\$numero_di_zeri = 0; \$numero_di_uni = 0; \$numero_di_otti = 0; \$numero_di_novantanovi = 0; \$numero_di_cinquecenti = 0;   for (\$i = 0; \$i &lt; 1000; \$i++) { \$j = int(rand()**3*1000); print "\$j\n"; if (\$j == 0) { \$numero_di_zeri++; } elsif (\$j == 1){ \$numero_di_uni++; } elsif (\$j == 8){ \$numero_di_otti++; } elsif (\$j == 99){ \$numero_di_novantanovi++; } elsif (\$j == 500){ \$numero_di_cinquecenti++; } }   print "We had \$numero_di_zeri zeros.\n"; print "We had \$numero_di_uni ones.\n"; print "We had \$numero_di_otti eights.\n"; print "We had \$numero_di_novantanovi 99s.\n"; print "We had \$numero_di_cinquecenti 500s.\n";```

Remarks:

• we used a new keyword of perl: elsif. Normal ifs are fine too. The difference is that, with elsif, if we found that \$j is zero then we do not check the other conditions (since \$j cannot be equal to both zero and any of 1, 8, 99, 500;
• lots of cut and paste (at least for me): this is usually a bad sign, your code will be longer and harder to read and it is easy to make mistakes (I caught one myself, I hope that was the only one).

## Exercise 2 (perl2): counting with hashes

The second exercise is the correct way to do the first one, that is, with hashes:

```for (\$i = 0; \$i &lt; 1000; \$i++) { \$j = int(rand()**3*1000); #print "\$j\n"; \$numero_di_numeri{\$j}++; }   foreach \$j (sort {\$a &lt;=&gt; \$b} keys %numero_di_numeri) { print "\$j: \$numero_di_numeri{\$j}\n"; }```

Remarks:

• here we do not initialize the hash, so perl creates an empty hash for us, which is exactly what we want;
• note how the code is much shorter and how it does more than before (since it counts every number that appear);
• we are cheating a bit by using sort {\$a <=> \$b} without explaining, but think of it as a way to show you that you do not need to understand every little part of your code (of course if you do it is better!). Anyway it sorts the keys of the hash by comparing them as numbers and not alphabetically as strings. If you are curious you can learn more from the official documentation.
• as many of you noticed, the values were not uniformly distributed because of that pesky **3 we put 😉

1. Matteo says: