Main Content

Selling curry to the chinese takeaway

Archive - Originally posted on "The Horse's Mouth" - 2008-03-31 18:00:40 - Graham Ellis

Have you ever walked into a Chinese Takeaway and sold them three chicken curries with rice? Or gone to your local station and bought three tickets for yesterday? I'll be you haven't - there are certain things that don't work quite the same way when you go negative. I can't carry on once my car has run out of petrol, secure in the knowledge that I can then put 11 gallons into my 10 gallon tank when I reach the next filling station.

But with some things, negative values ARE acceptable. What is the temperature today? 6? 4? -4? The only difference is that you'll want gloves and need to scrape ice in the latter case.

When writing code to establish the maximum of a series of numbers, it's very tempting to assume that the largest_so_far is zero, then compare each of your series with largest_so_far and note the new value if it's higher. Which works very well if you've got positive numbers. But what were the temperatures in Sptitzbergen last week? -15, -20, -15, a hot -8, and -14. So my tempting algorithm wouldn't work - it would give me a scorching zero degrees.

Solution? Don't start at zero ... start at the first value in the series. Here's an example of a part of that code in Tcl:

if {$count} {
  if {$biggest < $input} {set biggest $input}
  if {$smallest > $input} {set smallest $input}
} else {
  set biggest $input
  set smallest $input
  }