Algorithms

How hard did the scanner work?

How hard did the scanner work?

A warehouse scanner checks a shelf by reading barcodes from left to right, one at a time, and stops the moment it reads the code it was looking for. The manager wants to know how much reading each lookup actually costs, so that the busiest codes can be moved to the front of the shelf.

Write comparisons_to_find(codes, target), which returns the number of barcodes the scanner reads. Reading a barcode and comparing it with the target counts as one comparison. The scanner stops at the first match, and if the target is not on the shelf at all it has read every barcode.

Worked example: with codes = [14, 3, 27, 8, 5, 41] and target = 27, the scanner reads 14 (one comparison, no match), then 3 (two, no match), then 27 (three, match) and stops. The answer is 3. With target = 99 it reads all six and answers 6.

  • Constraints: the shelf holds between 0 and 100000 barcodes, and each code is between -1000000 and 1000000.
  • The shelf may be empty, in which case nothing is read and the answer is 0.
  • The same code may appear more than once. The scanner stops at the first one it meets, so later copies cost nothing.
  • Do not sort the codes or search them cleverly. The task is to report what this particular scanner does, not to improve it.
Code

Run your code to see how it does on the examples. Submit also runs the hidden cases.