HW4 Solution

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 < 1000; $i++) {
  $j = int(rand()**3*1000);
  print "$j\n";
  if ($j == 0) {
  } elsif ($j == 1){
  } elsif ($j == 8){
  } elsif ($j == 99){
  } elsif ($j == 500){
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";

The code in codepad.


  • 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 < 1000; $i++) {
  $j = int(rand()**3*1000);
  #print "$j\n";
foreach $j (sort {$a <=> $b} keys %numero_di_numeri) {
  print "$j: $numero_di_numeri{$j}\n";

The code in codepad.


  • 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 😉

If you still find hashes misterious, read the post about them and ask us!

Tagged ,

One thought on “HW4 Solution

  1. Matteo says:

    Ora mi è tutto molto meno oscuro!
    Non avevo capito che anche gli hash venivano inizializzati se non già presenti, e infatti non capivo il significato di:
    Grazie del problem solving!

Leave a Reply

Your email address will not be published. Required fields are marked *