Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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.

share|improve this question
2  
Between 1 and n (as per title) or 0 and n (as per body)? And which of the bounds does "between" include? –  Peter Taylor Aug 23 '11 at 11:45
    
Corrected now. Thanks! –  Wok Aug 23 '11 at 11:46
    
@wok: You still haven't answered if it's inclusive or exclusive range? Is n part of the range to include? –  mellamokb Aug 23 '11 at 15:09
    
@mellamokb Inclusive range. –  Wok Aug 23 '11 at 15:15

33 Answers 33

up vote 6 down vote accepted

Golfscript, 15 chars

~),{.`-1%~=},n*
share|improve this answer
    
You may save a char comparing strings instead of numbers '~),{`.-1%=},n*'. –  Howard Oct 28 '12 at 9:09
    
@Howard, if you want to post that yourself I'll upvote it. –  Peter Taylor Oct 28 '12 at 15:32
    
That would feel like plain copying ;-) –  Howard Oct 29 '12 at 12:53

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.

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

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.

share|improve this answer

Perl 5.10 - 27 characters

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

Reads the argument from stdin.

share|improve this answer

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}
share|improve this answer
    
Rohit proposed saving 3 characters in each of these by using p instead of puts. –  Peter Taylor May 23 '12 at 9:20
    
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. –  Rohit May 23 '12 at 9:29
    
@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. –  Ventero May 23 '12 at 14:18

J, 20 characters

(#~(-:|.)@":"0)>:i.n
share|improve this answer
    
I can read it!:) Nice –  mlatu Aug 17 '12 at 8:54
    
btw, to meet a requirement output numbers one per line you should add ,"0. –  mlatu Aug 17 '12 at 10:22

Python, 57 51 chars

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

Usage:

echo 500 | python palindromic.py
share|improve this answer
3  
Shorter: for i in range(input()):if`i`==`i`[::-1]:print i –  Steven Rumbalski Aug 23 '11 at 14:42
    
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). –  Bakuriu Mar 26 '13 at 19:13
    
The range should be inclusive. And i think you can change you byte count to 50 (linebreaks are shorter on linux). –  malkaroee Nov 5 at 18:04

Perl > 5.10 : 25 characters

map$_==reverse&&say,0..<>
share|improve this answer

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.

share|improve this answer

APL (25 17)

↑t/⍨t≡∘⌽¨t←⍕¨0,⍳⎕
share|improve this answer

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"));
share|improve this answer
    
Well, for starters the vars are unneeded, you can just make things global. Also prompt() doesn't strictly need parameters. –  Clueless Aug 23 '11 at 14:27
    
thanks. :) brought down to 108. :) –  Thomas Clayson Aug 23 '11 at 14:51
    
However, you can use parameters to prompt() to save one semicolon: n=prompt(o=[]);. –  mellamokb Aug 23 '11 at 15:01
1  
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. –  mellamokb Aug 23 '11 at 17:21
1  
alert(o.join(" ")) needs to be alert(o.join("\n")) according to the specs. Add 1 to your character count when you fix this. –  Thomas Eding Aug 23 '11 at 18:02

PHP 64 58

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

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

share|improve this answer

Scala 59

(0 to readInt)filter(x=>""+x==(""+x).reverse)mkString("\n")
share|improve this answer
    
I don't know any Scala, but does that really print on stdout? I would've guessed it's an expression returning a string. –  Omar Antolín-Camarena Nov 29 '11 at 20:58
    
In the interactive scala REPL, yes. You may test it here simplyscala.com but have to replace readInt with a concrete number, online. –  user unknown Nov 29 '11 at 22:39

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

share|improve this answer
    
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. –  Thomas Clayson Aug 23 '11 at 16:28

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;}
share|improve this answer

k (23 chars)

