Hey, I already did that!
At least all this time spent running errands all over Commander Lamda's space station have given you a really good understanding of the station's layout. You'll need that when you're finally ready to destroy the LAMBCHOP and rescue the bunny workers.
Commander Lambda uses an automated algorithm to assign minions randomly to tasks, in order to keep minions on their toes. But you've noticed a flaw in the algorithm : it eventually loops back on itself. Instead of assigning new minions as it iterates, it gets stuck in a cycle of values so that the same minions end up doing the same tasks over and over again. You think proving this to Commander Lambda will help you make a case for your next promotion.
You have worked out that the algorithm has the following process
Start with a random minion ID n, a nonnegative integer of length k in base b. Define x and y as integers of length k. X has the digits of n in descending order. Y has the digits of n in ascending order. Define z = x - y. Add leading zeros to z to maintain length k if necessary. Assign n = z to get the next minion Id, repeat.
For example, given minion ID n = 1211, k =4, b = 10, then x = 2111, y = 1112 and z = 2111 - 1112 = 0999. Then, the next minion ID will be n = 0999.
At some point, the algorithm reaches a cycle. For example, starting with n = 210022, k = 6, b =3, the algorithm will reach the cycle of values [210111, 122221, 102212] and it will stay in this cycle no matter how many times it continues iterating.
Given a minion ID as a string representing a nonnegative integer of length k in base b where 2 <= k <= 9 and 2 <= b <= 10, write a function solution(n,b) which returns the length of the ending cycle of the algorithm above starting with n. .
solution('22022',3) = 3
solution('1211',10) = 1