20
\$\begingroup\$

In this task you will take as input a non-negative integer \$n\$, and output the number of pairs of non-negative integers \$a,b\$ such that both are palindromes*, \$a \leq b\$, and \$a+b = n\$. For example if \$n\$ is \$22\$ then the valid pairs are

\$ \begin{array}{c|c} a & b \\ \hline 0 & 22 \\ 11 & 11 \\ \end{array} \$

So the output is \$2\$.

As another example, if \$n\$ is \$145\$ then the valid pairs are

\$ \begin{array}{c|c} a & b \\ \hline 4 & 141 \\ 44 & 101 \\ \end{array} \$

So the output is 2.

Your submission should be a program or function. Answers will be scored in bytes with fewer bytes being the goal.

Test Cases

\$ \begin{array}{c|c c|c} \mathrm{Input} & \mathrm{Output} & \mathrm{Input} & \mathrm{Output} \\ \hline 0 & 1 & 12 & 5\\ 1 & 1 & 13 & 4\\ 2 & 2 & 14 & 4\\ 3 & 2 & 15 & 3\\ 4 & 3 & 16 & 3\\ 5 & 3 & 17 & 2\\ 6 & 4 & 18 & 2\\ 7 & 4 & 19 & 1\\ 8 & 5 & 20 & 1\\ 9 & 5 & 21 & 0\\ 10 & 5 & 22 & 2\\ 11 & 5 & 23 & 1\\ \end{array} \$

OEIS A260254


* In base 10

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Related \$\endgroup\$
    – Luis Mendo
    Feb 2, 2020 at 17:16
  • 9
    \$\begingroup\$ I like how this challenge was posted on a palindromic date, 02/02/2020 \$\endgroup\$
    – DJMcMayhem
    Feb 2, 2020 at 17:56
  • 3
    \$\begingroup\$ @DJMcMayhem Additionally the number of days since the beginning of the year (33) and the number of days to the end of the year (333) today are both palindromes. \$\endgroup\$
    – Wheat Wizard
    Feb 2, 2020 at 17:57
  • 3
    \$\begingroup\$ @DJMcMayhem I think you mean 20200202 or 2020-02-02 (ISO 8601) -- today is special, it is palindromic in the UK, the US, and internationally. \$\endgroup\$ Feb 2, 2020 at 18:26

14 Answers 14

4
\$\begingroup\$

Jelly, 9 bytes

ŻŒḂ€ḋṚ$HĊ

A monadic Link accepting a non-negative integer which yields a non-negative integer.

Try it online!

How?

Counts all pairs without the \$a\leq b\$ restriction, halves and rounds up. Note that the halved count is only a fraction if \$\frac n 2\$ is a palindrome and in such cases we want to count this \$a=b\$ pair.

ŻŒḂ€ḋṚ$HĊ - Link: integer, n    e.g. 22
Ż         - zero-range               [0,1,2,...,9,10,11,12,...,21,22]
   €      - for each:
 ŒḂ       -   is palindrome (digits) [1,1,1,...,1,0,1,0,...0,1]
      $   - last two links as a monad:
     Ṛ    -   reverse                [1,0,...,0,1,0,1,...,1,1,1]
    ḋ     -   dot-product           3  (=1×1+1×0+...+1×0+1×1+0×1+...+0×1+1×1)
       H  - halve                   1.5
        Ċ - ceil                    2
\$\endgroup\$
3
\$\begingroup\$

JavaScript (ES6),  74  73 bytes

n=>(g=a=>a>n-a?0:![a,n-a].some(n=>[...n+''].reverse().join``-n)+g(-~a))``

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ could you please tell me what is the last `` mean, thanks ! \$\endgroup\$
    – Chau Giang
    Feb 3, 2020 at 9:57
  • 3
    \$\begingroup\$ @chaugiang (g=a=>...)`` is equivalent to (g=a=>...)(['']) (TIO). So we have a=[''] for the first iteration, which happens to behave like a=0 would with our code and is turned into 1 for the 2nd iteration with -~a. All in all, this is one byte shorter than (g=a=>...)(0). \$\endgroup\$
    – Arnauld
    Feb 3, 2020 at 10:23
  • \$\begingroup\$ The tagged template plus the usage of -~ is actually super clever I definitely need to incorporate them more \$\endgroup\$
    – emegolf123
    Feb 3, 2020 at 21:40
