Running the Loop
This is the Click Event for the Start Button, btnStart.
It has initialization code to set up for the loop, further down:
We need to have:
- The ListView ListView1 emptied out before we go adding anything to it
- The global variable latest loaded with our input starting number
- Our history emptied out before running the loop
- Our number of digits set, for use in padding short numbers.
The loop will be testing if the latest number is not in our history list, so we should not be adding it to history prematurely, otherwise we would skip the loop entirely.
It takes a bit of work to set up the two descending and ascending sorted numbers for the pending subtraction, so I added two local variables (descending and ascending) with initialization code to run at the top of my while loop.
They need to be read from right to left, to see how they work.
The text split block will break a number down into a list of its digits, if you give it an empty (zero length) delimiter (at)
AI2 has a handy list sorting block to sort the list of digits into ascending order.
It also has a list block to text join the resulting list back into a piece of text interposing a delimiter (in my case, another zero length text value).
The descending number needs to have itself reversed (a text block) to be in descending order It may need trailing 0's, so it is run through the rpad function.
The ascending number is already in ascending order, so it only needs left padding with zeroes to the required number of digits.
The rest of the loop builds on these values, in three steps:
- adding the lates value to the history list, to help stop the loop when duplication is encountered
- Calculating the new latest number by subtracting the ascending value from the descending value, then left padding it if needed.
- Formatting a new ListView Element from the descending, ascending, and latest values, and adding it to the ListView.
Finally, after the loop, we take the list length of the ListView Elements and display it as a nice summary of how many steps we took.
For those of you who hung in through the tutorial, here is the aia source:
Kaprekars_Constant.aia (4.9 KB)
Ideas for further work:
- Establishing the loop length limit for different ranges (number of digits)
- Listing the termination values for different ranges.