text:
Test if a given number is a Vampire Number
EDIT: In the interest of increasing the complexity, i've added more to the challenge.

In mathematics, a vampire number (or
  true vampire number) is a composite
  natural number v, with an even number
  of digits n, that can be factored into
  two integers x and y each with n/2
  digits and not both with trailing
  zeroes, where v contains precisely all
  the digits from x and from y, in any
  order, counting multiplicity. x and y
  are called the fangs.

More about Vampire Number
Pseudovampire numbers

Pseudovampire numbers are similar to
  vampire numbers, except that the fangs
  of an n-digit pseudovampire number
  need not be of length n/2 digits.
  Pseudovampire numbers can have an odd
  number of digits, for example 126 =
  6×21.

Input
Accept Numbers from command line or stdin
Output

"1260 = 21 * 60" (smaller fang first if the number is a Vampire.)
"1261 is not a Vampire Number." (if the number is not a Vampire number)
"126 = 6 * 21". (if the number is a Pseudovampire number)

EDIT: If the number has multiple fangs, display it so.
x = fang1a * fang1b = fang2a * fang2b

I've decided not to include Prime vampire's, i won't go overboard with it.

Maybe i should add Printing if its a Vampire or a PseudoVampire, what do you guys say?

What about multiple pairs of fangs?

@gnibbler, i'll ammend it.

If number has several pair, does their order important? I mean 125460 = 204 * 615 = 246 * 510 or 125460 = 246 * 510 = 204 * 615? Or doesn't matter?

BTW, there is still no increasing the complexity, because nothing denied to use full permutations' processing, as we solved with gnibbler. Another thing is that it could be not golf problem, but smth like how large number can you find, which has exactly n pairs, but it's already another question, and this can't be modified so.

@Nakilon, print them in the increasing order. fang1a appears before fang2a when fang1a < fang2a

Python - 188 chars
Doesn't do Pseudovampire numbers
from itertools import*
n=input()
a=[]
for i in map("".join,permutations(`n`)):x,y=int(i[::2]),int(i[::-2]);a+=[(x,y)]*(x*y==n)
print n,a and"=%s*%s"%min(a)or"is not a Vampire Number"

Also doesn't handle multiple pairs (for 125460) and space missed after =.

(checked here)

@Nakilon, this answer predates the amendment for multiple pairs

Ruby, 190 chars
o=[]
[*x.chars].permutation{|r|a=r.pop(x.size/2).join.to_i
r=r.join.to_i
o|=[[a,r]]if a<=r&&a*r==x.to_i}
puts x+(o.any? ? o.map{|i|" = "+i*" * "}*"":" is not a Vampire Number.")

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/2.5/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Poisson random number generator
What is the shortest function (implemented in C) that will return a random draw from a Poisson distribution (given the mean or λ parameter)?
int random_poisson(double lambda);

Why is this question restricted to C? Might be a better fit for SE.

Taken from the wikipedia article which credits Knuth (and notes that there are implementations with better time performance) this code is a complete program implementing a minimal test scaffold. The code that does the actual work is 169 characters still formatted:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
#include <string.h>

/* For serious work you need a high quality random number generator
 *
 * And these macros may need to be adjusted for your system and choice
 * of random number engine.
 */
#define GOODRAND random()
#define GOODRANDMAX INT_MAX
#define RANDTYPE long

/* poisson.c
 *
 * Implementation straight from
 * http://en.wikipedia.org/wiki/Poisson_distribution#Generating_Poisson-distributed_random_variables
 * which credits Knuth.
 *
 * Time complexity is O(lambda), which is not optimal.
*/
RANDTYPE poisson(double lambda){
  RANDTYPE k=0;
  double L=exp(-lambda), p=1;
  do {
    ++k;
    p *= GOODRAND/(double)GOODRANDMAX;
  } while (p > L);
  return --k;
}

/* minimal testing scaffold
*
* Note that with no initialzation the sequece will repeat on every test.
*/
int main(int argc, char**argv){
  while (argc > 1) {
    RANDTYPE in = atoi(argv[--argc]);
    printf("lambda=%d:  %d\n",in,poisson(in));
  }
}

not very golfed, imho.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/2.5/


text:
Morse code translator
Write the shortest program to transform the standard input into Morse code. Characters not in the table should be printed as they are.

Are both capital and lowercase letters encoded?

Also, could you provide a sample input and output to clarify details like spacing between words?

Well, in Morse, there's no difference between lower and upper case. There's no real symbol for space (it's just a 3/4 times silence) so I guess it should be translated as a space.

@Joey: The details are up to you.

Similar to the Stack Overflow question Code Golf: Morse code.

Doing the reverse might be a bit more challenging. Say, with no letter separation?

How is pauses (The silence equal to one dot) encoded?

Golfscript - 74 chars
This answer supports only uppercase and digits. The letters are separated by newlines and words are separated by 2 newlines
{." ETIANMSURWDKGOHVF L PJBXCYZQ"?)"?/'#! 08<>"@))10%=or 2base(;{!45+}%n}%

Analysis

    { }%          as usual works like a map over the array
    .             push a copy of the char onto the stack
    " ETIAN..."   this is a lookup table for the uppercase characters
    ?             like a string.find returns the index of the char in the string
                  or -1 if it is not found (ie it's a digit)
    )             increment that index so E=>2 T=>3 I=>4 etc. notice that if the
                  char is not an uppercase letter or space this is now 0 (False)
    "?/'#!..."    this is a lookup table for the digits. it will be used in the
                  reverse way to the other lookup table.
    @             pull that copy we made of the char to the top of the stack
    ))%10         convert ascii digit to a number by adding 2 and taking mod 10.
                  It's important to do it this way because all the uppercase
                  letters hit this code too, and we need to make sure they fall
                  in the range 0..9 or the next step will fail.
    =             pull the nth char from the string eg "Hello"1= gives "e"
    or            remember if the uppercase lookup fails we have a 0 result, so
                  the digit lookup will be used
    2base         convert to base 2 so E=>[1 0], T=>[1 1], I=>[1 0 0] etc.
    (;            pop the front of the list and throw it away so E=>[0], T=>[1]
    {!45+}%       negate each bit and add 45, this gives ascii value of . and -
    n             newline separates each word. this could be 32 if you wanted to
                  separate the words with spaces for a cost of 1 stroke

Golfscript - 85 chars
This is shorter than my SO answer due to the relaxed requirements here
The input must be uppercase/digits and the punctuation characters ".,?"
{." ETIANMSURWDKGOHVF!L!PJBXCYZQ"?)"UsL?/'#! 08<>"@".,?"58,48>+?=or
2base(;{!45+}%n}%

Since the punctuation is not even required here, I may shorten the answer even more
My answer from SO
Golfscript - 107 chars
newline at the end of the input is not supported, so use something like this
echo -n Hello, Codegolfers| ../golfscript.rb morse.gs
Letters are a special case and converted to lowercase and ordered in their binary positions.
Everything else is done by a translation table
' '/{{.32|"!etianmsurwdkgohvf!l!pjbxcyzq"?)"UsL?/'#! 08<>"@".,?0123456789"?=or
2base(;>{'.-'\=}%' '}%}%'/'*

The order of your code blocks here is confusing George's UserScript. Could I trouble you to rearrange? And I would like to see it explained. I get the implicit tree, but the rest is a mystery to me.

@dmckee, done. George's script noticed my count was out by one, so I fixed that too

Requiring upvotes to see the analysis... boo!  The analysis is what makes answers worth the upvotes!

@Nick, ok I think it's as short as I can get it, so I'll get to work on that analysis

C# (213 characters)
I'm sure this wont stand long, but at least I got the technique here first!
class P{static void Main(string[] a){foreach(var t in a[0]){var c="";for(int i=" ETIANMSURWDKGOHVF L PJBXCYZQ  54 3   2       16       7   8 90".IndexOf(t);i>0;i/=2)c="-."[i--%2]+c;System.Console.Write(c+"  ");}}}

And in readable format:
class P
{
    static void Main(string[] a)
    {
        foreach(var t in a[0])
        {
            var c="";
            for(int i=" ETIANMSURWDKGOHVF L PJBXCYZQ  54 3   2       16       7   8 90".IndexOf(t);i>0;i/=2)c="-."[i--%2]+c;
            System.Console.Write(c+" ");
        }
    }
}

For a brief explanation, the string of characters is a heap in which the left child is a dot and the right child is a dash.  To build the letter, you traverse back up and reverse the order.

This is the best idea I've seen so far.

And then I read the linked thread and noticed this is far from original.

When I saw the ETIAN... in there, I assumed it worked the same as the golfscript, but you have a different way of interpreting the string. I think it is equivalent but I add 1 to the index and use the binary representation to get the dots and dashes for all the digits after the leading 1" eg F=>18=>0b10010=>..-.

You don't need the space in String[] a

tr + sed (347)
tr a-z A-Z | sed 's/0/--O/g;s/1/.-O/g;s/2/.J/g;s/3/..W/g;s/4/.V/g;s/5/.H/g;
 s/6/-.H/g;s/7/-B/g;s/8/-Z/g;s/9/--G/g;s/X/-U/g;s/V/.U/g;s/U/.A/g;
 s/Q/-K/g;s/K/-A/g;s/A/.T/g;s/J/.O/g;s/O/-M/g;s/Y/-W/g;s/W/.M/g;
 s/M/-T/g;s/T/- /g;s/H/.S/g;s/B/-S/g;s/S/.I/g;s/L/.D/g;s/Z/-D/g;
 s/D/-I/g;s/I/.E/g;s/C/-R/g;s/F/.R/g;s/R/.N/g;s/P/.G/g;s/G/-N/g;
 s/N/-E/g;s/E/. /g'

The space around a pipe could be eliminated as well ;-)

Yes, I'm not counting those spaces, I just print them here for clarity :)

You could use brace expansion to shorten it lots (/g;s/ becomes , -- plus a bit of overhead).