3
\$\begingroup\$

Python 2,  73 70  63 bytes

lambda n:sum(`n-v`+`v`==(`v`+`n-v`)[::-1]for v in range(n/2+1))

Try it online!

Note that:

(string_a == reverse(string_a)) and (string_b == reverse(string_b))

is equivalent to

reverse(string_a + string_b) == (string_b + string_a)

(where + is concatenation)

\$\endgroup\$
3
  • \$\begingroup\$ Are the backtits converting the integers to strings? \$\endgroup\$
    – RGS
    Feb 2, 2020 at 17:52
  • \$\begingroup\$ Yes, in Python 2 it is a shorthand for repr(...) \$\endgroup\$ Feb 2, 2020 at 17:56
  • \$\begingroup\$ very clever. Adapting it in Python 3 with f" " format strings I shaved 18 bytes ;) have a +1 \$\endgroup\$
    – RGS
    Feb 2, 2020 at 17:59
2
\$\begingroup\$

Prolog (SWI), 99 bytes

N-C:-aggregate_all(count,(between(0,N,A),B is N-A,B=<A,+A,+B),C).
+N:-atom_codes(N,C),reverse(C,C).

Try it online!

Ungolfed Code

After adding white space, this solution reads very similarly to the challenge specification. It simply asks for the number of pairs palindrome integers within specified bounds that sum to N.

count_splits(N,C) :- 
  aggregate_all(count,(
    between(0,N,A),
    B is N-A, B=<A,
    palindrome(A),
    palindrome(B)
  ),C).

palindrome(N) :-
  atom_codes(N,C),
  reverse(C,C).
\$\endgroup\$
2
\$\begingroup\$

05AB1E, 10 bytes

ÝεÂQ}Â*O;î

Port of @JonathanAllan's Jelly answer, so make sure to upvote him as well!

Try it online or verify all test cases.

Explanation:

Ý        # Push a list in the range [0, (implicit) input-integer]
 ε       # Map each value to:
  Â      #  Bifurcate the value; short for Duplicate & Reverse copy
   Q     #  And check if it's equal to the value itself (1 if a palindrome; 0 if not)
 }Â      # After the map: bifurcate the entire list as well
   *     # Multiply the values at the same indices in the lists
    O    # Take the sum of that
     ;î  # And then halve and ceil it
         # (after which the result is output implicitly)
\$\endgroup\$
2
\$\begingroup\$

Perl 6, 44 bytes

{+grep {.flip eq[R,] $_},(^$_ Z($_...$_/2))}

Try it online!

Finds the number of pairs of numbers such that the reverse of the string representation is equal to the string representation of the reversed pair.

\$\endgroup\$
1
\$\begingroup\$

Charcoal, 18 bytes

ILΦ⊕⊘θ⬤I⟦ι⁻θι⟧⁼λ⮌λ

Try it online! Link is to verbose version of code. The halved input has to be incremented because a needs to vary over the inclusive range from 0 to n/2. Explanation:

     θ              Input `n`
    ⊘               Halved
   ⊕                Incremented
  Φ                 Filter over implicit range
        ⟦           Begin list
         ι          Current index `a`
           θ        Input `n`
            ι       Current index `a`
          ⁻         Subtracted (i.e. `b`)
             ⟧      End list
       I            Vectorised cast to string
      ⬤             Both strings satisfy
                 λ  Current string
                ⮌   Reversed
               λ    Current string
              ⁼     Are equal
 L                  Length
I                   Cast to string for implicit print
\$\endgroup\$
1
\$\begingroup\$

Python 3.8, 89 87 68 66 bytes

Adapting Jonathan's clever answer to Python 3 (with f format strings) and removing [] for a generator expression instead of list comprehension, we shave 21 bytes with

