Just saw this interesting math process which always converges on the value 6174. Might make a good learning challenge for Picaxe students to teach data input and sorting.
That is something I had never heard of before and very interesting.
The challenges do seem to be input, checking the digits aren't all the same, and particularly sorting.
For checking the digits aren't all the same one can either split into digits then compare them against each other, or check the number isn't 0000, 1111, 2222 through 9999 which could be done quite compactly with a LOOKDOWN command.
Sorting is the challenging one. I went with a Bubble Sort. My 'd1' is most significant (highest value) digit, 'd4' the least significant (lowest value) digit, flagged any swapping and repeated until there was none ...
Code:
SortDigitsIntoDescendingOrder:
Do
swapped = False
if d1 < d2 Then : dX = d1 : d1 = d2 : d2 = dX : swapped = True : End If
if d2 < d3 Then : dX = d2 : d2 = d3 : d3 = dX : swapped = True : End If
if d3 < d4 Then : dX = d3 : d3 = d4 : d4 = dX : swapped = True : End If
Loop Until swapped <> True
Return
That will loop a maximum of three times in the worst case ...
Code:
1234 -> 2134 -> 2314 -> 2341
2341 -> 3241 -> 3421 -> 3421
3421 -> 4321 -> 4321 -> 4321
Because we are progressively ensuring the lowest value digits are in the lowest digit positions that allows for a nice unrolling of the loop which will speed things up ...
Code:
SortDigitsIntoDescendingOrder:
if d1 < d2 Then : dX = d1 : d1 = d2 : d2 = dX : End If
if d2 < d3 Then : dX = d2 : d2 = d3 : d3 = dX : End If
if d3 < d4 Then : dX = d3 : d3 = d4 : d4 = dX : End If
; d4 must now be lowest
if d1 < d2 Then : dX = d1 : d1 = d2 : d2 = dX : End If
if d2 < d3 Then : dX = d2 : d2 = d3 : d3 = dX : End If
; d3 must now be correct
if d1 < d2 Then : dX = d1 : d1 = d2 : d2 = dX : End If
Return
Swapping the digits could be done with SWAP for those PICAXE which have it, and one could also use the magic XOR sequence, for example to swap 'd1' with 'd2' ...
Code:
d1 = d1 Xor d2
d2 = d1 Xor d2
d1 = d1 Xor d2
That this XOR sequence does work never ceases to amaze me.
It would probably be worth putting the swapping in a #MACRO so it can be easily changed to try various techniques ...
Code:
#Macro SWAP_IF_NEEDED(hi, lo)
If hi < lo Then
dX = hi : hi = lo : lo = dX
End If
#endMacro
SortDigitsIntoDescendingOrder:
; d1 is msd, d4 is lsd
SWAP_IF_NEEDED(d1, d2)
SWAP_IF_NEEDED(d2, d3)
SWAP_IF_NEEDED(d3, d4)
; d4 must now be lowest
SWAP_IF_NEEDED(d1, d2)
SWAP_IF_NEEDED(d2, d3)
; d3 must now be correct
SWAP_IF_NEEDED(d1, d2)
Return
And the contest after that will be who can write the smallest code to display the sequence to the constant.
Smallest code, fastest code, most understandable code, most elegant code, are all in the running there.