@nabb good idea.

You can drop the tr, use sed's y command instead

Actually sed's y command not supports character ranges, so you have to enumerate the entire alphabet. Twice. But s/.*/\U&/ would do it, at least in GNU sed.

Haskell — 314 292 291 characters
import Data.List
i=intercalate
m=i"       ".map(i" ".map(\c->words".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----."!!(head.findIndices(==c)$['a'..'z']++['0'..'9']))).words

A more user readable form:
tbl :: [String]
tbl = words ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----."

lookupChar :: Char -> String
lookupChar c = tbl !! (fromJust . elemIndex c $ ['a'..'z'] ++ ['0'..'9'])

encWord :: String -> String
encWord = intercalate " " . map lookupChar

encSent :: String -> String
encSent = intercalate "       " . map encWord . words

Sample run:
*Main> m "welcome humans"
".-- . .-.. -.-. --- -- .       .... ..- -- .- -. ..."

There's a single whitespace between two letters, and seven whitespaces between two words.

Just checked the question referenced by @dmckee "Code Golf: Morse code" and didn't find a Haskell version. I think, shorter than 314 would be possible.

fromJust.elemIndex c can be written as head.findIndices(==c). That is one character more, but you can then get rid of import Data.Maybe, so you'll save 17 characters total. You can also save two characters by removing the space in front of the string each time you call intercalate. And another few characters by doing i=intercalate at the beginning and replacing the two calls to intercalate with i.

@sepp2k: Nice idea! Thanks. I also played with intercalate and have saved another 6 characters! :-)

You can also do w=words, which saves one character if I'm not mistaken. And instead of l c=... and map l, you should do map\c->... (you don't even need parens around the lambda since there's already a closing paren afterwards anyway).

@sepp2k: Inlining of l c=... did save me 1 character, but I couldn't put it without parens, only as map(\c->...). GHC version 6.12.3.