{i@&{&/i=|i:$x}'i:!1+x}
share|improve this answer

Mathematica 61

Column@Select[0~Range~Input[],#==Reverse@#&@IntegerDigits@#&]
share|improve this answer

Haskell 66 characters

main=do n<-readLn;mapM_ putStrLn[s|s<-map show[0..n],s==reverse s]
share|improve this answer
    
Misspelled the language name... –  eternalmatt Sep 1 '11 at 16:37
    
Fixed (filler chars) –  Thomas Eding Sep 1 '11 at 18:03

Python

n=raw_input('')
for a in range(0,int(n)+1):
    r=str(a)
    if str(a)==r[::-1]:
        print r
share|improve this answer
    
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? –  Gareth Nov 25 '11 at 15:34
    
Thanks for suggestion. I could make it a bit shorter –  user1027046 Nov 25 '11 at 15:39
    
Good job. Some good tips for golfing Python can be found in this question: codegolf.stackexchange.com/questions/54/… –  Gareth Nov 25 '11 at 15:48
    
Thanks for the link Gareth. Its really excellent. –  user1027046 Nov 25 '11 at 16:07
    
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 –  Omar Antolín-Camarena Nov 29 '11 at 20:49

Groovy, 83

System.in.eachLine{(0..it.toInteger()).each{if("$it"=="$it".reverse())println(it)}}
share|improve this answer

Q (34 chars)

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

{i(&)({all i=(|)i:($)x}')i:(!)1+x}
share|improve this answer

Q,32

{a(&)a~'((|:)')a:((-3!)')(!)1+x}
share|improve this answer

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.

share|improve this answer

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
share|improve this answer

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();
    }
}
share|improve this answer

PHP 53

Can 53 be any lower? Four different options:

for($i=$argv[1];$i-->0;)echo$i==strrev($i)?"$i\n":"";
for($i=$argv[1];$i-->0;)if($i==strrev($i))echo"$i\n";
while(($i=$argv[1]--)>0)echo$i==strrev($i)?"$i\n":"";
while(($i=$argv[1]--)>0)if($i==strrev($i))echo"$i\n";

If you want to get funky...

PHP 47

while(($i=$argv[1]--)>0)if($i==strrev($i))`$i`;

You have to ignore the error text. The palindrome numbers are still output to the command line, however.

share|improve this answer

Pyth, 11

VhQIq`N_`NN

Example:

$ pyth -c 'VhQIq`N_`NN' <<< 200
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
share|improve this answer

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.)

share|improve this answer
    
+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. –  har-wradim Nov 7 at 11:24

Burlesque, 13

rz{J<-==}f[p^

Burlesque has some useful commands for golfing, in this case <- reverses anything you put before it.

          rz             creates a range from 0 to input
            {            start of filtering (discards any element not returning 1) the created range
              J <- ==    duplicates element, reverses duplicate, compare
            }f[          end filtering, now we're left with a block of palindromic integer which
            p^           takes care of, and outputs the numbers as desired.

Try it here The linked example has 1000 as input, change it to see more or fewer palindromic numbers.

share|improve this answer
1  
How does your script accept the input? In your example it seems to be part of the script itself. –  har-wradim Nov 7 at 11:06
    
@har-wradim Burlesque takes input the same way as Golfscript does. Meaning that input is placed on the stack before the program code. [input][code]. In my program above input can be any positive number (the linked example has 1000 for input), which will be followed by the code rz{J<-==}f[p^ You can change the 1000 to 10 000 or 100 000 and the code will run all the palindromic number up until the input value. –  AndoDaan Nov 10 at 5:42
    
GolfScript is expected to push what comes from stdin on top of the stack by default. If this behavior is absent from the Burlesque specifications than your solution seems to violate one of the requirements. –  har-wradim Nov 10 at 17:00
    
@har-wradim As does Burlesque. I linked to the online shell for ease of access, but feel free to download and compile the Burlesque source code to check the different ways it can read input. –  AndoDaan Nov 11 at 4:20
    
@har-wradim wait, it's because I put [Input n] in my explenation, isn't it? Solved! –  AndoDaan Nov 11 at 4:28

C++, 145 143

#include<iostream> 
int i,j,n,r;int main(){std::cin>>n;for(;i<=n;i++){j=i;while(j!=0){r=r*10;r=r+j%10;j=j/10;}if(i==r)std::cout<<i<<' ';r=0;}}

Alternative [143 too]:

#include<stdio.h>
int i,j,n,r;int main(){scanf("%d",&n);for(;i<=n;i++){j=i;while(j!=0){r=r*10;r=r+j%10;j=j/10;}if(i==r)printf("%d ", i);r=0;}}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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