title: Reverse a string by chunks

text:
# Question
Title: Reverse a string by chunks
Your task is to write a program which, given a number and a string, splits the string into chunks of that size and reverses them.

## Rules

Your program will receive a positive integer `n`, as well as a string `s` with length at least one consisting of only printable ASCII (not including whitespace). The string should then be split into chunks of length `n`, if the length of the string isn't divisible by `n` any leftover at the end should be considered its own chunk. Then, reverse the order of the chunks and put them together again.

## Test Cases

```
n   s           Output

2   abcdefgh    ghefcdab
3   foobarbaz   bazbarfoo
3   abcdefgh    ghdefabc
2   a           a
1   abcdefgh    hgfedcba
2   aaaaaa      aaaaaa
2   baaaab      abaaba
50  abcdefgh    abcdefgh
6   abcdefghi   ghiabcdef

```

This is , so you should aim for as few bytes as possible.

# Answer
# Jelly, 2 bytes

```
sṚ

```

A full program that prints the result.

**Try it online!**

### How?

```
sṚ - Main link: string, number                                   e.g. 'abcdefg', 3
s  - split string into chunks of length number (keeping any overflow) ["abc","def","g"]
 Ṛ - reverse the resulting list                                       ["g","def","abc"]
   - implicit print                                                   gdefabc

```
> 29 votes

# Answer
# Python 3, 35 bytes

```
f=lambda s,n:s and f(s[n:],n)+s[:n]

```

Try it online!
> 16 votes

# Answer
# 05AB1E, ~~5 4~~ 3 bytes

-1 thanks to Dennis
-1 thanks to carusocomputing

```
ôRJ

```

Try it online!

```
     # Implicit: push input
 ô   # Split in pieces of length b
  RJ # Reverse and join

```
> 9 votes

# Answer
## JavaScript (ES6), 37 bytes

```
n=>F=s=>s&&F(s.slice(n))+s.slice(0,n)

```

Takes input by currying: number first, then string, like `f(2)("abcdefgh")`.

```
let f =
n=>F=s=>s&&F(s.slice(n))+s.slice(0,n)

let g = (n, s) => console.log(`f(${n})("${s}"): ${f(n)(s)}`)

g(2, "abcdefgh")
g(3, "foobarbaz")
g(3, "abcdefgh")
g(2, "a")
g(1, "abcdefgh")
g(2, "aaaaaa")
g(2, "baaaab")
g(50, "abcdefgh")
```
> 8 votes

# Answer
# Perl 6,  ~~28~~  20 bytes

```
{$^b.comb($^a).reverse.join}

```

Try it

```
{[R~] $^b.comb($^a)}

```

Try it

## Expanded:

```
{  # bare block lambda with placeholder parameters ｢$a｣ and ｢$b｣
  [R[~]] # reduce the following using the reverse meta operator `R`
         # combined with the string concatenation operator

    # `comb` with a number splits the invocant into chunks of that size
    $^b.comb($^a)
}

```
> 7 votes

# Answer
# Bash + coreutils, 22

```
fold -$1|tac|tr -d \\n

```

Try it online.
> 7 votes

# Answer
# Haskell, 32 bytes

```
n#""=""
n#s=n#drop n s++take n s

```

Try it online!
> 7 votes

# Answer
# PHP, 53 Bytes

```
<?=join(array_reverse(str_split($argv[2],$argv[1])));

```
> 4 votes

# Answer
# Röda, 36 bytes

```
f n{[[_]..[try head n-1]]|reverse|_}

```

Try it online!

It's a function that takes one argument. The characters of the string must be in the stream.

`try` is used to discard errors in case that the `head` function can't read `n-1` values.

Explanation:

```
f n{[[_]..[try head n-1]]|reverse|_}
f n{                               } /* Function declaration */
                                     /* In a loop: */
      _                              /*   Pull one value */
           try head n-1              /*   Pull n-1 values (or less) */
     [ ]..[            ]             /*   Make an array */
    [                   ]            /*   Push it to the stream */
                         |reverse    /* Reverse all values in the stream */
                                 |_  /* Flat all arrays in the stream */
                                     /* Characters in the stream are printed */

```

Not as obfuscated as usually. I think it's quite beautiful. :)
> 4 votes

# Answer
# CJam, 5 bytes

```
q~/W%

```

Input is a number and a string enclosed in double quotes, separated by whitespace.

Try it online! Or verify all test cases.

### Explanation

```
q~   e# Read all input and evaluate: pushes a number and a string
/    e# Split string into chunks of that size. Last chunk may be
     e# smaller. Gives an array of strings
W%   e# Reverse the array. Implicitly display

```
> 4 votes

# Answer
## Batch, 74 bytes

```
@if %2=="" (echo %~3)else set s=%~2&call %0 %1 "%%s:~%1%%" "%%s:~,%1%%%~3"

```

Rather annoyingly this ends up being recursive rather than tail recursive.
> 4 votes

# Answer
# , ~~13~~ 10 bytes

```
òÀ|lDÏpòÍî

```

Try it online!

```
ò      ò    ' Recursively
 À|         ' Go to the "nth" column
   l        ' Move one character right (breaks loop when no more chunks)
    D       ' Delete from here to the end of the line
     Ï      ' Add a line above the current line (now contains one chunk)
      p     ' Paste the remainder of the line that was deleted
        Íî  ' Remove all newlines

```

In Action:

```
abcdefghijkl

```

turns into

```
efghijkl
abcd

```

which becomes

```
ijkl
efgh
abcd

```

before all newlines are removed
> 4 votes

# Answer
# PowerShell, ~~56~~ 49 bytes

-7 bytes thanks to mazzy

```
param($n,$s)$s-split"(.{$n})"-ne''|%{$r=$_+$r};$r

```

Try it online!
> 4 votes

# Answer
# brainfuck, 78 bytes

```
,<<<+[[>]>+>[[>],<[<]>+>-]<-[->>[>]>>+<<<[<]<]>>]<<<<[[<]>[-[+.[-]]+>]<[<]<<<]

```

The first byte of the input is the chunk size, given by byte value. The rest of the bytes are considered to be the string.

Try it online!

**Expanded and commented**

```
Read the chunk size byte
This cell will become a counter cell
,

Move left a few cells an increment;
this is to make the starting position
line up with the relative positioning
needed to fit in with the loop
<<<+

While the current cell is nonzero:
[

 Move right to the first zero cell
 [>]

 Move right once and increment and then move right to the counter cell
 The increment is required because of "move to zero cell" loops
 >+>

 This loop will store one chunk of the input in consecutive memory cells
 [
  [>]   Move right until a zero cell is hit
  ,     Store 1 byte of input there
  <[<]  Move back left until a zero cell (other than the current one) is hit
  >+>-  Increment the temporary cell by 1 and decrement the counter
 ] (end loop once the counter hits zero)

 Decrement the temp cell (because we needed to have 1 there initially to make the cell location work)
 <-

 Move the temp cell to three cells after the end of the chunk
 This is the new counter cell for the next chunk
 [->>[>]>>+<<<[<]<]

 Move two cells right from where the temp cell was
 This is the first cell of the chunk; if it's 0
 then the input is finished and the loop should end
 >>
]

Due to the way the counter is kept track of the tape head
will always be four cells to the right of the last input cell
when the loops breaks
<<<<

Now the chunks are printed one by one
At the start of an iteration the tape head is at the end of a chunk
[
 Locate the start of the last chunk
 [<]>

 Print the chunk:
 [
  Print the byte held in the current cell if it isn't 1
  This is necessary because we left a stray 1 in a cell at
  the start which shouldn't be printed
  -[+.[-]]+

  Move to the next cell
  >
 ]

 Move to just left of the chunk
 <[<]

 Move three cells over to the end of the next chunk
 <<<
]

```
> 4 votes

# Answer
# Mathematica, 46 bytes

```
""<>Reverse@Partition[Characters@#2,#,#,1,{}]&

```

Anonymous function. Takes a number and a string as input and returns a string as output. Not much to see here.
> 3 votes

# Answer
# Pyth, 5 bytes

```
s_c.*

```

Try it online.

### Explanation

```
   .*  splat implicit input
  c    split into chunks length n
 _     reverse
s      join

```
> 3 votes

# Answer
# **Javascript - ~~54~~ ~~47~~ 46 bytes**

Remade:

```
(s,n)=>s.match(eval(`/.{1,${n}}/g`)).reverse()

```

Used as

```
f=(s,n)=>s.match(eval(`/.{1,${n}}/g`)).reverse()
alert(f("abcdefgh",2));

```

Thank you to @ETHproductions for some RegEx quickenning Thank you to @Shaggy for an extra byte in the eval!

Original:

```
(s,n)=>s.match(new RegExp('.{1,'+n+'}','g')).reverse()

```
> 3 votes

# Answer
## Java, 147 138 Bytes

`String r(String s,int n){String r="";int l=s.length();for(int i=l/n*n;i>=0;i-=n)if(!(i>=l))r+=(i+n)>=l?s.substring(i):s.substring(i,i+n);return r;}`

Saved 9 Bytes thanks to Kevin Cruijssen!

```
String r(String s,int n){String r="";int l=s.length(),i=l/n*n;for(;i>=0;i-=n)if(i<l)r+=i+n>=l?s.substring(i):s.substring(i,i+n);return r;}

```

In expanded form:

```
String r(String s,int n){
    String r="";
    int l=s.length(),i=l/n*n;
    for(;i>=0;i-=n)
        if(i<l)
            r+=i+n>=l?s.substring(i):s.substring(i,i+n);
    return r;
}

```

This is actually my first try to codegolf ever, so any feedback is welcome!
> 3 votes

# Answer
# Retina, 38 bytes

*1 byte saved thanks to @LeakyNun*

```
^

+`(.* (1)+¶)((?<-2>.)+)
$3$1
 1+¶

```

(Note the space on the second line, and the trailing space)

This program takes input as unary on the first line, and the string on the second.

Try it online!

Test Suite! (slightly modified)

### Explanation

The first step is to prepend a space (will become important later on).

```
^

```

Now we reverse. This uses .NET's balancing groups. It is important to note that groups here act as stacks, so every match is essentially pushed onto the stack. Here we capture every digit in the unary number into group 2. Now each time a character in the string is found, a match is popped from group 2. This ensures the the number of characters does not exceed that of the unary number.

```
+`(.* (1)+¶)                       Capture the unary number in group 2
             ((?<-2>.)+)           Balancing group for substrings
$3$1                               Reverse

```

And finally remove the unary number and the newline.

```
 1+¶

```
> 3 votes

# Answer
# Perl 5, 25 bytes

Uses the `-lnM5.010` flags.

```
say reverse<>=~/.{1,$_}/g

```

Try it online!

Shoutout to Grinnz for telling me about `=~ m/.{1,$n}/g`

`-M5.010` enables the use of the `say` function, which for our purposes is print with a shorter name.

`-n` puts the first line of input into `$_`, and `-l` chomps off the trailing newline.

We then get the second line of input using `<>`, and apply it to the regex `.{1,$_}`: any character, between 1 and $\_ (the first input) times. Since this is greedy by default, it tries to always match $\_ characters. The `1,` is needed for the possible leftover chunk at the end.

The `/g` modifier gives us *every* match of that regex in the input string as a list, which is then reversed and printed. In Perl, passing a list to `say` joins it without any delimiter by default.
> 3 votes

# Answer
# Dyalog APL Extended, ~~16~~ 15 bytes

```
{∊⌽⍵⊂⍨(≢⍵)⍴=⍳⍺}

```

Try it online!
> 3 votes

# Answer
# Python, 62 bytes

```
lambda n,s:''.join([s[i:i+n]for i in range(0,len(s),n)][::-1])

```

Try it online!
> 2 votes

# Answer
# Stacked, 9 bytes

```
#<rev''#`

```

Try it online!

`#<` chunks, `rev` reverses, and `''#`` joins by empty string. Quite simple.
> 2 votes

# Answer
## QBIC, 24 bytes

```
:;[1,_lA|,a|Z=_sA,b,a|+Z

```

This makes excellent use of the new substring-function I recently added to QBIC:

```
:;          Read in the cmd line params a (number) and A$ (text)
[1,_lA|,a|  Set up a FOR loop: FOR b = 1; b <= A$.length; b += a
Z=          Modify Z$; Z$ is autoprinted at the end of QBIC code
_sA,b,a|    SUBSTRING: _s is the function followed by the string
               to take from, the starting pos and the # of chars
+Z          Take chunks from further into A$, put them before Z$

```
> 2 votes

# Answer
# Pyth, 4 bytes