lambda n:sum(f"{i}{n-i}"==f"{n-i}{i}"[::-1]for i in range(n//2+1))

Try it online

My old answer:

lambda n:len([i for i in range(n//2+1)if(s:=str(i))==s[::-1]and(t:=str(n-i))==t[::-1]])

You can try it online

\$\endgroup\$
1
  • 1
    \$\begingroup\$ @JonathanAllan damn generator expressions ;) \$\endgroup\$
    – RGS
    Feb 2, 2020 at 18:01
1
\$\begingroup\$

JavaScript (Node.js),  70 69  67 bytes

-2 thanks to Arnauld (change each string cast from x+''+y to x+[y])

I don't really know much JavaScript, I based this around Arnauld's answer, any advice is very welcome!

n=>(g=a=>(v=n-a)<a?0:(v+[a]==[...a+[v]].reverse().join``)+g(-~a))``

Try it online!

Note that:

(string_a == reverse(string_a)) and (string_b == reverse(string_b))

is equivalent to

reverse(string_a + string_b) == (string_b + string_a)

(where + is concatenation)

\$\endgroup\$
3
  • \$\begingroup\$ 67 bytes by coercing to strings in a slightly shorter way. \$\endgroup\$
    – Arnauld
    Feb 3, 2020 at 12:03
  • \$\begingroup\$ It also means that you can get rid of v like this, but that's the same byte count. \$\endgroup\$
    – Arnauld
    Feb 3, 2020 at 12:08
  • \$\begingroup\$ Thanks @Arnauld ...it seems that there are many, many ways to --skin-- golf a cat in JS. \$\endgroup\$ Feb 3, 2020 at 13:07
1
\$\begingroup\$

PHP, 83 86 85 73 bytes

for(;$i<=$argn/2;$i++)$k+=strrev($j=$argn-$i)==$j&&strrev($i)==$i;echo$k;

Try it online!

-13 bytes and bug fix thanks to @640KB

\$\endgroup\$
0
1
\$\begingroup\$

C (gcc), 114 \$\cdots\$ 105 98 bytes

Saved 7 bytes thanks to rtpax!!!

i;m;p(n){for(i=0,m=n;i=i*10+n%10,n/=10;);n=i==m;}r;a;f(n){for(a=r=0;a<=n/2;)r+=p(a)*p(n-a++);n=r;}

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ @rtpax Very nice, adding the if condition to the result is especially sweet - Thanks!:-) \$\endgroup\$
    – Noodle9
    Feb 3, 2020 at 20:25
1
\$\begingroup\$

Vyxal l, 63 bitsv2, 7.875 bytes

½ʀ2('Ḃ⁼;-

Try it Online!

Bitstring:

000100100000010110000001100101111001000100100001100010110111001

Explained

½ʀ2('Ḃ⁼;-­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁢​‎‏​⁢⁠⁡‌­
½ʀ         # ‎⁡Push the range [0, input / 2] for later
  2(       # ‎⁢Twice:
    'Ḃ⁼;   # ‎⁣  Filter the top of the stack by is palindromic
        -  # ‎⁤  And subtract that from the input.
        -  # ‎⁢⁡  This acts as a check for pairs, by keeping numbers that are palindromes before and after subtraction
# ‎⁢⁢The l flag outputs the length of the top of the stack
💎

Created with the help of Luminespire.

Only took me around 3 and a half years to finally write this answer. Things sure have changed since then.

\$\endgroup\$
0
\$\begingroup\$

MathGolf, 14 bytes

)rmÑ_x^mÅε*Σ)½

Try it online.

Explanation:

)               # Increase the (implicit) input-integer by 1
 r              # Pop and push a list in the range [0, input+1)
  mÑ            # Check for each value whether it's a palindrome (1 if truthy; 0 if falsey)
    _           # Duplicate this list
     x          # Reverse the copy
      ^         # Zip the two together to create pairs
       m        # Map over each pair,
        Å       # using the following two commands:
         ε      #  Reduce by:
          *     #   Multiplying
           Σ    # Then take the sum of this list
            )   # Increase this sum by 1
             ½  # And integer-divide it by 2
                # (after which the entire stack joined together is output implicitly)
\$\endgroup\$
0
\$\begingroup\$

Perl 5 -p, 51 bytes

$\+=($,==reverse$,)&&$_==reverse;++$,<=--$_&&redo}{

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.