14
\$\begingroup\$

Given a non-negative integer n, enumerate all palindromic numbers (in decimal) between 0 and n (inclusive range). A palindromic number remains the same when its digits are reversed.

The first palindromic numbers (in base 10) are given here:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, ...

This is a code golf with the prize going to fewest characters. The palindromic numbers should be output one per line to stdout. The program should read n from the commandline or stdin.

\$\endgroup\$
3
  • 3
    \$\begingroup\$ Between 1 and n (as per title) or 0 and n (as per body)? And which of the bounds does "between" include? \$\endgroup\$ Aug 23, 2011 at 11:45
  • \$\begingroup\$ @wok: You still haven't answered if it's inclusive or exclusive range? Is n part of the range to include? \$\endgroup\$
    – mellamokb
    Aug 23, 2011 at 15:09
  • \$\begingroup\$ @mellamokb Inclusive range. \$\endgroup\$
    – Wok
    Aug 23, 2011 at 15:15

50 Answers 50

10
\$\begingroup\$

Perl 5.10, 29 (or 39) characters

say for grep$_==reverse,0..<>

Needs the say feature enabled. 29 chars if you consider that to be free, otherwise 39 to add use 5.010;. Argument on STDIN.

Perl, 35 characters

#!perl -l
print for grep $_==reverse,0..<>

using the old perlgolf convention that #!perl is not counted but any flags following it are.

Perl, 36 characters

print$_,$/for grep $_==reverse,0..<>

If none of the others qualify.

\$\endgroup\$
5
  • \$\begingroup\$ Would you be so kind to explain what does $/ do? \$\endgroup\$
    – Gurzo
    Aug 24, 2011 at 8:38
  • 1
    \$\begingroup\$ @Gurzo $/ is the input record separator, which defaults to newline. It's just a little shorter than literal "\n". \$\endgroup\$
    – hobbs
    Aug 24, 2011 at 11:54
  • \$\begingroup\$ Using map is shorter: map{say if$_==reverse}0..<> \$\endgroup\$
    – jho
    Sep 1, 2011 at 20:16
  • 2
    \$\begingroup\$ @jho evil. Submit it :) \$\endgroup\$
    – hobbs
    Sep 1, 2011 at 21:02
  • 1
    \$\begingroup\$ If you use -E in lieu of -e, you get say for free. \$\endgroup\$
    – tchrist
    May 28, 2012 at 20:56
9
\$\begingroup\$

Befunge 320 313 303 characters

(including significant newlines and whitespace)

 &:#v_v#  #                  :-1<
v91:<         v          <
0     >0.@    >\25**\1-:#^_v
pv   p09+1g09<^_           >$+     v
:>:25*%\25*/:| ^:p18:+1g18\<
 :          > >90g 1-:90p  | >  ^
>|           $^     <      >-|  ^  #<
 @           > 0 81p^        >:.25*,^
            ^                      <

I wonder if I could make this smaller by rerouting the paths...

Edit: redid the top part to avoid an extra line.

\$\endgroup\$
8
\$\begingroup\$

Perl 5.10 - 27 characters

map{say if$_==reverse}0..<>

Reads the argument from stdin.

\$\endgroup\$
7
\$\begingroup\$

Golfscript, 15 chars

~),{.`-1%~=},n*
\$\endgroup\$
3
  • \$\begingroup\$ You may save a char comparing strings instead of numbers '~),{`.-1%=},n*'. \$\endgroup\$
    – Howard
    Oct 28, 2012 at 9:09
  • \$\begingroup\$ @Howard, if you want to post that yourself I'll upvote it. \$\endgroup\$ Oct 28, 2012 at 15:32
  • \$\begingroup\$ That would feel like plain copying ;-) \$\endgroup\$
    – Howard
    Oct 29, 2012 at 12:53
7
\$\begingroup\$

Ruby 1.9, 39 characters

puts (?0..gets).select{|i|i==i.reverse}

Input (must not be terminated with a newline) via stdin. Example invocation:

echo -n 500 | ruby1.9 palinenum.rb

40 characters for a version which uses commandline args:

puts (?0..$*[0]).select{|i|i==i.reverse}
\$\endgroup\$
3
  • \$\begingroup\$ Rohit proposed saving 3 characters in each of these by using p instead of puts. \$\endgroup\$ May 23, 2012 at 9:20
  • \$\begingroup\$ Using your code I got the following output, which seems to be wrong(I am using ruby 1.9.2p0 (2010-08-18) [i386-mingw32]) irb(main):023:0> p (?0..gets).select{|i|i==i.reverse} 1 ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "11", "22", "33", "44", "55", "66", "77", "88", " 99"] => ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "11", "22", "33", "44", "55", "66", "77", "88" , "99"] The code below works for me p ('0'..gets[0..-2]).select{|i|i==i.reverse} Could you explain your code. \$\endgroup\$
    – Rohit
    May 23, 2012 at 9:29
  • \$\begingroup\$ @PeterTaylor @Rohit p and puts are not equivalent, in fact using p breaks the output, as puts writes every element on a newline, if called with an array, whereas p simply calls .to_s. \$\endgroup\$
    – Ventero
    May 23, 2012 at 14:18
