Print the Nth non-palindromic number

22

3

A palindromic number (in case you don't know) is a number which reads the same backwards and forwards (example, 11). The first 15 non-palindromic numbers are: 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26. This is A029742. I constantly need these numbers, but my sticky note pad is very small, so your code must be as short as possible.

Rules

  • Each submission must be a full program or function (e.g. in C, you can't just define a function without headers, but you can define a function WITH necessary headers ).
  • If it is possible, provide a link to a site where your program can be tested.
  • Your program must not write anything to STDERR.
  • You can take input as an argument or from STDIN (or the closest alternative in your language).
  • Programs are scored according to bytes. The usual character set is UTF-8, if you are using another please specify.
  • Standard loopholes are forbidden.

Test Cases

1
==> 10

-----

5
==> 15

-----

12
==> 23

Scoring

This is , so least bytes wins.

Submissions

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:

# [><>](http://esolangs.org/wiki/Fish), 121 bytes

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 79251; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();
    
    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>

George Gibson

Posted 2016-05-03T15:11:00.510

Reputation: 2 369

1Any testcases ? – Leaky Nun – 2016-05-03T15:17:45.187

@KennyLau I'll do some. – George Gibson – 2016-05-03T15:18:53.847

Can we use a 0-based index, so 15 would be the 4th number? – nimi – 2016-05-03T15:58:12.330

@nimi Either, but please specify if yours is 0-indexed. – George Gibson – 2016-05-03T16:29:29.857

@nimi Sorry, that's what I meant, have edited to clarify. – George Gibson – 2016-05-03T16:34:23.030

Any restriction on completion time? – cat – 2016-05-04T03:57:34.780

@cat I guess not, as long as it completes... – George Gibson – 2016-05-04T06:24:31.890

Answers

9

Pyth, 7 bytes

e.f!_I`

Test suite

Explanation:

e.f!_I`
e.f!_I`ZQ    Implicit variable introduction.
 .f     Q    Find the first Q numbers whether the following is truthy,
             starting at 1, where Q is the input.
      `Z     Convert the number to a string.
     _I      Check if it's the same when reversed.
    !        Logical not.
 e           Return the last element of the list.

isaacg

Posted 2016-05-03T15:11:00.510

Reputation: 39 268

5

Haskell, 38 bytes

([x|x<-[1..],(/=)<*>reverse$show x]!!)

Uses 0-based index. ([x|x<-[1..],(/=)<*>reverse$show x]!!) 11 -> 23.

The test whether to keep a number (/=)<*>reverse$show x translates to (show x) /= (reverse (show x)), i.e check if the string representation of the number does not equal the reverse of the string representation.

nimi

Posted 2016-05-03T15:11:00.510

Reputation: 34 639

4

Brachylog, 14 11 bytes

;0{<≜.↔¬}ⁱ⁽

-3 bytes tanks to Fatalize

Explanation

; {      }ⁱ⁽        --  Find the nth number
 0                  --      (starting with 0)
   <                --      which is bigger then the previous one
    ≜               --      make explicit (otherwise it fucks up)
      .             --      which is the output
       ↔            --      and if reversed
        ¬           --      is not the output

Try it online!

Kroppeb

Posted 2016-05-03T15:11:00.510

Reputation: 1 558

;İ{ℕ≜.↔¬}ᶠ⁽t is 2 bytes shorter. – Fatalize – 2018-08-22T07:06:48.370

Actually, using iterate is 1 byte shorter: ;0{<≜.↔¬}ⁱ⁽ – Fatalize – 2018-08-22T07:09:20.390

3

Jelly, 9 bytes

1 bytes thanks to @Sp3000.

ṚḌ_
0dz#Ṫ

Try it online!

Test suite.

Explanation

DUḌ_   Helper link. Check if x is not palindrome.

D      Convert to decimal.
 U     Reverse.
  Ḍ    Convert back to integer.
   _   Subtract x from the result above.
       For 23, this will yield 32-23 = 9.
       Only yield 0 (falsy) if x is palindrome.
       If x is not a palindrome,
       it will return a truthy number.


0dz#Ṫ  Main link.

0      Start from 0.
   #   Find the first         numbers:
  ³                   <input>
 Ç         where the above link returns a truthy number.
    Ṫ  Yield the last of the matches.

Leaky Nun

Posted 2016-05-03T15:11:00.510

Reputation: 45 011

1Fun fact: try 123Ṛ – Sp3000 – 2016-05-03T15:47:36.667

@Sp3000 Very interesting indeed! – Leaky Nun – 2016-05-03T15:53:39.980

You can drop the ³. If you place the input on STDIN, you can drop the 0 as well. (In the latest version of Jelly, ṚḌ_ø#Ṫ works too, but it is newer than this challenge.) – Dennis – 2016-05-03T18:26:37.450

Doesn't work for me... – Leaky Nun – 2016-05-03T23:03:17.343

7 bytes but it may use newer features – caird coinheringaahing – 2017-11-02T22:24:10.200

3

05AB1E, 8 bytes

Code:

µNÂÂQ>i¼

Uses CP-1252 encoding. Try it online!.

Adnan

Posted 2016-05-03T15:11:00.510

Reputation: 41 965

This has most likely something to do with the old version of 05AB1E, but out of curiosity: why the double bifurcated Â? PS for anyone else reading this: Can now be 5 bytes µNÂʽ.

– Kevin Cruijssen – 2018-08-21T14:31:28.657

@KevinCruijssen: Likely due to no implicit output of N (only top of stack). Also, it can be 4 bytes now as the ½ is also implicit. – Emigna – 2018-08-21T16:02:38.247

@Emigna Ah, completely forgot about ½ being implicit, even though I mentioned it in a tip I wrote myself.. >.< Thought the ¼ (increase counter_variable by 1) was implicit for the while-loop µ for a moment, but it's indeed the ½ (if top of the stack is 1: increase counter_variable by 1) instead..

– Kevin Cruijssen – 2018-08-21T17:54:01.687

3

Clojure, 62 bytes

#(nth(for[i(range):when(not=(seq(str i))(reverse(str i)))]i)%)

0-indexed. Generate lazily infinite range of non-palindromic numbers using list comprehension and take ith one. See it online: https://ideone.com/54wXI3

cliffroot

Posted 2016-05-03T15:11:00.510

Reputation: 1 080

2

Clojure, 62 bytes

#(nth(filter(fn[i](not=(seq i)(reverse i)))(map str(range)))%)

A quite different approach than the other answer, but equal length.

NikoNyrh

Posted 2016-05-03T15:11:00.510

Reputation: 2 361

2

Forth (gforth), 103 99 bytes

: f 9 swap 0 do begin 1+ dup 0 over begin 10 /mod >r swap 10 * + r> ?dup 0= until = 0= until loop ;

Try it online!

Explanation

Loop n times, each iteration finds the next non-palindromic number by incrementing a counter by 1 until the number doesn't equal itself reversed

Ungolfed Code

Normally I wouldn't "ungolf" the code, but since this code is somewhat messy I figured it would help

: reverse ( s -- s )
    0 swap 
    begin 
        10 /mod
        >r swap
        10 * +
        r> ?dup 0=
    until 
; 

: f ( s -- s )
    9 swap 0
    0
    do
        begin
            1+ dup dup
            reverse =
        0= until
    loop
;

Code Explanation

: f                \ start a new word definition
  9                \ start at 9, since all positive ints < 10 are palindromic
  swap 0           \ set up loop parameters from 0 to n-1
  do               \ start a counted loop       
    begin          \ start an indefinite loop
      1+ dup       \ increment counter and place a copy on the stack
      ( Reverse )
      0 over       \ add 0 to the stack (as a buffer) and copy the top counter above it
      begin        \ start another indefinite loop
        10 /mod    \ get the quotient and remainder of dividing the number by 10
        >r         \ store the quotient on the return stack
        swap 10 *  \ multiply the current buffer by 10
        +          \ add the remainder to the buffer
        r>         \ grab the quotient from the return stack
        ?dup       \ duplicate if not equal to 0
        0=         \ check if equal to 0
      until        \ end inner indefinite loop if quotient is 0
      ( End Reverse )
      = 0=         \ check if counter =/= reverse-counter            
    until          \ end the outer indefinite loop if counter =/= reverse-counter
  loop             \ end the counted loop
;                  \ end the word definition 

reffu

Posted 2016-05-03T15:11:00.510

Reputation: 1 361

2

R, 133 117 93 76 bytes

-16 bytes thanks to JayCe. -41 bytes thanks to Giuseppe.

x=scan();while({F=F+any((D=T%/%10^(1:nchar(T)-1)%%10)!=rev(D));F<=x})T=T+1;T

Try it online!

Robert S.

Posted 2016-05-03T15:11:00.510

Reputation: 1 253

1

You can some some bytes abusing F, etc.: TIO. Also, why are you restricting the loop to (0:97)+10 ?

– JayCe – 2018-08-21T19:13:54.153

1

use tip #3 from my answer Tips for Golfing in R to extract the digits; you can do all(D==rev(D)) where D is a vector of digits. I believe a while loop will be shorter, and as @JayCe asks, why are you only checking numbers between 10 and 107?

– Giuseppe – 2018-08-21T20:01:26.687

@Giuseppe Updated with your recommendations. Still a little confused on how to implement a while loop while at the same time saving bytes. – Robert S. – 2018-08-21T22:09:13.517

1

@RobertS. if you have any questions, feel free to ping me in the R chatroom!

– Giuseppe – 2018-08-22T14:38:49.457

2

PowerShell v2+, 65 bytes

for(;$j-lt$args[0]){if(++$i-ne-join"$i"["$i".length..0]){$j++}}$i

Loops through numbers from 0 (implicit value for uninitialized $i) until we find input $args[0] many matches, then outputs the last one. Note that we don't initialize the loop, so $j=0 is implicit.

Each iteration, we pre-increment $i, and check if it's not-equal to $i reversed. If so, that means we've found a non-palindrome, so increment $j. The loop then continues as many times as necessary.

Examples

PS C:\Tools\Scripts\golfing> .\print-nth-palindromic-number.ps1 100
120

PS C:\Tools\Scripts\golfing> .\print-nth-palindromic-number.ps1 5
15

PS C:\Tools\Scripts\golfing> .\print-nth-palindromic-number.ps1 55
70

PS C:\Tools\Scripts\golfing> .\print-nth-palindromic-number.ps1 212
245

AdmBorkBork

Posted 2016-05-03T15:11:00.510

Reputation: 41 581

2

Python 2, 60 bytes

f=lambda n,i=0,j=1:j>n and i-1or f(n,i+1,j+(`i`!=`i`[::-1]))

A one-indexed function that takes input of n via argument and returns the nth non-palindromic number.

How it works

This is an exhaustive recursive search, which consecutively tests integers i in the range [1,∞) until n non-palindromic numbers have been found; since i is pre-incremented, i-1 is then returned. Testing whether a number is palindromic is performed by converting to a string, reversing, and then checking whether the original and reversed strings are equal.

The code is logically equivalent to:

def f(n,test=0,count=1):
    if count>n:
        return test
    elif str(test)!=reversed(str(test)):
        return f(n,test+1,count+1)
    else:
        return f(n,test+1,count)

which itself is essentially:

def f(n):
    test=0
    count=1
    while count<=n:
        if str(test)!=reversed(str(test)):
            count+=1
        test+=1
    return test-1

Try it on Ideone

TheBikingViking

Posted 2016-05-03T15:11:00.510

Reputation: 3 674

1

APL NARS 35 chars

r←v a;c
r←c←0
A:r+←1⋄c+←r≠⍎⌽⍕r⋄→A×⍳c<a

it is the function v; "⍎⌽⍕"r traslate number r in string, reverse that string, traslate from string to number. Test and help functions:

  ⍝ return the one string for the basic types ('Char', 'Int', 'Float', 'Complex or Quaternion or Oction')
  ⍝ or one string for composite types ('Tensor 3' 'Tensor 4' etc 'Matrix', 'List', 'String')
  ⍝ follow the example in: https://codegolf.stackexchange.com/a/39745
  type←{v←⍴⍴⍵⋄v>2:'Tensor ',⍕v⋄v=2:'Matrix'⋄(v=1)∧''≡0↑⍵:'String'⋄''≡0↑⍵:'Char'⋄v=1:'List'⋄⍵≢+⍵:'Complex or Quaternion or Oction'⋄⍵=⌈⍵:'Int'⋄'Float'}
  h←{'Int'≢type ⍵:¯1⋄(⍵<1)∨⍵>2e5:¯1⋄v ⍵} 
  h 1
10
  h 1.32
¯1
  h 7878
8057
  h¨3 5 12
13 15 23 
  h 6 7 8
¯1
  h '123'
¯1
  h '1'
¯1
  h 1.0
10
  h 1.0003
¯1
  h ¯2
¯1
  h 0
¯1
  h 200000
201200
  h 200001
¯1

RosLuP

Posted 2016-05-03T15:11:00.510

Reputation: 3 036

1

Japt, 14 12 11 10 9 bytes

1-indexed

@UµX¦sw}f

Try it

Shaggy

Posted 2016-05-03T15:11:00.510

Reputation: 24 623

1

Husk, 6 bytes

Yay for :)

!fS≠↔N

Try it online!

Explanation

 f   N  -- filter the naturals by:
  S≠    --   is it not equal to..
    ↔   --   ..itself reversed
!       -- index into that list

ბიმო

Posted 2016-05-03T15:11:00.510

Reputation: 15 345

1

Perl 5, 33 + 1 (-p) = 34 bytes

map{1until++$\!=reverse$\}1..$_}{

Try it online!

Xcali

Posted 2016-05-03T15:11:00.510

Reputation: 7 671

1

C# 7, 89 bytes

n=>{int i=9;for(;n-->0;)if(Enumerable.SequenceEqual(++i+"",(""+i).Reverse()))i++;return i;}

1 indexed Try on Repl.It

n=>
  int i = 9;                                  | Start at 9. Iterate exactly n times. Assume n >= 1      
  for(;n-->0;)                                | Iterate n times
  if(EnumerableSequenceEqual(                 | Compare two sequences
  ++i+"",(""+i).Reverse())                    | Generate the forward and backward strings, which behave like char sequences for Linq
  i++                                         | If the sequences are equal, the number is a palindrome. Increment i to skip
  return i;                                   | Return the number after the for loop exits

I don't think this uses any language features from c# 7, but I put there since that's what I tested against

ryzngard

Posted 2016-05-03T15:11:00.510

Reputation: 11

Welcome to PPCG. – Jonathan Frech – 2018-08-22T00:34:58.323

1

Perl 6, 29 bytes

{grep({$_!= .flip},^Inf)[$_]}

( uses 0 based index )

{         # The $_ is implied above
  grep(   # V
    { $_ != $_.flip }, # only the non-palindromic elements of
    ^Inf               # an Infinite list ( 0,1,2,3 ...^ Inf )
  )[ $_ ]              # grab the value at the given index
}

Usage:

my &non-palindrome = {grep({$_!= .flip},^Inf)[$_]}

say non-palindrome 1  - 1; # 10
say non-palindrome 5  - 1; # 15
say non-palindrome 12 - 1; # 23

# this also works:
say non-palindrome 0..20;
# (10 12 13 14 15 16 17 18 19 20 21 23 24 25 26 27 28 29 30 31 32)

Brad Gilbert b2gills

Posted 2016-05-03T15:11:00.510

Reputation: 12 713

1

Actually, 17 bytes

;τR9+;`$;R=Y`M@░E

Try it online!

Values are 1-indexed. This could be easily changed to 0-indexed by replacing the first R with r. But, R is what I initially typed, so that's what I'm going with.

The nonpalindromic numbers satisfy a(n) ≈ n + 10, so 2n+9 is a sufficient upper bound.

Explanation:

;τR9+;`$;R=Y`M@░E
;τ9+R;             push n, range(1,(2*n)+10)
      `$;R=Y`M@░   take values that are not palindromic
                E  take nth element

Mego

Posted 2016-05-03T15:11:00.510

Reputation: 32 998

1

JavaScript (ES6), 54 bytes

Uses 1-based indexing. Only works up until the 7624th number.

d=(i,a=0)=>i?d(i-=++a!=[...''+a].reverse().join``,a):a

Usage

d=(i,a=0)=>i?d(i-=++a!=[...''+a].reverse().join``,a):a
d(1)
10
d(123)
146
d(7624)
7800
d(7625)
// Uncaught RangeError: Maximum call stack size exceeded

JavaScript (ES6), 59 bytes

Doesn't use recursion and so can handle much larger inputs.

i=>eval("for(a=9;i-=++a!=[...`${a}`].reverse().join``;);a")

Usage

(i=>eval("for(a=9;i-=++a!=[...`${a}`].reverse().join``;);a"))(1)
10
(i=>eval("for(a=9;i-=++a!=[...`${a}`].reverse().join``;);a"))(7625)
7801
(i=>eval("for(a=9;i-=++a!=[...`${a}`].reverse().join``;);a"))(123456)
124579

Dom Hastings

Posted 2016-05-03T15:11:00.510

Reputation: 16 415

1

Java 8, 117 95 94 bytes

n->{int r=10;for(;n-->0;)if((++r+"").contains(new StringBuffer(r+"").reverse()))r++;return r;}

0-indexed

Explanation:

Try it here.

n->{             // Method with integer as both parameter and return-type
  int r=10;      //  Result-integer, starting at 10
  for(;n-->0;)   //  Loop an amount of times equal to the input
    if((++r+"")  //   First raise `r` by 1, and then check if `r`
               .contains(new StringBuffer(r+"").reverse()))
                 //   is the same as `r` reversed (and thus a palindrome)
      r++;       //    And if it is: raise `r` by 1 again
  return r;}     //  Return result-integer

Kevin Cruijssen

Posted 2016-05-03T15:11:00.510

Reputation: 67 575

@ceilingcat That gives incorrect results.. new StringBuffer(int) is not equal to new StringBuffer(String), nor is String.equals(StringBuffer) instead of String.equals(String).. This is an old answer however, so I can use (++r+"").contains(new StringBuffer(r+"").reverse()) to save 1 byte. – Kevin Cruijssen – 2019-01-03T09:13:20.847

1

Ruby, 54 bytes

This function is 1-indexed and is partially based on Dom Hastings's Javascript answer. I think there's a way to golf this better, especially with that last ternary condition. Also, this function currently returns a string, which may need to be edited later. Any golfing suggestions are welcome.

f=->x,y=?9{x<1?y:(y.next!.reverse!=y)?f[x-1,y]:f[x,y]}

Ungolfed:

def f(x, y="9")
 if x<1
  return y
 else
  y = y.next
  if y.reverse != y
   return f(x-1, y)
  else
   return f(x, y)
  end
 end
end

Sherlock9

Posted 2016-05-03T15:11:00.510

Reputation: 11 664

1

Javascript (using external library) (97 bytes)

n=>_.Sequence(n,i=>{i=_.From(i+"");if(!i.Reverse().SequenceEqual(i)){return i.Write("")}}).Last()

Link to lib: https://github.com/mvegh1/Enumerable

Code explanation: Library has static method called Sequence, where first param defines how many elements the sequence will guarantee to create, and the 2nd parameter is a predicate accepting the current iteration value, "i". The predicate converts the integer to a string, which gets converted to a char array by calling _.From. The char array is compared against the reversal of the char array, and if they are not equal the char array is joined back into a string and returned. Otherwise, nothing is returned (i.e the result is undefined, which the library will always ignore). Finally, the last element of the sequence, i.e the Nth element is returned

enter image description here

applejacks01

Posted 2016-05-03T15:11:00.510

Reputation: 989

1

C++ (GCC), 148 bytes

It's 1-based and the algorithm is really naive

#import <iostream>
using namespace std;int n,i=1;string s;main(){cin>>n;while(s=to_string(i+1),(n+=equal(begin(s),end(s),s.rbegin()))-i++);cout<<i;}

FoxyZ

Posted 2016-05-03T15:11:00.510

Reputation: 81

@enedil regarding your edit: #import is an compiler extension of gcc. It is deprecated, but this doesn't really matter here – ovs – 2017-12-08T13:55:24.430

1

C, 84 bytes

Function f(n) takes integer n and returns n-th non-palindromic number (1 based).

g(n,r){return n?g(n/10,r*10+n%10):r;}s;f(n){for(s=9;n--;g(++s,0)==s&&s++);return s;}

Test it on Ideone!

It's fairly trivial code, thus there is probably space for improvement.

Jasmes

Posted 2016-05-03T15:11:00.510

Reputation: 131

Suggest n=n?g(n/10,r*10+n%10):r;}s;f(n){for(s=9;n--;g(++s,0)-s||s++);n=s; instead of return n?g(n/10,r*10+n%10):r;}s;f(n){for(s=9;n--;g(++s,0)==s&&s++);return s; – ceilingcat – 2019-01-02T22:36:07.527

-2

TCC, 11 bytes

?>!~<>;i;'T

Try it online!

            | Printing is implicit
?>          | Find n-th number for which the following is "T":
  !~        | If not equal...
    <>;     | reverse. No value specified, so input is assumed.
       i;   | Input, since double semicolons are ignored
         'T | ... print string "T"

brianush1

Posted 2016-05-03T15:11:00.510

Reputation: 300

1This does not work with the tcc.lua file with timestamp 16-07-26 12:46 UTC, which didn't have the ?> command. If your answer requires a version of the language that postdates the challenge, you must label it as non-competing in the header. I'll remove my downvote when you do. – Dennis – 2016-07-26T17:07:44.070

@Dennis I stumbled over this two year old post and wanted to mention that answers are now no longer to be marked non-competing when their language post-dates the challenge. – Jonathan Frech – 2018-08-21T14:38:16.663