-1

Sorry, I don't even know what title to give this problem.

I have an array of numbers I call pages.

They are pages I need to print out physically from say a browser.

pagesToPrint = [2,3,4,5,7,8,9,12,14,15,16,17,18,19,20]

Now, what is the problem with just printing 2,3,4,5,7...20?

When a page or pages are sent to the printer it takes a while to be sent and process. So to speed up the process it is preferable to just print in batches. Say instead of printing 2-2, 3-3, 4-4 let's just print 2-5 we can not print 2-20 because it would print pages 6,10,11,13 and so on.

example of custom print

I don't really care in which programming language the answer is but the logic behind it. Ultimately I am trying to fix this problem in AutoHotkey.

AMC
  • 2,642
  • 7
  • 13
  • 35
fenchai
  • 518
  • 1
  • 7
  • 21

1 Answers1

0

Well you can solve this by a bit of "top-down" thinking. In an ideal world, there'd already be a function you could call: split_into_consecutive_batches(pages).

How would you describe, on a high level, how that would work? That's basically just a slightly more precise rewording of your initial post and requirements!

"Well as long as there's pages in left in the list of pages it should give me the next batch."

Aha!

def split_into_consecutive_batches(pages):
  batches = []
  while pages:
    batches.append(grab_next_batch(pages))

  return batches

Aha! That wasn't so bad, right? The big overall problem is now reduced to a slightly smaller, slightly simpler problem. How do we grab the very next batch? Well, we grab the first page. Then we check if the next page is a consecutive page or not. If it is, we add it to the batch and continue. If not, we consider the batch done and stop:

def grab_next_batch(pages):
  first_page = pages.pop(0)  # Grab (and delete) first page from list.
  batch = [first_page]

  while pages:
    # Check that next page is one larger than the last page in our batch:
    if pages[0] == batch[-1] + 1:
      # It is consecutive! So remove from pages and add to batch
      batch.append(pages.pop(0))
    else:
      # Not consecutive! So the current batch is done! Return it!
      return batch
  # If we made it to here, we have removed all the pages. So we're done too!
  return batch

That should do it. Though it could be cleaned up a bit; maybe you don't like the side-effect of removing items from the pages list. And instead of copying stuff around you could just figure out the indices. I'll leave that as an exercise :)

cadolphs
  • 9,014
  • 1
  • 24
  • 41