Post Reply 
HHC 2021 Programming Contests - Surprise !
10-04-2021, 02:21 AM
Post: #7
RE: HHC 2021 Programming Contests - Surprise !
Here is my 40-byte program that won the RPN contest.

The program just counts up from the input number to find the first palindrome. To detect a palindrome, I reverse the digits, which can be done with very little code, and then compare the reversed number to the original.

Speed wasn't a contest criteria, except that the code couldn't appear to be in an infinite loop. By counting up by ones, I ran the risk of it taking too long, so I submitted to code on a DM42 for maximum speed and hoped that none of the test cases would take too long.

To reverse the digits of the original (old) number, I start with a new number of zero. Then in a loop do:
digit := old MOD 10
new := 10*new + old
old = (old-digit) / 10

For example, with an input number of 1234, igoes like this:
Code:
Iteration   old    new
0          1234      0
1           123      4
2            12     43
3             1    432
4             0   4321

Here's the code.

R01 = old number
R02 = new number
R03 = current candidate for a palindrome
Code:
01 LBL "PAL"    // program must be called PAL
02 LBL 02       // because GTO "PAL" is bigger
03 1
04 +            // Start looking for palindrome from the next number
05 STO 03       // candidate := input + 1
06 STO 01       // Old number is the same
07 0
08 STO 02       // "new" := 0
09 LBL 01
10 RCL 01       // old
11 10
12 ST*02        // new := new * 10
13 MOD          // old MOD 10 (the least significant digit)
14 ST-01        // old := old - digit, guaranteeing that old now ends in 0
15 ST+02        // new := new + digit
16 LASTX        // 10
17 ST/ 01       // old := old/10, but since it ends in zero, this shifts digits down
18 RCL 01       // old
19 X<>0?
20 GTO 01       // If more digit in old then go do another digit
21 RCL 02       // new, which is now the reverse of candidate
22 RCL 03       // Candidate
23 X<>Y?        // If they're different ...
24 GTO 02       // ... then candidate isn't a palindrome, go try the next one
25 END          // If you get here then candidate is a palindrome
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: HHC 2021 Programming Contests - Surprise ! - David Hayden - 10-04-2021 02:21 AM



User(s) browsing this thread: 3 Guest(s)