When the Moisture Readings Turn Around
The isopods have vanished under the cork bark, so the enclosure looks quiet. The moisture log has more to say: four readings, taken in order at the same spot, are 70, 60, 65 and 55. The brief rise to 65 interrupts the decline, but how much disorder is there in the sequence?
One answer is to count inversions. An inversion is a pair of readings where the earlier value is greater than the later one. Here, 70 forms three such pairs; 60 and 65 each form one more. The total is five. Equal readings would contribute nothing.
This QB64 program compares each reading with every reading that follows it:
DIM reading(1 TO 4) AS INTEGER
reading(1) = 70: reading(2) = 60
reading(3) = 65: reading(4) = 55
count = 0
FOR i = 1 TO 3
FOR j = i + 1 TO 4
IF reading(i) > reading(j) THEN count = count + 1
NEXT j
NEXT i
PRINT "Inversions:"; count
Haskell can express the same comparison by choosing pairs of positions from a list. The condition i < j keeps the original order and makes sure each pair is counted once.
main :: IO ()
main = do
let readings = [70, 60, 65, 55]
indexed = zip [0 :: Int ..] readings
inversions = [() | (i, x) <- indexed,
(j, y) <- indexed,
i < j, x > y]
putStrLn ("Inversions: " ++ show (length inversions))
Both print Inversions: 5. This direct approach is easy to inspect, though the number of comparisons grows quadratically as the log gets longer; faster inversion-counting algorithms can use a modified merge sort.
The count describes ordering, not how quickly the enclosure dried or whether it needs water. For that, keep the timestamps and measurement method alongside the readings—and pay attention to where the isopods choose to settle.