```
s_cF

```

Takes input as `"s",n`: Try it for yourself!
> 2 votes

# Answer
# Convex, 2 bytes

Try it online!
> 2 votes

# Answer
# Scala, 57 55 bytes

```
(n:Int,s:String)=>(""/:s.grouped(n).toSeq.reverse)(_+_)

```

Thanks Jacob! Try it here.

Note: By using the symbol form of foldLeft ("/:"), I was able to take off a couple more bytes.
> 2 votes

# Answer
## C, 69 bytes

```
i;f(s,n)char*s;{i=strlen(s);for(i-=i%n;printf("%.*s",n,s+i),i;i-=n);}

```

Result is printed out to the standard output.
> 2 votes

# Answer
# Ohm, 5 bytes

```
σ]QWJ

```

Try it online!

### Explanation

```
σ]QWJ
σ         # Split input1 into input2 pieces
 ]        # Flatten array
  Q       # Reverses stack
   W      # Wraps stack to array
    J     # Joins stack
          # Implicit print

```
> 2 votes

# Answer
# APL (Dyalog Unicode), 14 bytesSBCS

```
∊∘⌽⊢⊂⍨⊢∘≢⍴1↑⍨⊣

```

Try it online!

Explanation:

```
∊∘⌽⊢⊂⍨⊢∘≢⍴1↑⍨⊣ ⍝ This is a giant composed function, made of all these pieces:
               ⍝ Left argument: ⍺, the split size (refered as ⊣)
               ⍝ Right argument: ⍵, the string (refered as ⊢)
          1↑⍨⊣ ⍝ Swapped operator ↑:
               ⍝     Start with a 1, then pads with `0` until size ⍺
      ⊢∘≢      ⍝ Get the tally (≢) composed with ⊢, gives the of length ⊢
         ⍴     ⍝ Reshape the list of 1 0 0... into the size of the string:
               ⍝     As opposed to ↑, this will repeat the sequence instead of padding with 0. Gives (1 0 0 1 0 0) for a string of length 6.
   ⊢⊂⍨         ⍝ Swapped operator ⊂:
               ⍝ Split the string at all the 1s
  ⌽            ⍝ Reverse the list
∊              ⍝ Enlist, flattens
 ∘             ⍝ (composition necessary for parsing precedence)

```

---

Works similarly to @dzaima's, though it took me a lot of attempts to get there.
> 2 votes

# Answer
# , ~~69~~ 60 bytes

```
function(s,n)cat(substring(s,(x=nchar(s):0*n)+1,x+n),sep="")

```

Try it online!

Thanks to Kirill L. for the suggestion to remove `seq`.
> 2 votes

# Answer
# PHP, 78 bytes

```
function h($n,$s){return$n>strlen($s)?$s:h($n,substr($s,$n)).substr($s,0,$n);}

```

Try it online!

Shockingly, there's no other submission for this using recursion in PHP. I mean, when you think PHP you think recursion, right?

**Ungolfed**

```
function g($n, $s) {
    if ( $n > strlen( $s ) ) {
        return $s;
    } else {
        return g( $n, substr( $s, $n ) ) . substr( $s, 0, $n );
    }
}

```
> 2 votes

# Answer
# \>\<\>, ~~37~~ 34 bytes

```
1[&\&
0=?\i:0(?v}l&:&%
28o ]!?l~<.

```

Try it online!
> 2 votes

# Answer
# J-uby, 25 bytes

```
~:each_slice%A|A|:~|:join

```

Attempt This Online!
> 2 votes

# Answer
# Arturo, 32 bytes

```
$=>[split.every:&&|reverse|join]

```

Try it!
> 2 votes

# Answer
# C++, 111 bytes

```
#import<string>
using S=std::string;S f(S s,int n){S r;for(int i=0;i<s.size();i+=n)r=s.substr(i,n)+r;return r;}

```

Try it online!
> 1 votes

# Answer
## Haskell, ~~40~~ 37 bytes

```
n#""=""
n#s|(a,b)<-splitAt n s=n#b++a

```

Usage example: `2 # "abcdefgh"` -\> `"ghefcdab"`. Try it online!

Split the input string `s` at position `n` and into `a` (first part) and `b` (second part). Return a recursive call with `b` appended by `a`. The base case is the empty input string, where the result is also the empty string.

Note: `splitAt` returns the whole string as the first part and the empty string as the second part if the position is greater than the length of the string (`splitAt 5 "a"` -\> `("a","")`).

Edit: @Ørjan Johansen saved 3 bytes. Thanks!
> 1 votes

# Answer
# Octave, 44 bytes

```
@(n,s){[~,I]=sort(-ceil(find(s)/n));s(I)}{2}

```

Try it online!

or

Verify all test cases!

Explanation:

Example input: `s = 'abcdefgh'` and `n = 3`

```
-ceil(          %round and negate
    find(s)     %generate a range from 1 to len(s)
    /n          %divide by n
    )

a=-ceil([1 2 3 4 5 6 7 8]/3) =

    a = -1  -1  -1  -2  -2  -2  -3  -3

[~,I] = sort(a)  %return index of sorted elements

    I = 7   8   4   5   6   1   2   3
s(I)             %sort s by I
      = ghdefabc

```
> 1 votes

# Answer
# k, 13 bytes

```
{,/|(x,0N)#y}

```

Takes in a number `x`, and a string `y`. Splits the string `y` into a list of strings of length `x` with `(x,0N)#y`, reverses the list with `|`, and turns it into one string by folding join through the list with `,/`.
> 1 votes

# Answer
# Ruby, 37 Bytes

```
->n,s{s.scan(/.{1,#{n}}/).reverse*''}

```

Sample run:

```
irb(main):001:0> ->n,s{s.scan(/.{1,#{n}}/).reverse*''}[3,'abcdefgh']
=> "ghdefabc"

```
> 1 votes

# Answer
# Cheddar, 25 bytes

```
s->n->s.chunk(n).rev.fuse

```

Try it online!
> 1 votes

# Answer
# PowerShell, 75 bytes

```
$n,$r=$args;if($r-match"(.{1,$n})(.*)"){$s=&$f $n $matches.2;$s+$matches.1}

```

\*I'm guessing that it may be a repeating in a some sense but it's the Recursion
\** It's a few bit of fat-free version

Try it online
> 1 votes

# Answer
## Clojure, 50 bytes

```
#(apply str(flatten(reverse(partition-all % %2))))

```

Just following the spec, couldn't figure how to make it any shorter.
> 1 votes

# Answer
# Implicit, ~~4~~ 3 bytes

```
×®"

```

Try it online!

```
×®"    « input: string, integer               »;
×      « split string into chunks of integer  »;
 ®     « reverse entire stack                 »;
  "    « stringify entire stack               »;
       « implicit string output               »;

```
> 1 votes

# Answer
## REXX, 69 bytes

```
parse arg s,n,c
do length(s)%n+1
  parse var s b+(n) s
  c=b||c
  end
say c

```

Explanation:

1. Get arguments `s` and `n`. Given that there are only two arguments, `c` will be initialized as empty.
2. Loop for the length of `s` MOD `n` adding 1 to account for leftovers.
3. For each iteration, chop off `n` characters from beginning of `s` and store them in `b`, then append `b` to beginning of `c`.
> 1 votes

# Answer
# Husk, 3 bytes

```
Σ↔C

```

Try it online!

Takes input as two separate command-line arguments, which thanks to Husk's strong typing and overloaded builtins, don't actually need to be in any particular order since they both get fed directly into `C`, which cuts whichever one of its arguments is a list into sublists of the length given by whichever argument is a number.

```
Σ      Concatenate
 ↔     the reversed
  C    chunks of the given length of the string input.

```
> 1 votes

# Answer
# Perl 5, 29 bytes

My solution is almost the same as @Pavel. Uses the `-lnM5.010` flags. Just another 4-byte longer way to split line with **unpack** instead regexp match. Needs one to calc penalty bytes for 3 flags? Takes flag `M5.010` only one byte penalty?

```
say reverse unpack"(A$_)*",<>

```

Try it online!
> 1 votes

# Answer
# APL(NARS), 73 chars, 146 bytes

```
r←a f w;k;i;j
k←≢w⋄i←1⋄j←a⋄r←⍬
→3×⍳i>k⋄r←r,⊂w[i..k⌊j]⋄i+←a⋄j+←a⋄→2
r←∊⌽r

```

This is better because easier to write and to read... test:

```
  2 f '123'
312
 2 f 'abcdefgh'
ghefcdab
  3 f 'foobarbaz'
bazbarfoo
  2 f 'aaaaaa'
aaaaaa
  2 f 'baaaab'
abaaba
  50 f 'abcdefgh'
abcdefgh
  6  f  'abcdefghi'
ghiabcdef

```
> 1 votes

# Answer
# APL (Dyalog Classic), 22 bytes

```
{0~⍨∊⊖(⌈⍺÷⍨≢⍵)⍺⍴⍵,⍺⍴0}

```

Try it online!
> 1 votes

# Answer
# Forth (gforth), 101 bytes

```
: f >r dup i mod tuck - dup 3 pick + rot type i - -1 max r> -1 rot ?do over i + over type dup -loop ;

```

Try it online!

Definitely not the most golfed it could be, but this one requires more stack manipulation than usual, so it's a bit more complicated to golf.

### Explanation

* Get `string-length % chunk-size`
* Print `string-length % chunk-size` characters starting from `addr + (string-length - (string-length % chunk-size))` \[effectively, we're printing the last chunk separate, since it's size might be smaller than the chunk-size\]
* Loop backwards from the start of the last chunk to the beginning of the string, printing the appropriate chunk for each iteration of the loop

### Code Explanation

```
: f            \ start a new word definition
  >r           \ stick chunk-size on the return stack (accessible by i)
  dup i mod    \ duplicate string-length and length%chunk-size (size of last chunk)
  tuck -       \ make copy of last-chunk-size then get last-chunk start position
  dup 3 pick + \ add last-chunk position to string address to get address of last-chunk
  rot type     \ print last-chunk
  i -          \ subtract chunk-size from last-chunk position to get second-to-last chunk position
  -1 max       \ change to -1 in case string is smaller than chunk-size
  r> -1 rot    \ move chunk-size off return stack, end loop at -1, and arrange params for loop
  ?do          \ start loop from last-chunk-pos to -1
    over i +   \ get current chunk start address
    over type  \ print current chunk
    dup        \ duplicate chunk-size
  -loop        \ subtract chunk-size from loop-index and end loop body
;              \ end word definition

```
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 74 bytes

```
	S =INPUT
	N =INPUT
S	S LEN(N) . X REM . S	:F(O)
	O =X O
O	OUTPUT =S O
END

```

Try it online!
> 1 votes

# Answer
# Japt `-P`, 4 bytes

```
òV w

```

Try it

```
òV w     :Implicit input of string U and integer V
òV       :Split U into chunks of length V
   w     :Reverse
         :Implicitly join & output

```
> 1 votes

# Answer
# Elixir, 35 bytes

```
&Enum.reverse Enum.chunk_every&2,&1

```

Try it online!
> 1 votes

# Answer
# q, 20 bytes

An anonymous composition of built-ins:

```
'[raze reverse@;cut]

```

Example:

```
q)'[raze reverse@;cut][2;"abcdefghi"]
"ighefcdab"

```

(equivalent to lambda `{raze reverse x cut y}`)
> 1 votes

# Answer
# Perl 6, 11 bytes

```
&[R~]o&comb

```

Try it online!

Anonymous combination of two functions, `&comb`, which splits a string into chunks of size `n`, and `&[R~]`, which reverse concatenates a list.
> 1 votes

# Answer
# Vyxal `s`, 2 bytes

```
/Ṙ

```

Try it online!
> 1 votes

# Answer
# Factor, 24 bytes

```
[ group reverse concat ]

```

Try it online!
> 1 votes

# Answer
# Thunno 2 `J`, 2 bytes

```
ẇr

```

Attempt This Online!

#### Explanation

```
ẇr  # Implicit input
ẇ   # Split (input 1) into chunks of length (input 2)
 r  # Reverse the resulting list
    # Implicit output, joined

```
> 1 votes

---
Tags: code-golf, string
---


# Question
Title: Find the number of integers in the range from 1 to N that ends with 2
# Task

As input you have:

* a positive integer `N`

And you should output:

* The number of integers in \\$\[1,N\]\\$ (an inclusive range) which end with the digit \\$2\\$ in base ten.

# Test cases

```
1 -> 0
2 -> 1
5 -> 1
10 -> 1
12 -> 2
20 -> 2
30 -> 3
54 -> 6
97 -> 10
100 -> 10

```

