Question

I'm working on a homework assignment that asks us to create a type of Units class that can keep track of units and perform basic arithmetic on them. The problem description has this bit, which I don't completely understand:

Probably the easiest way to keep track of the units is to give Units a dictionary that maps symbols to integers. If you are dividing by a unit then it has a negative value in the dictionary. You add two Units together by adding the value together for each symbol in the dictionary. When it is zero, throw the symbol away!

For reference, this is also included in the description:

[...] you could write an expression 3 elephants / (1 sec sec) and it would return the right thing.

Could someone shed some light here? How can I use a dictionary to map these types of units? Am I making this way harder than it needs to be?

Was it helpful?

Solution

It sounds like your teacher is giving you a hint about how to wind up with the proper units at the end of the calculation.

When you're parsing the problem, as you encounter items that are obviously units, enter them into a dictionary. The dictionary would consist of a number and a string (the supposed "unit"). Then you'd use a set of rules to increase or decrease the integer count. The resultant integer value would help you to output the units correctly.

A count of 1 indicates it's a unit in the output. A count of -1 indicates it's inverse is a unit in the output. A count of 0 indicates that it doesn't appear in the output at all. Similarly, a count of 2 would indicate that it's square appears as a unit in the output.

To wit:

5 Hippo + 10 Hippo = 15 Hippos

Parsing:       Dictionary:
--------       -----------
5 Hippo        Hippo:1
+
10 Hippo       Hippo:1  (previous operation was addition or subtraction, and already have Hippo in dictionary

But consider this problem:

5 Hippo * 5 sec/Hippo = 25 sec

Parsing:       Dictionary:
5 Hippo        Hippo:1
*
5 sec          Hippo:1, sec:1
/
Hippo          Hippp:0, sec:1  (previous operation was division of Hippo, so decrement Hippo count)

Or perhaps:

10 feet / 5 sec = 2 feet/sec

Parsing:       Dictionary:
10 feet        feet:1
/
5 sec          feet:1, sec:-1  (divided by sec, and second is not in dictionary, so second implicitly = 0.  0 + (-1) = -1.

In the example above, feet will be on the top of the bar because it's equal to 1, and sec will be below the bar because it's value is -1. If it's value had been -2, it would have been (feet/(sec*sec) or feet/(sec squared).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top