@Yasir: Seems I was wrong about that (didn't test it). But good that you could save a character anyway.

VB.NET, 233 bytes
Module Module1
 Sub Main(a$())
   For Each c In a(0)
     Dim i = "ETIANMSURWDKGOHVF L PJBXCYZQ  54 3   2       16       7   8 90".IndexOf(c)
     If c <> " " And i >= 0 Then
       Console.Write("{0} ", Morse(i))
     Else
       Console.Write(c)
     End If
   Next
End Sub

Function Morse(i) As String
  Dim b = Math.Log(i) / Math.Log(2)
  Return (From m In MorseSeq(If(Double.IsInfinity(b), 0, b)) Order By m.Length)(i)
End Function

Function MorseSeq(i) As IEnumerable(Of String)
  Return If(i < 0, {}, From n In ".-" From m In MorseSeq(i - 1).DefaultIfEmpty
                       Select n & m)
End Function
End Module

That last function is evil.
edit
A couple of improvements.
Function Morse(i) As String
  Return (From m In MorseSeq(i) Order By m.Length)(i)
End Function

Function MorseSeq(i) As IEnumerable(Of String)
  Return If(i=0,{".","-"},From n In".-"From m In MorseSeq(i>>1) Select n & m)
End Function

I decided to +1 this because I can't remember ever seeing VB.net used for golfing.

Ruby, 161
d=proc{|x|x>1?d[x/2]+".-"[x&1]:' '}
$><<$<.gets.bytes.map{|i|
e=i>64?"-@B4*:68,?5</.7>E20+193ACD"[(i&95)-65]:i>47?"gWOKIHX`df"[i-48]:nil
e ?d[e.ord-40]:i.chr}*''

Encodes each digit into a single char, where 1 is dash, 0 is dot, with a leading 1 as a marker bit (plus an offset to keep it printable.  Uses ASCII math to use the input chars as lookup indices.

Postscript (310) (462) (414) (319) including (46) for the table.
Combined numbers and letters with a ternary encoding. 5 ternary digits fit in a byte! This eliminates those silly difference loops, and special-casing numbers entirely.
ASCII85 cuts 1/3 of each table. And simplifying the code (finally!) gets back under 400!
errordict/undefined{pop( )dup 0 4 3 roll put print{}}put<</*{{[exch/@ cvx]cvx 1
index 1 add}forall pop}def/C{<~#:VD<!AP07"A]ga#R),'7h?+2(./s-9e6~>*}def/#{load
exec}/P{print}0{}1{(.)P}2{(---)P}/S{( )P}48<~o'u/0b'A;]L7n~>* 65 C 97 C/@{5{dup
3 mod # S 3 idiv}repeat # S S S}>>begin{(%stdin)(r)file read not{exit}if #}loop

Sample output
Luser Dr00g!
. --- . .     . . ---      . . .      .        . --- .          --- . .      . --- .      --- --- --- --- ---    --- --- --- --- ---    --- --- .      !

Ungolfed and commented. I'm very proud of this one. I feel it's elegant, making the numbers do the work. :)
%!
%Morse Code Translator (Simplified)

%if `load` signals /undefined in /#{load exec},
%  pop --load--,
%  print the char,
%  leave dummy object for `exec` to find
errordict/undefined{pop( )dup 0 4 3 roll put print{}}put

<<
%create int->proc pairs
%from initial int and string values
/*{{[exch/@ cvx]cvx 1 index 1 add}forall pop}def

%the alpha map is applied to Upper and Lower case
/C{<~#:VD<!AP07"A]ga#R),'7h?+2(./s-9e6~>*}def
65 C 97 C

%the number map
48<~o'u/0b'A;]L7n~>*

/#{load exec}  %execute a number
/P{print}

0{}       % 0: nop
1{(.)P}   % 1: '.' dit
2{(---)P} % 2: '---' dah
/S{( )P}  % S: space

%execute a morse sequence, from the table
/@{5{dup 3 mod # S 3 idiv}repeat # S S S}
>>begin

%read and execute each char from stdin
{(%stdin)(r)file read not{exit}if #}loop

The tables (33)+(13)=(46)
Here's how the strings encode the table. Each byte represents a 5-digit ternary number. And the bytes are further encoded in ASCII85 (which postscript can automagically decode).
%The Morse Table in Ternary Encoding
% 3  ^4 ^3 ^2 ^1 ^0
%    81 27  9  3  1                 Dec  Hex  dc ->ASCII85
%   ---------------                 ---  ---  ---
% A            2  1            6+1    7    7  7 256*41+256*50+256*14+
% B      1  1  1  2      27+ 9+3+2   41   29  d85%n85/d85%n85/d85%n85/d85%n85/n
% C      1  2  1  2      27+18+3+2   50   32  2 25 53 35 27  chr(x+33)
% D         1  1  2          9+3+2   14    E  #  :  V  D  <
% E               1              1    1    1
% F      1  2  1  1      27+18+3+1   49   31
% G         1  2  2          9+6+2   17   11  0 32 47 15 22
% H      1  1  1  1      27+ 9+3+1   40   28  !  A  P  0  7
% I            1  1            3+1    4    4
% J      2  2  2  1      54+18+6+1   79   4F
% K         2  1  2         18+3+2   23   17  1 32 60 70 64
% L      1  1  2  1      27+ 9+6+1   43   2B  "  A  ]  g  a
% M            2  2            6+2    8    8
% N            1  2            3+2    5    5
% O         2  2  2         18+6+2   26   1A  2 49 8 11 6
% P      1  2  2  1      27+18+6+1   52   34  #  R )  , '
% Q      2  1  2  2      54+ 9+6+2   71   47
% R         1  2  1          9+6+1   16   10
% S         1  1  1          9+3+1   13    D  22 71 30 10 17
% T               2              2    2    2   7  h  ?  +  2
% U         2  1  1         18+3+1   22   16
% V      2  1  1  1      54+ 9+3+1   67   43
% W         2  2  1         18+6+1   25   19  7 13 14 82 12
% X      2  1  1  2      54+ 9+3+2   68   44  (  .  /  s  -
% Y      2  2  1  2      54+18+3+2   77   4D  77 256*44+256*256*
% Z      1  1  2  2      27+ 9+6+2   44   2C  24 68 21 [23 36]
%                                              9  e  6 [ 8  E] (omit final 2)
% 0   2  2  2  2  2  162+54+18+6+2  242   F2
% 1   2  2  2  2  1  162+54+18+6+1  241   F1
% 2   2  2  2  1  1  162+54+18+3+1  238   EE  78 6 84 14 15
% 3   2  2  1  1  1  162+54+ 9+3+1  229   E5   o '  u  /  0
% 4   2  1  1  1  1  162+27+ 9+3+1  202   CA
% 5   1  1  1  1  1   81+27+ 9+3+1  121   79
% 6   1  1  1  1  2   81+27+ 9+3+2  122   7A  65 6 32 26 60
% 7   1  1  1  2  2   81+27+ 9+6+2  125   7D   b '  A  ;  ]
% 8   1  1  2  2  2   81+27+18+6+2  134   86  134 256*161+256*256*
% 9   1  2  2  2  2   81+54+18+6+2  161   A1  43 22 77 [50 40]
%                                              L  7  n [ S  I] (omit final 2)

Python 3, 99 Characters
lambda a:print(*[str(ord('ӆҼzࢤpࢮ࠿yࡊoࡀѡÔÞÝࢭÓӅһѢ'[ord(c)%32])).translate(' -.'*18)for c in a])

Works on upper and lowercase.

Neat! Sadly it only works until T

Your solution is very inspiring :) I'd love to learn how you invented it! for anyone looking for the string that works you can use result of this: "".join(['a',chr(51),chr(1222),chr(1212),chr(122),chr(5),chr(2542),chr(445),chr(2555),chr(55),chr(2411),chr(421),chr(2422),chr(44),chr(45),chr(111),chr(2412),chr(1121),chr(215),chr(525),chr(4),chr(254),chr(2554),chr(544),chr(1554),chr(1241),chr(1155),'a'])

Ah, this was a while ago, so I am fuzzy on the details, but I was aware of the mod 32 trick beforehand, and so I fixed the translate string (possibly had to try a few strings) and then generated the other string like you did?  I had done lots of similar code golf challenges in a group (and I'm pretty sure we did this one as well), so alot of the tricks here were probably invented by other people :)

Lisp (532 466 chars)
(loop(princ(let((c(read-char)))(case c(#\a".- ")(#\b"-... ")(#\c"-.-. ")(#\d"-.. ")(#\e". ")(#\f"..-. ")(#\g"--. ")(#\h".... ")(#\i".. ")(#\j".--- ")(#\k"-.- ")(#\l".-.. ")(#\m"-- ")(#\n"-. ")(#\o"--- ")(#\p".--. ")(#\q"--.- ")(#\r".-. ")(#\s"... ")(#\t"- ")(#\u"..- ")(#\v"...- ")(#\w".-- ")(#\x"-..- ")(#\y"-.-- ")(#\z"--.. ")(#\1".---- ")(#\2"..--- ")(#\3"...-- ")(#\4"....- ")(#\5"..... ")(#\6"-.... ")(#\7"--... ")(#\8"---.. ")(#\9"----. ")(#\0"----- ")(t c)))))

This encodes lower case letters, and morse code sequences are printed with a trailing space

In Java, 475 characters.
    import java.io.*;class M{public static void main(String[]b){String s,t="-",m=t+t,o=m+t,z="",e=".",i=e+e,p=t+e,a=e+t,n=i+e,c[]={o+m,a+o,i+o,n+m,n+a,n+i,p+n,m+n,o+i,o+p,z,z,z,z,z,z,z,a,t+n,p+p,t+i,e,i+p,m+e,n+e,i,e+o,p+t,a+i,m,p,o,a+p,m+a,e+p,n,t,i+t,n+t,e+m,p+a,p+m,m+i};BufferedReader r=new BufferedReader(new InputStreamReader(System.in));try{s=r.readLine().toUpperCase();for(int j=48;j<91;j++)s=s.replace(z+(char)j,c[j-48]+" ");System.out.println(s);}catch(Exception x){}}}

Translates a-z, A-Z and 0-9.
Edit:
Or in 447 characters, if you don't mind Java throwing an error after the translation.
    import java.io.*;class M{static{String s,t="-",m=t+t,o=m+t,z="",e=".",i=e+e,p=t+e,a=e+t,n=i+e,c[]={o+m,a+o,i+o,n+m,n+a,n+i,p+n,m+n,o+i,o+p,z,z,z,z,z,z,z,a,t+n,p+p,t+i,e,i+p,m+e,n+e,i,e+o,p+t,a+i,m,p,o,a+p,m+a,e+p,n,t,i+t,n+t,e+m,p+a,p+m,m+i};BufferedReader r=new BufferedReader(new InputStreamReader(System.in));try{s=r.readLine().toUpperCase();for(int j=48;j<91;j++)s=s.replace(z+(char)j,c[j-48]+" ");System.out.println(s);}catch(Exception x){}}}

Perl6 (238)
my%h="A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--..0-----1.----2..---3...--4....-5.....6-....7--...8---..9----.".split(/<wb>/)[1..72];while$*IN.getc ->$c{print %h{$c.uc}||$c}

Readable version
# Split string on word breaks to create a hash
# I get an extra token at the beginning and end for some reason
# [1..72] is a slice without the extra pieces
my %h = "A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--..0-----1.----2..---3...--4....-5.....6-....7--...8---..9----."
    .split(/<wb>/)[1..72];

# For each character in STDIN, print either the looked up value, or itself
while $*IN.getc -> $c {
    print %h{$c.uc} || $c;
}

"I get an extra token at the beginning and end for some reason": I don't know Perl 6, but I'd guess it's because the empty string matches before the first word boundary and after the last one.

C, 162 160 chars
char M[256] = "_^\\XP@ACGO       &15)\"4+0$>-2'%/6;*(#,8.9=3", v;
main(c) {
  for (;
         c = getchar(), v = M[c + 208 & 255] - 32, ~c;
         putchar(v-1? c : 32))
    for (; v > 1; v /= 2) putchar(".-"[v & 1]);
}

(With non-significant whitespace stripped, no trailing newline)
char M[256]="_^\\XP@ACGO       &15)\"4+0$>-2'%/6;*(#,8.9=3",v;main(c){for(;c=getchar(),v=M[c+208&255]-32,~c;putchar(v-1?c:32))for(;v>1;v/=2)putchar(".-"[v&1]);}

M is a lookup table where the characters' bitpatterns correspond to dots and dashes in the morse code.  Characters [0-9A-Z] are decoded to morse using this table (with a space appended after the morse code), other characters are simply passed through unchanged.
Sample run:
HELLO WORLD
.... . .-.. .-.. ---  .-- --- .-. .-.. -..
hello world
hello world
ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
.- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----.

That's not 162 chars... please post the golfed version.

@Cyoce Sorry, I didn't strip non-significant whitespace since that is a boring mechanical process and only makes it harder to read the source code, which is (used to be?) fairly standard practice on PPCG. Added a version with such whitespace stripped for you :).

144 bytes

sed, 159 bytes
s/.*/\L&/
s/[02]/&-/g
s/[89]/&./g
:
s/[b-ilnprsz5-9]/&./g
s/[ajkmoqt-y0-4]/&-/g
y/abcdefghijklmnopqrstuvwxyz0123456789/edri umsewnrttmwkai isadkgojuvhhbzoo/
t

We start by downcasing the entire line (because y can't do case-insensitive conversions); subtract 10 bytes if we are to only handle lower-case input.  Then we preprocess the digits 0, 2, 8 and 9 to emit their final symbols.
The loop generates the final symbol for each input character, then translates each character for the next iteration. This is equivalent to walking up the dichotomic search table shown in the Wikipedia article; the digits that needed special treatment can be seen to have parents that are not in our ASCII alphanumerics.
The loop terminates when all characters have reached the terminating space (after 'e' or 't').
For example, the letter k is transformed in three passes:

k => k- => n-
n- => n.- => t.-
t.- => t-.- =>  -.-

Powershell, 142 bytes
-join($args|% t*y|%{if($_-match'\w'){for($d='ihfbZJKMQY+mazzy+0;?3,>5:.H7<1/9@E42-6B8CG='[$_-48]-42;$d-1){'.-'[$d%2]
$d=$d-shr1}' '}else{$_}})

Less golfed test script:
$f = {

-join(
    $args|% toCharArray|%{
        if($_-match'\w'){
            for($d='ihfbZJKMQY+mazzy+0;?3,>5:.H7<1/9@E42-6B8CG='[$_-48]-42;$d-1){
                '.-'[$d%2]
                $d=$d-shr1
            }
            ' '
        }else{
            $_
        }
    }
)

}

@(
    ,("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----. ")
    ,("HELLO WORLD", ".... . .-.. .-.. ---  .-- --- .-. .-.. -.. ")
    ,("#$%^&","#$%^&")
) | % {
    $s,$expected = $_
    $result = &$f $s
    "$($result-eq$expected): $result"
}

Output:
True: .- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----.
True: .... . .-.. .-.. ---  .-- --- .-. .-.. -..
True: #$%^&

Note: The output contains trailing spaces.

+mazzy+ is some cheeky padding

JavaScript (ES6), 184 bytes
For both of these versions, they will put spaces between any characters. Converts 0-9 and a-z(case insensitive) are converted. A space is converted to 3.
s=>s.split("").map(e=>isNaN(d=parseInt(e.toLowerCase(),36))?e:`_OGCA@PX\\^\r\n  `.charCodeAt(d).toString(2).substr(1).split("").map(e=>".-"[e]).join("")).join(" ")

Replace \n with a newline character(0x0a). It is not showing a couple of nonprintable characters because of SE. Going into edit mode shows it.
Here is the hex:
73 3d 3e 73 2e 73 70 6c 69 74 28 22 22 29 2e 6d 61 70 28 65 3d 3e 69 73 4e 61 4e 28 64 3d 70 61 72 73 65 49 6e 74 28 65 2e 74 6f 4c 6f 77 65 72 43 61 73 65 28 29 2c 33 36 29 29 3f 65 3a 60 5f 4f 47 43 41 40 50 58 5c 5c 5e 05 18 1a 0c 02 12 0e 10 04 17 5c 72 14 07 06 0f 16 1d 0a 08 03 09 11 0b 19 1b 1c 60 2e 63 68 61 72 43 6f 64 65 41 74 28 64 29 2e 74 6f 53 74 72 69 6e 67 28 32 29 2e 73 75 62 73 74 72 28 31 29 2e 73 70 6c 69 74 28 22 22 29 2e 6d 61 70 28 65 3d 3e 22 2e 2d 22 5b 65 5d 29 2e 6a 6f 69 6e 28 22 22 29 29 2e 6a 6f 69 6e 28 22 20 22 29

Ungolfed
s=>            //declare anonymous function
s.split("")    //split into array of characters
.map(          //for each character
e=>            //declare anonymous function
 isNaN(        //is the character not in range 0-9a-zA-Z
  d=parseInt(e.toLowerCase(),36)
               //take it as base 36(digits are 0-9a-z) and assign to d
 )?e:          //if outside range, return as is
 `_OGCA@PX\\^\r\n  `
               //table of the morse code as binary as code point with leading 1
 .charCodeAt(d)//get the corresponding code
 .toString(2)  //convert to binary, 0=., 1=-, with an extra 1 bit
 .substr(1)    //remove the extra 1 bit
 .split("")    //split into each bit
 .map(         //for each bit
  e=>          //declare anonymous function
  ".-"         //the corresponding symbol for bits
  [e]          //get it
 )
 .join("")     //join the bits
)
.join(" ")     //join the characters with a space between each character

Readable version, 234 bytes
s=>s.split("").map(e=>isNaN(d=parseInt(e.toLowerCase(),36))?e:[95,79,71,67,65,64,80,88,92,94,5,24,26,12,2,18,14,16,4,23,13,20,7,6,15,22,29,10,8,3,9,17,11,25,27,28][d].toString(2).substr(1).split("").map(e=>".-"[e]).join("")).join(" ")

Ungolfed
s=>            //declare anonymous function
s.split("")    //split into array of characters
.map(          //for each character
e=>            //declare anonymous function
 isNaN(        //is the character not in range 0-9a-zA-Z
  d=parseInt(e.toLowerCase(),36)
               //take it as base 36(digits are 0-9a-z) and assign to d
 )?e:          //if outside range, return as is
 [95,79,71,67,65,64,80,88,92,94,
   5,24,26,12, 2,18,14,16, 4,23,
  13,20, 7, 6,15,22,29,10, 8, 3,
   9,17,11,25,27,28]
               //table of the morse code as binary with leading 1
 [d]           //get the corresponding code
 .toString(2)  //convert to binary, 0=., 1=-, with an extra 1 bit
 .substr(1)    //remove the extra 1 bit
 .split("")    //split into each bit
 .map(         //for each bit
  e=>          //declare anonymous function
  ".-"         //the corresponding symbol for bits
  [e]          //get it
 )
 .join("")     //join the bits
)
.join(" ")     //join the characters with a space between each character

s.split("") => [...s]

Perl (489 chars)
%c=("A"=>".-","B"=>"-...","C"=>"-.-.","D"=>"-..","E"=>".","F"=>"..-.","G"=>"--.","H"=>"....","I"=>"..","J"=>".---","K"=>"-.-","L"=>".-..","M"=>"--","N"=>"-.","O"=>"---","P"=>".--.","Q"=>"--.-","R"=>".-.","S"=>"...","T"=>"-","U"=>"..-","V"=>"...-","W"=>".--","X"=>"-..-","Y"=>"-.--","Z"=>"--..",1=>".----",2=>"..---",3=>"...--",4=>"..---",5=>".....",6=>"-....",7=>"--...",8=>"---..",9=>"----.",0=>"-----");while(<>){foreach(split(//)){if(exists($c{$_})){printf"%s ",$c{$_}}else{print"$_"}}}

Can be executed via command line like so.
$ perl -e '$CODE' < textfile

Edit: Thanks @tobyodavies for pointing out that my original solution had the translation backwards!

You can get this down to 286 characters: %c=qw(A .- B -... C -.-. D -.. E . F ..-. G --. H .... I .. J .--- K -.- L .-.. M -- N -. O --- P .--. Q --.- R .-. S ... T - U ..- V ...- W .-- X -..- Y -.-- Z --.. 1 .---- 2 ..--- 3 ...-- 4 ..--- 5 ..... 6 -.... 7 --... 8 ---.. 9 ----. 0 -----);while(<>){print($c{$_}||$_)for split//}

PHP, 474 characters
<?$a=strtoupper(fgets(STDIN));$m=array(65=>".-",66=>"-...",67=>"-.-.",68=>"-..",69=>".",70=>"..-.",71=>"--.",72=>"....",73=>"..",74=>".---",75=>"-.-",76=>".-..",77=>"--",78=>"-.",79=>"---",80=>".--.",81=>"--.-",82=>".-.",83=>"...",84=>"-",85=>"..-",86=>"...-",87=>".--",88=>"-..-",89=>"-.--",90=>"--..",49=>".----",50=>"..---",51=>"...--",52=>"..---",53=>".....",54=>"-....",55=>"--...",56=>"---..",57=>"----.",48=>"-----",32=>" ");while($i++<strlen($a))echo$m[ord($a[$i])];

Its 462 characters if all input is in uppercase:
<?$a=fgets(STDIN);$m=array(65=>".-",66=>"-...",67=>"-.-.",68=>"-..",69=>".",70=>"..-.",71=>"--.",72=>"....",73=>"..",74=>".---",75=>"-.-",76=>".-..",77=>"--",78=>"-.",79=>"---",80=>".--.",81=>"--.-",82=>".-.",83=>"...",84=>"-",85=>"..-",86=>"...-",87=>".--",88=>"-..-",89=>"-.--",90=>"--..",49=>".----",50=>"..---",51=>"...--",52=>"..---",53=>".....",54=>"-....",55=>"--...",56=>"---..",57=>"----.",48=>"-----",32=>" ");while($i++<strlen($a))echo$m[ord($a[$i])];

With some minor tricks that can be reduced to: <?$a=strtoupper(fgets(STDIN));$m=array(65=>12,2111,2121,211,1,1121,221,1111,11,1222,212,1211,22,21,222,1221,2212,121,111,2,112,1112,122,2112,2122,2211)+array(48=>22222,12222,11222,11122,11222,11111,21111,22111,22211,22221)+array(32=>' ');while($a[$i++])echo strtr($m[ord($a[$i])],12,'.-');

05AB1E, 81 bytes (Non-competing)
Çvy©58‹i®58-•6V%·,Õo•2B5ôsè}®64›i®64-•4…·]ÑUZ“×\ó$9™¹“ÌLÈÎ%´•3B4ôsè}"012"".- "‡})

Try it online!
Convert letter patterns to base-3, number patterns to base-2, use zero indexed ascii transliteration to get to periods and hyphens. Does not work on lowercase.

Jelly, 50 bytes
“¤⁵©ḤọḌṄ’B‘s5;“ḄẇɗÞI/QẊṂjỵr’Œ?ḃ2¤ṖṖƊ⁺ị⁾.-;
ØBiịÇ)K

A full program accepting a Python formatted string as a command line argument which prints space delimited output.
Try it online!

APL(NARS), 71 chars, 142 bytes
{36≥y←⍵⍳⍨⎕A,⎕D:'•-'[0∼⍨⌽(5⍴3)⊤y⊃∊(2⍴256)∘⊤¨⎕AV⍳'ܨ㈍İᄧюᜪࠄᨳ䜏ഁᙂ᥃䴫쩸穼蚠']⋄⍵}

test:
  q←{36≥y←⍵⍳⍨⎕A,⎕D:'•-'[0∼⍨⌽(5⍴3)⊤y⊃∊(2⍴256)∘⊤¨⎕AV⍳'ܨ㈍İᄧюᜪࠄᨳ䜏ഁᙂ᥃䴫쩸穼蚠']⋄⍵}
  q¨'0123456789'
----- •---- ••--- •••-- ••••- ••••• -•••• --••• ---•• ----•
  q¨"HELLO WORLD"
•••• • •-•• •-•• ---   •-- --- •-• •-•• -••

each letter is separated from one space, each word would be separated from 3 spaces. The table is build on alphanumeric string ⎕A,⎕D and 16bit characters 'ܨ㈍İᄧюᜪࠄᨳ䜏ഁᙂ᥃䴫쩸穼蚠' they split in 8bit characters each converted in base 3 with reversed digits.

05AB1E, 52 bytes
Ažh«•1Ju&àøΘn₆δβαLmSÂZΘ=+BD1
 ÷ΓùwÒмVšh•… .-ÅвJ#ðδJ‡

Try it online!
    •1Ju&àøΘn₆δβαLmSÂZΘ=+BD1
    ÷ΓùwÒмVšh•                push compressed number
              … .-ÅвJ#        convert to custom base " .-"
                      ðδJ     append a space to each morse code
Ažh«                     ‡    transliterate

Vyxal, 56 bytes
ka»ƛ[¬τ*‹∧□C‛Ṡḣ6ƒO⌈=gṫO=D»`-.,`τ⌐Ŀkd5ɾ\.*5ʁṘ-:ƛ‛.-ḂĿ;JĿṄ

Try it Online!
  »...»                               # Base-256 compressed integer
       `-.,`τ⌐                        # Decompressed with the key `-.,`and split on commas
ka            Ŀ                       # Replace letters with those
                 5ɾ\.*                # 1..5 .
                      5ʁṘ-            # With 4..0 - appended
                          :ƛ‛.-ḂĿ;J   # Make a copy with `.-` swapped
               kd                  Ŀ  # Replace digits with those
                                    Ṅ # Join on spaces and implicitly output

Python 2, 283 274 Bytes
I created a string of alphanumerics such that their placement in the string describes their Morse code representation. Originally I was going to use binary, but 01 would be the same as 1. So I used ternary with - = 1 and . = 2. Thus is character c is at index 1121 in this string, its Morse code representation is --.-.

To save bytes, I created variables for space, dash and dot.
Then I hard coded the 'decoder' string using a couple replace statements to reduce whitespace.
The part of the function converts an index into an array of the ternary digits
The other part function takes an string and converts each character into Morse code with 3 spaces after letters and 7 (4 extra) between words

q,d,D=" .-"
s=" TE MN AI.OG KD.WR US-.QZ.YC XB- JP  L. F VH---.09  8..7--  6---.1--  2..3  45".replace(D,d*3).replace(d,q*4)
lambda n:''.join(''.join([0,D,d][i]for i in [s.index(c)//3**i%3 for i in range(5)if s.index(c)//3**i!=0][::-1])+q*3 if c!=q else q*4for c in n.upper())

Test Harness
print(f("Hi")=="....   ..   ")
print(f("Hello")=="....   .   .-..   .-..   ---   ")
print(f("Hello World")=="....   .   .-..   .-..   ---       .--   ---   .-.   .-..   -..   ")
print(f("To be or not to be")=="-   ---       -...   .       ---   .-.       -.   ---   -       -   ---       -...   .   ")
print(f("3 14 15")=="...--       .----   ....-       .----   .....   ")

Update

-9 [16-05-09] Incorporated the ternary calculating function into the main function

[NOTE: There is always trailing white space but white space represents a pause, so I guest that is ok ]

PHP, 157 150 157 bytes
for(;$d=ord($c=$argv[1][$i++]);)echo ctype_alnum($c)?strtr(substr(decbin(ord($d>64?".CTRH@ZF\DUGXABEVOJL?K[ISQP"[$d&31]:"]muy{|ld`^"[$c])-48),1),10,".-"):$c;

takes input from first command line argument. no pause between letters. Run with -nr.
breakdown

for(;$d=ord($c=$argv[1][$i++]);)    # loop through input characters
    echo                                # print ...
    ctype_alnum($c)                     # if char is alphanumeric:
    ?   strtr(
        substr(
        decbin(
            ord($d>64                   # 1. map char to char-encoded morse
            ?".CTRH@ZF\DUGXABEVOJL?K[ISQP"[$d&31]
            :"]muy{|ld`^"[$c]
            )-60                        # 2. subtract 60 from ordinal value
        )                               # 3. decbin: convert to base 2
        ,1)                             # 4. substr: skip leading `1`
        ,10,".-")                       # 5. strtr: translate binary digits to dash/dot
    :$c;                                # not alphanumeric: no conversion

Beating JavaScript, Python2, C, Ruby and sed. I´m happy.
4th step: un-merged the mapping to handle lowercase characters without using strtoupper.
previous versions:
fail for lowercase letters; +12 bytes to fix:
Replace $argv[1] with strtoupper($argv[1]).
simple string translation, 254 bytes
<?=strtr($argv[1],["-----",".----","..---","...--","....-",".....","-....","--...","---..","----.",A=>".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]);

straight forward: translates the whole string at once, character to morse code.
Save to file to execute or replace <?= with echo and run with -r.
decimal interpretation of morse codes, 184 bytes (-70)
for(;""<$c=$argv[1][$i++];)echo($m=[32,48,56,60,62,63,47,39,35,33,A=>6,23,21,11,3,29,9,31,7,24,10,27,4,5,8,25,18,13,15,2,14,30,12,22,20,19][$c])?strtr(substr(decbin($m),1),10,".-"):$c;

first golfing step: morse codes encoded to binary with an additional leading 1 to preserve leading zeroes. Loops through characters and translates them one by one. Run with -nr.
decimals encoded to character, 157 bytes (-27)
for(;""<$c=$argv[1][$i++];)echo ctype_alnum($c)?strtr(substr(decbin(ord("@"<$c?"CTRH@ZF\DUGXABEVOJL?K[ISQP"[ord($c)-65]:"]muy{|ld`^"[$c])-60),1),10,".-"):$c;

second golfing: added 60 to the decimal value and encoded to character.
merged mapping, 150 bytes (-7)
for(;""<$c=$argv[1][$i++];)echo ctype_alnum($c)?strtr(substr(decbin(ord("]muy{|ld`^8901234CTRH@ZF\DUGXABEVOJL?K[ISQP"[ord($c)-48])-60),1),10,".-"):$c;

third golfing: merged mapping for digits and letters to a single string.

SmileBASIC, 194 190 bytes
INPUT S$WHILE""<S$B=INSTR(" ETIANMSURWDKGOHVFLPJBXCYZQ  54 3   2       16       7   8 90",S$[0])+1IF B THEN S=LOG(B,2)FOR I=0TO S-1?"._"[B-(1<<S)AND S>>I||0];:NEXT?" ";
?SHIFT(S$)*!B;
WEND

JavaScript (Node.js), 143 bytes
s=>[...s].map(t=>`?/'#! 08<>

	`.charCodeAt(parseInt(t,36)+1).toString(2).slice(1).replace(/./g,e=>'.-'[e])||t).join` `

Try it online!

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Tips for golfing in C++
What general tips do you have for golfing in C++?
I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C++ (e.g. "remove comments" is not an answer). Please post one tip per answer.
(Tips that apply to C as well can be found in Tips for golfing in C - but note that some C tips don't work in C++.  For example, C++ does require function prototypes and return values.)

Many of the tips for golfing in C are also applicable to C++, so please assume that readers are familiar with that question; only post here if you have something that isn't also a valid C golfing tip.

@TobySpeight Probably because they have the same url besides the question ID.

C and C++, even if not 'golfing' type, are right and easy (if one consider the right subset of C++)

The ternary conditional operator ?: can often be used as a stand in for simple if--else statements at considerable savings.
It is of special value in that it can be used to select alternate lvalues as in
#include <iostream>
#include <cstdlib>
int main(int c, char**v){
  int o=0,e=0,u;
  while(--c) ((u=atoi(v[c]))%2?o:e)+=u;
  std::cout << "Sum of odds " << o <<std::endl
            << "Sum of evens " << e <<std::endl;
}

Replace std::endl with '\n' that saves 5 chars

@MukulKumar Well, yes. But for the purposes of demonstrating this tip I left everything except the ternary-conditional un-golfed for clarity.

But std::endl isn't "ungolfed", it's just bad style / gratuitous flushing of cout even when that's not needed.  endl is the same as << '\n' plus a flush; it's a different layer of stdio that handles conversion from \n to the native platform line ending (e.g. CRLF on DOS) for text streams.  If you were golfing or optimizing, you'd put the first \n into the 2nd string literal: "\nSum of evens "

Sometimes you can save two characters by using the fact that static storage duration variables (that especially includes all global scope variables) are automatically zero-initialized at the beginning (unlike automatic variables where you have no such guarantee). So instead of
int main()
{
  int a=0;
  // ...
}

you can write
int a;
int main()
{
  // ...
}

Some compilers (e.g. GCC) support multi-character constants. This can save a few characters when a large integer value is required. Example:
int n='  ';

The value is implementation-specific. Usually the value of 'ab' is 256*'a'+'b' or 'a'+256*'b'. You can specify up to 4 characters between the quotation marks.

Shorter header
This is GCC specific, it may be extensible to other compilers.
Precompiled header.
In G++ bits/stdc++.h is the precompiled header consists of all other headers. If you need to import 2 different ones you can just use this.
Shorter header.
This is all headers listed on http://en.cppreference.com/w/cpp/header:

$("#a").text(pako.inflate(atob('eJx9VkuW1DAM3HON2cOGx4o3V8lzK0q3wZ9gy90TTo+dDKCyM710yT9VqWS/2ECuzPzdhO3108vfUeCHGmUWNfJmVSMbsxo5m/VUEutZjaWsTo9NSkYfO/OvouNZDP1U4xqFOHkjNzVORmzU8YXDXcf5ym86lSIwvljBXOmWYtA7evYxbXCEi0aAAl930TM4JdiDSLYV0njQzSQNlA7Ikmy4KuDOJDFB6mGOHoVZHrPeNMsM7LhIBuWQ6C1pvW6Jjd5jKVKSXtII/qwlaIoA0EoAgHYPZy+A2GswDhCWH37tVpmkKShinZWtmzPzomkyyZoAika/GkiBRsUaU7jK5MxJULNexUGkdpaDAgvFcwKKq2Eqx1q4OCDLgOQBsdGbYIGxQV+KM9NdnmvRsgK99vIFZC95QPbSAmSvYEAeA0Jy7QxMNsdvX789RdoFbVh0Jce1+r6roHoYRXC/Fa4NAlxzN67vQXbk/xAfrn7UDEI73UjLXsUI7aXek1cru4dqIQ8Uh4H1Kl4HtRrseB8kpbEyDylg1sH84N1LjG6QY4bNqN604dpU/Ea8y4QJHLAm211jsnLzsJapDGvTaIsduBTdAt5TxTTOsCaDq+rg/Vq2WPwl0FBteQs02tY6zlsWBp++MzNUQDsaG2edNkky2JsOgae7xRe6brA3b9x2P3yqBoaiX2J6mDRP3WOdq2N4nvo3sYSYZm4RfBr/4/ghOF7IKXGOJRFD6lZszfM3p+FsimvdybhmIrQov621ZXoOYtwX/KVACG8BIbw4hPoPSwyzbepO+8txgfYJC/uvCgT7fwgGu08IBPsfEgSH3whEh7cZ6ek/LshQ/3RBdPhsQHR80yA8PtMQPmndqPhpO9Bpn7msI+bEsSfp96ZCYU7diOec+wpPOrckMvaBsz6Y9KS6//Xcp3f62LHdZu9NeFqjs7S9/gHXxXg4'), {to: 'string'}));

sorted in increasing order of length.
Some of them are already longer than bits/stdc++.h, and some of them requires C++17 support. Some others are not supported by TIO G++ (for reasons I don't know of). Filter out them we have:

$("#a").text(pako.inflate(atob('eJx9VcuS3CAMvOc39p5Tak+p/MoUI2SbhIcDYrz++4BdW6WG1B7VYI36IebNRfLV8s/Ix69vb59VYVFVMLuqXCqq8q7oqyQusKql7l7XJmdzqtry36rPixj6o+p2CucUjGyqzkZc0ucLx5c+55U/NJUqUD+dIFfacoq6Y+CQ8gk/4ZMRkCC0LvoG5ww9iOTcgcZBm8kaqANQJLu4KuDFJCkD9WhTQGOWw+qmRSyo4xMZtENScKT92jIb3WOpUrP+pAv8XVvQHQGgRwCAPod3T0DcGo0HhOV32IevTNYSVHHeyTncsbxoZHajqxDBY1MKZ0E/RocmAyiFlmUdnlgDZ5CvLUPTT5uSJmSZkDIhLgUTHagxeUfJMr3ka507K/DiiiYgV5wBuWIDyJVOQI4JIVmH5SRX0vuP9y+RPqCLi06pE25rDVl/GT++HG5W9rYVhrrTgNAlJBK+sofQFdBRlpbHEWrxm8SLk57NlgHq6RoUncyiOXO3yHDr1nTauGdKfhLaQjNqk3Zcrwt/EO/tUY1I4Ia12H5N2ckWkNUc7gt4VljSmxaO/D+sS+6bEzhLZ4YRrpH6yPCifHKbPOwN8cFq1x6SDb4b5SzC4dEWBqK4pHyYbB/DH19p68D2cf+//APa+54V'), {to: 'string'}));

It may happens that some of them can be replaced by shorter ones. Just binary search whether the one you need can be replaced. In particular:
cstdio -> ios        (-3 bytes)
algorithm -> regex   (-4 bytes)
vector -> queue      (-1 byte)
string -> map        (-3 bytes)
bitset -> regex      (-1 byte)
numeric -> random    (-1 byte)

I wish I could star answers. This is good.

The stack snippet seems broken

One that I found handy:
Taking advantage of the fact that non-zero values evaluate to true in boolean expressions, and that x&&y evaluates to x*y when dealing with booleans
(x!=0 && y!=0)

evaluates to
(x*y)

You just have to be aware of overflows, as pointed out below.

Technically, it's x!=0 && y!=0. But when using multiplication you need to be careful with overflows. When using 32-bit integers x = y = 65536 (and several other combinations of powers of two) would also yield x*y = 0.

Yes, that's right.  I used it as a twodimensional array bounds check here: http://codegolf.stackexchange.com/a/37571/31477 where that didn't matter.  I'll edit those points in.

Note however that && has a short-circuit behaviour which * lacks. For example, you can't replace i++!=0&&j++!=0 with i++*j++.

@celtschk yes, good point.  But if you're purely doing the boolean algebra, then it works

@S.S.Anne the point is you can use x*y saving a character.

Instead of using while(1), use for(;;), saving one character :)

When possible, change && and || to & and | respectively.
When using simple if statements:
if(<condition>)<stuff>;

can be changed to:
<condition>?<stuff>:<any single character variable or literal>;

which saves a character.

Using the comma operator in lieu of open and close braces can save a few characters, if you have a situation where your clauses have more than one statement in them:
if(c){x=1;cout<<"Hi";y=2;}else{x=2;cout<<"Bye";y=3;}

vs.
if(c)x=1,cout<<"Hi",y=2;else x=2,cout<<"Bye",y=3;###

Two characters saved on a plain IF, or three total for an IF/ELSE.
As a point of distinction between C and C++, the result of a comma expression in C++ as a whole may be used as an lvalue...FWIW.

How about x=1,y=2/*...*/else x++,y++?

Use the following types:
u64, s64, u32, s32 (or int)

For repetitive words/types, use #defines:
#define a while

It's only worth it if you use while a lot to make up for the extra 10 characters. (About 4.)

The types u64, s64, u32 and s32 are not part of C++. They may be a non-standard extension of your compiler (I've never ever seen them, though).

These two tips would be better placed in two separate answers so they can be voted on individually.

What implementations provide these type names?  Is there a header you need to include?  u8 is probably useful as a 2-byte type name when you don't need large values.

If you're willing to use C++0x, you can use new features like lambdas.

Since array elements are stored directly after one another in memory, instead of something like this:
for(int x = 0; x < 25; x++) {
    for(int y = 0; y < 25; y++)
        array[x][y] = whatever;
}

You can do something like this:
int* pointer = array;
for(int i = 0; i < 25*25; i++, pointer++)
    *pointer = whatever;

Obviously neither of the above are golfed, for readability, but explicitly using pointers can save you a lot of space.

Don't forget you can cut out all that whitespace! (Different tip altogether, but should be mentioned)

@stokastic The examples aren't meant to be golfed, only to demonstrate how to use the technique.

why not for(int* i=array; i<array+25*25; i++)? Then you only have to keep  track of one variable.

Quite an obvious one, but it you are using a lot of the standard library, using namespace std; might save a few characters.

If you only use a single name, but that quite often, using std::name; may be shorter, though.

This only saves characters if you use std:: five or more times.

Use GCC builtins instead of importing
If you are using a GCC compiler, it sometimes helps to use their builtin functions, such as __builtin_puts or __builtin_clz. For example,
44 bytes:
int main(){__builtin_puts("Hello, world!");}`

50 bytes:
#import<cstdio>
int main(){puts("Hello, world!");}

Instead of writing big powers of 10, use e notation. For example, a=1000000000 is longer than a=1e9. This can be extended to other numbers like a=1e9+24 is better than a=1000000024.

Note that this is not exactly equivalent, need to cast to integer types before using. For example 1e9/x is not the same as 1000000000/x or int(1e9)/x.

You may use the ternary operator ?: without any expressions in the true-block (it saves a byte)
#include <iostream>

int foo()
{
    std::cout << "Foo\n";
}

int main()
{
    1?foo():0;  // if (true) foo()
    0?:foo();   // if (!false) foo()
}

Check it here

This appears to be a GNU extension and not in the C++ standard. https://gcc.gnu.org/onlinedocs/gcc-4.4.4/gcc/Conditionals.html#Conditionals

r?foo():0;  // if (r) foo() this is ok;;;;; but For this
r?:foo();  i don't Know that

Functions in <algorithm> often requires passing a.begin(),a.end() which is really long, instead you can use &a[0],&*end(a) to save a byte or two if a is vector or string.
std::sort(a.begin(),a.end());
std::sort(&a[0],&*a.end());

// with using namespace std;
sort(begin(a),end(a));
sort(&a[0],&*end(a));
```

#import instead of #include gives you one more byte.
Also, the space character between #import and header is not necessarily:
#include <map>
// vs
#import<map>

And if you need something from stdlib header, you may import any header with STL container (preferable set or map) instead of cstdlib.

#import is a deprecated GCC extension.  But still is supported by modern versions of GCC.

If you want to swap two integer variables a and b then ,
a^=b^=a^=b;

can be used , saving 5 characters than the standard way
a+=b;
b=a-b;
a-=b;

About that standard way. ,t at the ints created earlier and then t=a;a=b;b=t; would have already been 3 bytes shorter than the a+=b;b=a-b;a-=b;. Still, your a^=b^=a^=b; is even shorter than that, so +1 from me. I don't know C++, but it indeed works. As a Java code-golfer I'm sad it doesn't seem to work there. :(

@KevinCruijssen Yeah , I should have mentioned C++ , I dont know java much , but a^=b;b^=a;a^=b; is working fine in java .

No need to explicitly mention C++. All these tips are for C++. :) As a Java developer I was just curious if something similar could be done in Java, but apparently not. a^=b;b^=a;a^=b; indeed works, but is longer than the ,t+t=a;a=b;b=t;. Sorry about mentioning Java, since it's off-topic here. But nice tip for C++ codegolfers!

If you already have a using namespace std, (std::) swap(a,b) is shorter.  To avoid #include <algorithm> or <utility>, another answer suggests GCC #import<bits/stdc++.h> to get every C++ header.

I don't know why anyone would think +- swaps are the "standard" way, though.  You'd never do that outside of code golf, you'd use auto t=a; or something.  XOR-swap is the better known no-temporary swap, using just 3 separate ^= statements instead of a b=a-b; that has to name b twice.  But yes, you save 4 bytes vs. a^=b;b^=a;a^=b;.  I guess you might consider that "standard" in a code-golf context if you don't have any spare variables you can use as a temporary.

Well even if it is not the standard way, it is what I am learning in school. But yours doesn't have any overflow problems. Will there be type issues?

Arithmetic operations on Booleans:
Although
a*=b>0?.5:-.5

is better than
if(b>0)a*=.5;else a*=-.5;

it is not as good as
a*=(b>0)-.5

Also, using #define on anything that is used a lot. It is often shorter than using functions, since type names are not necessary.
Combine things as much as possible:
a+=a--;

is the same as
a=2*a-1;

While your examples are correct, be careful of invoking undefined behavior when using x as an lvalue and x++ as an rvalue. undefined behavior and sequence points

Yes possible a+=a--; has Undefined Behaviour

It is useful to remember is that a[i] is the same as *(a+i).
Replace a[0] with *a for two character savings. Also, a[i][0] is equivalent to *a[i] and a[0][i] shrinks down to i[*a]. So if you are hard-coding a 0 index in your array, a better way probably exists.

Use generic lambdas as cheap templates
For types other than int, using them as function arguments can be expensive.  However, generic lambdas were introduced (in C++14?) and allow any lambda to be a template - using auto for the argument types can save bytes.  Compare:
double f(double x, double y)
[](auto x, auto y)

Generic lambdas are also very convenient for accepting iterators - probably the best way to accept array inputs in C++ is [](auto a, auto z), where a and z are passed as begin() and end() of the array/vector/list/etc.

If you're doing C++11 or newer (which should always be the case now), use auto for complex types, if possible.
Example: 54 Bytes instead of 66
#include<vector>
std::vector<int> f(std::vector<int> l){return l;}

#include<vector>
auto f(std::vector<int> l){return l;}

Also, as performance does not matter, for some challenges a std::list may just do the job for a few bytes less:
#include<list>
auto f(std::list<int> l){return l;}

When std::list can't be used (usually because you need indexing), std::deque is often usable, saving 1 character per use over std::vector, and still lets you index it.

It's rather straightforward to cacluate when replacing something with a #define results in shorter code.
#define a blabla

Where a is a single letter name and blabla is the replacement of length \$x\$ has in total \$10+x\$ characters.
If you have \$n\$ times blabla in the code then the #define pays off when
$$10 + x + n < nx$$
With the define you have \$10 + x\$ to define it and \$n\$-times a single character. Without it you have \$n\$-times blabla of length \$x\$. The following table lists how often blabla has to appear given its length for the define to make the code shorter:

\$x\$
\$n\$

2
13

3
7

4
5

5
4

Because the inequality is symmetric, the same table applies when \$n\$ and \$x\$ are swapped, ie if blabla appears \$n = 2\$ times in the code then the define results in shorter code when blabla is of length \$x \ge 13\$. The formula is
$$n > \frac {10 + x} {x - 1}$$
or
$$x > \frac {10 + n} {n - 1}$$
PS: Sometines the single letter named preprocessor symbol has to be followed by a space. This shifts the matters a little towards not using the define, but just a little.

Welcome to Code Golf, and nice tip!

G++ allows for variable-sized arrays, so there is no need to go through the lengthy pointer-malloc-new stuff.
int* array = new int[array_size];

becomes
int array[array_size];

Saves 9 bytes minimum with int.

Use auto instead of complex type names.
This can be done with generic lambdas and C++20 abbreviated function templates
int x(std::set<std::string>y){}
template<class T>int x(T&y){}
int x(auto&y){}
[](auto&x){}

This also allows you to avoid most includes.
Note that g++ on TIO requires -fconcepts.

When writing a full program you can use argc to initialize an integer variable to 1:
main(a){

is the same as:
main(){int a=1;

this is C, not C++

In my first attempt at code golf for task "Subtract the next numbers" I have started from function (58 bytes)
int f(int N, int P){int F;for(F=N;P;F-=++N,P--);return F;}

then safe 5 bytes with shifting to lambda and moving initialization out of for (53)
[](int N,int P){int F=N;for(;P;F-=++N,P--);return F;}

and finally after switching from for to while I got 51 bytes:
[](int N,int P){int F=N;while(P--)F-=++N;return F;}

The ungolfed test code is something like:
#include <iostream>
int main(void)
{
    int N, P;
    std::cin >> N >> P;
    auto f = [](int N,int P)
    {
        int F = N;
        while (P--)
            F -= ++N;
        return F;
    };
    std::cout << f(N, P) << std::endl;
    return 0;
}

UPDATE:
Actually for can reach the same length as while:
[](int N,int P){int F=N;for(;P--;F-=++N);return F;}

Kind of late to the party I guess...
If you want to turn an expression into -1 and 1 instead of 0 and 1, instead of this:
int x;
if (a * 10 > 5)
    x = 1;
else
    x = -1;

do this:
int x = (a * 10 > 5) * 2 - 1;

It can save some bytes depending on usage.

Instead of int x=(a*10>5)*2-1;, couldn't you do int x=a*10>5?1:-1;, which is 1 byte shorter?

If you need a type alias, using is two bytes shorter than #define:
#define T ... // newline
using T=...;

Don't use string(""), use "". It saves 8 bytes.

It's not exactly equivalent. For example "" + 'a' is char* + char, which is pointer addition, while std::string("") + 'a' is std::string + char - string concatenation. string() would work.

I would suggest using ""s. This saves 7 bytes and still is a std::string.

you need using namespace std::literals to use ""s

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Write a compressing util for gzip files
The task of this challenge is as following:
Write a program that reads a file of reasonable size (let's say <16 MB) from stdin or anywhere else (however you like, but must not be hardcoded), and put's the compressed output onto stdout. The output must be a valid gzip compressed file and if the compressed file runs through gunzip, it should yield exactly the same file as before.
Rules

The programming language used must be known before this competition started
The score of your program is the number of characters of the source code or the assembled program (whatever is shorter)
You're not allowed to use any kind of existing compression libraries.
Have fun!

Is the use of built-in libraries allowed?

@hallvabo: Nope. Forgot this. Thx

Probably the best way to do this is just to pad the input with the "the following block is uncompressed" markers at the start of every block.

gzip is a programming language. Not a Turing complete one though.

This is pretty much identical to the Guns and Zips problem. Why anyone would post their answers here rather than at codegolf.com is beyond me, unless they want to solve it in a language not supported by codegolf.com (e.g., GolfScript).

The difference is, that they expect a rather complete implementation of gzip there. In my excercise you may try to cheat instead, as decompression isn't needed.

Could you be more specific as to what constitutes a "valid gzipped file"?  100% RFC compliant?  Whatever goes through gunzip unharmed?

@J B: Your second choice is right. A valid gzipped representation of a file f is any file g that is equal to f if passed through gunzip.

Pushing the boundaries even further... is zcat (gzip -cd) enough?  IOW, how many warnings/errors are we allowed at decompression time?

J B: I only count what goes to stdout. Warnings aren't important in codegolf.

@FUZxxl: what I mean is: I've got a file that's not valid enough for gunzip with no arguments.  But if you get it through zcat 2>/dev/null, you do get the uncompressed contents back.  Is that good enough?

9 bytes: gzip -c -. I didn't use any compression libraries.

C# (534 characters)
using System.IO;using B=System.Byte;class X{static void Main(string[]a){var f=File.ReadAllBytes(a[0]);int l=f.Length,i=0,j;var p=new uint[256];for(uint k=0,r=0;k<256;r=++k){for(j=0;j<8;j++)r=r>>1^(r&1)*0xedb88320;p[k]=r;}uint c=~(uint)0,n=c;using(var o=File.Open(a[0]+".gz",FileMode.Create)){o.Write(new B[]{31,139,8,0,0,0,0,0,4,11},0,10);for(;i<l;i++){o.Write(new B[]{(B)(i<l-1?0:1),1,0,254,255,f[i]},0,6);c=p[(c^f[i])&0xFF]^c>>8;}c^=n;o.Write(new[]{(B)c,(B)(c>>8),(B)(c>>16),(B)(c>>24),(B)l,(B)(l>>8),(B)(l>>16),(B)(l>>24)},0,8);}}}

Much more readable:
using System.IO;
using B = System.Byte;
class X
{
    static void Main(string[] a)
    {
        // Read file contents
        var f = File.ReadAllBytes(a[0]);
        int l = f.Length, i = 0, j;

        // Initialise table for CRC hashsum
        var p = new uint[256];
        for (uint k = 0, r = 0; k < 256; r = ++k)
        {
            for (j = 0; j < 8; j++)
                r = r >> 1 ^ (r & 1) * 0xedb88320;
            p[k] = r;
        }

        uint c = ~(uint) 0, n = c;

        // Write the output file
        using (var o = File.Open(a[0] + ".gz", FileMode.Create))
        {
            // gzip header
            o.Write(new B[] { 31, 139, 8, 0, 0, 0, 0, 0, 4, 11 }, 0, 10);
            for (; i < l; i++)
            {
                // deflate block header plus one byte of payload
                o.Write(new B[] { (B) (i < l - 1 ? 0 : 1), 1, 0, 254, 255, f[i] }, 0, 6);
                // Compute CRC checksum
                c = p[(c ^ f[i]) & 0xFF] ^ c >> 8;
            }
            c ^= n;
            o.Write(new[] {
                // CRC checksum
                (B) c, (B) (c >> 8), (B) (c >> 16), (B) (c >> 24),
                // original file size
                (B) l, (B) (l >> 8), (B) (l >> 16), (B) (l >> 24)
            }, 0, 8);
        }
    }
}

Comments:

Expects path to file as first command-line argument.
Output file is input file + .gz.
I am not using any libraries to do the gzip, deflate or CRC32. It’s all in there.
This “compressor” increases the filesize by a factor of 6. But it’s in valid gzip format!
Tested using GNU gunzip and WinRAR.


text:
Compress programs
Write a program/script that decompresses and passes any compressed data appended at the end of the binary/file as standard input to a program specified as arguments.
$ gzip --to-stdout input >> your_solution
$ your_solution program args...

should have the same effects as:
$ program args... < input

zsh: (20 chars)
Edit: because zsh doesn't re-parse arguments like bash, I can lose the "s and it will still work with spaces in args
#!/usr/bin/zsh
tail -n+3 $0|zcat|$@

Bash (25 24 chars not including shebang line)
#!/bin/bash
tail -n+3 "$0"|zcat|"$@"

Could -n +3 be changed to -n+3?

@idealmachine yes, yes it could... (tho i had to test that :D)

Also just realized that if i used zsh, I would be able to lose the "s and still have it work with spaces...

C (251 chars)
Way too long to win, but I wanted to do one in a compiled language to make things interesting. (It turned out to be quite straightforward actually).
It's probably very compiler-dependent (I used GCC 4.4.3 with the default settings on 32-bit Linux)
#include<stdio.h>
#define q(x)FILE*x=x##open(
#define w strcpy(o+b
o,s=7462;char b[99];main(int i,char**a){q(f)*a,"r");while(--s)fgetc(f);
for(o=0;++s<i;o++[b]=32)w,a[s]),o+=strlen(a[s]);w,"|zcat");q(p)b,"w");
for(;~(i=fgetc(f));fputc(i,p));fclose(p);}

Bash (OP solution)
This is an example I came up with:
cat $0 | awk 'NR > 1' | zcat | $* ; exit

this fails if there are spaces in any args

Thanks for the info. I will leave it as such, your solution is better.


text:
Shortest path in a graph
Write a program to take a graph (from either standard input or a file, your choice) and find a shortest path in the graph.
Graphs are specified using the following format:
A---S   F--T
|  / \  |
| /   5 0
|/     \|
D----3--E

    A-Z: nodes in the graph
   -|/\: edges in the graph
    0-9: weights on the edges
<space>: all the holes

All edges are undirected and lie along one of the 8 cardinal directions (i.e., no bends).  Edges may optionally contain a weight from 0 to 9.  The weight will not be on the last symbol that connects the edge to a node (i.e. edges need to have at least 3 symbols to contain a weight).  Unweighted edges have a default weight of 1.
Your code should compute the shortest path between nodes S and T and print the length and the path, like this:
5:SDEFT

Shortest correct program wins.

Puzzles, where you must write the shortest code outputing the best output have a problem: they can be solved by generation random outputs until it suits the task. So such puzzles better should have not the shortest solution but the fastest. But shortest path in graph is trivial, so no sense of fastest, then you may specify, that you want to get the shortest solution with complexity of O(<???) or maybe some another way to determine goal effectiveness.

I'm looking for the shortest program.  Go ahead and randomly generate solutions and test them if you think that will get you a shorter program.  Keep in mind your program must always be correct.

Does the graph diagram have to be parsed or can you use your own format? One example of a format - your graph could be represented as: AS0,SD0,SE5,DE3,FE0,FT0 (you could omit the commas if each entry is 3 bytes long.)

Algorithm wise, an MST or Dijkstra comes to mind.

Yes, you have to parse the graph as I specified.  That's most of the problem, actually.  The shortest path part just makes sure your parsing is correct.

The input format is really far too complicated and imho doesn't really add that much to the problem.

Just thought folks here would like to try something a bit more challenging.

Differences in character widths could possibly ruin the alignment, especially across different fonts. For this reason, I agree that the input format is too complicated.

@SimpleCoder: I would assume monospace

Here's my code, 494 characters in python:
import sys,re
m=sys.stdin.readlines()
Z=lambda c,s:re.findall(r'(\w)%s+(\d*)[^\w]*(\w)'%c,''.join(x*2for x in s))
T=lambda n:''.join(x for a in map(None,*n)for x in a if x)
E=Z('-',''.join(m))+Z('\\|',T(m))+Z('/',T(' '*m.index(s)+s for s in m))+Z('\\\\',T(' '*m[::-1].index(s)+s for s in m))
E+=[x[::-1]for x in E]
S={}
for x in E:S[x[0]]=1e9
S['S']=0
P={}
for i in E:
 for x,w,y in E:
  w=int('1'+w)%10
  if S[y]>S[x]+w:S[y]=S[x]+w;P[y]=x
i=p='T'
while i!='S':i=P[i];p=i+p
print'%d:'%S['T']+p


text:
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.

@Nakilon please give a reason for your edit.

Because your question is probably the only one involving the 196 algorithm. Making single-use tags is not useful.

@Chris: It's a private beta with 34 questions so far; single-use tags is a normal thing at this point. Anyway, let's leave it as it is for now, retagging later is always an option :)

What I meant was, your question is likely to be the only one ever to involve this topic, even in 2 years' time. :-)

@Chris: Well, 196-algorithm is a pretty popular one, going by many different names. Just to be sure, though, I'll post another question about it before the 2-year-time lapses ;)

I'm assuming you expect it to work for all positive integers not in A023108?

@GigaWatt It should at least work for all positive integers that fit in the  type of the language that you use.

@Eelvex - So... when the input is 196, what's the expected output?  It fits in the integer data type quite comfortably.

@GigaWatt the expected output in this case is the palindrome reached with input 196, but since we wouldn't want to wait forever, I won't ask you to try it.

@GigaWatt also, I had missread your fist question :) Just don't bother with A023108s' case.

@Eelvex: How will Lychrel numbers be handled?

@Joel, as with A023108, just ignore them (act like you don't know about them); we don't know if any exists anyway.

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

It saves a few characters to use numeric input. {⍵=A←⍎⌽⍕⍵:⍵⋄∇A+⍵}⎕. You save the braces, a reverse and an eval.

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

Hehe ..))))))))