# Rules

It is a code-golf so the lowest score in bytes wins!

# Answer
# Python 2, 17 bytes

```
lambda n:(n+8)/10

```

Try it online! Uses Python 2's integer division. In Python 3 would be a byte longer with `lambda n:(n+8)//10`.
> 20 votes

# Answer
# Jelly, 4 bytes

```
Ḋm⁵L

```

A monadic Link accepting a positive integer, `N`, which yields a non-negative integer.

**Try it online!**

### How?

Every tenth number starting with \\$2\\$ ends with the digit \\$2\\$...

```
Ḋm⁵L - Link: integer, N                           e.g. 15
Ḋ    - dequeue (implicit range [1..N]) -> [2..N]       [2,3,4,5,6,7,8,9,10,11,12,13,14,15]
  ⁵  - literal ten                                     10
 m   - modulo slice                                    [2,12]
   L - length                                          2

```

---

Alternative 4 byter:

```
+8:⁵

```

Add eight, integer divide by ten (as first used in RGS's Python answer I believe).
> 8 votes

# Answer
# Perl 5 `-pl`, ~~13~~ 10 bytes

*@Grimmy got it back down to 10 bytes, with correct output.*

```
$_+=1<chop

```

Try it online!
> 7 votes

# Answer
# APL (Dyalog Unicode), 8 7 bytes

-1 byte thanks to Bubbler

Full program

```
⌊.1×8+⎕

```

Try it online!
> 5 votes

# Answer
# Jelly, ~~7~~ ~~6~~ 5 bytes

```
R%⁵ċ2

```

Try it online! Thanks to Nick Kennedy for saving me one byte.

How it works:

```
R      Range from 1 to n,
 %⁵    modulo 10.
   ċ2  Then count how many of those are 2.

```
> 4 votes

# Answer
# Retina 0.8.2, ~~15~~ 13 bytes

```
.+
$*
.{2,10}

```

Try it online! Edit: Saved 2 bytes thanks to @Grimmy. Explanation:

```
.+
$*

```

Convert to unary.

```
.{2,10}

```

Count the number of multiples of 10, each of which contains an integer that ends in 2 in base 10, plus count an additional match for a final 2-9, as that's enough for one last integer that ends in 2 in base 10.
> 4 votes

# Answer
# Haskell, 14 Bytes

```
f x=div(x+8)10

```
> 4 votes

# Answer
# 05AB1E, 4 bytes

```
8+T÷

```

Same approach as everyone else.

Try it online or verify all test cases.

Some (slightly) more interesting 5-bytes alternatives:

```
LT%2¢
L€θ2¢
L2Å¿O
FNθΘO

```

Try each online.

**Explanation:**

```
8+     # Add 8 to the (implicit) input-integer
  T÷   # Integer-divide it by 10
       # (after which the result is output implicitly)

L      # Push a list in the range [1, (implicit) input-integer]
 T%    # Take modulo-10 on each
       # or
 €θ    # Leave the last digit of each
   2¢  # Count the amount of 2s
       # (after which the result is output implicitly)

L      # Push a list in the range [1, (implicit) input-integer]
 2Å¿   # Check for each whether it ends with a 2 (I'm actually surprised it vectorizes..)
    O  # Sum to get the amount of truthy values

F      # Loop `N` in the range [0, (implicit) input-integer):
 N     #  Push `N`
  θ    #  Pop and leave only its last digit
   Θ   #  05AB1E trutify: check if it's exactly 1
    O  #  Sum all values on the stack together
       # (after the loop, the result is output implicitly)

```
> 4 votes

# Answer
## Python 3, 55 40 bytes

Any help with golfing it would be appreciated

```
lambda N:sum(x%10==2for x in range(N+1))

```

Lots of thanks to the commentors for helping me out( I have problems with memory, see names below)
> 4 votes

# Answer
# Desmos

I know I'm 7 months late but this is my first code golf answer. I'm looking for some easier coding challenges to take down. I have two answers(one where I tried it without looking at any answers, then one after I looked through some answers.).

## First Answer, 62 bytes:

`f(N)=\sum_{n=1}^N\left\{\operatorname{mod}(n,10)=2:1,0\right\}`

Try it on Desmos!

Explanation:

```
f(N)=                                               a function taking in an argument of N
     \sum_{n=1}^N                                   summation from 1 to N
                 \left\{                            starting piecewise
                        \operatorname{mod}(n,10)=2: if the remainder of n/10 is 2...
1                                                   sum 1
 ,                                                  otherwise...
  0                                                 sum 0
   \right\}                                         end piecewise

```

Not too sure why I can't take out the `\left` and `\right` for the brackets(`{` and `}`). Theoretically it should work(I've taken out the `\left`'s and `\right`'s of all the other "left-right pairs"), but I guess Desmos doesn't allow it.

## Second Answer, 20 18 bytes:

Saved two bytes thanks to @golf69

`f(N)=floor(.1N+.8)`

Try it on Desmos!

Explanation:

My answer is equivalent to `f(N)=floor((N+8)/10)`, which is explained in RGS's comment under his answer.
> 4 votes

# Answer
# , 4 bytes

```
8+T/

```

Just another boring formula: Add eight, divide by 10. (W performs integer division if both operands are integers.)

# `d`, 5 bytes

```
[ⁿNy|

```

Uncompressed:

```
Tm2=Wk

```

## Explanation

```
    W % For every number in the range [1 .. N]:
      % Keep all that satisfies:
Tm    % After modulo by 10,
  2=  % The result is equal to 2
     k% Find the length of that

```
> 3 votes

# Answer
# Powershell, ~~50~~ 20 bytes

```
1.."$args"-match"2$"

```

$args are arguments to pass as number.
> 3 votes

# Answer
# Julia 1.0, 12 bytes

```
x->(x+8)÷10

```

Try it online!
> 3 votes

# Answer
# Kotlin, 25 bytes

```
{(1..it).count{it%10==2}}

```

Try it online!
> 3 votes

# Answer
# Pyt <sup>\[sic!\]</sup>, 3 bytes

