retroforth/example/palindromic-numbers.retro
crc f668c87df4 add palindromic numbers example (svfig challenge)
FossilOrigin-Name: 37c5106501efcc58bf78bb92db28a989763b451e7df101cb6bab6b2c8178251d
2020-12-21 00:11:53 +00:00

54 lines
1.6 KiB
Text

# palindromic-numbers.retro
## Description
December: Palindromic numbers
Palindromic Numbers: The programming challenge for the Saturday, Dec. 19 Silicon Valley Forth Interest Group meeting. Numbers the same forward and backward as for RADAR but with numbers. Such as 88 and 666 and 12321.
Program a generator or a filter to find all palindromic integers from 1 (yes, it is) to 99999. Please confirm your interest to Bill Ragsdale, bill@billragsdale.cc
## Code & Commentary
Well this is really easy. I begin by creating an array of potential values.
~~~
#100000 [ I n:inc , ]
'Potentials d:create over , times<with-index>
~~~
Then a simple `palindrome?` word to convert the number to a string and return a flag indicating if it's a palindrome.
~~~
:palindrome? n:to-string dup s:reverse s:eq? ;
~~~
Use `palindrome?` to filter out invalid values.
~~~
&Potentials [ palindrome? ] a:filter
~~~
And finally, display the palindromes.
~~~
[ n:put nl ] a:for-each
~~~
## Notes
*Numeric Bases*
While Retro only supports decimal values by default, if you have extended `n:to-string` to support a `Base`, this will still work with other bases.
*Memory Use*
In my tests, this isn't memory efficient, as I'm keeping both the list of potentials and the results in memory, so it ends up consuming about 101k memory locations. If the results don't need to be kept, a much smaller solution would look like:
:palindrome? n:to-string dup s:reverse s:eq? ;
:value I n:inc dup ;
:process [ n:put nl ] &drop choose ;
#100000 [ value palindrome? process ] times<with-index>
This only uses 74 memory locations.