text:
Generate the DH series
I see from this SMBC comic that Zach Weinersmith is offering a generous 14 points to anybody who can find a way of generating the following series:
0, 1, 4, -13, -133, 52, 53, -155

Now, we all know that there are infinite ways of generating any given numeric series, so Zach is clearly just giving those points away. But what's the shortest code that will do it?
I'll be particularly impressed if anyone can beat 25 bytes, particularly in a non-golfing language, since that's what it takes to write the following reference implementation in Python:
0,1,4,-13,-133,52,53,-155

The output can be in whichever format works best for you:

a program that spits out plaintext representation of signed decimal numbers
an expression that evaluates to a static sequence of numeric objects with these values (as in my Python example)
an expression for f(n) that returns the nth value of the sequence.  You can choose a zero-based or one-based convention for n as you wish and need not worry what the expression produces subsequent to the known elements.  (By "expression" here, I mean let's not count the characters in the function prototype itself, and let's say you can assume n is pre-initialized.)

Longer sequences (including infinite sequences) are permitted provided the first 8 elements match Weinersmith's DH Series above. The ninth and subsequent elements, if present, can be anything at all.

Jelly, 12 bytes
“ĊĊḊḢṬ3gƈ¢‘I

Try it online!
Explanation
“ĊĊḊḢṬ3gƈ¢‘      String representing code points
           I     Consecutive increments

PHP, 75 Bytes
0-Indexing
prints a underscore separeted string till the n th value

<?=+$e;for(;$i++<$argn;)echo _,$e+=[185,1,7-4*$e-log($e)^0,-17,-120][$i%5];

Try it online!
Expanded
<?=+$e; #Output zero 0 th value
for(;$i++<$argn;) # loop till reach input n
  echo _,$e+=[185,1,7-4*$e-log($e)^0,-17,-120][$i%5];
# Output and assign the next value in sequence

Steps depending on mod 5 start with 1
1: plus 1
2: plus 7 minus 4 times last value minus natural logarithm of last value cast to int
3: minus 17
4: minus 120
0: plus 185
Natural logarithm
PHP, 33 Bytes
prints a string representation

<?="[0,1,4,-13,-133,52,53,-155]";

Try it online!

05AB1E, 20 bytes
•3—ι]½ý.¢Σ”•6¡4'-:.¥

Try it online!
Uses: 16364176412061856164208
Replace the 6's with commas (split on 6):
['1', '3', '417', '4120', '185', '1', '4208']
Replace 4's with negative symbol:
['1', '3', '-17', '-120', '185', '1', '-208']
Undelta.

Simpler approach (turned out worse):
•5Û€ïÛ†!eŽΓ•8BR7¡6'-:

Jelly, 17 Bytes
153B-*“¡¢¥Æ⁵45ɓ‘×

Try it online!
Explanation:
153B-*

decode the signs from the binary digits of 153
“¡¢¥Æ⁵45ɓ‘

the magnitudes of the numbers represented as a code-page index list
×

elementwise multiplication

Python 3, 37 bytes
for i in 'ÝÞáÐXđĒB':print(ord(i)-221)

That is great—I fiddled with that approach briefly myself but couldn't get there. Note that you could make it a list comprehension and ditch the print to achieve a result of type 2

Welcome to the site! You don't need the space after the in.

Or say ord('ÝÞáÐXđĒB'[n])-221 for an even shorter answer, of type 3

This works nicely, but Python only supports non-UTF-8 encodings with a magic comment (which would have to be counted towards the score).  With UTF-8, your code is 43 bytes long.

You can remove a space between in and the string, so i in'ÝÞá

05AB1E, 14 bytes
"ÈÉÌ»Cüý-"ÇƵ%-

Try it online!
Explanation
"ÈÉÌ»Cüý-"      # push this string
          Ç     # convert to code points
           Ƶ%-  # subtract 200 from each

Previous 15 bytes solution
•∍ÉΣ-ú—("o•3ô¬-

Try it online!
Explanation
•∍ÉΣ-ú—("o•       # push the number 1551561591420222072080
           3ô     # split into pieces of 3
             ¬-   # subtract the first element from all elements

Way better than mine, admittedly I just wanted to try using undelta.

@carusocomputing: Yeah I'm glad you did. I was unsure what it was until I saw you answer :)

Neim, 11 + 1 (-n) = 12 bytes
0γ4π./

Try here
Note: might not work in the future. For reference, this works for commit db32a5e.
Explanation:
0γ4π./ Push 0
 γ          Push 1
  4         Push 4
   π        Push 13
           Negate
           Push 133
           Negate
       .    Push 52
        /   Push 53
           Push 155
           Negate

Mathematica, 79 bytes
s={-22,-83,408,-489,-25};i=2;While[i!=-1,t=Join[{i},Accumulate[s]+i];i--;s=t];s

Try it online!
in order to run on mathics the original code needs 2 more bytes

><>, 26 bytes
'!ñð7¯À½¼'80g-nao90.

Standard unicode solution, same as the other answers. Sad I couldn't get to 25.


text:
Plot the Gaussian Distribution in 3D

In probability theory, the normal (or Gaussian) distribution is a very common continuous probability distribution. Normal distributions are important in statistics and are often used in the natural and social sciences to represent real-valued random variables whose distributions are not known.

The challenge
Your challenge is to plot the probability density of the Gaussian Distribution on a 3-dimensional plane. This function is defined as:

Where:

A = 1, σx = σy = σ
Rules

Your program must take one input σ, the standard deviation.
Your program must print a 3D plot of the Gaussian Distribution in the highest quality as your language/system allows.
Your program may not use a direct Gaussian Distribution or probability density builtin.
Your program does not have to terminate.
Your plot may be in black and white or color.
Your plot must have grid lines on the bottom. Grid lines on the sides (as shown in the examples) are unnecessary.
Your plot does not need to have line numbers next to the grid lines.

Scoring
As usual in code-golf, the submission with the least bytes wins! I may never "accept" an answer using the button, unless one is incredibly small and intuitive.
Example output
Your output could look something like this:

Or it could look like this:

More valid outputs. Invalid outputs.

I was confused that you just showed the function for the X-axis. Do we need to take separate input/outputs for the X and Y sigma and mu's?

So are we to assume that μ equals 0? And what scale do you require for x and y? If the x-and y-ranges are chosen very small relative to σ, then the graph will essentially look like a constant function.

(For the two-dimensional distribution, I think it is clearer if you use |x-μ|^2 in the definition rather than (x-μ)^2.)

@GregMartin Edited.

@ScottMilner Edited.

Still not clear ... what are x_o and y_o and θ?

@GregMartin Well, from what I can make out, (x_o,y_o) seems to be the center of the plot on the xy-plane (which seems to be (0,0) in this case based on the sample outputs provided) and θ can be ignored since σ_x = σ_y = σ making the trigonometric functions cancel out.

Can we do a top down view of it?

@RohanJhunjhunwala  No, then it'd just be a grid :P

@MDXF I mean if we color code it. As opposed to a three D height map, can we do a series of boxes whose color correspond to a probability. I'm going to guess no, but it's worth asking

@RohanJhunjhunwala No, that would completely defeat the purpose of the challenge, sorry.

@MDXF it's ok, I figured that it wouldn't make much sense.

Someone has to do a Python answer if we have an R one!

@Lembik Well, a few months later it has still not been done; want to give it a shot?

Gnuplot 4, 64 62 61 60 47 bytes
(Tied with Mathematica! WooHoo!)
se t pn;se is 80;sp exp(-(x**2+y**2)/(2*$0**2))

Save the above code into a file named A.gp and invoke it with the following:
gnuplot -e 'call "A.gp" $1'>GnuPlot3D.png
where the $1 is to be replaced with the value of σ. This will save a .png file named GnuPlot3D.png containing the desired output into the current working directory.
Note that this only works with distributions of Gnuplot 4 since in Gnuplot 5 the $n references to arguments were deprecated and replaced with the unfortunately more verbose ARGn.
Sample output with σ = 3:

This output is fine according to OP.

Gnuplot 4, Alternate Solution, 60 bytes
Here is an alternate solution which is much longer than the previous one but the output looks much better in my opinion.
se t pn;se is 80;se xyp 0;sp exp(-(x**2+y**2)/(2*$0**2))w pm

This still requires Gnuplot 4 for the same reason as the previous solution.
Sample output with σ = 3:

I am not sure if it molds to the specifications required what specifications do you think it does not meet?

@MDXF Firstly, I am not sure if the transparency of the graph is okay. I honestly don't really like it, which is why I was not sure if it would be okay here. Secondly, the graph begins one unit high from the bottom by default, and I am not sure if that is all right either. Thirdly, because the graph begins one unit high, I am not sure the disproportionality of the graph compared to the graphs given in the original post is all right. However, if this is all okay with you, I will happily make it the main answer.

@MDXF In fact, I was going to post it as the original answer, but for these reasons I chose not to and posted by current answer instead.

@MDXF Actually, I can make it even shorter if this is okay. I understand if it won't be, but it does not hurt to ask. It is the default way Gnuplot would plot the probability density of the Gaussian distribution with a Sigma of 2 without any environment modifications.

@MDXF I guess I could have asked before posting my original answer, but at the time I was very eager to post an answer.

For your first comment, all of those are perfectly all right. Third coomment... nope,  that doesn't really work... sorry. Feel free to make your 47-byte solution the main one. You'll be tied for first, too... and if you golf it I'd be happy to see a non-Mathematica solution win a [tag:math] contest :P

@MDXF All right, great! Thanks for the clarification! :)

C++, 3477 3344 bytes
Byte count does not include the unnecessary newlines.
MD XF golfed off 133 bytes.
There's no way C++ can compete for this, but I thought it would be fun to write a software renderer for the challenge.  I tore out and golfed some chunks of GLM for the 3D math and used Xiaolin Wu's line algorithm for rasterization.  The program outputs the result to a PGM file named g.

#include<array>
#include<cmath>
#include<vector>
#include<string>
#include<fstream>
#include<algorithm>
#include<functional>
#define L for
#define A auto
#define E swap
#define F float
#define U using
U namespace std;
#define K vector
#define N <<"\n"
#define Z size_t
#define R return
#define B uint8_t
#define I uint32_t
#define P operator
#define W(V)<<V<<' '
#define Y template<Z C>
#define G(O)Y vc<C>P O(vc<C>v,F s){vc<C>o;L(Z i=0;i<C;++i){o\
[i]=v[i]O s;}R o;}Y vc<C>P O(vc<C>l, vc<C>r){vc<C>o;L(Z i=0;i<C;++i){o[i]=l[i]O r[i];}R o;}
Y U vc=array<F,C>;U v2=vc<2>;U v3=vc<3>;U v4=vc<4>;U m4=array<v4,4>;G(+)G(-)G(*)G(/)Y F d(
vc<C>a,vc<C>b){F o=0;L(Z i=0;i<C;++i){o+=a[i]*b[i];}R o;}Y vc<C>n(vc<C>v){R v/sqrt(d(v,v));
}v3 cr(v3 a,v3 b){R v3{a[1]*b[2]-b[1]*a[2],a[2]*b[0]-b[2]*a[0],a[0]*b[1]-b[0]*a[1]};}m4 P*(
m4 l,m4 r){R{l[0]*r[0][0]+l[1]*r[0][1]+l[2]*r[0][2]+l[3]*r[0][3],l[0]*r[1][0]+l[1]*r[1][1]+
l[2]*r[1][2]+l[3]*r[1][3],l[0]*r[2][0]+l[1]*r[2][1]+l[2]*r[2][2]+l[3]*r[2][3],l[0]*r[3][0]+
l[1]*r[3][1]+l[2]*r[3][2]+l[3]*r[3][3]};}v4 P*(m4 m,v4 v){R v4{m[0][0]*v[0]+m[1][0]*v[1]+m[
2][0]*v[2]+m[3][0]*v[3],m[0][1]*v[0]+m[1][1]*v[1]+m[2][1]*v[2]+m[3][1]*v[3],m[0][2]*v[0]+m[
1][2]*v[1]+m[2][2]*v[2]+m[3][2]*v[3],m[0][3]*v[0]+m[1][3]*v[1]+m[2][3]*v[2]+m[3][3]*v[3]};}
m4 at(v3 a,v3 b,v3 c){A f=n(b-a);A s=n(cr(f,c));A u=cr(s,f);A o=m4{1,0,0,0,0,1,0,0,0,0,1,0,
0,0,0,1};o[0][0]=s[0];o[1][0]=s[1];o[2][0]=s[2];o[0][1]=u[0];o[1][1]=u[1];o[2][1]=u[2];o[0]
[2]=-f[0];o[1][2]=-f[1];o[2][2]=-f[2];o[3][0]=-d(s,a);o[3][1]=-d(u,a);o[3][2]=d(f,a);R o;}
m4 pr(F f,F a,F b,F c){F t=tan(f*.5f);m4 o{};o[0][0]=1.f/(t*a);o[1][1]=1.f/t;o[2][3]=-1;o[2
][2]=c/(b-c);o[3][2]=-(c*b)/(c-b);R o;}F lr(F a,F b,F t){R fma(t,b,fma(-t,a,a));}F fp(F f){
R f<0?1-(f-floor(f)):f-floor(f);}F rf(F f){R 1-fp(f);}struct S{I w,h; K<F> f;S(I w,I h):w{w
},h{h},f(w*h){}F&P[](pair<I,I>c){static F z;z=0;Z i=c.first*w+c.second;R i<f.size()?f[i]:z;
}F*b(){R f.data();}Y vc<C>n(vc<C>v){v[0]=lr((F)w*.5f,(F)w,v[0]);v[1]=lr((F)h*.5f,(F)h,-v[1]
);R v;}};I xe(S&f,v2 v,bool s,F g,F c,F*q=0){I p=(I)round(v[0]);A ye=v[1]+g*(p-v[0]);A xd=
rf(v[0]+.5f);A x=p;A y=(I)ye;(s?f[{y,x}]:f[{x,y}])+=(rf(ye)*xd)*c;(s?f[{y+1,x}]:f[{x,y+1}])
+=(fp(ye)*xd)*c;if(q){*q=ye+g;}R x;}K<v4> g(F i,I r,function<v4(F,F)>f){K<v4>g;F p=i*.5f;F
q=1.f/r;L(Z zi=0;zi<r;++zi){F z=lr(-p,p,zi*q);L(Z h=0;h<r;++h){F x=lr(-p,p,h*q);g.push_back
(f(x,z));}}R g;}B xw(S&f,v2 b,v2 e,F c){E(b[0],b[1]);E(e[0],e[1]);A s=abs(e[1]-b[1])>abs
(e[0]-b[0]);if(s){E(b[0],b[1]);E(e[0],e[1]);}if(b[0]>e[0]){E(b[0],e[0]);E(b[1],e[1]);}F yi=
0;A d=e-b;A g=d[0]?d[1]/d[0]:1;A xB=xe(f,b,s,g,c,&yi);A xE=xe(f,e,s,g,c);L(I x=xB+1;x<xE;++
x){(s?f[{(I)yi,x}]:f[{x,(I)yi}])+=rf(yi)*c;(s?f[{(I)yi+1,x}]:f[{x,(I)yi+1}])+=fp(yi)*c;yi+=
g;}}v4 tp(S&s,m4 m,v4 v){v=m*v;R s.n(v/v[3]);}main(){F l=6;Z c=64;A J=g(l,c,[](F x,F z){R
v4{x,exp(-(pow(x,2)+pow(z,2))/(2*pow(0.75f,2))),z,1};});I w=1024;I h=w;S s(w,h);m4 m=pr(
1.0472f,(F)w/(F)h,3.5f,11.4f)*at({4.8f,3,4.8f},{0,0,0},{0,1,0});L(Z j=0;j<c;++j){L(Z i=0;i<
c;++i){Z id=j*c+i;A p=tp(s,m,J[id]);A dp=[&](Z o){A e=tp(s,m,J[id+o]);F v=(p[2]+e[2])*0.5f;
xw(s,{p[0],p[1]},{e[0],e[1]},1.f-v);};if(i<c-1){dp(1);}if(j<c-1){dp(c);}}}K<B> b(w*h);L(Z i
=0;i<b.size();++i){b[i]=(B)round((1-min(max(s.b()[i],0.f),1.f))*255);}ofstream f("g");f
W("P2")N;f W(w)W(h)N;f W(255)N;L(I y=0;y<h;++y){L(I x=0;x<w;++x)f W((I)b[y*w+x]);f N;}R 0;}