Finally found the right language. I had a now-deleted answer in Vim, but it returned the empty string for an input of 1 :(

```
8+₀

```

Explanation:

```
8    In fact, I have no idea whether is this language stack-based, I guess it pushes 8
 +   add that 8 to the seemingly-implicit input
  ₀  divide by 10. There are also instructions to divide by numbers from 2 to 11 :)

```

Try it online!
> 3 votes

# Answer
# Husk, 7 bytes

```
#ȯ=2→dḣ

```

Try it online!
> 3 votes

# Answer
# Husk, ~~5~~ 4 bytes

*Edit: -1 byte thanks to Jo King*

```
hs+8

```

Try it online! or check all test cases

**How?**

```
            # implicit input
    +8      # plus 8
   s        # convert to string
  h         # remove last character
            # (so hs effectively divides by 10)

```
> 3 votes

# Answer
# Japt `-x`, 6 bytes

The straightforward solution of adding 8 and floor dividing by 10 would be a byte shorter: `+8 zA`. But where's the fun in that?!

```
õ_ìÌ¶2

```

Try it

```
õ_ìÌ¶2     :Implicit input of integer U
õ          :Range [1,U]
 _         :Map
  ì        :  To digit array
   Ì       :  Last element
    ¶2     :  Is equal to 2?
           :Implicit output of sum of resulting array

```
> 3 votes

# Answer
# Jelly, ~~10~~ 7 bytes

```
ṾṪ=”2)S

```

Try it online!

But there's already 2 shorter answers I hear you say... Well, this doesn't use mathematics but rather uses strings
> 3 votes

# Answer
# Scala, 11 bytes

```
n=>(n+8)/10

```

Try it online!
> 3 votes

# Answer
# C (gcc), 17 bytes

```
f(n){n=(n+8)/10;}

```

Try it online!
> 2 votes

# Answer
# PHP, ~~18~~ 17 bytes

```
<?=$argn/10+.8|0;

```

Try it online!

-1 bytes thanks to @oxgeba
> 2 votes

# Answer
# C (gcc), 17 bytes

```
f(n){n+=8;n/=10;}

```

Try it online!

Alternative 17-byter:

# C (gcc), 17 bytes

```
f(n){n=n/10.+.8;}

```

Try it online!

Alternative 17-byter

# C (gcc), 17 bytes

```
f(n){n=(n+8)/10;}

```

Try it online!
> 2 votes

# Answer
# Clojure, 28 bytes

```
(defn e[n](int(/(+ n 8)10)))

```

Ungolfed:

```
(defn ends-in-two [n]
  (int (/ (+ n 8) 10)))

```

Test harness:

```
(println (e 1))
(println (e 2))
(println (e 5))
(println (e 10))
(println (e 12))
(println (e 20))
(println (e 30))
(println (e 54))
(println (e 97))
(println (e 100))

```

Try it online!
> 2 votes

# Answer
# , ~~18~~ 15 bytes

Thanks @Giuseppe! Guess I didn't really know what the %/% operator did.

```
(scan()+8)%/%10

```

Try it online!
> 2 votes

# Answer
# Python 3, ~~22~~ 18 bytes

```
lambda n:(n+8)//10

```

Thanks to @JoKing for suggesting to use integer division.
> 2 votes

# Answer
# GolfScript, 6 bytes

GolfScript has no decimal support, that's why the `/` works.

```
~8+10/

```

Try it online!
> 2 votes

# Answer
# Pyth, 5 bytes

```
/+8QT

```

Try it online!

### Explanation

```
/+8QT
   Q   : Variable containing evaluated input
 +8    : Add 8 to it
/   T  : Divide result of add by 10

```
> 2 votes

# Answer
## Javascript (node) \- 25 Bytes

```
f=n=>n?(n%10==2)+f(n-1):0

```

Try it online!
> 2 votes

# Answer
# JavaScript (V8), 15 bytes

```
f=n=>(n+8)/10|0

```

Try it online!
> 2 votes

# Answer
# Stax, 4 bytes

```
8+A/

```

Run and debug it

Just a standard add 8, integer divide by 10
> 2 votes

# Answer
# Burlesque, 7 bytes

```
8|+10|/

```

Try it online!

Using RGS's method

```
8|+  # Add 8 (Parse string implcit)
10|/ # Divide by 10

```

# Burlesque, 10 bytes

```
riq[~GO2CN

```

Try it online!

```
ri   # Read int
q[~  # Boxed tail (last digit)
GO   # Generate from 1, N
2CN  # Count number of 2's

```
> 2 votes

# Answer
# Rail, 87 bytes

```
$'main'
 -0(!a!)-/-(a)ia(!a!)\
#od[01]a*8(a)-\ /e-----@
@-(!a!)/      >-
  \m(a)[01]--/

```

Try it online!

### Explanations:

```
0(!a!)         Put 0 into variable "a"
(a)ia(!a!)     Add "a" with input (one number at a time), put into variable "a"
e              check if it's EOF, then go left or right at the next junction

               if false:
[10](a)m(!a!)  multiply "a" by 10, put into variable "a"

               if true:
(a)8a[10]do#   add a with 8, then divide by 10, print the output. Fin.

The rest of symbols are tracks

```
> 2 votes

# Answer
# Erlang (escript), 18 bytes

```
f(N)->(N+8)div 10.

```

Try it online!

# Explanation

```
f(N)->  % Function taking N as input
(N+8)   % Add input by 8
div 10. % Floor division by 10

```
> 2 votes

# Answer
# Excel, 43 bytes

```
=SUM(1*(RIGHT(ROW(OFFSET(A1,0,0,A1)))="2"))

```

`OFFSET(A1,0,0,A1)` generates a range starting at `A1` that is `A1's value` rows tall.
`ROW(OFFSET(~))` returns an array of row numbers for that range (\\$\[1,N\]\\$).
`RIGHT(ROW(~))` returns an array of the right-most character of those row numbers as a string.
`RIGHT(~)="2"` returns an array of TRUE or FALSE.
`1*(~)` transforms TRUE to 1 and FALSE to 0.
`SUM(~)` sums.
> 2 votes

# Answer
# Vyxal, 4 bytes

```
8+ĳ∖

```

the easy solution.

# Vyxal `Ms`, 6 bytes

```
ƛSt\2=

```

-2 bytes from Lyxal.

## Explanation

```
ƛSt\2=
ƛ      map range 1..n to the following:
 S     convert to string
  t    get last character
   \2= is it equal to '2'?
       sum the results(s flag)

```
> 2 votes

# Answer
# Brachylog, 3 bytes

```
+₈k

```

Try it online!

Since Brachylog likes to treat integers as lists of decimal digits when appropriate, the "remove last element" builtin `k` can be used to floor-divide by 10.
> 2 votes

# Answer
# Io, 24 bytes

```
method(i,((i-1)/10)ceil)

```

Try it online!

1 byte saved, thanks to xigoi
> 2 votes

# Answer
# Nim, 29 28 bytes

```
func f[I](n:I):I=(n+8)div 10

```

Try it online!
> 2 votes

# Answer
# Factor, 13 bytes

```
[ 8 + 10 /i ]

```

Try it online!

It's a quotation (anonymous function) that adds 8 to its input and then (integer) divides it by 10.
> 2 votes

# Answer
# Mathematica, 14 bytes

```
⌊.1*#+.8⌋&

```

RGS did most of the work by coming up with the clever function to determine the answer. Putting it into Wolfram Langage was then trivial.

Try it online!

NB:

⌊ = \\\[LeftFloor\] = U+230A (3 bytes)

⌋ = \\\[RightFloor\] = U+230B (3 bytes)
> 2 votes

# Answer
# APL+WIN, 9 bytes

Prompts for integer n:

+/2=10|⍳⎕

Try it online! Courtesy of Dyalog Classic
> 1 votes

# Answer
# dc, ~~5~~ 4 bytes

```
8+I/

```

Try it online!

This is a dc "function": it pops the input from the stack, and then pushes the output onto the stack. (dc is a stack-based language.)

To call it, enter the desired input first (to push it on the stack), follow with the code above, and then enter `p` to print the output.
> 1 votes

# Answer
# Bash \+ Unix utilities, 13 bytes

```
dc<<<$1d8+I/p

```

Try it online!

The input is passed as an argument, and the output is printed.

(This just uses my dc answer internally.)
> 1 votes

# Answer
# AWK, 17 bytes

```
$1=int($1/10+.8)e

```

Try it online!

This substitutes the input `$1` for the formula `int($1/10+.8)`, and also appends the `e` variable, which is null (not defined variables return null). This causes `$1` to become a string, preventing the expression from evaluating `0` when input is `0` or `1`. A false pattern wouldn't allow the line to be printed (`0` is false).
> 1 votes

# Answer
# Java (JDK), 11 bytes

```
n->(n+8)/10

```

Try it online!
> 1 votes

# Answer
# Groovy, 18 bytes

```
{(it+8).intdiv 10}

```

Try it online!
> 1 votes

# Answer
# Kotlin, 13 bytes

```
{a->(a+8)/10}

```

Try it online!
> 1 votes

# Answer
# C, ~~29~~ ~~21~~ ~~20~~ 17 bytes

```
f(n){n=(n+8)/10;}

```

### Try It Online

Which works only if optimizations are turned off (more info).
If you love optimizations, then I got this **18 bytes** solution for you:

```
#define N (n+8)/10

```

Try It Online
> 1 votes

# Answer
# Coconut, 12 bytes

```
n->(n+8)//10

```

Try it online!
> 1 votes

# Answer
# TI-BASIC, 8 bytes

```
int(.1(N+8

```

There are a handful of equivalent solutions here because of the number of ways you can do implicit multiplication by .1 - there's also a solution available using the default value of Xmax from the graphscreen variables.

```
int(.1N+.8

int(N/Xmax+.8

```
> 1 votes

# Answer
# Ruby, 44 bytes

```
->x{(1..x).to_a.map{|e|(e%10)==2?1:0}.sum}

```

Try it online!

I don't use Ruby very often, I'm sure it can be golfed further.
> 1 votes

# Answer
# Risky, 3.5 bytes

```
?++//+/

```

Try it online!
> 1 votes

# Answer
# tinylisp, 35 bytes

```
(load library
(d y(q((n)(/(+ 8 n)10

```

Try it online!

Luckily, `library` had a builtin for division.
> 1 votes

# Answer
# Knight, 17 bytes

```
OUTPUT/+8PROMPT10

```

My first submission for the language of the month; Knight, which I just found out was a thing. Implements the same function as my previous Haskell (and basically everyone else's) answer.

Try it online! (online interpreter implemented in TIO in C)
> 0 votes

# Answer
# Thunno 2, 4 bytes

```
8+T÷

```

Attempt This Online! Port of RGS's Python answer.

## Thunno 2 `L`, 4 bytes

```
æ2ø>

```

Attempt This Online! Literal solution.

#### Explanation

```
8+T÷  # Implicit input
8+    # Add 8 to the input
  T÷  # Floor divide by 10
      # Implicit output

```

```
æ2ø>  # Implicit input
æ     # Filter [1..input] by:
 2ø>  #  Ends with 2
      # Push the length
      # Implicit output

```
> 0 votes

---
Tags: code-golf, math
---


# Question
Title: Output the largest number with the fewest digits
Given a nonempty list of positive decimal integers, output the largest number from the set of numbers with the fewest digits.

The input list will not be in any particular order and may contain repeated values.

**Examples:**

```
[1] -> 1
[9] -> 9
[1729] -> 1729
[1, 1] -> 1
[34, 3] -> 3
[38, 39] -> 39
[409, 12, 13] -> 13
[11, 11, 11, 1] -> 1
[11, 11, 11, 11] -> 11
[78, 99, 620, 1] -> 1
[78, 99, 620, 10] -> 99
[78, 99, 620, 100] -> 99
[1, 5, 9, 12, 63, 102] -> 9
[3451, 29820, 2983, 1223, 1337] -> 3451
[738, 2383, 281, 938, 212, 1010] -> 938

```

**The shortest code in bytes wins.**

# Answer
# Pyth, ~~7~~ ~~3~~ 6 bytes

```
eS.ml`

```

Test Suite

Explanation:

```
e      Still grab the last element
 S      Still sort
  .ml`   But prefilter the list for those with the (m)inimum length.

```

---

7 byte solution:

```
eSh.gl`

```

Test Suite

Explanation:

```
   .g   Group items in (implicit) input by:
     l  The length of
      ` their representation
  h     Get those with the shortest length
 S      Sort the resulting list
e       and grab the last (i.e. largest) element

```
> 14 votes

# Answer
# Jelly, 7 bytes

```
DL,NµÞḢ

```

Test it at **TryItOnline**
Or see all test cases also at **TryItOnline**

How?

```
DL,NµÞḢ - Main link takes one argument, the list, e.g. [738, 2383, 281, 938, 212, 1010]
D       - convert to decimal, e.g. [[7,3,8],[2,3,8,3],[2,8,1],[9,3,8],[2,1,2],[1,0,1,0]]
 L      - length, e.g. [3,4,3,3,3,4]
   N    - negate, e.g [-738, -2383, -281, -938, -212, -1010]
  ,     - pair, e.g. [[3,-738],[4,-2383],[3,-281],[3,-938],[3,-212],[4,-1010]]
    µ   - make a monadic chain
     Þ  - sort the input by that monadic function, e.g [938,738,281,212,2383,1010]
          (the lists in the example are not created, but we sort over the values shown)
      Ḣ - pop and return the first element, e.g. 938

```
> 7 votes

# Answer
# 05AB1E, 5 bytes

Code:

```
({é¬(

```

Explanation:

```
(      # Negate the list, e.g. [22, 33, 4] -> [-22, -33, -4]
 {     # Sort, e.g. [-22, -33, -4] -> [-33, -22, -4]
  é    # Sort by length, e.g. [-33, -22, -4] -> [-4, -22, -33]
   ¬   # Get the first element.
    (  # And negate that.

```

Uses the **CP-1252** encoding. Try it online!
> 7 votes

# Answer
# Python 2, ~~48~~ 42 bytes

-6 bytes thanks to @Dennis (use `min` rather than `sorted`)

```
lambda l:min(l,key=lambda x:(len(`x`),-x))

```

All test cases are at **ideone**

Take the minimum of the list by (length, -value)
> 6 votes

# Answer
# Ruby, 34 bytes

```
->a{a.max_by{|n|[-n.to_s.size,n]}}

```

See it on eval.in: https://eval.in/643153
> 4 votes

# Answer
# MATL, 14 bytes

```
10&YlktX<=G*X>

```

Try it online!

Explanation:

```
  &Yl           % Log
10              % Base 10
     kt         % Floor and duplicate
       X<       % Find the smallest element
         =      % Filter out elements that do not equal the smallest element
          G     % Push the input again
           *    % Multiply (this sets numbers that do not have the fewest digits to 0)
            X>  % And take the maximum

```
> 4 votes

# Answer
# Retina, ~~24~~ 16 bytes

```
O^`
O$#`
$.0
G1`

```

Try it online! or run all test cases.

Saved 8 bytes thanks to Martin!

The all test is using a slightly older version of the code, but the algorithm is identical. I'll update it to be closer when I get more time.

The trailing newline is significant. Sorts the numbers by reverse numeric value, then sorts them by number of digits. This leaves us with the largest number with the fewest digits in the first position, so we can just delete the remaining digits.
> 4 votes

# Answer
# Perl 6, 18 bytes

```
*.min:{.chars,-$_}

```

## Explanation:

```
*\        # Whatever lambda
.min:     # find the minimum using

{         # bare block lambda with implicit parameter ｢$_｣

  .chars, # number of characters first ( implicit method call on ｢$_｣ )
  -$_     # then negative of the value in case of a tie
}

```

## Usage:

```
say [738, 2383, 281, 938, 212, 1010].&( *.min:{.chars,-$_} ); # 938

my &code = *.min:{.chars,-$_}

say code [78, 99, 620, 10]; # 99

```
> 4 votes

# Answer
# Mathematica, ~~33~~ 31 bytes

```
Max@MinimalBy[#,IntegerLength]&

```

MinimalBy selects all the elements of the original input list with the smallest score according to `IntegerLength`, i.e., with the smallest number of digits; and then Max outputs the largest one.

*Thanks to Martin Ender for finding, and then saving, 2 bytes for me :)*
> 4 votes

# Answer
# K (ngn/k), ~~16~~ ~~15~~ 14 bytes

```
|/{=/&/\#'$x}#

```

Try it online!

* `{...}#` set up a filter, returning elements from the (implicit) right argument where the code in `{...}` returns `1`s
    + `#'$x` count the number of characters in the string representation of each input
    + `&/\` generate a two item list of the character counts and their minimum
    + `=/` generate a boolean mask indicating which indices have the fewest digits
* `|/` return the maximum (remaining) value
> 4 votes

# Answer
# Jelly, 8 bytes

```
DL€İMị¹Ṁ

```

Try it online! or Verify all test cases.

## Explanation

```
DL€İMị¹Ṁ  Input: list A
D         Convert each integer to a list of base 10 digits
 L€       Get the length of each list (number of digits of each)
   İ      Take the reciprocal of each
    M     Get the indices of the maximal values
      ¹   Get A
     ị    Select the values at those indices from A
       Ṁ  Find the maximum and return

```
> 3 votes

# Answer
# J, ~~21~~ 14 bytes

Saved 7 bytes thanks to miles and (indirectly) Jonathan!

```
{.@/:#@":"0,.-

```

This is a four-chain:

```
{.@/: (#@":"0 ,. -)

```

Let's walk over the input `10 27 232 1000`. The inner fork consists of three tines. `#@":"0` calculates the sizes, `,.` concats each size with its negated (`-`) member. For input `10 27 232 1000`, we are left with this:

```
   (#@":"0 ,. -) 10 27 232 1000
2   _10
2   _27
3  _232
4 _1000

```

Now, we have `{.@/:` as the outer tine. This is monadic first (`{.`) over dyadic sort (`/:`). That is, we'll be taking the first element of the result of dyadic `/:`. This sorts its right argument according to its left argument, which gives us for our input:

```
   (/: #@":"0 ,. -) 10 27 232 1000
27 10 232 1000

```

Then, using `{.` gives us the first element of that list, and we are done:

```
   ({.@/: #@":"0 ,. -) 10 27 232 1000
27

```

## Old version

```
>./@(#~]=<./@])#@":"0

```

Still working on improvements. I golfed it down from 30, and I think this is good enough. I'm going to first break it down into basic parts:

```
   size =: #@":"0
   max =: >./
   min =: <./
   over =: @
   right =: ]
   left =: [
   selectMin =: #~ right = min over right

   f =: max over selectMin size
   f 3 4 5
5
   f 3 4 53
4
   f 343 42 53
53

```

Here's how this works.

```
>./@(#~ ] = <./@]) #@":"0

```

This is a monadic train, but this part is a hook. The verb `>./@(#~ ] = <./@])` is called with left argument as the input to the main chain and the sizes, defined as `#@":"0`, as the right argument. This is computed as length (`#`) over (`@`) default format (`":`), that is, numeric stringification, which is made to apply to the 0-cells (i.e. members) of the input (`"0`).

Let's walk over the example input `409 12 13`.

```
   (#@":"0) 409 12 13
3 2 2

```

Now for the inner verb, `>./@(#~ ] = <./@])`. It looks like `>./@(...)`, which effectively means maximum value (`>./`) of (`@`) what's inside `(...)`. As for the inside, this is a four-train, equivalent to this five-train:

```
[ #~ ] = <./@]

```

`[` refers to the original argument, and `]` refers to the size array; `409 12 13` and `3 2 2` respectively in this example. The right tine, `<./@]`, computes the minimum size, `2` in this case. `] = <./@]` is a boolean array of values equal to the minimum, `0 1 1` in this case. Finally, `[ #~ ...` takes values from the left argument according the right-argument mask. This means that elements that correspond to `0` are dropped and `1` retained. So we are left with `12 13`. Finally, according to the above, the max is taken, giving us the correct result of `13`, and we are done.
> 3 votes

# Answer
# JavaScript (ES6), 51

```
l=>l.sort((a,b)=>(a+l).length-(b+l).length||b-a)[0]

```

**Test**

```
f=l=>l.sort((a,b)=>(a+l).length-(b+l).length||b-a)[0]

;[
 [[1], 1]
,[[9], 9]
,[[1729], 1729]
,[[1, 1], 1]
,[[34, 3], 3]
,[[38, 39], 39]
,[[409, 12, 13], 13]
,[[11, 11, 11, 1], 1]
,[[11, 11, 11, 11], 11]
,[[78, 99, 620, 1], 1]
,[[78, 99, 620, 10], 99]
,[[78, 99, 620, 100], 99]
,[[1, 5, 9, 12, 63, 102], 9]
,[[3451, 29820, 2983, 1223, 1337], 3451]
,[[738, 2383, 281, 938, 212, 1010], 938]
].forEach(([l,x])=>{
  var r=f(l)
  console.log(r==x?'OK':'KO',l+' -> '+r)
})
```
> 3 votes

# Answer
# Julia, 39

```
f(l)=sort(l,by=x->(length("$x"),-x))[1]

```

ATOable
> 3 votes

# Answer
# JavaScript (ES6), 62 bytes

```
var solution =

a=>a.map(n=>(l=`${n}`.length)>a?l>a+1|n<r?0:r=n:(a=l-1,r=n))|r

;document.write('<pre>' + `
[1] -> 1
[9] -> 9
[1729] -> 1729
[1, 1] -> 1
[34, 3] -> 3
[38, 39] -> 39
[409, 12, 13] -> 13
[11, 11, 11, 1] -> 1
[11, 11, 11, 11] -> 11
[78, 99, 620, 1] -> 1
[78, 99, 620, 10] -> 99
[78, 99, 620, 100] -> 99
[1, 5, 9, 12, 63, 102] -> 9
[3451, 29820, 2983, 1223, 1337] -> 3451
[738, 2383, 281, 938, 212, 1010] -> 938
`.split('\n').slice(1, -1).map(c =>
  c + ', result: ' + solution(eval(c.slice(0, c.indexOf('->'))))
).join('\n'))
```
> 2 votes

# Answer
## Javascript (ES6), ~~57~~ ~~54~~ 53 bytes

```
l=>l.sort((a,b)=>(s=a=>1/a+`${a}`.length)(a)-s(b))[0]

```

For the record, my previous version was more math-oriented but 1 byte bigger:

```
l=>l.sort((a,b)=>(s=a=>1/a-~Math.log10(a))(a)-s(b))[0]

```

### Test cases

```
let f =
l=>l.sort((a,b)=>(s=a=>1/a+`${a}`.length)(a)-s(b))[0]

console.log(f([1]));                              //  -> 1
console.log(f([9]));                              //  -> 9
console.log(f([1729]));                           //  -> 1729
console.log(f([1, 1]));                           //  -> 1
console.log(f([34, 3]));                          //  -> 3
console.log(f([38, 39]));                         //  -> 39
console.log(f([409, 12, 13]));                    //  -> 13
console.log(f([11, 11, 11, 1]));                  //  -> 1
console.log(f([11, 11, 11, 11]));                 //  -> 11
console.log(f([78, 99, 620, 1]));                 //  -> 1
console.log(f([78, 99, 620, 10]));                //  -> 99
console.log(f([78, 99, 620, 100]));               //  -> 99
console.log(f([1, 5, 9, 12, 63, 102]));           //  -> 9
console.log(f([3451, 29820, 2983, 1223, 1337]));  //  -> 3451
console.log(f([738, 2383, 281, 938, 212, 1010])); //  -> 938
```
> 2 votes

# Answer
# Java 7, ~~112~~ 104 bytes

```
int c(int[]a){int i=a[0],j;for(int b:a)i=(j=(i+"").length()-(b+"").length())>0?b:b>i&j==0?b:i;return i;}

```

Different approach to save multiple bytes thanks to *@Barteks2x*.

**Ungolfed & test cases:**

Try it here.

```
class M{
  static int c(int[] a){
    int i = a[0],
        j;
    for(int b : a){
      i = (j = (i+"").length() - (b+"").length()) > 0
           ? b
           : b > i & j == 0
              ? b
              : i;
    }
    return i;
  }

  public static void main(String[] a){
    System.out.println(c(new int[]{ 1 }));
    System.out.println(c(new int[]{ 9 }));
    System.out.println(c(new int[]{ 1729 }));
    System.out.println(c(new int[]{ 1, 1 }));
    System.out.println(c(new int[]{ 34, 3 }));
    System.out.println(c(new int[]{ 409, 12, 13 }));
    System.out.println(c(new int[]{ 11, 11, 11, 1 }));
    System.out.println(c(new int[]{ 11, 11, 11, 11 }));
    System.out.println(c(new int[]{ 78, 99, 620, 1 }));
    System.out.println(c(new int[]{ 78, 99, 620, 100 }));
    System.out.println(c(new int[]{ 1, 5, 9, 12, 63, 102 }));
    System.out.println(c(new int[]{ 3451, 29820, 2983, 1223, 1337 }));
    System.out.println(c(new int[]{ 738, 2383, 281, 938, 212, 1010 }));
  }
}

```

**Output:**

```
1
9
1729
1
3
13
1
11
1
99
9
3451
938

```
> 2 votes

# Answer
## dc, 54 bytes

```
?dZsL0sN[dsNdZsL]su[dlN<u]sU[dZlL=UdZlL>ukz0<R]dsRxlNp

```

**Explanation:**

```
?dZsL0sN                  # read input, initialize L (length) and N (number)
[dsNdZsL]su               # macro (function) 'u' updates the values of L and N
[dlN<u]sU                 # macro 'U' calls 'u' if N < curr_nr
[dZlL=U dZlL>ukz0<R]dsR   # macro 'R' is a loop that calls 'U' if L == curr_nr_len
                          #or 'u' if L > curr_nr_len
xlNp                      # the main: call 'R' and print N at the end

```

**Run example:** 'input.txt' contains all the test cases in the question's statement

```
while read list;do echo "$list -> "$(dc -f program.dc <<< $list);done < input.txt

```

**Output:**

```
1 -> 1
9 -> 9
1729 -> 1729
1 1 -> 1
34 3 -> 3
38 39 -> 39
409 12 13 -> 13
11 11 11 1 -> 1
11 11 11 11 -> 11
78 99 620 1 -> 1
78 99 620 10 -> 99
78 99 620 100 -> 99
1 5 9 12 63 102 -> 9
3451 29820 2983 1223 1337 -> 3451
738 2383 281 938 212 1010 -> 938

```
> 2 votes

# Answer
# bash, awk, sort 53 bytes

```
set `awk '{print $0,length($0)}'|sort -rnk2n`;echo $1

```

Read input from stdin, one value per line

~~bash and sort, ~~58~~ 57 bytes
```
set `sort -n`;while((${#2}==${#1}));do shift;done;echo $1

```~~
> 2 votes

# Answer
# JavaScript ES6, ~~80~~ ~~77~~ 70 bytes

```
a=>Math.max(...a.filter(l=>l.length==Math.min(...a.map(i=>i.length))))

```

I hope I am going in the right direction...
> 1 votes

# Answer
# Brachylog, 16 bytes

```
or:@]feL:la#=,Lh

```

Try it online!

### Explanation

```
or                 Sort the list in descending order.
  :@]f             Find all suffixes of the list.
      eL           Take one suffix L of the list.
        :la        Apply length to all numbers in that suffix.
           #=,     All lengths must be equal.
              Lh   Output is the first element of L.

```
> 1 votes

# Answer
# Haskell, 39 bytes

```
snd.maximum.map((0-).length.show>>=(,))

```
> 1 votes

# Answer
# Perl, ~~38~~ 37 bytes

Includes +1 for `-a`

Give input on STDIN:

```
perl -M5.010 maxmin.pl <<< "3451 29820 2983 1223 1337"

```

`maxmin.pl`:

```
#!/usr/bin/perl -a
\$G[99-y///c][$_]for@F;say$#{$G[-1]}

```

Uses memory linear in the largest number, so don't try this on too large numbers. A solution without that flaw is 38 bytes:

```
#!/usr/bin/perl -p
$.++until$\=(sort/\b\S{$.}\b/g)[-1]}{

```

All of these are very awkward and don't feel optimal at all...
> 1 votes

# Answer
# MATL, 11 bytes

```
tV48\&XS0))

```

Input is a column vector (using `;` as separator), such as

```
[78; 99; 620; 100]

```

Try it online! Or verify all test cases.

### Explanation

Let's use input `[78; 99; 620; 100]` as an example.

```
t      % Input column vector implicitly. Duplicate
       %   STACK: [78; 99; 620; 100], [78; 99; 620; 100]
V      % Convert to string. Each number is a row, left-padded with spaces
       %   STACK: [78; 99; 620; 100], [' 78'; ' 99'; '620'; '100']
48\    % Modulo 48. This transforms each digit into the corresponding number,
       % and space into 32. Thus space becomes the largest "digit"
       %   STACK: [78; 99; 620; 100], [32 7 8; 32 9 9; 6 2 0; 1 0 0]
&XS    % Sort rows in lexicographical order, and push the indices of the sorting
       %   STACK: [78; 99; 620; 100], [4; 3; 1; 2]
0)     % Get last value
       %   STACK: [78; 99; 620; 100], 2
)      % Index
       %   STACK: 99
       % Implicitly display

```
> 1 votes

# Answer
# R, ~~72~~ ~~41~~ 36 bytes

Rewrote the function with a new approach. Golfed 5 bytes thanks to a suggestion from @bouncyball.

```
n=nchar(i<-scan());max(i[n==min(n)])

```

Explained:

```
        i<-scan()       # Read input from stdin
n=nchar(         );     # Count the number of characters in each number in i
max(             )      # Return the maximum of the set where
    i[n==min(n)]        # the number of characters is the minimum number of characters.

```
~~```
function(i){while(1){if(length(o<-i[nchar(i)==T]))return(max(o));T=T+1}}

```
Indented/explained:<br>```
function(i){               # Take an input i
  while(1){                # Do the following continuously:
    if(length(
        o<-i[nchar(i)==T]) # Define o to be the subset of i with numbers of length T,
      )                    # where T is 1 (a built-in!).
                           # We take the length of this subset (its size), and then pass
                           # it to if(). Thanks to weak typing, this numeric is converted
                           # to a logical value. When this occurs, zero evaluates to FALSE
                           # and any non-zero number evaluates to TRUE. Therefore, the if()
                           # is TRUE iff the subset is not empty.
      return(max(o));      # If it's true, then we just return the largest element of the
                           # subset, breaking out of our loop.
    T=T+1                  # Otherwise, increment our counter and continue.
  }
}

```~~
> 1 votes

# Answer
## PowerShell v2+, 41 bytes

```
($args[0]|sort -des|sort{"$_".length})[0]

```

Takes input `$args`, `sort`s it by value in `-des`cending order (so bigger numbers are first), then `sort`s that by the `.length` in ascending order (so shorter lengths are first). We then take the `[0]` element, which will be the biggest number with the fewest digits.

## Examples

```
PS C:\Tools\Scripts\golfing> @(78,99,620,1),@(78,99,620,10),@(78,99,620,100),@(1,5,9,12,63,102),@(3451,29820,2983,1223,1337),@(738,2383,281,938,212,1010)|%{($_-join',')+" -> "+(.\output-largest-number-fewest-digits.ps1 $_)}
78,99,620,1 -> 1
78,99,620,10 -> 99
78,99,620,100 -> 99
1,5,9,12,63,102 -> 9
3451,29820,2983,1223,1337 -> 3451
738,2383,281,938,212,1010 -> 938

```
> 1 votes

# Answer
## Bash + coreutils, 58 bytes

```
d=`sort -n`;egrep ^.{`sed q<<<"$d"|wc -L`}$<<<"$d"|tail -1

```

Input format is one value per line. Golfing suggestions are welcomed.

**Explanation:**

```
d=`sort -n`                             #save the list in ascending numerical order
egrep ^.{                    }$<<<"$d"  #print only list lines having as many chars
         `sed q<<<"$d"|wc -L`                 #as the first sorted line does
|tail -1                                #and then get the last one (the answer)

```
> 1 votes

# Answer
# **Python 2 - 41 bytes**

```
lambda l:max((-len(`x`),x) for x in l)[1]

```
> 1 votes

# Answer
# APL (Dyalog Unicode), 36 bytes

-4 thanks to @rak1507.

```
f←⌈/⊢×((⌊/=⊢)≢∘⍕¨)

```

Try it online!
> 1 votes

# Answer
# Jelly, 6 bytes

```
DL$ÐṂṀ

```

Try it online!

## How it works

```
DL$ÐṂṀ - Main link. Takes a list L on the left
  $ÐṂ  - Take the elements of L for which the following is minimal:
DL     -   Digit Length
     Ṁ - Maximum of those elements

```
> 1 votes

# Answer
# Factor, 25 bytes

```
[ all-shortest supremum ]

```

Try it online!

Get the largest of the shortests.
> 1 votes

# Answer
# Japt `-h`, 4 bytes

Input as an array of integer strings, output as an integer string.

```
üÊÎñ

```

Try it

```
üÊÎñ     :Implicit input of array
ü        :Group and sort by
 Ê       :  Length
  Î      :First element
   ñ     :Sort
         :Implicit output of last element

```
> 1 votes

# Answer
# Vyxal, 5 bytes

```
⁽₍LN∵

```

Try it Online!

## How?

```
⁽₍LN∵
⁽     # Next element as a lambda:
 ₍    #  Apply both of the next two elements and wrap the results in a list:
  L   #   Length...
   N  #   ...and negate
    ∵ # Get the minimum of the input by that function

```
> 1 votes

# Answer
# Pip, 11 bytes

```
@Y#_AE-_SKa

```

Try It Online!
> 1 votes

# Answer
# C (clang), 77 bytes

```
m,n,i,j;f(*a,l){for(j=99;l--;m=i<j|i>j^n>m?j=i,n:m)i=log10(n=a[l]);return m;}

```

Try it online!
> 1 votes

# Answer
# Python 2, ~~63~~ ~~30~~ 63 bytes

```
lambda a:a.sort()or[`i`for i in a if len(`i`)==len(`a[0]`)][-1]

```
> 0 votes

# Answer
## Python 2, 58 bytes

```
def F(x):l={len(`i`):i for i in sorted(x)};print l[min(l)]

```
> 0 votes

# Answer
# Python 3, 56 bytes

```
lambda a:sorted(sorted(a),key=lambda x:-len(str(x)))[-1]

```

Uses a lambda in a lambda!

## Python 2, 53 bytes

```
s=lambda a:sorted(sorted(a),key=lambda x:-len(`x`))[-1]

```

Same but with backticks
> 0 votes

# Answer
## Pip, 11 bytes

```
(SNgSK-#_v)

```

Takes input as command-line args. Try it online!

First time using the `S`ort-`K`eyed operator! Like Python's `sorted()`, it takes a function that is applied to each item of the iterable and the result used as a sort key. Here's how this program works:

```
 SNg         List of cmdline args, sorted numerically in increasing order
    SK       Sort with key function...
      -#_    ... negative length(x), thus putting the shortest numbers at the end but not
               affecting the relative ordering among numbers with the same length
(        v)  Get the last element (index -1) and auto-print

```
> 0 votes

# Answer
# Clojure, 63 bytes

```
(reduce #(if(=(quot %1 10)(quot %2 10))(max %1 %2) %1)(sort x))

```

as in:

```
(reduce #(if(=(quot %1 10)(quot %2 10))(max %1 %2) %1)(sort[3 7 121 11 8 2 10 9]))
=> 9

```

Though I'm sure there's a way to make it smaller.
> 0 votes

# Answer
# PHP , 86 Bytes

```
<?$l=strlen($r=min($a=$_GET[a]));foreach($a as$v)if($v>$r&strlen($v)==$l)$r=$v;echo$r;

```
> 0 votes

# Answer
## Pyke, 7 bytes

```
.#_il)h

```

Try it here!
> 0 votes

# Answer
# **C#, 119 bytes**

```
int L(int[]n){var g=n.GroupBy(o=>(o+"").Length);return g.Where(o=>o.Key==g.Min(k=>k.Key)).OrderBy(o=>o).First().Max();}

```

Ungolfed:

```
public int L(int[]n)
{
  var g = n.GroupBy(o => (o+"").Length);
  return g.Where(o => o.Key == g.Min(k => k.Key)).OrderBy(o => o).First().Max();
}

```

Magical Linq...

Usage:

```
var a = new LargestNumberFewestDigits();
Console.Write(a.L(new int[] { 738, 2383, 281, 938, 212, 1010 }));

```

Output:

```
938

```
> 0 votes

# Answer
## Java 8, 110 bytes

```
int f(int[]a){java.util.Arrays.sort(a);int i=a[0];for(int z:a)i=(z+"").length()>(i+"").length()?i:z;return i;}

```

Ungolfed:

```
int f(int[]a){
    java.util.Arrays.sort(a);                  //sorts the array in ascending order
    int i=a[0];                                //declare output variable, uses 1 less byte than using a[0]
    for(int z:a) {
        i=(z+"").length()>(i+"").length()?i:z; //for each int, if the length isn't longer set as output
    }
    return i;
}

```

Any elements that aren't longer in a sorted array must be a higher value.

Also lambda version (101 bytes):

```
a->{java.util.Arrays.sort(a);int i=a[0];for(int z:a)i=(z+"").length()>(i+"").length()?i:z;return i;};

```
> 0 votes

# Answer
# C# (85 bytes)

It's a full function:

```
int y(int[] t) {int m=t.Min(i=>(i+"").Length);return t.Max(n=>(n+"").Length==m?n:0);}

```

Unriddled:

```
int y(int[] t)
{
    int m = t.Min(i => (i+"").Length);
    return t.Max(n => (n+"").Length == m ? n : 0);
}

```
> 0 votes

# Answer
# C# 85 bytes

```
int S(int[] i){var m=i.Min();return i.Where(v=>v<m*10&&$"{v}{m}".Length%2==0).Max();}

```

Usage:

```
Console.WriteLine(S(new[] { 738, 2383, 281, 938, 212, 1010 }));

```

Output: 938

**Explanation**

Get the minimum value from the array and assume that the minimum value is the value with the shortest length.

Filter the array to remove all values greater than 10 * the minimum. i.e if the value is 8, the first check removes all values greater than 80.

Also filter to remove all values where the length of the combined string is odd. "8" + "9" is length 2 which is even, "8" + "10" is length 3 which is odd and eliminated.

```
int S(int[] i)
{
    var m = i.Min();
    return i.Where(v => v < m * 10 && $"{v}{m}".Length % 2 == 0).Max();
}

```
> 0 votes

# Answer
# C# 72 bytes

```
int S(int[]i){return i.OrderBy(v=>(""+v).Length).ThenBy(v=>-v).First();}

```

Borrowing from some of the other answers, a very efficient way to accomplish this task is to sort by number of digits, then by value descending. This moves the answer to the first position. Linq accomplishes this fairly simply with the OrderBy and ThenBy statements.

```
Console.WriteLine(S(new[] { 738, 2383, 281, 938, 212, 1010 }));

```

Output: 938
> 0 votes

# Answer
## Racket 148 bytes

```
(λ(l)(define l2(map number->string l))(apply max(map string->number
(filter(lambda(x)(eq?(string-length x)(apply min(map string-length l2))))l2))))

```

Testing:

```
(f (list 1 5 9 12 63 102))

```

Output:

```
9

```

Detailed version:

```
(define (f sl)
  (define sl2 (map number->string sl))
  (apply max
         (map string->number
              (filter (lambda(x)
                        (equal? (string-length x)
                                (apply min (map string-length sl2))
                                )) sl2))))

```
> 0 votes

# Answer
## SQLite, 49 bytes

```
SELECT n FROM a ORDER BY length(n),n DESC LIMIT 1

```

Of course only if the list is allowed to be in a table. The type of the field should be INTEGER.
> 0 votes

# Answer
## C++11, 109 bytes

```
[](auto a){sort(a.begin(),a.end(),[](auto x,auto y){return (int)log10(x)<=(int)log10(y)&&x>y;});return a[0];}

```

a should be a container like vector or list. E.g. (lambda as f)

```
cout<<f(vector<int>{ 10, 13, 19, 100, 12200 });

```
> 0 votes

# Answer
# Common Lisp, 136 bytes

Golfed:

```
(defun o(&rest r &aux(s(sort r '<)))(flet((f(x)(floor(log x 10))))(apply 'max(remove-if(lambda(x)(<(apply 'min(mapcar 'f s))(f x)))s))))

```

Ungolfed:

```
(defun o (&rest r
      &aux (s (sort r '<)))
  (flet ((f (x) (floor (log x 10))))
    (apply 'max
       (remove-if (lambda (x)
            (< (apply 'min (mapcar 'f s))
               (f x)))
              s))))

```
> 0 votes

# Answer
# Pascal (FPC), ~~169~~ 167 bytes

A function which takes variable array as input:

```
function m(a:array of integer):integer;var i:integer;begin m:=a[0];for i in a do if(int(log10(i))<int(log10(m)))or((int(log10(i))=int(log10(m)))and(i>m))then m:=i;end;

```

Try it online!

(Yes I know, pascal sucks at this, in addition there is no sort function in it's library..)
> 0 votes

# Answer
# Coconut, 56 bytes

This is just a Coconut-ification of the best (currently only) Python 3 answer (as well as some of the other answers), so most of the credit should go to them. Any valid Python 3 is Coconut which means it's at most the same length. Also, Coconut compiles to Python.

`lambda a:sorted(sorted(a),key=lambda x:-len(str(x)))[-1]` can be changed into `->sorted(sorted(_),key=->-len(str(_)))[-1]`. This compiles to `lambda _=None: sorted(sorted(_), key=lambda _=None: -len(str(_)))[-1]` (along with a ton of other stuff like additional Coconut builtins).
> 0 votes

# Answer
# JavaScript (Node.js), 53 bytes

```
a=>a.reduce((N,n)=>~(L=Math.log10)(N)!=~L(n)^N>n?N:n)

```

Attempt This Online!

## Explanation

For any two values `N,n`, we need to decide which to return, this table describes that:

```
         length
        | < = >
     ---+-------
value < | N n .
      = | . ? .
      > | . N n

```

Where `.` will never happen and `?` means either `N` or `n` works.

This looks a lot like an exclusive or (XOR) table:

```
      A
    | 0 1
 ---|-----
B 0 | 0 1
  1 | 1 0

```

Where we XOR `length(N) != length(n)` with `N > n`. The cheapest way (I think) to get the length of a number in JS is using `Math.log10`, then flooring the result with a bitwise operator (in this case `~`).

I also \[ab\]use the fact that `^` has lower operator precedence than comparisons.
> 0 votes

# Answer
# Thunno 2 `hG`, 3 bytes

```
Ṡñl

```

Attempt This Online!

## Thunno 2, 5 bytes

```
ṠñlhG

```

Attempt This Online!

#### Explanation

```
ṠñlhG  # Implicit input
Ṡ      # Sort the input, so the minimum item is at the start
 ñ     # Group this sorted list by the following:
  l    #  Length (for integers this is number of digits)
   h   # Get the first group (the minimum digits)
    G  # And get the maximum item in this group
       # Implicit output

```
> 0 votes

---
Tags: code-golf, number, arithmetic
---


title: 196 algorithm code golf

text:
# Question
Title: 196 algorithm code golf
Write a short program for 196-algorithm. The algorithm starts from an integer, then adds its reverse to it until a palindrome is reached.

e.g.

```
input = 5280
5280 + 0825 = 6105
6105 + 5016 = 11121
11121 + 12111 = 23232
output = 23232

```

**Input**

an integer, which is not a lyrchrel number (that is, it does eventually yield a palindrome under this algorithm, rather than continuing infinitely)

**Output**

the palindrome reached.

# Answer
> 10 votes
## APL (22 characters)

```
{a≡⌽a←⍕(⍎⍵)+⍎⌽⍵:a⋄∇a}⍞

```

This works in Dyalog APL. Here's an explanation, from right to left:

* `{ ... }⍞`: Get input from the user as characters () and feed it to our function (`{ ... }`).
* Within the direct function ( separates statements, so we look at them from left to right):
    + `a≡⌽a←⍕(⍎⍵)+⍎⌽⍵ : a`: Evaluate () the right argument's () reverse (), and add that to the evaluated version of the right argument itself. Then, format the result (; i.e., give its character representation), assign () that to the variable `a`, and finally test if `a`'s reverse is equivalent to `a` (i.e., is `a` a palindrome?). If true, return `a`; otherwise...
    + `∇a`: Feed `a` back into our function ( is implicit self-reference).

Example:

```
      {a≡⌽a←⍕(⍎⍵)+⍎⌽⍵:a⋄∇a}⍞
412371
585585

```

# Answer
> 10 votes
# Python 2, 55 bytes

Following JPvdMerwe suggestion:

```
n=input()
while`n`!=`n`[::-1]:n+=int(`n`[::-1])
print n

```

**Python 2, 62:**

```
n=raw_input()
while n!=n[::-1]:n=`int(n)+int(n[::-1])`
print n

```

# Answer
> 10 votes
## GolfScript, 29 chars

```
~]{{.`.-1%.@={;0}{~+1}if}do}%

```

---

**Selected commentary**

The meat of the program is the `do` loop, of course. So I'll just cover that.

1. `.`` copies the number and stringifies it.
2. `.-1%` copies that string version and reverses it.
3. `.@` copies the reversed version, and brings the original non-reversed version to the front.

So, say, the number is 5280. At this stage, the stack is: `5280 "0825" "0825" "5280"`. The stage is set for the comparison. (After the comparison, the stack will be left at `5280 "0825"` no matter what---the items to compare have been popped off.)

1. If the string and the reverse are the same, we don't care about the reversed string, so just pop it off (`;`) and return 0 (to end the `do` loop).
2. If they don't match, then evaluate (`~`) the reversed string (to make it a number), add (`+`) that to the original number, and return 1 (to continue the `do` loop).

# Answer
> 7 votes
**Ruby — 56 chars**

```
x,r=gets
x="#{x.to_i+r.to_i}"until x==r=x.reverse
puts x

```

# Answer
> 7 votes
Just exercising my Pyth skills, not a serious contender.

# Pyth, 16 bytes

```
L?bqb_by`+vbi_bTyz

```

Equivalent to Python 3:

```
y=lambda b:b if b==b[::-1] else y(str(eval(b)+int(b[::-1],10)))
print y(input())

```

# Answer
> 6 votes
# J 25 27 31

```
f=:(+g)^:(~:g=.|.&.":)^:_
e.g.
f 5280
23232

```

# Answer
> 6 votes
# CJam, ~~22~~ 21 bytes

CJam was created after this question was asked, so technically its an invalid submission. But I found the question interesting, so here goes:

```
r{__W%:X=0{~X~+s1}?}g

```

Explanation:

```
r{                 }g    "Read the input number as string and enter a while-do loop";
  __                     "Make 2 copies of the string number";
    W%:X                 "Reverse the second and store it in X";
        =                "Check if the number is already palindrome";
         0{      }?      "Put 0 on stack if it is palindrome, else, run the code block";
           ~             "Convert the string to int";
            X~           "Put the reverse string on stack and convert it to int too";
              +s         "Add the two numbers and covert back the result to string";

```

The core logic is that in each while-do iteration, you first check if palindrome is achieved or not. If not, add the reverse to the number. Pretty much what the algorithm is!

Try it online here

# Answer
> 6 votes
This is an actual contender, since J has been around for decades.

# J (16 bytes)

```
(+^:~:|.&.":)^:_

```

This is a verb, so it can be assigned to a variable in a J session and used like so:

```
   f =. (+^:~:|.&.":)^:_
   f 5280
23232

```

How it works:

```
(+^:~:|.&.":)^:_
 +^:~:           add if unequal
      |.&.":     reverse under string format
 +^:~:|.&.":     add reverse unless a palindrome
(           )^:_ repeat until unchanged

```

# Answer
> 6 votes
# 05AB1E, 7 bytes

Code:

```
[DÂQ#Â+

```

Explanation:

```
[        # Infinite loop.
 DÂ      # Duplicate and bifurcate (which duplicates it and reverses the duplicate).
   Q#    # If the number and the number reversed are equal, break.
     Â+  # Add the reversed number to the initial number.

```

Uses the **CP-1252** encoding. Try it online!.

# Answer
> 4 votes
Python: 66

```
n=input()
while 1:
 r=int(`n`[::-1])
 if n==r:break
 n+=r
print n

```

# Answer
> 4 votes
Perl, 40 chars

```
$_=<>;$_+=$r while$_!=($r=reverse);print

```

# Answer
> 4 votes
# PHP - ~~54~~ 48 characters

```
<?for($s=`cat`;$s!=$r=strrev($s);$s+=$r);echo$s;

```

Test:

```
$ php 196.php <<< 5280
23232

```

# Answer
> 4 votes
### Scala 82

```
def p(n:Int):Int={val s=n.toString.reverse.toInt
if(n==s)n else p(n+s)}
p(readInt)

```

# Answer
> 4 votes
# JAGL Alpha 1.2 - 19, 21 with stdin

***Not contending***, just getting some experience with my language
Expects a number from stdin

```
T~d{DddgCi+dgdC=n}uSP

```

Explanation

```
T~                       Get a line of input, and eval to an integer
  d                      Duplicate (for first round)
   {Ddd                  Drop last and duplicate twice
       gCi               Convert to string, reverse, and convert back to integer
          +d             Add to original and duplicate
            gdC          Convert to string, duplicate, reverse
               =n}       If it isn't a palindrome, keep going
                  uSP    Run until palindrome reached, then print output number

```

# Answer
> 4 votes
# Brachylog, 8 bytes

```
↔?|↔;?+↰

```

Try it online!

Somewhat similar to one of the first Brachylog programs I saw and was intrigued by, from the Brachylog introduction video.

```
?↔?.|↔;?+↰.  (initial ? and the .s are implicit)

?↔?          % If the input and its reverse are the same,
   .         %   then the input is the output
    |↔;?+↰   % Or, add the input and its reverse, and call this predicate recursively
          .  % The result of that is the output

```

# Answer
> 3 votes
## In Q (39 characters)

```
f:{while[x<>g:"I"$reverse -3!x;x+:g];x}

```

Sample Usage:

```
q)f 5280
23232

```

Edit:

Down to 34 now, same usage:

```
{while[x<>g:"I"$(|) -3!x;x+:g];x} 5280

```

# Answer
> 3 votes
## C# - 103 99 chars

```
public int P(int i)
{
    var r = int.Parse(new string(i.ToString().Reverse().ToArray())));
    return r == i ? i : P(i + r);
}

```

C# never does very well in golf. Elegant, but verbose.

# Answer
> 3 votes
## Bash (64)

```
X=`rev<<<$1|sed s/^0*//`;[ $1 = $X ]&&echo $1||. $0 $(($1+$X))

```

Call with: bash \<filename\> \<number\>

# Answer
> 3 votes
```
r=input()
while 1:
    r=`r`
    if r==r[::-1]:
      break
    else:
      r=int(r)+int(r[::-1])

print r

```

# Answer
> 3 votes
# Jelly, 9 bytes (non competing)

A very simple answer, just for the challenge of coding in and esoteric language.

`ṚḌ+µŒḂ¬$¿`

```
ṚḌ        : take the argument, reverse (and vectorize) it
  +µ      : add both
    ŒḂ¬$¿ : while the result isn't a palindrome

```

Try it online!

Should this answer be unclear or wrong on any level, feel free to point it out.

Thanks to Dennis for helping me out with this first small piece of code.

# Answer
> 3 votes
# Java (JDK), ~~78~~ 71 bytes

```
i->{for(int r=0,t;i!=r;)for(t=i+=r,r=0;t>0;t/=10)r=r*10+t%10;return i;}

```

Try it online!

-7 Thanks to Celingcat!

# Answer
> 2 votes
Python. 85 characters:

```
s,i=str,int;rs=lambda q:s(q)[::-1];n=i(input());
while rs(n)!=s(n):n+=i(rs(n));print n

```

If you don't want output on each iteration:

```
s,i=str,int;rs=lambda q:s(q)[::-1];n=i(input());
while rs(n)!=s(n):n+=i(rs(n))
print n

```

(one less character)

# Answer
> 2 votes
### Windows PowerShell (63)

```
for($a=+"$input";-join"$a"[99..0]-ne$a){$a+=-join"$a"[99..0]}$a

```

I still hate it that there is no easy way to reverse a string.

# Answer
> 2 votes
**Haskell ~~89~~ 87 chars**

```
r=read.reverse.show
main=getLine>>=print.head.filter(\x->x==r x).iterate(\x->x+r x).read

```

Somewhat readable version:

```
myFind p = head . filter p
rev = read . reverse . show
isPalindrome x = x == rev x
next x = x + rev x
sequence196 = iterate next
palindrome196 = myFind isPalindrome . sequence196

main = getLine >>= print . palindrome196 . read

```

The golfed version was created by manual inlining and renaming the remaining functions to single character names.

# Answer
> 2 votes
## befunge, 57 bytes

```
"KCTS"4(&:0\v
\T\a*+\:0`jv>:a%\a/
0:+_v#-TD2$<^\
  @.<

```

though the code is places in a 4x19 grid, so might call it 76.

* first line is initializeing, and reading input number
* second line reverse first number in stack and put it in the second stack position.
* and the third line checks if a number is palindrome.

# Answer
> 2 votes
## C++ TMP (256 characters)

```
#include<cstdio>
#define Y(A,B,C,D)template<int N>struct A<C,D>{enum{v=B};};
#define Z(A)template<int N,int M>struct A{enum{v=
#define n 5194
Z(R)R<N/10,M*10+N%10>::v};};Y(R,N,0,N)Z(S)S<N+M,R<N+M,0>::v>::v};};Y(S,N,N,N)main(){printf("%d",S<n+R<n,0>::v,0>::v);}

```

This version could be shortened a bit, but a 256-character answer is hard to pass up. Here's an un-golfed version:

```
#include <iostream>

template<size_t N>
class Reverse
{
    template<size_t M, size_t R>
    struct Inner
    {
        enum { value = Inner<M/10, R*10 + M%10>::value };
    };

    template<size_t R>
    struct Inner<0, R>
    {
        enum { value = R };
    };

public:
    enum { value = Inner<N, 0>::value };
};

template<size_t N>
class OneNineSix
{
    template<size_t M, size_t R=Reverse<M>::value>
    struct Inner
    {
        enum { value = OneNineSix<M + R>::value };
    };

    template<size_t M>
    struct Inner<M, M>
    {
        enum { value = M };
    };

public:
    enum { value = Inner<N + Reverse<N>::value>::value };
};

int main()
{
    const size_t N = 4123;

    std::cout << OneNineSix<N>::value << std::endl;
}

```

# Answer
> 2 votes
## Pyke, 13 bytes (noncompeting)

```
D`_b]D$XIsr)h

```

Try it here!

```
 `_b          -     int(reversed(str(num))
D   ]         -    [num, ^]
     D        -   _ = ^
      $       -  delta(^)
       XI     - if ^:
         s    -  num = sum(_)
          r   -  goto_start()
            h - _[0]

```

# Answer
> 2 votes
# Add++, 57 bytes

```
L,BDbRBv
D,f,@,1]A+
D,g,@,1]A=
D,h,@,{f}A{g}Q{h}
L,{h}2/i

```

Try it online!

## How it works

```
L,	; Create a function 'lambda 1'
	; Example argument:   [5280]
    BD	; Digits;     STACK = [[5 2 8 0]]
    bR	; Reverse;    STACK = [[0 8 2 5]]
    Bv	; Undigits;   STACK = [825]

D,f,@,	; Define a monadic function 'f'
	; Example argument:         [5280]
    1]	; Call 'lambda 1';  STACK = [825]
    A+	; Add the argument; STACK = [6105]

D,g,@,	; Define a monadic function 'g'
	; Example argument:          [5280]
    1]	; Call 'lambda 1';   STACK = [825]
    A=	; Equal to argument; STACK = [0]

D,h,@,	; Define a monadic function 'h'
	; Example argument:  [5280]
   {f}	; Call 'f';  STACK = [6105]
   A{g}	; If 'g'...
   Q	;   Return
   {h}	; Else call 'h'

L,	; Define a function, 'lambda 2'
	; Example argument: [5280]
   {h}	; Call 'h'; STACK = [46464]
   2/i	; Halve;    STACK = [23232]

```

# Answer
> 2 votes
# C (gcc), 132 bytes

```
t;r(char*s){char*e=s+strlen(s)-1;for(;e>s;*e--=*s,*s++=t)t=*e;}g(o,l,f){for(l=malloc(9);sprintf(l,"%d",o),r(l),f=atoi(l),f-o;)o+=f;}

```

Call with `g(n)` for an `int n`. Try it online here.

Ungolfed:

```
t; // temporary varaiable fpr swapping characters
r(char *s) { // helper function to reverse a string: takes a string argument and modifies it
    char *e = s + strlen(s) - 1; // find the end of the string
    for(; e > s; // move the end pointer and the start pointer towards each other until they meet
        *e-- = *s, *s++ = t) // swap the characters under the start and end pointers ...
        t = *e; // ... using the temporary variable
}
g(o, // function for the 196 algorithm: takes an int argument and returns an int
  l, f) { // abusing the argument list to declare to extra variables: one is a string for reversing the number, the other is an int
    for(l = malloc(9); // allocate space for the string
        sprintf(l, "%d", o), // convert the number to a string
        r(l), // reverse that string
        f = atoi(l), // convert it back to an int
        f - o; ) // loop until the two numbers are equal
        o += f; // add the two numbers
}

```

# Answer
> 2 votes
# GNU dc, 46 bytes

Requires GNU dc, min version 1.4 (for `R` command).

```
[O~3RO*+rd0<R]sR[+lfx]sg[ddO~rd0<R+d3R!=g]dsfx

```

Input and output are top-of-stack, as usual. It takes a surprising amount of code to reverse digits in dc (unless I'm missing something, which is far from impossible). It does have the numeric range to behave nicely with inputs such as these (which will overflow 32-bit unsigned arithmetic, for example):

* 89 ⇒ 8,813,200,023,188
* 8997 ⇒ 16,668,488,486,661
* 10677 ⇒ 4,668,731,596,684,224,866,951,378,664

### Explanation

```
# Reverse digits, starting after first digit extracted
[O~3RO*+r d0<R]sR

# Recursion helper - add and recurse
[+ lfx]sg

# Main recursive function
[dd O~r d0<R+ d3R !=g]dsfx

```

# Answer
> 2 votes
# , ~~193~~ ~~109~~ 105 bytes

-84 bytes thanks to Giuseppe! -4 byes thanks to JayCe!

```
function(x){"-"=utf8ToInt
S=strtoi
"!"=rev
while({z=paste(S(x)+S(intToUtf8(!-x),10));any(-z!=!-z)})x=z
z}

```

Try it online!

# Answer
> 2 votes
# Powershell, ~~63~~ 62 bytes

*-1 byte thanks to @AdmBorkBork*

```
param($m)for(;$m-$s;$m=-join"$s"[-1..-"$s".Length]){$s+=$m};$s

```

Test script:

```
$f = {
param($m)for(;$m-$s;$m=-join"$s"[-1..-"$s".Length]){$s+=$m};$s
}

&$f 5280

```

# Answer
> 2 votes
# Thunno 2, 7 bytes

```
(ḲQ;ḲN+

```

Attempt This Online!

#### Explanation

```
(ḲQ;ḲN+  # implicit input
(  ;     # while loop
  Q      # (condition)  not equal to
 Ḳ       #              its reverse
     N+  # (body)       add
    Ḳ    #              the reverse
         # implicit output

```

# Answer
> 1 votes
# Dyalog APL, 17 bytes

```
{⍵+⍎⌽⍕⍵}⍣{⍺≡⍎⌽⍕⍺}

```

`{⍵+⍎⌽⍕⍵}` add argument and its reverse...
... until...
`{⍺≡⍎⌽⍕⍺}` ... the result is a palindrome.

# Answer
> 1 votes
# Javascript ES6, 56 bytes

```
f=a=>(g=_=>[...""+a].reverse().join``)()==a?a:f(a+ +g())

```

# Answer
> 1 votes
# Java, ~~90~~ 84 bytes

```
n->{for(long t;(t=new Long(new StringBuffer(n+"").reverse()+""))!=n;)n+=t;return n;}

```

-6 bytes thanks to *@O.O.Balance*.

Try it online.

**Explanation:**

```
n->{           // Method with long as both parameter and return-type
  for(long t;  //  Temp-long, starting uninitialized
      (t=new Long(new StringBuffer(n+"").reverse()+""))
               //  Before every iteration, reverse the temp-long
      !=n;)    //  And loop as long as it's not equal to `n` yet
    n+=t;      //   Add this temp-long to the input
  return n;}   //  Return the modified input as result

```

# Answer
> 1 votes
# Japt, ~~11~~ 10 bytes

```
@¶ìw}a@±ìw

```

Try it

```
@¶ìw}a@±ìw     :Implicit input of integer U
@              :Left function
 ¶             :  Test U for equality with
  ì            :  Convert to digit array
   w           :    Reverse and convert back to integer
    }          :End function
     a         :Get the first result of the right function that returns true when run through the left function
      @        :Right function
       ±       :  Increment U by
        ìw     :  As above

```

# Answer
> 1 votes
## PHP, 57 Bytes

Try it online!

**Code, recursive function**

```
function f($n){echo(strrev($n)!=$n)?f(strrev($n)+$n):$n;}

```

**Explanation**

```
function f($n){
    echo(strrev($n)!=$n)? #check if non-palindrome
        f(strrev($n)+$n): #true, call again with $n + reverse $n
        $n;               #false (is a palindrome) echo $n

}

```

# Answer
> 1 votes
# Perl 6, 36 bytes

```
{($_,{$_+.flip}...{$_==.flip})[*-1]}

```

Try it online!

An anonymous code block that returns the last element of a sequence defined by:

* The first element is the first parameter
* The `i+1`th element is the `i`th element plus the reverse of itself
* And ends when the element is equal to its reverse

# Answer
> 1 votes
# MATL, 18 bytes

```
`Vt2&P=?5M.}1MvUsT

```

Try it on MATL Online

```
         % (implicit input)
`        % do-while loop
  Vt     % convert the number into a string, duplicate it
  2&P    % flip the copy left-to-right
  =      % are they equal?
    ?5M. % if yes, push the number back on the stack and exit
         % (implicit output display)
    }1M  % else, push the number and its reverse (as strings) again on to the stack
    vUs  % convert them to numbers and add them
    T    % "True" value to continue loop, this time with the sum as the input number
         % (implicit loop end)

```

# Answer
> 1 votes
# Husk, 7 bytes

```
¤Ω`S↔=+

```

Try it online!

Alternatively we could use `ΩS=↔S+↔` for the same amount of bytes, but I like the one above more.

## Explanation

```
¤Ω`S↔=+
¤        -- compose the arguments of
 Ω       -- | iterate second function until first is truthy
         -- with
  `S     -- | flipped S: applying binary function to itself and
    ↔    -- | | itself reversed
         -- first function: check if palindrome (\x-> x == reverse x)
         -- second function: "196ify" (\x-> x + reverse x)

```

# Answer
> 1 votes
# Ruby, 55 bytes

```
l=->x{x.reverse==x ? x:l[(x.to_i+x.reverse.to_i).to_s]}

```

Different approach than the other Ruby one, ended up golfing it down to one byte fewer

Explanation: makes a lambda `l` that recursively calls itself, each time adding the number's reverse, until the string is a palindrome

Slightly less golfed version:

```
func = ->x do
  (x.reverse == x) ? x : func[(x.to_i + x.reverse.to_i).to_s]
end

```

# Answer
> 1 votes
# Excel VBA, 49 bytes

An immediate window function which takes input from range `[A1]` and outputs to the VBE immediate window.

```
n=[A1]:Do:n=n+r:r=StrReverse(n):Loop While n-r:?n

```

# Answer
> 1 votes
# Lua 5.3.3, 57 bytes

Takes `i` as input, prints output:

```
r=0while i~=r do i=i+r|0r=0+(i..""):reverse()end print(i)

```

More readable version:

```
r=0
while i~=r do
  i=i+r|0
  r=0+(i..""):reverse()
end
print(i)

```

Super simple. Just repeatedly adds `i` to its reverse until `i` is equal to its reverse. Then it just prints the new value of `i`.

# Answer
> 1 votes
# Actually, 16 bytes

```
;WX;$R≈+;$;R=YWX

```

Try it online!

Explanation:

```
;WX;$R≈+;$;R=YWX
;                 push a copy of n
 W            W   while top of stack is truthy:
  X                 pop and discard
   ;$R≈+            copy n, cast to string, reverse, cast to int, add
        ;$;R=Y      not palindrome (cast to string, copy, reverse, check inequality)
               X  pop and discard

```

# Answer
> 1 votes
# , 27 bytes

```
(+&.".|.)^:(-.@-:|.)^:_&.":

```

Try it online!

# Answer
> 1 votes
# Python 2, 53 bytes

```
f=lambda x,y=0:x if x==y else f(x+y,int(`x+y`[::-1]))

```

Try it online!

# Answer
> 1 votes
# Ruby, 47 bytes

```
->a{v=a.to_s.reverse;v==a.to_s ? a:f[a+v.to_i]}

```

Try it online!

# Answer
> 1 votes
# Vyxal, 6 bytes

```
{Ḃ≠|m:

```

Try it Online!

Wooo cursed behaviour for numbers ftw.

## Explained

```
{Ḃ≠|m:
{Ḃ≠|      # while t.o.s[::-1] != tos:
    m     #     mirror the tos (that is, add the reverse of the number to the number)
     :    #     and duplicate the tos so that the while loop condition has a value to work on.

```

# Answer
> 1 votes
# Python 2, 49 bytes

\\$n\\$ added to its reverse is \\$2n\\$ iff \\$n\\$ is a palindrome.

```
f=lambda n,r=0:n-r*2and f(n+int(`n`[::-1]),n)or r

```

Try it online!

# Answer
> 1 votes
# Pyt, 10 bytes

```
`ΠĐ₫+Đ₽¬ł+

```

Try it online!

```
`       ł          do... while top of stack is not 0
 Π                 product of everything on the stack (gets input on first pass;
                       otherwise removes the pesky 1 that resulted from the loop checking)
  Đ                Đuplicate
   ₫               reverse the ₫igits
    +              add
     Đ             Đuplicate
      ₽¬           is the result not a ₽alindrome?
         +         add (removes the pesky 0 that was used to break out of the loop)

```

# Answer
> 0 votes
# Wren, 102 bytes

A super long program.

```
Fn.new{|x|
while(x!=x[-1..0])x=(Num.fromString(x)+Num.fromString(x[-1..0])).toString
System.write(x)
}

```

Try it online!

# Answer
> 0 votes
# Vyxal, 7 bytes

```
{:Ḃ≠|Ḃ+

```

Try it Online!

```
{       # While...
 :Ḃ≠    # It's not a palindrome
    |   # Do...
     Ḃ+ # Concatenate to its reverse

```

# Answer
> 0 votes
# JavaScript, 46 bytes

```
f=n=>[r=``,...n+r].map(d=>r=d+r)|n-r?f(+r+n):n

```

Try it online!

# Answer
> 0 votes
# Rattle, 12 bytes

```
|[st[~q]+~]0

```

Try it Online!

# Explanation

```
|              take input
 [ ....... ]0  infinite loop
   s           save top of stack to storage
    t          reverse this value
     [~ ]      execute if the reversed value is equal to the saved value
       q       quit the program, the result is printed implicitly
         +~    add the stored value to the current value

```

# Rattle, 21 bytes (a different approach)

```
|[st+~s1/~[2g1/q]g1]0

```

Try it Online!

# Explanation

```
|                    take input
 [ ... ]0            infinite loop

  s                  save top of stack to storage in slot 0
   t                 reverse top of stack
    +~               add value in slot 0 to top of stack
      s1             save result in slot 1
        /~           divide this by the value in slot 0 (the previous number)

  [2 ... ]           if the result is exactly 2, execute code inside if statement
    g1               get value in slot 1
      /              divide (with no argument, divides by 2)
       q             quit program, top of stack is output implicitly
          g1         get value in slot 1

```

---
Tags: code-golf, palindrome
---