Code inspired by "Programming Pearls" by Jon Bentley, 2nd edition