By looking at n as an int you can shorten by 6 characters, check for the code: http://meta.codegolf.stackexchange.com/q/75/62

Seems I accidentally included the new line vim sneakily added to the end of my file to my count. The real count is 55.

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.

.` copies the number and stringifies it.
.-1% copies that string version and reverses it.
.@ 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.)

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

Are you sure you didn't press random keys on your keyboard? It looks like that...

@M28: GolfScript looks even more like line noise than Perl, doesn't it? ;-)

I feel sorry for you, it must be painful to code that

@M28: That wasn't nearly as painful as the solution I wrote for Luhn algorithm. Just think about that. :-P

Your family is worried about you

@M28 look at my answer, that's what I call random keys on keyboard!

Ruby — 56 chars
x,r=gets
x="#{x.to_i+r.to_i}"until x==r=x.reverse
puts x

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

Just trying some old challenges, already answered, so not serious contender.

Some challenge authors will update the accepted answer if a shorter solutions comes in, so I think it's fair to inform the OP, that this is not technically a valid submission. (Don't get me wrong, I like to answer old challenges with CJam for fun, too - and I just did a few minutes ago. I'm just saying, if you do, leave a note, that the language is newer than the challenge.)

Actually being "not a serious contender" makes an answer subject to deletion -- but I don't see any reason this shouldn't be considered a serious contender.

J 25 27 31
f=:(+g)^:(~:g=.|.&.":)^:_
e.g.
f 5280
23232

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

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

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

Could you explain a little more on the process of bifurcation?

@CᴏɴᴏʀO'Bʀɪᴇɴ For example, on the stack is the string hello. The bifurcation will keep the original string, and pushes the string reversed. It's short for duplicate and reverse.

Oh, I see. Cool! Thanks

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

Perl, 40 chars
$_=<>;$_+=$r while$_!=($r=reverse);print

I know this is a really old post but a few changes can reduce this to 26 bytes: Try it online!

PHP - 54 48 characters
<?for($s=`cat`;$s!=$r=strrev($s);$s+=$r);echo$s;

Test:
$ php 196.php <<< 5280
23232

I'm going to have to remember the $str = cat`` thing for future golfing.  Heck of a lot better than using STDIN and still better than $argv[0].

@GigaWatt: $s='m4' should also work.

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

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

Edited. @Optimizer

Please don't edit all your submissions at once for minor edits (like a version number), as this unnecessarily clutters the front page. It's fine if you do 2 or maybe 3 at a time, but please wait a few hours before doing more systematic edits.

Forgot that it would push to front page, my bad. @MartinBüttner

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

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

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.

You can easily golf it more. Use ""+ rather than .ToString and get rid of some spaces.

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

Call with: bash <filename> <number>

What is the  for?

@Eelvex the script needs to call itself so you need to store it in a file.

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

print r

Please leave what language you used and how many bytes it has; although I recognized it written in Python 2.

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.

Wow, not everyone uses Jelly in their first post.

It was on my to-do list to post an answer on PPCG using an esoteric language. Jelly happened to be the first one I thought of :)

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!

Welcome to Code Golf! Nice first answer.

Thanks :D A friend showed me https://code.golf/ and I've been loving it since. first submission on this forum.

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)

The task description states that only the final palindrome should be printed.

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.

Can be shortened by two characters if there only ever are ten digits of input. This way it's safe for long as well which is the largest integral type PowerShell supports anyway but still, I waste two chars.

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.

You can shorten this quite a bit by taking advantage of the underused function until from the Prelude, as well as extracting the pattern of applying a binary operator to x and r x. Also, use readLn instead of getLine and read. The result saves 20 characters: f%x=f x$read.reverse.show$x;main=readLn>>=print.until((==)%)((+)%)

@hammar: You could use the function monad and save even more: Define r=(=<<read.reverse.show) and just use r(==)`until`r(+). Apart from that saving, it doesn't need to be a full program, a valid submission could just be the unnamed function from before. This brings you down to 41 bytes: Try it online!

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.

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;
}

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]

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]

R, 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!

You can (and should) choose a different way of doing this than string manipulation, but here are some golfing tips for the method you've chosen: strsplit(x,"") is shorter than strsplit(x,NULL), and el(L) is shorter than L[[1]]. as.double is shorter than as.numeric and strtoi is shorter than both; instead of setting t just use it directly in your if statement. also this is a recursive function if I'm not mistaken, so you need to put f= as part of your submission.

@Giuseppe Got it. Thanks for the tips. I'll keep working on this. It's easier for me to just get something that works then go back and optimize.

Hehehe, no worries. If you're hell-bent on using strings (or forced to by the problem), consider utf8ToInt to convert to digits and intToUtf8 to convert back. That'll be a big byte saving!

Here is a 109 bytes golf using utf8ToInt and a while loop

@Giuseppe That is very helpful. I was running into issues with trying to add the two utf8ToInt converted numbers. Funny enough, using a recursive function instead of a while loop results in 108 byes assuming I don't have to put f=. Were you able to figure out if that was allowed?

You must use f= if it is recursive, unfortunately.

Save 4 more bytes by using - in place of U. I also replaced rev with ! but it does not save any byte...

@JayCe Interesting way to save bytes. Thanks!

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

You don't need the ; between param($m) and for.

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
}

119 bytes

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

Try it online! (Javascript)

Might want to specify that this works only on GNU dc 1.4 and later, since it uses the new R command. Good solution, though!

I'm working on a totally different approach but not sure it will wind up smaller.

Thanks Sophia - I hadn't realised that R was new.  Looking forward to seeing your method!

Ah, nope...I tried a different approach to arranging the outside loop but it ended up about five bytes larger and no prettier. You win. =)

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

Dyalog APL, 17 bytes
{⍵+⍎⌽⍕⍵}⍣{⍺≡⍎⌽⍕⍺}

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

Javascript ES6, 56 bytes
f=a=>(g=_=>[...""+a].reverse().join``)()==a?a:f(a+ +g())

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

84 bytes: https://tio.run/##jY6xTgMxDIb3PoXplKg0QkVIReE6MDCVqSNiCNekypE6keMcqqp79iMHt4MsWbb/T9bXmd6sY7LYHT/HNpic4dV4vC4AMhv2LXSVUIV9UK5gyz6iepmHp33E0y1MfQcOmhHXu6uLJEK9AGlBDdqvn1xMw4HJ4@m5OGdJ4Gq5lIpsbylbIadN3jSoJa4a0mS5EALqYdTVJZWPUF1mpT76I5yrpvj9@PZu5GQMcLhktmcVC6tUEw4onDIphYt42Gzv9lLqv7jt43@ozX2tGRwWw/gN

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

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

}

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)

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

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

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+1th element is the ith element plus the reverse of itself
And ends when the element is equal to its reverse

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)

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.

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

J, 27 bytes
(+&.".|.)^:(-.@-:|.)^:_&.":

Try it online!

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

Try it online!

Ruby, 47 bytes
->a{v=a.to_s.reverse;v==a.to_s ? a:f[a+v.to_i]}

Try it online!

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.

Alternate 6 byter w/ flag

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!

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)

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!

Vyxal, 7 bytes
{:Ḃ≠|Ḃ+

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

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

Try it online!

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