And if you want to write some code that you look and think how nice it is then instead of using 0 and 1 for dir use -1 and 1. Then you can add it to count rather than testing to see what you need to do. When the value gets to the min or max you can negate dir.