Distinct palindromes within decimal numbers: Difference between revisions

Content added Content deleted
Line 159: Line 159:
1320267947849490361205695 false
1320267947849490361205695 false
</pre>
</pre>

=={{header|Nim}}==
<lang Nim>import algorithm, sequtils, sets, strutils

iterator substrings(s: string): string =
## Yield the substrings of the given string.
for istart in 0..s.high:
for istop in istart..s.high:
yield s[istart..istop]

func isPalindrome(s: string): bool =
## Return true if "s" is a palindrome.
result = true
for i in 0..(s.high div 2):
if s[i] != s[s.high - i]: return false

func cmpPal(s1, s2: string): int =
## Compare two palindromes (used for sort).
result = cmp(s1.len, s2.len)
if result == 0:
result = cmp(s1[0], s2[0])

func palindromes(str: string): seq[string] =
## Return the sorted list of palindromes contained in "str".
var palSet: HashSet[string]
for s in substrings(str):
if s.isPalindrome: palSet.incl s
result = sorted(toSeq(palSet), cmpPal)


when isMainModule:

for n in 100..125:
echo n, ": ", palindromes($n).mapIt(it.align(3)).join(" ")

echo()
for s in ["9", "169", "12769", "1238769", "123498769", "12346098769",
"1234572098769", "123456832098769", "12345679432098769",
"1234567905432098769", "123456790165432098769",
"83071934127905179083", "1320267947849490361205695"]:
let pals2 = palindromes(s).filterIt(it.len >= 2)
let verb = if pals2.len == 0: " doesn't contain palindromes "
else: " contains at least one palindrome "
echo s, verb, "of two digits or more"</lang>

{{out}}
<pre>100: 0 1 00
101: 0 1 101
102: 0 1 2
103: 0 1 3
104: 0 1 4
105: 0 1 5
106: 0 1 6
107: 0 1 7
108: 0 1 8
109: 0 1 9
110: 0 1 11
111: 1 11 111
112: 1 2 11
113: 1 3 11
114: 1 4 11
115: 1 5 11
116: 1 6 11
117: 1 7 11
118: 1 8 11
119: 1 9 11
120: 0 1 2
121: 1 2 121
122: 1 2 22
123: 1 2 3
124: 1 2 4
125: 1 2 5

9 doesn't contain palindromes of two digits or more
169 doesn't contain palindromes of two digits or more
12769 doesn't contain palindromes of two digits or more
1238769 doesn't contain palindromes of two digits or more
123498769 doesn't contain palindromes of two digits or more
12346098769 doesn't contain palindromes of two digits or more
1234572098769 doesn't contain palindromes of two digits or more
123456832098769 doesn't contain palindromes of two digits or more
12345679432098769 doesn't contain palindromes of two digits or more
1234567905432098769 doesn't contain palindromes of two digits or more
123456790165432098769 doesn't contain palindromes of two digits or more
83071934127905179083 doesn't contain palindromes of two digits or more
1320267947849490361205695 contains at least one palindrome of two digits or more</pre>


=={{header|Perl}}==
=={{header|Perl}}==