6
\$\begingroup\$

J, 20 characters

(#~(-:|.)@":"0)>:i.n
\$\endgroup\$
3
  • \$\begingroup\$ I can read it!:) Nice \$\endgroup\$
    – defhlt
    Aug 17, 2012 at 8:54
  • \$\begingroup\$ btw, to meet a requirement output numbers one per line you should add ,"0. \$\endgroup\$
    – defhlt
    Aug 17, 2012 at 10:22
  • \$\begingroup\$ @defhlt ,. works as well \$\endgroup\$ Mar 19, 2018 at 17:15
5
\$\begingroup\$

Python, 57 51 chars

for i in range(input()):
 if`i`==`i`[::-1]:print i

Usage:

echo 500 | python palindromic.py
\$\endgroup\$
3
  • 3
    \$\begingroup\$ Shorter: for i in range(input()):if`i`==`i`[::-1]:print i \$\endgroup\$ Aug 23, 2011 at 14:42
  • \$\begingroup\$ If using the interactive interpreter is legit, then you can avoid the print and just do if`i`==`i`[::-1]:i (I say this because the Scala solution depends on this). \$\endgroup\$
    – Bakuriu
    Mar 26, 2013 at 19:13
  • \$\begingroup\$ The range should be inclusive. And i think you can change you byte count to 50 (linebreaks are shorter on linux). \$\endgroup\$
    – malkaroee
    Nov 5, 2014 at 18:04
5
\$\begingroup\$

Perl > 5.10 : 25 characters

map$_==reverse&&say,0..<>
\$\endgroup\$
4
\$\begingroup\$

APL (25 17)

↑t/⍨t≡∘⌽¨t←⍕¨0,⍳⎕
\$\endgroup\$
3
\$\begingroup\$

Javascript 122 108 107 chars...

I'm sure this can be golfed more - I'm new to this!

n=prompt(o=[]);for(i=0;i<=n;i++)if(i+''==(i+'').split("").reverse().join(""))o.push(i);alert(o.join("\n"));

or

n=prompt(o=[]);i=-1;while(i++<n)if(i+''==(i+'').split("").reverse().join(""))o.push(i);alert(o.join("\n"));
\$\endgroup\$
13
  • \$\begingroup\$ Well, for starters the vars are unneeded, you can just make things global. Also prompt() doesn't strictly need parameters. \$\endgroup\$
    – Clueless
    Aug 23, 2011 at 14:27
  • \$\begingroup\$ However, you can use parameters to prompt() to save one semicolon: n=prompt(o=[]);. \$\endgroup\$
    – mellamokb
    Aug 23, 2011 at 15:01
  • \$\begingroup\$ Also you still have a var i=0 that can have the var removed in your for. \$\endgroup\$
    – mellamokb
    Aug 23, 2011 at 15:02
  • 1
    \$\begingroup\$ The trick is that i++<n compares i<n before adding 1 to i. Thus, it runs all the way to i=n. If you wanted to stop at i=n-1, you would use ++i<n instead. \$\endgroup\$
    – mellamokb
    Aug 23, 2011 at 17:21
  • 1
    \$\begingroup\$ alert(o.join(" ")) needs to be alert(o.join("\n")) according to the specs. Add 1 to your character count when you fix this. \$\endgroup\$ Aug 23, 2011 at 18:02
3
\$\begingroup\$

Perl - 43 chars

for$i(0..<>){if($i==reverse$i){print$i,$/}}

This is my first attempt at code golf, so I'm pretty sure a Perl pro could golf it down.

\$\endgroup\$
3
\$\begingroup\$

Haskell 66 characters

main=do n<-readLn;mapM_ putStrLn[s|s<-map show[0..n],s==reverse s]
\$\endgroup\$
2
  • \$\begingroup\$ Misspelled the language name... \$\endgroup\$ Sep 1, 2011 at 16:37
  • \$\begingroup\$ Fixed (filler chars) \$\endgroup\$ Sep 1, 2011 at 18:03
3
\$\begingroup\$

Mathematica 61

