A Common-Sense Guide to Data Structures and Algorithms, Second Edition: suggestion for sum_swap example (page 413)

Maybe you were just trying to keep the sum_swap code clean and streamlined for ease of reading, but this method didn’t seem as air-tight as other example methods in the book. You may want to at least comment that not all cases are handled by the method.

Two ways I think this method might fail are 1) the method does not handle the case where swapping to even out the sums is not possible, and 2) since shift_amount is calculated with integer division and thus will always be an integer, I suspect that sum_swap could give an incorrect answer if sum_1 - sum_2 is an odd number.

Then again, maybe those types of caveats are understood and maybe I missed other such scenarios elsewhere in the book.

I’m getting close to the end…finally! Great book, very well-written and helpful for me!

Thank you! Currently, the method does handle cases where swapping the sums isn’t possible, as it returns nil at the end. However, you are correct about the odd number issue. I will handle this in a future version. Good catch!

1 Like