l is the length of one side of the grid in world space.
c is the number of vertices along each edge of the grid.
The function that creates the grid is called with a function that takes two inputs, the x and z (+y goes up) world space coordinates of the vertex, and returns the world space position of the vertex.
w is the width of the pgm
h is the height of the pgm
m is the view/projection matrix. The arguments used to create m are...

field of view in radians
aspect ratio of the pgm
near clip plane
far clip plane
camera position
camera target
up vector

The renderer could easily have more features, better performance, and be better golfed, but I've had my fun!

Wow, that is incredible!

Thanks, I probably won't golf this any further, but it was a good opportunity to set up some pre-golfed code for future challenges.

In that case, do you mind if I golf it and edit my golfs in? Oh, on top of that, you messed up your byte count - it should be 3415 bytes.

Not at all...go for it!

There you go, 133 bytes off!

This is terrific ! If you could tell me where you learnt all of that, that would be great !

@HatsuPointerKun Glad you enjoy it!  This tutorial... http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/ ...is a great place to start.

You crazy, crazy golfer.

Mathematica, 47 bytes
Plot3D[E^(-(x^2+y^2)/2/#^2),{x,-6,6},{y,-6,6}]&

takes as input σ
Input

[2]

output

-2 bytes thanks to  LLlAMnYP

Mathematica winning? No surprises there :P

Saving 2 bytes with E^(-(x^2+y^2)/2/#^2)

R, 105 102 87 86 bytes
s=scan();plot3D::persp3D(z=sapply(x<-seq(-6,6,.1),function(y)exp(-(y^2+x^2)/(2*s^2))))

Takes Sigma from STDIN. Creates a vector from -6 to 6 in steps of .1 for both x and y, then creates an 121x121 matrix by taking the outer product of x and y. This is shorter than calling matrix and specifying the dimensions. The matrix is now already filled, but that's ok, because we are overwriting that.
The for-loop loops over the values in x, making use of the vectorized operations in R, creating the density matrix one row at a time.
(s)apply again is a shorter method for vectorized operations. Like the hero it is, it handles the creation of the matrix all by itself, saving quite a few bytes.

128 125 110 109 bytes, but way more fancy:
This plot is created by the plotly package. Sadly the specification is a bit wordy, so this costs a lot of bytes. The result is really really fancy though. I would highly recommend trying it out for yourself.
s=scan();plotly::plot_ly(z=sapply(x<-seq(-6,6,.1),function(y)exp(-(y^2+x^2)/(2*s^2))),x=x,y=x,type="surface")

I specified in the question that the graph does not need to have line numbers, your second submission is fine.

Oh, I must've missed that. I swapped my solutions around. I think the plotly plot is fancy enough to warrant still being included here.

Well, both are much, much fancier than mine :P

Since you only use s once, could you do 2*scan()^2 and remove the s=scan(); at the start? It would save 3 bytes.

Applesoft BASIC, 930 783 782 727 719 702 695 637 bytes
-72 bytes and a working program thanks to ceilingcat spotting my error and a shortened algorithm
0TEXT:HOME:INPUTN:HGR:HCOLOR=3:W=279:H=159:L=W-100:Z=L/10:B=H-100:C=H-60:K=0.5:M=1/(2*3.14159265*N*N):FORI=0TO10STEPK:X=10*I+1:Y=10*I+B:HPLOTX,Y:FORJ=0TOL STEP1:O=10*J/L:D=ABS(5-I):E=ABS(5-O):R=(D*D+E*E)/(2*N*N):G=EXP(-R)*M:A=INT((C*G)/M):X=10*I+Z*O+1:Y=10*I+B-A:HPLOTTOX,Y:IF(I=0)GOTO4
1IF(J=L)GOTO3
2V=INT(J/10):IF((J/10)<>V)GOTO5
3D=ABS(5-I+K):E=ABS(5-O):R=(D*D+E*E)/(2*N*N):U=EXP(-R)/(2*3.14159*N*N):S=INT((C*U)/M):P=10*(I-K)+Z*O+1:Q=10*(I-K)+B-S:HPLOT TOP,Q:HPLOTX,Y
4IF(J=0)GOTO7:IF(I<10)GOTO5:IF(J=L)GOTO6:V=INT(J/10):IF((J/10)=V)GOTO6
5HCOLOR=0
6HPLOTTOX,10*I+B:HCOLOR=3:HPLOTX,Y
7NEXTJ:NEXTI:HPLOTW+1,H:HPLOTTO101,H:HPLOTTO0+1,H

Ungolfed version here.
When given input 1:

When given input 2:

This yet again shows the superiority of BASIC ....

Can save a few more bytes by setting one or more variables to some frequently used value, such as 10. Also, suggest replacing EXP(X)/(2*3.14159*S1*S1) with EXP(X)*M

source: Stack Exchange

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

sort: votes


text:
Eyeballing the bits
Eyeballing the binary values printed as ovals and sticks is not so easy...
To help with that, you must write a function (or a program) that prints numbers in custom binary representation.
So I want to take a number, say 3 (00000011) and output the bits in user-defined format, for example with space separated pairs:
00 00 00 11

or, say, in reversed order and with some decorators, e.g.:
11_00_00_00

Furthermore, there must be possibilty to show '0' and '1' as custom characters to distinguish them better, e.g.:
XX oo oo oo

So the challenge is to write the code which does that all whithin the following specification.

Specification
The function takes input like this:  f(A, mask, zeros, ones)
Parameters:
A -- input number -- any (unsigned) integer in range 0-255.
mask -- a string parameter which defines the construction of the output.
zeros -- a string of the same length, defines 'zero' glyphs for each output slot.
ones --  a string of the same length, defines 'one' glyphs for each output slot.
Rules for the output construction:
Look at this image with example closely to understand how the output is generated:

So only the single digits in the mask are parsed and replaced by corresponding bits of A, other characters are left as is. Further, if the value of the taken bit is 1 then it shows up in the final output as "X" and if it is 0 then it shows up as "o".
In the above example all four taken bits are "1" so we see "X" in all slots.
If the input number was 128, then, logically, the output would be X foo bar ooo. Characters in parameters "zeros" and "ones": any printable ASCII chars, assume they are always char-aligned with the mask.
Notes:

Bits are 0-indexed: 0th bit is the MSB.
Assume that digits 8,9 are not allowed in the mask string.
Input Strings include any printable ASCII chars.
'Zeros' and 'ones' are char-aligned with the mask.
For special characters/modifiers in your language: we can assume they will not appear in the input string.

For the clarity, see more examples.

Input -> Output examples
Output all 8 bits in common order with a space delimiter, in common oval-and-stick notation:
mask  =  "0123 4567"
zeros =  "0000 0000"
ones  =  "1111 1111"

A=1 ->    0000 0001

Output in reversed order, in dash-and-glyph notation:
mask =    "| 7654 3210 |"
zeros=    "  ---- ----  "
ones =    "  ssss ssss  "

A=1  ->    | s--- ---- |
A=3   ->   | ss-- ---- |
A=128->    | ---- ---s |

Diverse notations in one output, e.g. for packed data:
mask =       "0 | 123 4567"
zeros=       "    --- ----"
ones =       "X   kkk ssss"

A= 15  ->       | --- ssss
A= 16  ->       | --k ----
A= 32  ->       | -k- ----
A= 128 ->     X | --- ----
A= 255 ->     X | kkk ssss

Repeating patterns:
mask =    "| 7 66 555 4444 |"
zeros=    "  . .. ... ....  "
ones =    "  0 00 000 0000  "

A= 0 ->    | . .. ... .... |
A= 1 ->    | 0 .. ... .... |
A= 2 ->    | . 00 ... .... |
A= 3 ->    | 0 00 ... .... |
A= 4 ->    | . .. 000 .... |

Update
The rules have been slightly simplified - the program must print one number only (not array/list of numbers as it was proposed initially).

Can we also submit a program that accepts the four inputs? Some languages don't do functions too well.

@StephenS I suppose yes, but I am not sure I'll understand those :/

The last two arguments seem entirely irrelevant in most languages, why not just require 1 and 0? The first argument being a list doesn't seem to do much besides make regular languages add a simple loop/recursion while making it much harder for more esoteric languages to compete.

@MikhailV if you want to understand all of the submissions on your challenges, good luck :/ most of them have TryItOnline links so you can see them works, but they most golfing languages look like nonsense until you know what they do

@FryAmTheEggman I also don't understand what A does, since it is the same in all of the test cases

@MikhailV have at least 3 different inputs for A so we know what it's supposed to do, "A - a list (or an array) of unsigned integers in range 0-255." does not tell me anything about what to do with A

@FryAmTheEggman "why not just require 1 and 0?" custom representation is the main point here.

@user202729 Examples are not a specification.  This question could use a lot more clarity in the actual specification.  I begin to understand the task when reading the examples, but I still think the specification is unclear.

Ruby, 48 bytes
->a,f,*b{f.gsub(/\d/){b[a[55-$&.ord]][$`.size]}}

The zeroes and ones parameters are treated as an array (*b) and with the zeroes parameter is stored in b[0] and the ones parameter stored in b[1].
The mask parameter f has each digit (/\d/) substituted with a character from the appropriate array. The special variable $`, which holds the text leading up to the current match, is (ab)used here to keep track of position.
Ruby's bit indexing calls 0 the least-significant bit, but the challenge calls 0 the most significant bit. ASCII subtraction from 55 (the '7' character) yields a usable Ruby bit index.
Try it online!

JavaScript (ES6), 57 bytes
(A,M,O,I)=>M.replace(/[\d]/g,(d,i)=>(A>>7-d)%2?I[i]:O[i])

f=
(A,M,O,I)=>M.replace(/[\d]/g,(d,i)=>(A>>7-d)%2?I[i]:O[i])

console.log( f(1, "0123 4567", "0000 0000", "1111 1111") )
console.log( f(3, "| 7654 3210 |", "  ---- ----  ", " ssss ssss ") )
console.log( f(4, "| 7 66 555 4444 |", "  . .. ... ....  ", "  0 00 000 0000  ") )

Perl 6, 60 bytes
->\a,$_,\o,\z{S:g|\d|{substr (z,o)[a+>(7-$/)%2],$/.from,1}|}

Mathematica, 131 bytes
""<>Table[(f/@{##2})[[x[[i]],i]],{i,Length[x=(f=Characters)@#2/.Table[ToString@i->2+Floor[#/2^(7-i)]~Mod~2,{i,0,7}]/._String->1]}]&

Length[x] can be Length@x and {#2,#3,#4} can be {##2}.

Also, StringJoin@@ can just be StringJoin@ and #1 is just #

I've simplified the rules slightly, see update.

Python, 97 bytes
lambda A,M,Z,O:"".join([[Z,O][1&(A>>7-int(d))][i] if d.isdigit() else d for i,d in enumerate(M)])

q/kdb+, 86 64 bytes
Solution:
f:{[A;M;Z;O]@[M;m;:;((-8#0b vs A)"I"$'M m)(Z;O)'m:(&)M in .Q.n]}

Examples:
q)f[1;"0123 4567";"0000 0000";"1111 1111"]
"0000 0001"
q)f[1;"| 7654 3210 |";"  ---- ----  ";"  ssss ssss  "]
"| s--- ---- |"
q)f[15;"0 | 123 4567";"    --- ----";"X   kkk ssss"]
"  | --- ssss"
q)f [0;"| 7 66 555 4444 |";"  . .. ... ....  ";"  0 00 000 0000  "]
"| . .. ... .... |"

Explanation:
Pull out indices where input mask M is a numeral, call it m this is where we will be modifying the input mask. Take the numerals out of the string, cast to integers and then index into our 8-bit array to get the correct ordering.
Use this 8-bit array to index into either O (if 1 is set) or Z (if 0 is set), and then index into these lists at the indices given by m.
Finally apply  (:) this new list to the original mask at indices m.
{[A;M;Z;O]                                                   } / lambda function with 4 parameters
          @[ ; ; ;                                          ]  / apply, applies 3rd parameter to 1st parameter at indexes from parameter 2 with parameter 4 :)
                   (-8#0b vs A)                                / convert input number to binary (64 bit), take the last 8 items
                                              m:(&)M in .Q.n   / returns indices where mask is in "0123..789", stores in variable m
                               "I"$'M m                        / index into mask at indices m, then cast these numbers to an integer array
                  (                    )                       / we then index into our 8 bits a these offsets to get the output order
                                        (Z;O)                  / 2-item list of the zeroes and ones mask
                                             '                 / take each item on the left and right and apply them to (Z;O) (ie index in at 0 / 1 and then 123..67)
            M m :                                              / apply *this* list to M at each index given by m

Notes:
Could shave off a further 14 bytes if we were allowed to give the arguments in the form:
[A;M;(Z;O)]
as q allows for up to 3 arguments to be given to a function without being explicitly named (they are x, y and z respectively):
f:{@[y;m;:;((-8#0b vs x)"I"$'y m)z'm:(&)y in .Q.n]}

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


text:
Tic Tac Toe: print all possible positions without duplicates
Write a program that outputs all possible Tic Tac Toe positions including the corresponding game outcome. Avoid duplicate output of equal positions.
The program takes no input.
Rules:

A position output must consist of 9 characters, using X and O for the taken squares, and an arbitrary non-whitespace character for the blank squares
Each position must be printed in 3 lines/columns, with a blank line as a separator between two positions.
Additional whitespace / blank lines / box drawing characters are welcome
Player X goes first
The outcome can be either of:

X has won
O has won
Draw
Game in progress

You are free to choose a suitable visualization of the position's outcome, e.g. as colored text, or as textual annotation, as long as it is placed near the corresponding position
Positions are considered equal if one can be obtained from the other by rotation or mirroring. Duplicate positions must not be printed. (In other words, print the equality classes only.)
For example, print only one of the following:

X••  ••X  •••  •••
•••  •••  •••  •••
•••  •••  X••  ••X

This is code-golf, so shortest code wins!

Sample output:
•••
•••
••• -

X••
•••
••• -

•X•
•••
••• -

•••
•X•
••• -

[…]

XXO
OOX
XXO /

OXO
XXX
OXO X

Hint: There are 765 positions, with 91 wins for X, 44 wins for O, and 3 draws.

A similar question has been asked before, but this one is different.

Welcome to PPCG! Every challenge on PPCG has to have a winning criterion. What is the criterion for this challenge? Is it [tag:code-golf] where the program with the shortest bytecount wins?

If you confirm the winning criterion, this should be opened again soon. I haven't counted the positions yet, but I was wondering, is the empty board a) required b) prohibited c) optional?

Just realised, you already said shortest code wins. Editing in code-golf tag. We usually score by number of bytes here, because there are some languages specifically invented to use multibyte characters to shorten code, which isn't very interesting.

@StephenS That's a different thing. A byte can have any value from 0-255. This website can only display single byte characters in the range 32-126 plus a few others. 256 byte codepages have been around for ages and I myself have posted C answers in codepage 437. UTF-8 was invented because these codepages didn't have enough characters for all natural languages, but UTF-8 is not designed to handle non-text data with random bytes. I was referring to languages like https://esolangs.org/wiki/Sclipting which extensively uses multibyte asian characters to exploit the loophole of scoring in characters

@LevelRiverSt ah, gotcha. Thanks for the info :)

There were many boring kolmorogorov complexity answers in Sclipting and similar which led PPCG to change to scoring by bytes to close this loophole. I disagree with your edit as the OP's stated intention was scoring in characters and your edit has made it more ambiguous.It is up to OP to decide (and OP should clarify), but for this particular challenge (as it is not kolmogorov) I suspect it will make little difference whether scoring by bytes or characters is used.

OP, feel free to rollback my character->byte edit.

@ThomasR : Whats a duplicate ? Mirrored, Rotated ?

@user7185318 Positions are considered equal if one can be obtained from the other by rotation or mirroring

Invalid positions (https://codegolf.stackexchange.com/questions/102985/is-this-tic-tac-toe-board-valid) must not be printed, and all in-game states to reach valid positions must be printed, right? And must outcome be printed?

Related?

Related but uses two different colours instead of three (as in this challenge)

Jelly, 192 179 168 bytes
5ĿḢṠµFf0L¬ị⁾-/µ5ĿḢṠµ?
U,µṚ,µ€µ“æɗþƑ’DịFs3,µ€€Fs9s3$€Ṣ
FSµ×’¬
ÑPµA_µọ9n1
,UŒDḢ$€;;ZS€f3,-3
Ç,SS€µṪµṪCµSṠ‘µ?÷Ḣ
Ça3Ŀa4Ŀ
3ṗ9_2s3$€ÇÐf2Ŀ€QḢ€µ;ÑFµ€µ3Ḷ’,“O¤X”yµ€Fs10µs3Gµ€j⁾¶¶

Try it online! (Takes about 30 seconds, so be patient).
How it Works
High level overview:
In intermediate steps, this stores X as 1, unplaced as 0, and O as -1.
The program generates all 3^9 possibilities, then keeps only the valid positions based on meeting the three criteria:

There is 1 or 0 more X than O.
Not both X and O have won.
If X has won, there is 1 more X than O. If O has won, there are an equal number of Os and Xs.

Then, the program replaces each game state with all of its rotations and reflections to get a list of all equivalence classes. This is the operation which takes most of the time.
The first game state is taken from each of the equivalence classes, then who won is calculated.
Where this happens
The lines are numbered for readability
1: 5ĿḢṠµFf0L¬ị⁾-/µ5ĿḢṠµ?          ••calculates who wins (output as -1 or 1) or draw ("-") or in game ("/")
                 µ5ĿḢṠµ?          - if(someone won based on line 5):
   5ĿḢṠ                             - return 1 if X won and -1 if O won
       µ                          - else:
        Ff0L¬ị⁾-/                   - return "/" if the game is in progress and "-" if the game is at a tied end-state
2: U,µṚ,µ€µ“æɗþƑ’DịFs3,µ€€Fs9s3$€Ṣ••outputs the equivalence class to a game state
   U,                             - list of game state [reflected horizontally, unaltered]
     µṚ,µ€                        - for each, replace with the list [reflected vertically,unaltered]
          µ“æɗþƑ’DịFs3,µ€€        - for each, replace with the list [rotated 90 degrees counter-clockwise,unaltered]
                          Fs9s3$€ - reformat into list of game states
                                 Ṣ- Sort
3: FSµ×’¬                         ••outputs truthy iff there is the right number of `X`s to `O`s (condition 1)
   FS                             - d = number of `X`s minus number of `O`s
     µ×’                          - d*(d-1): falsey iff d is 0 or 1
        ¬                         - logical not, to return truthy iff d is 0 or 1
4: ÑPµA_µọ9n1                     ••outputs truthy iff there is the right number of winners (condition 2)
   Ñ                              - the winners. [-3,3] is what we want to return falsy on
    PµA_µ                         - 18 on [-3,3] and 0 otherwise
         ọ9n1                     - not divisible by 9 exactly once: 0 on [-3,3] and 1 otherwise
5: ,UŒDḢ$€;;ZS€f3,-3              ••outputs the number of times each player won.
   ,UŒDḢ$€;;Z                     - the diagonals, rows, and columns of a board
             S€                   - sum of each. Returns -3 or 3 iff the line is only 1s or -1s
               f3,-3              - filter out, keeping only 3s and -3s
6: Ç,SS€µṪµṪCµSṠ‘µ?÷Ḣ             ••return truthy iff the winner corresponds to the respective numbers of X and O (condition 3)
   Ç,SS€                          - list of winners and how many more Xs than Os there are
             µSṠ‘µ?               - if O won, then
        µṪ                          - how many more Xs than Os there are
                                  - else:
          µṪC                       - the complement of how many more Xs than Os there are
                   ÷Ḣ             - deal with no one winning
7: Ça3Ŀa4Ŀ                        ••return truthy iff the game state meets all three conditions
   Ç 3Ŀ 4Ŀ                        - the three conditions: on line 3,4, and 6
    a  a                          - joined by logical ANDs
8: 3ṗ9_2s3$€ÇÐf2Ŀ€QḢ€µ;ÑFµ€µ3Ḷ’,“O¤X”yµ€Fs10µs3Gµ€j⁾¶¶ ••do everything
   3ṗ9_2                        - all possible game states, with -1 for O and 1 for X
        s3$€                    - turn into two-dimensional game boards
            ÇÐf                 - filter based on line 6: if the board meets all three ocnditions
               2Ŀ€Q             - generate the equivalence classes for each and remove repeats based on line 1
                   Ḣ€           - get the first board from each class
                     µ;ÑFµ€     - append the winner to each board based on line 1
   µ3Ḷ’,“O¤X”yµ€                   - map each -1, 0, and 1 to the proper `O`,  `¤`, and `X`.
                Fs10µs3Gµ€         - format each board- winner combos
                          j⁾¶¶     - join the combos by double-newlines

Python 2, 648 620 bytes
import re
M=re.match
x='X';o='O'
R=lambda b,z=[6,3,0,7,4,1,8,5,2]:''.join(b[z[i]]for i in range(9))
p='XXX......|...XXX...|......XXX|X...X...X';q=p.replace(x,o)
def e(b):c=b.count;d=c(x)-c(o);w=M(p,b)or M(p,R(b));v=M(q,b)or M(q,R(b));return 0 if d not in[0,1]else 0 if w and v else(x if d==1 else 0)if w else(o if d==0 else 0)if v else'.'if'.'in b else'/'
h=set()
for n in range(3**9):
 b=reduce(lambda a,v:('.XO'[a[1]%3]+a[0],a[1]/3),range(9),('',n))[0]
 if b not in h:
	u=e(b)
	if u:print'%s\n%s\n%s %s\n'%(b[:3],b[3:6],b[6:],u)
	h.update(reduce(lambda a,v:a+[R(a[-2]),R(a[-1])],range(3),[b,R(b,[2,1,0,5,4,3,8,7,6])]))

Try it online!
Probably a bit of minor golfing possible here with this approach; but not a lot.
Edit: Thx to ovs, who noted a tweak gaining 28 bytes; and 3 from Artemis Fowl
Un-golfed code
The basic idea here is: brute force each of the 3^9=19683 possible board encodings. Keep track of the conjugates (rotations and reflections) of boards that have already been examined so you don't duplicate entries. At a minimum, valid boards must have either an equal number of X's and O's or else one more X than O. Not possible to have both a win for X and a win for O; plus some additional finicky constraints.
import re
from collections import Counter

FLIP_XFRM = [2,1,0,5,4,3,8,7,6]
ROT_XFRM = [6,3,0,7,4,1,8,5,2]

def xfrm(b, xf):
    return ''.join(b[xf[i]] for i in range(9))

def flipIt(b):
    return xfrm(b,FLIP_XFRM)

def rotIt(b):
    return xfrm(b,ROT_XFRM)

def conjugates(b):
    conj = [b, flipIt(b)]
    for i in range(3):
        conj += [rotIt(conj[-2]), rotIt(conj[-1])]
    return conj

def tttToB(n):
    b = ''
    for i in range(9):
        b = '.XO'[n %3]+b
        n /= 3
    return b

def printBoard(b,outcome='.'):
    print '%s\n%s\n%s %s\n' % (b[:3],b[3:6],b[6:],outcome)

def evalBoard(b):
    c = Counter(b)
    if c['X']-c['O'] not in [0,1]:
        return False

    p1 = 'XXX......|...XXX...|......XXX|X...X...X'
    p2 = p1.replace('X','O')

    br = rotIt(b)
    w1 = re.match(p1,b) or re.match(p1,br)
    w2 = re.match(p2,b) or re.match(p2,br)
    if w1 and w2:
        return False

    if w1:
        return 'X' if c['X']==c['O']+1 else False

    if w2:
        return 'O' if c['X']==c['O'] else False

    if '.' in b:
        return '.'
    else:
        return '/'

def main():
    history = set()
    for m in range(3**9):
        b = tttToB(m)
        if b not in history:
            outcome = evalBoard(b)
            if outcome:
                printBoard(b,outcome)
            history.update(conjugates(b))

main()

I don't thonk you need the Counter. You can replace it with c=b.count;d=c(x)-c(o)

@ovs : so noted!

That big long return can be return 0if d not in[0,1]else 0if w and v else(x*(d==1))if w else(o*(d==0))if v else'.'if'.'in b else'/'

Old post I know, but this seems to be 623 bytes? You can replace the second level of indentation (2 spaces) with a single tab for 620 bytes, maybe you meant to do this?

@ArtemisFowl Yup, this was before I discovered TIO - easy to make counting errors!

Ruby, 305 bytes
19683.times{|i|c=(i%3).to_s
s=(9**8+i/3*6562).to_s(3)
w=0
t=(0..3).map{|j|r=s[1+j*2,9]
w|=1<<r[0..2].sum%8|1<<(c+r[j/2]+r[4+j/2]).sum%8
[r,r.reverse].min}.min
v=t[0..2]+$/+t[7]+c+t[3]+$/+t[6]+t[5]+t[4]
w&=65
b=v.sum%51
w<65&&b>w/64&&b<3-w%2&&t==s[1,9]&&puts(v.tr("012","X.O"),w<1?v.include?(?1):w%31,"")}

This works similiarly to the other answers in that it generates all 3**9 boards then filters out the valid ones. Internally, we use ternary numbers where 0=X 1=. 2=O in the output. Iterate c through the 3 possible values for the centre, and s through the 3**8 = 6561 values for the perimeter. Before converting i/3 to a string representation of a ternary number, we multiply by 6562 to duplicate all digits, and add 3**16 to start the number with a 1, in order to ensure there are leading zeros where applicable. w is the win condition - set this to zero.
For each board Iterate through 4 rotations of the digits in s to find the lexically lowest version of the current 8 digit ternary number representing the perimeter. At the same time, add the ascii values of the first 3 digits (top row of current rotation) and use this to check for a win. Also, add the ascii values of c and a pair of diametrically opposite digits to check if there is a win through the centre.
Check if the output is valid - If both 1's bit and 64's bit of w are both set, both sides win - this is not valid. Check the balance of X's and O's (if there is no winner yet it can be either equal X and O or one more X - but if the game is won, there is only one possible value, as the winner must have gone last.) To avoid showing different rotations of the same board, only output if the lexically lowest version of the perimeter corresponds to the current value of s[2,9].
Output the board, sustituting the symbols tr("012","X.O"). The game status is shown below the board. If w=0, this is true if there are still empty squares (game still in progress) and false if the board is full. If w is nonzero we output 1 if player 1 (X) has won or 64%31==2 if player 2 (O) has won.
Ungolfed
19683.times{|i|                             #check 3**9 possibilities
  c=(i%3).to_s                              #centre square: 0=X, 1=. 2=O
  s=(9**8+i/3*6562).to_s(3)                 #perimeter:multiply i/3 by 3**8+1 to duplicate digits, add 3**16 to give a 1 at left side to ensure leading zeros
  w=0                                       #set w=0 to clear wins (1´s bit holds win for X, 64´s bit holds win for O)
  t=(0..3).map{|j|                          #build an array of 4 different rotations of the perimeter
     r=s[1+j*2,9]                           #by taking different 9-character slices of s
     w|=1<<r[0..2].sum%8|                   #add ascii codes mod 8 for top row of current rotation, take sum modulo 8 to give sum of digits. set a bit in w (we only care about bits 0 and 6)
        1<<(c+r[j/2]+r[4+j/2]).sum%8        #do the same for one of the 4 lines through the centre. if j/2=0 check diagonal, if j/2=1 check horizontal/vertical.
     [r,r.reverse].min}.min                 #add to the array the lexically lowest version(forward or reverse) of the current rotation. When the loop ends, find the lexically lowest version overall and assign to t.
  v=t[0..2]+$/+t[7]+c+t[3]+$/+t[6]+t[5]+t[4]#format the output into a square 012\n 7c3\n 654
  w&=65                                     #clear bits 1 through 5 of w, leave only bits 0 and 6 which are the ones of interest.
  b=v.sum%51                                #valid values of sum of ascii codes in output are 461 (equal 0's and 2's) and 460 (one more 0 than 2). Take modulo 51 to reduce these values to 1 and 2
  w<65&&                                    #if a maximum of one player has a winning line (not both) and
  b>w/64&&                                  #b must be 1 or 2 (only 2 permitted if O's won)
  b<3-w%2&&                                 #b must be 1 or 2 (only 1 permitted if X's won)
  t==s[1,9]&&                               #s[2,9] is the lexically lowest version of the current board (to avoid duplicates) then
  puts(v.tr("012","X.O"),                   #output the board, subsituting internal "012" characters for external "X.O"
  w<1?v.include?(?1):w%31,"")               #if nobody won, output true if game in still in play (1's present on board) else false
}                                           #if there is a winner, output (player) 1 for X, (player) w%31=2 for O. Also output a blank line.

Checking scheme
The diagrams below show the scheme for rotation (and win checking, in capitals). The diagrams are shown unrotated. The four different rotations are taken as substrings from the double copy of i/3, with the 3 consecutive capital letters on the perimeter of each diagram (the "top" per current rotation) being the first 3 characters in the 9-character substring. For each rotation, 9-character reversal (diagonal flip about A-E or C-G  axis) is also tried. The board is only output if the current value of i/3 is the lexically lowest of all rotations and mirrors.
 ABC    abC    aBc    Abc
 hZd    hZD    hZd    HZD
 gfE    GfE    GFE    Gfe

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


text:
Shortest Addition Chain
An addition chain is a sequence of integers starting with 1, where every integer other than the initial 1 is a sum of two previous integers.
For instance, here's an addition chain:
[1, 2, 3, 4, 7, 8, 16, 32, 39, 71]

Here are the sums that make it an addition chain:
1 + 1 = 2
1 + 2 = 3
1 + 3 = 4
3 + 4 = 7
1 + 7 = 8
8 + 8 = 16
16 + 16 = 32
7 + 32 = 39
32 + 39 = 71

In this challenge, you will be given a positive integer n, and you must output one of the shortest addition chains which ends in n.
Examples - note that there are many possible outputs, all that you are required to find is an addition chain that's just as short:
1: [1]
2: [1, 2]
3: [1, 2, 3]
4: [1, 2, 4]
5: [1, 2, 3, 5]
6: [1, 2, 3, 6]
7: [1, 2, 3, 4, 7]
11: [1, 2, 3, 4, 7, 11]
15: [1, 2, 3, 5, 10, 15]
19: [1, 2, 3, 4, 8, 11, 19]
29: [1, 2, 3, 4, 7, 11, 18, 29]
47: [1, 2, 3, 4, 7, 10, 20, 27, 47]
71: [1, 2, 3, 4, 7, 8, 16, 32, 39, 71]

Standard I/O rules, etc. Standard Loopholes banned. Code golf: Fewest bytes wins.

Related

Related OEIS sequence.

Are we allowed to output the chain in reverse order?

@Arnauld No, this specific order.

Pyth, 13 bytes
h-DsM^N2/#QyS

Test suite
Gives the lexicographically first shortest chain. It's fairly slow, but not that bad - 19 completes in about 30 seconds using pypy.
Some ideas from @Dennis's solution.
I really like this one - there are a ton of neat tricks involved.
Explanation:
h-DsM^N2/#QyS
h-DsM^N2/#QySQ    Implicit variable introduction
            SQ    Inclusive range, 1 to input.
           y      Subsets - all subsets of the input, sorted by length then lexicographically
                  Only sorted subsets will be generated.
                  Our addition chain will be one of these.
        /#Q       Filter for presence of the input.
  D               Order by
 -                What's left after we remove
     ^N2          All pairs of numbers in the input
   sM             Summed
h                 Output the list that got sorted to the front.

This is still a bit hard to understand, but let me try to explain in a bit more detail.
We start with ySQ, which gives all possible ordered subsets of [1, 2, ... Q], in increasing order of size. The shortest addition chain is definitely one of these, but we need to find it.
The first thing we'll do is filter the list to only keep lists that contain a Q. We do this with /#Q.
Next, we order the list by what's left after we remove the result of a certain function. -D orders by the remainder after removing something.
The thing we remove is sM^N2, where N is the list we're removing things from. ^N2 gives the cartesian product of N with itself, all possible pairs of two elements in N. sM then sums each of the pairs.
What's the smallest possible result, after we do this removal? Well, the smallest element in the input list definitely will remain, because all the numbers are positive, so any sum of two numbers will be greater than the smallest number. And there will be at least one number, because we checked that the input was present in the list. Therefore, the smallest possible result will be when every number except the smallest number is the sum of two other numbers in the list, and the smallest number in the list is 1. In this case, the sorting key will be [1]. These requirements mean that the list must be an addition chain.
So, we sort the addition chains to the front. Remember that y gives its subsets in increasing order of size, so the list which is sorted to the front must be one of the shortest addition chains. h selects that list.

Haskell, 57 bytes
c=[1]:[x++[a+b]|x<-c,a<-x,b<-x]
f n=[x|x<-c,last x==n]!!0

A brute force solution.
Try it online!
Explanation
The infinite list c contains all addition chains, ordered by length.
It is defined inductively in terms of itself, by taking a list x from c and two elements from x, and appending their sum to x.
The function f finds the first list in c that ends with the desired number.
c=            -- c is the list of lists
 [1]:         -- containing [1] and
 [x           -- each list x
  ++[a+b]     -- extended with a+b
 |x<-c,       -- where x is drawn from c,
  a<-x,       -- a is drawn from x and
  b<-x]       -- b is drawn from x.
f n=          -- f on input n is:
 [x           -- take list of those lists x
 |x<-c,       -- where x is drawn from c and
  last x==n]  -- x ends with n,
 !!0          -- return its first element.

-1 byte with f n=[x|x<-c,elem n x]!!0. This is equivalent because if n is an element of x but not the last, then a shorter x would be taken first. Alternatives: f n=(filter(elem n)c)!!0 and f n=head$filter(elem n)c

Brachylog, 14 bytes
∧≜;1{j⊇Ċ+}ᵃ⁽?∋

Try it online!
A brute-force submission that builds all possible addition chains using iterative deepening, stopping when a chain containing its right argument is found. Unlike most Brachylog submissions, this is a function submission that inputs via its right argument (conventionally called the Output) and outputs via its left argument (conventionally called the Input); doing this is somewhat controversial, but the highest-voted meta answer on the subject says it's legal (and doing so is consistent with our normal I/O defaults for functions). If we used the input and output in a more conventional way, this would be 16 bytes (∧≜;1{j⊇Ċ+}ᵃ⁽.∋?∧), because the right-hand side of the program would not be able to make use of the implicit constraint (thus would need that disabled, and a new explicit constraint given, at a cost of 2 bytes).
Explanation
∧≜;1{j⊇Ċ+}ᵃ⁽?∋
∧               Disable implicit constraint to read the left argument
 ≜;        ⁽    Evaluation order hint: minimize number of iterations
    {    }ᵃ     Repeatedly run the following:
   1      ᵃ       From {1 on the first iteration, results seen so far otherwise}
     j            Make {two} copies of each list element
      ⊇           Find a subset of the elements
       Ċ          which has size 2
        +         and which sums to {the new result for the next iteration}
             ∋    If the list of results seen so far contains {the right argument}
            ?     Output it via the left argument {then terminate}

An interesting subtlety here is what happens on the first iteration, where the input is a number rather than a list like on the other iterations; we start with the number 1, make two copies of every digit (making the number 11), then find a 2-digit subsequence of it (also the number 11). Then we take its digit sum, which is 2, and as such the sequence starts [1,2] like we want. On future iterations, we're starting with a list like [1,2], doubling it to [1,2,1,2], then taking a two-element subsequence ([1,1], [1,2], [2,1], or [2,2]); clearly, the sums of each of these will be valid next elements of the addition chain.
It's a little frustrating here that the evaluation order hint is needed here, especially the ≜ component (it appears that ᵃ takes its evaluation order hint from inside rather than outside by default, thus the rather crude use of ≜ in order to force the issue).

I had tried for about 30 minutes to find a short way to do this challenge. My solution was way longer than this.

@Fatalize: ᵃ is one of those builtins that rarely comes up, but when you need it, you really need it, as there's no remotely terse way to implement it using other control constructs. Once I realised this was an ᵃ challenge, the rest came fairly directly from there.

Jelly, 17 bytes
’ŒP;€µ+þ;1Fḟ@µÐḟḢ

Outputs the lexicographically first solution in exponential time.
Try it online!
How it works
’ŒP;€µ+þ;1Fḟ@µÐḟḢ  Main link. Argument: n (integer)

’                  Decrement; n-1.
 ŒP                Powerset; generate all subarrays of [1, ..., n-1], sorted first
                   by length, then lexicographically.
   ;€              Append n to all generate subarrays.
     µ       µÐḟ   Filterfalse; keep only subarrays for which the chain between the
                   two chain separators (µ) returns a falsy value.
     µ             Monadic chain. Argument: A (array of integers)
      +þ               Add table; compute the sums of all pairs of elements in x,
                       grouping the results by the right addend.
        ;1             Append 1 to the resulting 2D array.
          F            Flatten the result.
           ḟ@          Filterfalse swapped; remove all elements of A that appear in
                       the result. This yields an empty list for addition chains.
                Ḣ  Head; select the first result.

PHP, 195 Bytes
function p($a){global$argn,$r;if(!$r||$a<$r)if(end($a)==$argn)$r=$a;else foreach($a as$x)foreach($a as$y)in_array($w=$x+$y,$a)||$w>$argn||$w<=max($a)?:p(array_merge($a,[$w]));}p([1]);print_r($r);

Try it online!

Unfortunately this algorithm doesn't give optimal answers, e.g. for 15.

@Neil it is now longer but it works. I have no Idea in the moment how to decide which of both ways is the right one. Maybe the count of primes plays a role

this code doesn't pass the 149 test. Length should be 10, not 11

@Jenny_mathy Corrected

JavaScript (ES6), 83 86 bytes
Edit: fixed to output the list in non-reverse order
n=>(g=(s,a=[1])=>s-n?s>n||a.map(v=>g(v+=s,a.concat(v))):r=1/r|r[a.length]?a:r)(r=1)&&r

Demo

let f =

n=>(g=(s,a=[1])=>s-n?s>n||a.map(v=>g(v+=s,a.concat(v))):r=1/r|r[a.length]?a:r)(r=1)&&r

for(n = 1; n <= 15; n++) {
  console.log(n, '-->', JSON.stringify(f(n)));
}

Mathematica, 140 bytes
t={};s={1};(Do[While[Last@s!=#,s={1};While[Last@s<#,AppendTo[s,RandomChoice@s+Last@s]]];t~AppendTo~s;s={1},10^4];First@SortBy[t,Length@#&])&

.
produces a different shortest addition chain everytime you run it
Try it online
paste the code with ctrl+v, place input i.e [71] at the end of the code and press shift+enter

As I don't have access to Mathematica, what length of chain does this give for an input of 15?

the right one {1, 2, 3, 5, 10, 15}

For input 149, I got a chain of length 11 from your program, but there exists one of length 10 ([1,2,4,5,9,18,36,72,77,149]). It seems that your program uses random sampling and isn't guaranteed to find the optimal solution.

fixed! but it takes longer

Python 3, 102 bytes
f=lambda n,s={(1,)}:next((p for p in s if n in p),0)or f(n,{p+(i+j,)for p in s for i in p for j in p})

Try it online!


text:
Interleaving reversing
Given a string, reverse it interleavingly. Here's how to do it for abcdefghi and abcdefghij, 0-indexed:

Separate the chars at even indices from the chars at odd indices:a c e g i
 b d f h
a c e g i
 b d f h j
Reverse the chars at odd indices:a c e g i
 h f d b
a c e g i
 j h f d b
Interleave into one string again:ahcfedgbi
ajchefgdib

Rules

You must support both even-length and odd-length strings.
0-index-wise, you must reverse the chars at odd indices, not even.
1-index-wise, of course, you must reverse the chars at even indices, not odd.
Input will consist of printable ASCII (code points 32-126), no newlines.
You can take input either as a string or as a list of chars (NOT 1-char strings). E.g. String/char[] or char* are allowed, but String[]/char[][] or char** aren't.

Test cases
Input
Output

Hello, World!
HdlroW ,olle!

Hello World!
H!llooW rlde

ABCDEFGHIJKLMNOPQRSTUVWXYZ
AZCXEVGTIRKPMNOLQJSHUFWDYB

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
 }"{$y&w(u*s,q.o0m2k4i6g8e:c<a>_@]B[DYFWHUJSLQNOPMRKTIVGXEZC\A^?`=b;d9f7h5j3l1n/p-r+t)v'x%z#|!~

P
P

AB
AB

xyz
xyz

For the empty string, return the empty string itself.

Related.

I remember this being a type of "secret code" (kind of like Pig Latin) that we learned as kids in 80's or 90's, something to do with the word "fence" or something, but my memory's a bit fuzzy. My friends and I would use this to encode secret messages, and I don't think the adults that found our letters ever did figure them out...

@phyrfox you may be thinking of the rail fence cipher, which is similar to this.

Ah I remember doing that.

Jelly, 7 bytes
s2ZU2¦Z

This is a full program.
Try it online!
How it works
s2ZU2¦Z  Main link. Argument: s (string)

s2       Split s into pairs.
  Z      Zip/tranpose, grouping characters by the parity of their indices.
     ¦   Sparse application:
   U         Upend; reverse both strings in the pair.
    2        Replace the second string with the reversed string.
      Z  Zip/transpose, interleaving the two strings.

That's exactly my solution byte-by-byte...

Alike minds think great. ;)

MATL, 8 bytes
t2L)P5M(

Try it online! Or verify all test cases.
Explanation
t     % Implicit input. Duplicate
      % STACK: 'abcdefghi', 'abcdefghi'
2L    % Push [2, 2, 1j]. This represents 2:2:end when used as an index
      % STACK: 'abcdefghi', 'abcdefghi', [2, 2, 1j]
)     % Get entries at those indices
      % STACK: 'abcdefghi', 'bdfh'
P     % Flip
      % STACK: 'abcdefghi', 'hfdb'
5M    % Push [2, 2, 1j] again
      % STACK: 'abcdefghi', 'hfdb', [2, 2, 1j]
(     % Write entries at those indices. Implicit display
      % STACK: 'ahcfedgbi'

So 2L is "Push [2,2,1j]", and 5M is "Push [2,2,1j] again"... And some people say that golfing languages are not readable!

@Leo :-D 2L produces a predefined literal. 5M is an automatic clipboard that stores inputs to recent function calls. It could actually be replaced by 2L for the same byte count

Alice, 10 bytes
/ZY
\IOR@/

Try it online!
Half of the bytes of this program are spent on correctly formatting the source, the actual commands are just IYRZO, because Alice has just the right builtins for this task.
Explanation
As I said, the mirrors (/\), the newline and @ are there just to make the ip move in the right direction and terminate the program at the end. The actual code, linearised, is the following:
IYRZO
I      Input a line
 Y     Unzip it into its even positions and its odd ones
  R    Reverse the odd positions
   Z   Zip it back again
    O  Output

Quite straightforward, I'd say.

If only I could grasp how mirrors work in corners...

@LuisMendo first you pass through the mirror, which makes you change from cardinal (horizontal/vertical) to ordinal (diagonal) mode or viceversa. Then if you are in cardinal mode you wrap to the other side of the line/column, while if you are in ordinal mode you bounce back against the corner. In this case the south-east mirror is encountered in ordinal mode, makes you switch to cardinal and wrap to the beginning of the second line, where another mirror makes you go back to ordinal and start moving towards north-east

Ah, so the bouncing is only in diagonal, in the same direction you came from. Then it's simpler than I thought. Thanks!

Java (OpenJDK 8), 108 96 94 93 bytes
Saved 1 byte by using @Neil's neat trick of using s[s.length+~i|1]
String f(char[]s){int a=s.length,b=0;String c="";for(;b<a;b++)c+=s[b%2<1?b:a+~b|1];return c;}

Try it online!

Java under 100 bytes...seems legit.

"Java (OpenJDK 8)" Then why are you using a Java 7 method without recursion? Use a Java 8 lambda by replacing String f(char[]s) with s->.. And you can save a byte as well by putting the int initialization inside the for-loop: for(int a=s.length,b=0;b<a;b++). Try it online.

Python 2, 52 50 bytes
-2 bytes (and a bug fix) thanks to pxeger
s=bytearray(input())
s[1::2]=s[1::2][::-1]
print s

Try it online! or Try all test cases

50 Try it online!

You don't seem to have actually updated the code in the post!

@pxeger happens ¯\(ツ)/¯

Octave, 32 bytes
@(a,b=a(x)=a(flip(x=2:2:end)))a;

Try it online!

JavaScript (ES6), 48 bytes

f=
s=>s.replace(/./g,(c,i)=>i%2?s[s.length+~i|1]:c)
<input oninput=o.textContent=f(this.value)><pre id=o>

Jelly, 9 bytes
Ḋm2U
m2żÇ

Try it online!
Ḋm2U Helper Link -> Dequeue (return last len-1 elements), take every second element, reverse
m2żÇ Main Link -> Take every second element, then interleave with the result of the helper link

-1 byte thanks to Dennis

If you replace ¢ with Ç, you don't need the ³ in the helper link.

@Dennis Oh what I thought I did that the first time >_> Nevermind, I must have screwed up something. Thanks!

Retina, 17 13 bytes
O^$`(?<=\G.).

Try it online!
Fixed an error thanks to Neil.
Saved 4 bytes thanks to Kobi.
Selects each letter preceded by an odd number of characters and reverses them. Does this by using \G which matches the end of the last match.

Last testcase is wrong. You'll need to use $ instead of #.

@Neil Whoops, you're totally right. Fixed!

You can use \G instead on the lookbehind, and you can remove the $: `O^`(?<=\G.).` (12 bytes)

@Kobi Thanks for the tips! But unfortunately it only seemed like I could remove the $ since all of the inputs were in sorted lexicographical order. I've added a new test case that your code would fail on.

@FryAmTheEggman - Got it, good point. Guess it was just luck.

PHP>=7.1, 58 Bytes
for(;$i<$l=strlen($a=$argn);$i++)echo$a[$i&1?-$i-$l%2:$i];

Online Version

perfect. OS says I have to type more, but those 7 chars say it all.

Japt, 14 13 bytes
12 bytes of code, +1 for the -P flag.
Saved 1 byte thanks to @Shaggy
¬ë íU¬Åë w)c

Explanation:
¬ë íU¬Åë w)c
¬                   Split the input into an array of chars
 ë                  Get every other char, starting at index 0
   í                Pair with:
    U¬                Input, split into a char array
      Å               .slice(1)
       ë              Get every other char
         w            Reverse
           c       Flatten
-P                 Join into a string

Try it online!

Hmm, ë2,1 is rather ugly. I think you can do ó o instead, perhaps...

@ETHproductions Yeah, I think Åë works too.

Oh, nice one :-)

APL (Dyalog), 9 bytes
Requires ⎕IO←0 (default on many systems) for proper definition of odd and even.
⌽@{2|⍳≢⍵}

Try it online!
⌽ reverse
@ at the elements filtered by the mask result from applying the
{ anonyomous function
 2| the mod-2 of
 ⍳ the indices of
 ≢ the tally (length) of
 ⍵ the argument
} on the argument

Was v16 even out when this question was posted?

@Zacharý It was in beta, but it doesn't even matter anymore.

Oh, so I suppose your gonna use v17 now?

Vyxal, s, 3 bytes
yṘY

Try it Online!
Turns out by making my answer valid I saved a byte. Oh the irony
Explained
yṘY
y      # un-interleave
 Ṙ     # reverse
  Y    # re-interleave

You don't need the flag.

05AB1E, 7 bytes
ι and .ι have been added since this challenge was posted, both of them save bytes here.
Sι`R.ιJ

Try it online!
If we were allowed to take a list of string of length 1, ι`R.ι would work for 5 bytes.
S         # split the string into a list of characters
 ι        # uninterleave: push [even indices, odd indices]
  `       # push both values seperately to the stack
   R      # reverse the odd indices
    .ι    # interleave the two lists
      J   # join into a string

Röda, 34 bytes
f a{a/=""a[::2]<>reverse(a[1::2])}

Try it online!
Explanation
a/=""                    Convert the argument a into an array of length-1 strings
      <>                 Interleave
a[::2]                   Every even element of a with
        reverse(a[1::2]) Every odd element of a reversed

Here is an alternative solution at the same bytecount
36 34 bytes
{[_/""]|_[::2]<>reverse(_1[1::2])}

This is an anonymous function that takes input as a string from the input stream.

Python 2, 67 bytes
lambda s,j=''.join:j(map(j,zip(s[::2]+' ',s[1::2][::-1]+' ')))[:-1]

Try it online!

Mathematica, 82 bytes
""<>(f=Flatten)[{#&@@#,Reverse@Last@#}&@f[Characters@#~Partition~UpTo@2,{2}],{2}]&

OCaml, 70 bytes
let f s=String.(mapi(fun i c->s.[(length s land-2-i-i)*(i mod 2)+i])s)

Try it online!

Haskell, 63 bytes
(_:r)!(a:s)=a:s!r
_!_=[]
f s=([' '|even$length s]++reverse s)!s

Try it online! Usage: f "some string".
For odd strings like abcdefghi, the function f passes the string and its reversal to the function !, which alternates taking chars from both strings. For even strings this does not work, and we need to append a dummy character first to get the offset right.

C, 69 bytes
c,l;f(char*s){l=strlen(s);for(c=0;c<l;++c)putchar(s[c&1?l-l%2-c:c]);}

Pretty simple. Walks the string, printing either the current character or the opposite one.
Ungolfed and explained:
f(char *str) {
    int len = strlen(str);      // Get the total length
    for(int c = 0; c<len; ++c)  // Loop over the string
        putchar(s[              // Print the char that is,
            c & 1               // if c is odd,
                ? l - l % 2 - c // c chars from the end (adjusting odd lengths),
                : c             // and at index c otherwise
        ]);
}

05AB1E, 21 bytes
DgÉi¶«}2ô.BøRćR‚˜øJ¶K

Try it online!
I'm guessing the reason this wasn't done in 05AB1E yet is because it's gross...
Yet another time the zip function's auto-drop-last-element hurts instead of helps.
P.S. If you have improvement suggestions on my answer, post your own; it's likely enough of an improvement to warrant you getting the points. I am pretty ashamed of this answer.

Japt, 8 6 bytes
ó oÔrí

Try it
ó oÔrí     :Implicit input of string
ó          :Uninterleave
  o        :Modify last element
   Ô       :  Reverse
    r      :Reduce by
     í     :  Interleaving

K (oK), 18 bytes
Solution:
{x[w:&2!!#x]:x@|w}

Try it online!
Examples:
> {x[w:&2!!#x]:x@|w}"Hello, World!"
"HdlroW ,olle!"
> {x[w:&2!!#x]:x@|w}"Hello World!"
"H!llooW rlde"

Explanation:
Interpretted mostly right-to-left, find the odd-indices characters, reverse them and put them back into the string
{x[w:&2!!#x]:x@|w} / solution
{                } / lambda function with implicit parameter x
         #x        / count x,    #"Hello, World!" -> 13
        !          / til,        !13 -> 0 1 2 3 4 5 6 7 8 9 10 11 12
      2!           / 2 modulo,   2!0 1 2 3 4 5 6 7 8 9 10 11 12 -> 0 1 0 1 0 1 0 1 0 1 0 1 0
     &             / where true, @0 1 0 1 0 1 0 1 0 1 0 1 0 -> 1 3 5 7 9 11
   w:              / store in variable w
               |w  / reverse w,  |1 3 5 7 9 11 -> 11 9 7 5 3 1
             x@    / index into x at these indices
 x[        ]:      / assign right to x at these indices

J, 26 bytes
[:,@,./(0 1$~#)]`(|.@])/.]

ungolfed
[: ,@,./ (0 1 $~ #) ]`(|.@])/. ]

explanation

(0 1$~#)]`(|.@])/.] Use Key /. to split the input into the even/odd groups: (0 1$~#) creates the group definition, by repeating 0 and 1 cyclically to the length of the input.  We use the gerundial form of Key for its main verb ]`(|.@]), which applies the identity to the first group and reverses the second group: (|.@]).
Now that we have the two groups, the odd one reversed, we just zip them together and flatten: ,@,./

Try it online!

21 bytes with (\:2|#\)({~/:)#\<.#\. and 19 bytes with [:,@,./]]|./.~2|#`

thanks miles.  is there a typo in the second one?  I'm getting an error

@miles also the first one: i understand how it parses and technically what's happening, but i'm not seeing the overall strategy.  can you clarify?

oh yes, it's supposed to be [:,@,./]]`|./.~2|#\, the ticks got parsed out

17 bytes with 0,@|:]]`|./.~2|#\

love that use of transpose.  i sort of feel at this point that specifying rank is a J code smell.  there always seems to be a way to avoid it....

Thunno 2, 3 bytes
^rI

Try it online!
Explanation
     # Implicit input

^    # Uninterleave into two parts and push them separately to the stack
     #   "Hello, World!"  ->  "Hlo ol!", "el,Wrd"
     #   "ABCDEF"         ->  "ACE", "BDF"
     #   "P"              ->  "P", ""

 r   # Reverse the top of stack (second part from before)
     #   "Hello, World!"  ->  "Hlo ol!", "drW,le"
     #   "ABCDEF"         ->  "ACE", "FDB"
     #   "P"              ->  "P", ""

  I  # Interleave the two strings together
     #   "Hello, World!"  ->  "HdlroW ,olle!"
     #   "ABCDEF"         ->  "AFCDBE"
     #   "P"              ->  "P"

     # Implicit output

Python 3, 93 87 bytes
lambda s:"".join("".join(t)for t in zip(s[::2],reversed(s[1::2])))+("",s[-1])[len(s)%2]

Replace reversed(s[1::2]) with s[1::2][::-1] to save 4 bytes

It comes down to 83 bytes and golfable, in the end: f=lambda s,j="".join:j(j(t)for t in zip(s[::2],s[1::2][::-1]))+("",s[-1])[len(s)%2]

Perl 6,  63 58  55 bytes
{[~] .comb[{flat roundrobin (0,2...^*>=$_),[R,] 1,3...^*>=$_}]}

Test it
{[~] flat roundrobin .comb[{0,2...*},{$_-1-$_%2,*-2...*}]}

Test it
{[~] flat roundrobin .comb[{0,2...*},{[R,] 1,3...^$_}]}

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

  [~]                 # reduce using string concatenation operator

    flat              # make the following a flat list

    roundrobin        # grab one from each of the following 2 lists,
                      # repeat until both are empty

    .comb\            # split the input into graphemes (implicit method call)

    [                 # index into that sequence

      { 0, 2 ... * }, # code block producing every non-negative even number

      {               # code block producing reversed odd numbers
                      # (｢$_｣ here contains the number of available elements)

        [R,]          # reduce with reversed comma operator
                      # (shorter than ｢reverse｣)

        1, 3 ...^ $_  # odd numbers stopping before it gets
                      # to the number of input elements
      }

    ]
}

I had to use roundrobin rather than zip, because zip stops as soon as one of the input lists is exhausted.

Mathematica, 62 bytes
takes as input a string
(s=Characters@#;Row@Riffle[s[[;; ;;2]],Reverse@s[[2;; ;;2]]])&

Try it online!

GNU APL 1.2, 24 bytes
R[X]←⌽R[X←2×⍳⌊.5×⍴R←⍞]◊R

APL works from right to left. ⍴R←⍞ assigns user input to R and then evaluates its length. Halve this by multiplying by .5 and apply ⌊ floor function. ⍳ returns all numbers from 1 to the argument.
APL operates on arrays, so 2× the array we just got from ⍳ doubles each element, giving us just the even indices (1-indexed, so relies on ⎕IO being 1).
When accessing multiple indices of a vector, APL gives the elements at those indices in a vector. R[X←2×⍳⌊.5×⍴R←⍞] gives just the even-indexed elements. ⌽ reverses the elements. Then, assign the reversed values back to the even indices (assigning these indices to X saves 6 bytes).
◊ is the statement separator. After the reversing is done, evaluate R to print the result.

q/kdb+, 70 56 47 38 35 29 27 bytes
Solution:
{x[w]:x(|)w:(&)#:[x]#0 1;x}

Example:
q){x[w]:x(|)w:(&)#:[x]#0 1;x}"Hello, World!"
"HdlroW ,olle!"
q){x[w]:x(|)w:(&)#:[x]#0 1;x}"Hello World!"
"H!llooW rlde"

Explanation:
Find the odd indices of the string, reverse this list, pull out elements at these points and then reassign them in-place to the original string.
{x[w]:x reverse w:where count[x]#0 1;x} / ungolfed
{                                   ; } / lambda function with two lines
                                 0 1    / the list (0;1)
                                #       / take
                        count[x]        / length of input
                  where                 / indices where this is > 0
                w:                      / save in variable w
        reverse                         / reverse this list
      x                                 / index into x at these points
     :                                  / assignment
 x[w]                                   / assign x at indices with new values
                                     x  / return x

Edits:

-9 bytes; switching out count for (#:), til for (!), where for (&:) and reverse for (|:).
-3 bytes; switching out (#:) for (#), (&:) for (&) and (|:) for (|)
-6 bytes; complete re-write
-2 bytes; using assignment rather than apply

APL (Dyalog), 24 bytes
Bytes golfed thanks to @Adám
A⊣A[i]←⌽A[i←2×⍳⌊2÷⍨⍴A←⎕]

Try it online!

Are you going to explain your code?

Perl 5, 46 + 3 for -F flag = 49 bytes
while(++$x<@F){print$F[$x%2?$x-1:@F-$x-$#F%2]}

Uses the -F flag to auto split the input into an array of characters, @F. Loops through the array and outputs that element for an even index or that index (plus one for an odd length string) from the end for an odd input.
Takes input with a trailing newline. Without the trailing newline, can just change the pre-increment on $x to a post-increment.
A little more readable:
while(++$x<@F) { #While the index is less than the number of elements in the array. $x is 1-indexing the array despite the fact that perl is 0-indexed because it keeps us from having to use a proper for loop or a do-while loop
    if($x%2) { #If $x is odd
        print $F[$x-1] #Print the element
    } else {
        print $F[@F-$x-$#F%2] #Print from the end. $#F%2 fixes it for odd length strings
    }
}

05AB1E, 12 bytes
RDgÈúøvyNÉè?

Try it online!
RDgÈúøvyNÉè?   Implicit input: "abcdefghij"
R              Reverse the string: "jihgfedcba"
 DgÈú          Put (length is even?1:0) spaces in front of it " jihgfedcba"
     ø         Zip (reinjects the input implicitly): ["a ", "bj", "ci", ...]
      vy       For each element of the list
        NÉè    Extract&push element[iteration is odd?1:0]
           ?   Print without newline

Jq 1.5, 84 bytes
[_nwise(2)|[_nwise(1)]]|transpose|map(map(values))|.[1]|=reverse|[transpose[][]]|add

Expanded
   [_nwise(2)|[_nwise(1)]] # make list of two character lists
 | transpose               # convert to list of two lists of characters
 | map(map(values))        # discard null
 | .[1] |= reverse         # reverse second list
 | [transpose[][]]         # transpose back to two lists and flatten
 | add                     # convert back to string

Try it online!

Perl, 27 bytes
Includes +5 for -F lp
perl -F -lpe 's/.\K./$F[@F%-2-pos]/g' <<< "abcdefghi"

If you give STDIN without newline you can drop the l option


text:
Generate chord charts for ukulele
Your task is to write a function which outputs a ukulele chord chart in the following format for a given chord symbol. For instance, for input "G7", it must output:
 G C E A
---------
| | |#| |
---------
| |#| |#|
---------
| | | | |
---------
| | | | |
---------
| | | | |
---------

It must support all chords of these forms:  X Xm X7 Xm7 Xmaj7 Xsus4 Xdim Xdim7
where X is any of A A# B C C# D D# E F F# G G#

(Supporting flats, such as Bb and Eb, is not required.)
The rest of the challenge description (until "Output and scoring") is purely explanatory: if you know ukulele chords already, you don't need it.
There are three steps parts to producing the chart for a chord.

First, work out which notes are in the chord.
Choose the correct fret for each string to match the notes.
Draw the chart.

Work out which notes are in the chord
There are 12 notes in the cyclical music scale, each a semitone apart: A, A#, B, C, C#, D, D#, E, F, F#, G, G#, then A, A#....
(If you're not into music, just mentally translate every "A" into a 0, every "A#" into a 1, etc, and everything will work out just fine.)
A chord is a set of 3 or 4 notes, according to a defined pattern of intervals starting from the base note:

X: 0 + 4 + 3 ("major"). Example: C, C+E+G
Xm: 0 + 3 + 4 ("minor"). Example: Cm, C+D#+G
X7: 0 + 4 + 3 + 3 ("seven"). Example: C7, C+E+G+A#
Xm7: 0 + 3 + 4 + 3 ("minor seven"). Example: Cm7, C+D#+G+A#
Xmaj7: 0 + 4 + 3 + 4 ("major seven") . Example: Cmaj7, C+E+G+B
Xsus4: 0 + 5 + 2 ("sus four"): Example: Csus4, C+F+G
Xdim: 0 + 3 + 3 ("diminished"). Example: Cdim, C+D#+F#
Xdim7: 0 + 3 + 3 + 3 ("diminished seven"). Example: C+D#+F#+A#. [You may find it helpful to know that this is the same chord as A#dim7, D#dim7 and F#dim7].

(The name in parentheses is just for your music education, it's not relevant to the challenge.)
For instance: "Am" is a chord, where "A" is the base note, and "m" is the chord type. Looking up the table ("Xm: 0 + 3 + 4"), we see it has 3 notes:

the base note (A),
the note 3 semitones above (C, counting A# and B), and
the note 4 semitones above that (E).

(Chords that have 3 notes will by necessity be repeating one of the notes across the 4 strings. That's fine.)
Choose the correct frets for the notes
Ukulele is an instrument with four strings, that play the notes G, C, E and A. Pressing the string against a fret makes it sound higher, one semitone per fret. (Pressing fret 1 on the A string turns it to A#, fret 2 turns it to B, etc).
Chord charts
The chord chart represents the first few frets, played by the left hand, read from top to bottom ("higher" frets are lower down the page). The strings are the columns separated by | symbols. The frets are the rows separated by - symbols. The symbol # means that the string is pressed against that fret ("is fretted"), while the right hand strums.
So in the chord chart at the start:

The G string is not fretted (it is "open"), so it sounds like G.
The C string is fretted on fret 2 (two semitones up), so it sounds like D.
The E string is on fret 1 (one semitone up), and sounds like F.
The A string is on fret 2, so sounds like B.

So this chord has notes: G, D, F, B. (It's G7, G+B+D+F - the order of the pitches doesn't matter.)
Calculating chords
To calculate which fret to play for a given string, for a given chord:

if the string's base note (G, E, A or C) is not already in the chord, play the lowest fret that belongs to the chord
repeat for each of the four strings.

Example #1
For instance, let's play E7 (consisting of E + G# + B + D).

The G string is not in the chord. Raise it to G# (fret 1).
The C string is not in the chord. Raise it to D (fret 2).
The E string is in the chord. Don't fret it. (Leave the string open.)
The A string is not in the chord. Raise it to B (fret 2).

So we are playing: G#, D, E, B.
So we output:
 G C E A
---------
|#| | | |
---------
| |#| |#|
---------
| | | | |
---------
| | | | |
---------
| | | | |
---------

Example #2
Another example: G# (consisting of G# + B# + D#):

The G string is not in the chord, raise it to G# (fret 1).
The C string is in the chord (B#), don't fret it.
The E string is not in the chord, raise it to G# (fret 4).
The A string is not in the chord, raise it to B#(C) (fret 3)

So we are playing G#, C, G#, C
 G C E A
---------
|#| | | |
---------
| | | | |
---------
| | | |#|
---------
| | |#| |
---------
| | | | |
---------

(You may notice that sometimes not every note in the chord ends up getting played. Don't worry about it. "Proper" ukulele chords are slightly more complicated than this basic algorithm.)
Output and scoring
Your output must closely match the above. (You can use other characters instead of |, - and #, such as em-dashes or ASCII line-drawing characters, if they are visually superior. An unfilled circle character would be better than #). Trailing linespace on each line is ok. Whitespace before the first line or after the last line is not ok. Final linefeed is optional.
Normal forms of input and output. You will receive one chord name, guaranteed to be in the table above, in the correct case.
Standard loopholes disallowed. Online services are disallowed. If your language has music functions in its standard library, you may use them (but not if they're plugins, packages, etc.)
This is code-golf. Lowest score (in bytes) wins.
Extra credit
This simple algorithm sometimes produces useless chord fingerings that don't include all the important notes of the chord. (For instance, for Dm, it produces ACFA, the same as Fm.)
For extra credit, modify the algorithm so that:

For all chords, the root and third (first two notes, usually 0 and 3 or 0 and 4) are played on at least one string each.
For 4-note chords (X7, Xm7, Xmaj7, Xdim7), the root, third and seventh (first, second and fourth notes) are played on at least one string each.

G# is G# B# D# (B# is the same as C, which is why this chord is more often written as Ab). That said, I assume in this challenge, we only have to support sharps in the input and not flats?

Thanks, sorry I really messed that example up - kept redoing it. Flats aren't required - clarified there.

Javascript 280 282 287 bytes
(Non-meaningful linebreaks inserted for readability)

f=

a=>' G C E A'+[1,2,3,4,5].map(y=>
(l=`
---------
`)+[-2,3,7,0].map(
x=>(z=a.match(/(.#?)(.*)/),
[...'9'+{'':14,7:147,m:40,m7:740,maj7:148,sus4:24,dim:30,dim7:360}[z[2]]]
.map(i=>(i-x+'D EF G A BC'.search(z[1][0])+!!z[1][1]+8)%12)
.sort((a,b)=>a-b)[0]-y?'| ':'|#'
)).join``+'|').join``+l

document.getElementById("mysubmit").onclick=function() {
  document.getElementById("out").innerHTML=f(document.getElementById("myinput").value)
}
<input type="text" value="G7" id="myinput">
<input type="submit" id="mysubmit">

Commentary
I've never been so happy at Javascript's weird type conversions. This is probably the first time I've ever wanted 40 + 9 to equal 409 :) It's also really fortunate that integers are acceptable as keys in Objects.
There's nothing too clever going on here. I subtract 3 from each chord note in order to keep the range within 0-9, so that I can temporarily express a chord as a 3-digit number. Luckily, the order of notes isn't important, so we can express 036 as 360.

FYI, if anyone wants to use this program, I've put it in a JSFiddle for easy access: https://jsfiddle.net/o5z28vbr/embedded/result/

Sadly it's not that useful for actual chord charts, because of the simplification of the algorithm. Maybe I'll add an extra credit section.

I dunno, it seems pretty accurate when I've tested it

Try C, Dm7, G#, F7, B7. They're all missing a pretty important note or two.

Huh, that's the way I usually play them

(err, that should be "Cm", not "C".)

I think [...'9'+[14,740,30,148,24,360,40,147][~~parseInt(z[2],30)%47&7]] saves 14 bytes.

Wow, never seen that trick with parseint before. How did you come up with %47&7? Just trial and error? Can you always find a combination that yields a sequence of different numbers like that?

Also, what does the ~~ do? It doesn't seem necessary? @Arnauld

Yes, it's just trial and error. Provided that the original list contains distinct strings matching [0-9a-z] and provided that these strings do not have a too long prefix in common, then yes: there exists at least one base b <= 36 such that parseInt(x,b) produces a list of distinct integers, and such a list can usually be reduced significantly by applying successive modulo operations.

You're correct about this ~~. I think my original approach was parseInt(s,30)%47%8 which produces NaN if s is an empty string. The ~~ was there to force it to 0 instead. But &7 is now taking care of that.

Python 2, 518, 448 bytes
Thanks to Wheat Wizard for the coding suggestions!
S='GCEA'
N=['A','A#','B','C','C#','D','D#','E','F','F#','G','G#']
C={'':(0,4,7),'m':(0,3,7),'7':(0,4,7,10),'m7':(0,3,7,10),'maj7':(0,4,7,11),'sus4':(0,5,7),'dim':(0,3,6),'dim7':(0,3,6,9)}
x=raw_input()
j=1+('#'in x)
c=[]
for s in S:c.append(min((N.index(i)-N.index(s))%12for i in [N[(a+N.index(x[:j]))%12]for a in C[x[j:]]]))
print' '+''.join(a+' 'for a in S)
for f in range(5):f=['|o'if i==f+1else'| 'for i in c];print'-'*9,'\n',''.join(f)+'|'

Try it online!
Sample Output
G
 G C E A
---------
| | | | |
---------
| |o| |o|
---------
| | |o| |
---------
| | | | |
---------
| | | | |

Commentary
Thanks for a fun challenge. My daughter and I are off to buy a uke this weekend. I've never played the uke, but I play mandolin, and the theory is similar.
For this submission (my first), I addressed the original challenge without the extra credit components.  I fear addressing the extra credit questions will add a lot of of bytes to the code.  I hope to submit again with the extra credit bits, time permitting.
The logic is pretty simple if you trace your way back through the successive functions:
   1. Parse the chord description.
   2. Identify what notes are in that chord.
   3. Figure out what frets on each string would fit
   4. Assemble a chord by selecting the lowest fret that works on each string
   5. Print out the chart fret by fret.
The core of the golfed code lies in the gnarly mess of nested list comprehensions in the eighth -- now seventh -- line of the code.  The best way I can explain what's going on is by presenting the ungolfed version.
(Wheat Wizard suggested a shift from list comprehensions to generators that was not reflected in this ungolfed code)
STRINGS = 'GCEA' # Ukelele
#STRINGS = 'GDAE' # Mandolin
NOTES=['A','A#','B','C','C#','D','D#','E','F','F#','G','G#']
TYPES = {'':(0,4,7),
     'm':(0,3,7),
     '7':(0,4,7,10),
     'm7':(0,3,7,10 ),
     'maj7':(0,4,7,11),
     'sus4':(0,5,7),
     'dim':(0,3,6),
     'dim7':(0,3,6,9)}

def parse(x):
    # parses the chord into the root and the chord type
    i=2 if '#' in x else 1
    return x[:i],x[i:]

def strng(string,notes):
    # Return a list of possible fret locations based on notes in a chord
    # This will return all possible fret locations, including those
    # beyond the fifth fret, where this code stops drawing.
    return sorted([(NOTES.index(i)-NOTES.index(string))%12 for i in notes])

def chordnotes(note,typ):
    #return the list of Notes that belong to the chord
    return  [NOTES[(a+NOTES.index(note))%12] for a in TYPES[typ]]

def chord((note,typ)):
    # Returns a list of four fret locations, in order of the strings.
    # This is the heart of the musical logic of the code. Here I use a naive
    # approach, and simply grab the lowest note on each string that fits the
    # chord.  This function needs to be rewritten to address the extra
    # credit parts of the challenge.
    # The extra parentheses in the function declaration allow us to pass in
    # the results of the parse function directly.
    x = []
    for s in STRINGS:
        x.append(min(strng(s,chordnotes(note,typ))))
    return x

def printchart(x):
    # Do the heavy lifting of formatting the output
    # I calculate the layout of each fret, and print them in turn.
    ch = chord(parse(x))
    print  ' '+''.join([a+ ' ' for a in STRINGS])
    fret = '-'*9
    for f in range(5):
        note = ['|o' if i==f+1 else '| ' for i in ch]
        print fret + '\n' + ''.join(note)+'|'

def main():
    x = raw_input('Chord?')
    printchart(x)

if __name__ == '__main__':
    main()

Hello and welcome to our site! This post looks good except for one thing, you should not prompt Chord? before input, its not in the specifications and thus is extra output.  This is good because not prompting saves more bytes anyway.  You also have a lot of whitespace you can trim off that is not required by python.

Here is a link with most of the extra whitespace trimmed away: Try it online!

Our site rules also allow you to use input() instead of raw_input() even though its not really good python practice.  If you have any more questions about the site, or golfing python I'd be happy to answer them so just ping me in a comment or in chat!

I don't want to bother you anymore so one last thing, but you use a bunch of list comprehensions in this code, which is a good idea.  However you can save bytes by using generators instead in some situations.  Built in functions like .join can use generators instead of lists meaning that you can get rid of the [...] inside the function.  My next comment will include a link showing how this might be implemented in your case.

Try it online!

Many thanks!  Just found the site a few days ago, and have been enjoying it a lot.  Lots to learn.  It's clear I need to be more aggressive about the golfing.  It goes against my training to obfuscate the code so!  I'll adopt your changes into the post and then go ponder how you did it.


text:
Vacancy or no vacancy?
We've all seen the signs on motels telling us if there's a vacancy or not:

Typically, these will permanently have the letters of VACANCY lit up, and have the letters of NO lit up if there isn't any room in the motel.
The challenge
The average motel in the U.S. has 200 rooms.
You will write a program/function that takes an integer T (for taken rooms) as its only input.
Your program will then display the words NO VACANCY. The letters of VACANCY will be printed in red.
If T ≥ 200, the letters of NO will also be printed in red.
For example, assuming a.out is your program and "input" = command line argument:

(I typo'd and my system ignores case.)
The rules

Your program/function must display (or, if lambda, return) the exact string NO VACANCY, including case.
Your program/function may only set the text foreground color to red and not the background.
If you wish, you may use ANSI escape codes to print the red color - \x1b[31m will work.
Your program/function may not change the text color of your shell after it finishes.
Your program/function must terminate normally.
Your program/function must print only to standard output.
Your program/function must use your shell/terminal/IDE's default background color. (If you choose to have graphical output you may choose whatever color you like, except red.)
If T ≤ 200, the letters of NO must be printed in your shell/terminal/IDE's default foreground color. (If you choose to have graphical output, once again you may choose whatever color you like)
If for some reason your shell/terminal/IDE's default foreground/background color is red, you must print with a black background and a default white foreground.
If you choose to use graphical output, red may only be used when specified in the program (e.g. your background color or default text color may not be red).

The winner
As usual with code-golf, the shortest program wins! Brownie points for graphical output.
I'll accept the shortest answer in a week. Happy golfing!
Leaderboard

var QUESTION_ID=123146,OVERRIDE_USER=61563;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

There is a conflicting rule: in and above the screenshot, it says to print NO in red "If T ≥ 200". Later, you say to print in the default color "If T ≤ 200"

@Arc676 Oops. Well, logically, if the hotel has 200 rooms then it must be the first description that is correct.

For extra credit, do it for the Hilbert Hotel, which has an infinite number of rooms.

Are these outputs valid: http://i.imgur.com/221Qxgj.png ?

@sergiol Yes, that's fine.

Jelly, 29 26 bytes
<200o-“NO“ɓ31m”m“=ȤŻ»Œu“ɓm

This uses <CSI> (0x9b), which is shorter than <ESC>[ (0x1b 0x5b).
It resets the foreground color with <CSI>m instead of <CSI>0m, as the 0 is implicit.
Verification
Note that your terminal emulator (e.g., Konsole) must be set to ISO 8859-1 or similar.

How it works
<200o-“NO“ɓ31m”m“=ȤŻ»Œu“ɓm  Main link. Argument: n (integer)

<200                        Compare with 200, yielding 1 if true, 0 if not.
    o-                      Logical OR -1; map 0 to -1 (and 1 to 1).
      “NO“ɓ31m”             Yield ["NO", "\x9b31m"].
               m            Take the list "modulo" 1 or -1, keeping it as is for 1,
                            reversing it for -1.
                “=ȤŻ»       Implicitly print the previous result and yield the
                            string " vacancy". This is achieved by indexing into
                            Jelly's in-built dictionary.
                     Œu     Convert to uppercase.
                       “ɓm  Implicitly print the previous result and yield the
                            string "\x9bm", which is printed on exit.

Javascript (ES6), 60 bytes
(Open your browser's console while running the snippet to see the colored result.)

f=
n=>console.log((n>199?'%cNO':'NO%c')+' VACANCY','color:red')
<input oninput=f(this.value)>

NO%c VACANCY color:red?

@MDXF check your actual browser console. the snippet console emulator doesn't support it.

Oh, good catch. +1

Standard JS rules allow you to shorten this greatly. Remove console.log() as the rules specify that returns are fine, you do not have to define the function as well.

@MayorMonty this solution specifically takes advantage of console.log functionality to create the colored text, so I would feel weird not including it.

I just learned that you can have colored output on the browser console. Thanks!

Ruby (*nix style terminal), 54 48 45 44 43 bytes
1 byte saved thanks to Value Ink
␛ stands in for a literal esc byte (ASCII 27)
->x{"#{x>199?"␛[31m":p}NO␛[31m VACANCY␛[m"}

A port of my python answer, that is a byte several bytes shorter.  I'm new to ruby golf but eager to learn so feedback is appreciated.

->x{"#{x>199?"␛[31m":p}NO␛[31m VACANCY␛[m"} saves a byte. The trick is the fact that in string interpolation, "#{nil}" will evaluate to an empty string, and p can be used as a substitute for nil.

Python 3 (*nix style terminal), 55 54 bytes
lambda x:"\033[31m"*(x-199)+"NO\033[31m VACANCY\033[m"

This uses ANSI escape codes.  \033[31m Makes the terminal red,  if x is less than 200 we will start with one making NO red, otherwise we will have one after NO making it red anyway.  When we are done \033[m clears the color from the terminal.

The multiplication of the color string instead of a condition is brilliant!

HTML, 72 71 bytes

<input min=200 type=number><x>NO <y>VACANCY