Column@Select[0~Range~Input[],#==Reverse@#&@IntegerDigits@#&]
\$\endgroup\$
3
\$\begingroup\$

Brachylog

With the I/O format stated in the question, 8 bytes

≥ℕA↔A≜ẉ⊥

Try it online!

With modern PPCG I/O rules, 4 bytes

≥ℕ.↔

Try it online!

This is a function that generates all the outputs, not a full program like the previous example, and so doesn't comply with the spec as written, but I thought I'd show how the program would look like if the question had been written to modern I/O standards (which permit the use of functions, and output via generators).

Explanation

≥ℕ.↔ 
 ℕ    Generate natural numbers
≥     less than or equal to the input
  .   but output only the ones
   ↔  that would produce the same output if reversed

For the full program version, we create a temporary variable A to hold the output, explicitly labelize it (this is done implicitly for the main predicate of a program), and use the well-known ẉ⊥ technique for outputting a generator's elements to standard output.

\$\endgroup\$
3
  • \$\begingroup\$ When did modern PPCG I/O rules allow you to use a generator as submission? \$\endgroup\$
    – Leaky Nun
    Apr 27, 2017 at 8:59
  • 1
    \$\begingroup\$ @LeakyNun: I made the proposal on 30 Nov 2016, but the consensus is that they were already legal at that point (just not documented). We have an explicit rule allowing them now; through most of 2016, they weren't explicitly allowed and they weren't explicitly banned either. \$\endgroup\$
    – user62131
    Apr 27, 2017 at 15:35
  • \$\begingroup\$ Oh, well, I see. \$\endgroup\$
    – Leaky Nun
    Apr 27, 2017 at 15:37
2
\$\begingroup\$

Scala 59

(0 to readInt)filter(x=>""+x==(""+x).reverse)mkString("\n")
\$\endgroup\$
2
  • \$\begingroup\$ I don't know any Scala, but does that really print on stdout? I would've guessed it's an expression returning a string. \$\endgroup\$
    – Omar
    Nov 29, 2011 at 20:58
  • \$\begingroup\$ In the interactive scala REPL, yes. You may test it here simplyscala.com but have to replace readInt with a concrete number, online. \$\endgroup\$ Nov 29, 2011 at 22:39
2
\$\begingroup\$

PHP, 59 55 53 chars

for($i=0;$i++<$argv[1];)if($i==strrev($i))echo"$i\n";

Usage

php palindromic.php 500

Edit : thanks Thomas

\$\endgroup\$
1
  • \$\begingroup\$ you can remove the {s around the for loop and remove the space in echo "$i\n" to get echo"$i\n". That'll save you a few chars. Also, if you want to be cheeky you can change \n for ` ` and save a char. \$\endgroup\$ Aug 23, 2011 at 16:28
2
\$\begingroup\$

C, 98 characters

n,i,j,t;main(){for(scanf("%d",&n);i<=n;i-j?1:printf("%d ",i),i++)for(t=i,j=0;t;t/=10)j=j*10+t%10;}
\$\endgroup\$
2
\$\begingroup\$

k (23 chars)

{i@&{&/i=|i:$x}'i:!1+x}
\$\endgroup\$
2
\$\begingroup\$

Befunge, 97 (grid size 37x4=148)

#v&#:< ,*25-$#1._.@
:>:::01-\0v >-!#^_$1-
*\25*/:!#v_::1>\#* #*25*#\/#$:_$\25*%
   `-10:\<+_v#

Have a better Befunge answer to this question. This is Befunge-93 specifically; I could probably make it even more compact with Befunge-98. I'll include that in a future edit.

Since you can't operate on strings in Befunge, the best I could do was compute the digit-reverse of each number (which I'm surprised I was able to manage without p and g) and compare it to the original number. The digit-reverse takes up most of the code (basically the entire third and fourth lines).

Note that the program, as it stands now, prints the numbers backwards from the input down to 0. If this is a big deal, let me know. (The challenge only says to enumerate them, not specifically in increasing order.)

\$\endgroup\$
1
  • \$\begingroup\$ +1. Lines can be closed by \n alone, so it's 94 bytes long. I don't think your "grid size" has any particular relevance. \$\endgroup\$
    – alephreish
    Nov 7, 2014 at 11:24
2
\$\begingroup\$

PHP, 64 58 bytes

for($i=0;$i<=$argv[1];print$i==strrev($i)?$i.'\n':'',$i++)

Changed $_GET['n'] to $argv[1] for command line input.

\$\endgroup\$
2
\$\begingroup\$

Perl 5, 24 bytes

map$_-reverse||say,0..<>

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Jelly, 5 bytes

ŻŒḂƇY

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Unfortunately, this doesn't join the output list on newlines. I hope it doesn't cost any extra bytes to fix this. \$\endgroup\$
    – lyxal
    Feb 14, 2021 at 2:23
  • 1
    \$\begingroup\$ @Lyxal Unsurprisingly, it does. Stupid older challenges and their crappy I/O formats \$\endgroup\$ Feb 14, 2021 at 2:27
2
\$\begingroup\$

05AB1E, 5 bytes

ƒNÂQ–

Explanation:

ƒ      # For N in range(0, input() + 1)
 N     #   Push N
  Â    #   Bifurcate (pushes N and N[::-1])
   Q   #   Check for equality
    –  #   If true, pop and print N

Uses CP-1252 encoding. Try it online!.

\$\endgroup\$
2
  • \$\begingroup\$ LʒÂQ is 4, non-competing still though.. \$\endgroup\$ Oct 24, 2017 at 17:49
  • \$\begingroup\$ @MagicOctopusUrn That doesn't work, as it uses the range \$1-n\$, not \$0-n\$. Also, it outputs a list, not numbers on separate lines. \$\endgroup\$
    – Makonede
    Feb 8, 2021 at 16:55
1
\$\begingroup\$

Python

n=raw_input('')
for a in range(0,int(n)+1):
    r=str(a)
    if str(a)==r[::-1]:
        print r
\$\endgroup\$
4
  • \$\begingroup\$ Hmm...232 characters is not really very competitive. Perhaps you could reduce the variable names to one character and delete the spaces between the variables and operators? \$\endgroup\$
    – Gareth
    Nov 25, 2011 at 15:34
  • \$\begingroup\$ Good job. Some good tips for golfing Python can be found in this question: codegolf.stackexchange.com/questions/54/… \$\endgroup\$
    – Gareth
    Nov 25, 2011 at 15:48
  • \$\begingroup\$ You can get rid of n --just replace int(n) by int(raw_input())-- and you can change str(a) to r in the if statement \$\endgroup\$
    – Omar
    Nov 29, 2011 at 20:49
  • 1
    \$\begingroup\$ @Omar that can be golfed even more. int(raw_input()) can be just input(), the 0, in the range is unnecessary, and you can use a map to map str over the range instead of using r. Also, the print statement can be on the same line as the if statement, and indentation can be a single space. This saves a whole 38 bytes. Try it online! \$\endgroup\$
    – Makonede
    Feb 8, 2021 at 17:05
1
\$\begingroup\$

Groovy, 83

System.in.eachLine{(0..it.toInteger()).each{if("$it"=="$it".reverse())println(it)}}
\$\endgroup\$
1
\$\begingroup\$

Q (34 chars)

Pass n rather than n+1 as an argument for this Q solution.

{i(&)({all i=(|)i:($)x}')i:(!)1+x}
\$\endgroup\$
1
\$\begingroup\$

Q,32

{a(&)a~'((|:)')a:((-3!)')(!)1+x}
\$\endgroup\$
1
\$\begingroup\$

Q (33)

{if[x="I"$(|:) -3!x;:x]} each til

Probably a neater way to do this but anyway, sample usage (you enter n+1 to get to n):

q){if[x="I"$(|:) -3!x;:x]} each til  10
0 1 2 3 4 5 6 7 8 9

Suggestion by tmartin, gets it down to 29:

({$[x="I"$(|:) -3!x;x;]}')(!)

Same usage.

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

Python, 106 characters

import sys as a
print(type(a.argv[1]))
for x in range(int(a.argv[1])+1):
 x=str(x)
 if x==x[::-1]:print(x)

usage:

python a.py 500
\$\endgroup\$
1
1
\$\begingroup\$

C# (217 214 191 chars)

Golfed version:

using System;using System.Linq;class P{static void Main(){int n=int.Parse(Console.ReadLine());do{var t=(n+"").ToArray();Array.Reverse(t);Console.Write(n+""==new string(t)?n+"\n":"");}while(n-->0);Console.ReadLine();}}

Readable:

using System;
using System.Linq;
class P
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        do
        {
            var t = (n + "").ToArray();
            Array.Reverse(t);
            Console.Write(n + "" == new string(t) ? n + "\n" : "");
        } while (n-->0);

        Console.ReadLine();
    }
}

This prints out palindromes in descending order making use of the n-->0 operator. (as n goes to 0).

*Edited version replaces do...while with while, saving 3 chars, but now you must input with n+1.

using System;using System.Linq;class P{static void Main(){int n=int.Parse(Console.ReadLine());while(n-->0){var t=(n+"").ToArray();Array.Reverse(t);Console.Write(n+""==new string(t)?n+"\n":"");}Console.ReadLine();}}

*edited: found a better way to reverse string without converting to array:

using System;using System.Linq;class P{static void Main(){int n=int.Parse(Console.ReadLine());while(n-->0)Console.Write(n+""==string.Join("",(""+n).Reverse())?n+"\n":"");Console.ReadLine();}}

Readable:

using System;
using System.Linq;
class P
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        while (n-->0)
            Console.Write(n + "" == string.Join("", ("" + n).Reverse()) ? n + "\n" : ""); 
        Console.ReadLine();
    }
}
\$\endgroup\$

Your Answer

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

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