text:
Space Navigation
Oh no! There are a bunch of meteoroids on my way through the universe ... what am I and my space ship, the SP4C3, supposed to do?
I need to manoeuver my shuttle through these rocks or I am done for!
Your Task
Write a program that guides my shuttle through a map of asteroids, using as few bytes as possible since I don't have much time left to type them into my navigation device.
And because this is code-golf, dammit.
You will receive map data as input, represented by either a 2-dimensional array of characters, or an aray of strings.  on the map will represent empty space, which is free to travel on, while #, or any other printable ASCII character, represents rocks. Somewhere on the map there will be a character representing the ship and its current direction, either <, v, > or ^.
Your output will have to be a string of instructions that my ship has to take. This ship only knows 4 instructions: <, v, >, ^, which represent moving left, down, right and up, but the ship is not allowed to navigate out of map bounds.
The top-left coordinate of your map is (0|0), so going down the Y-axis increases your y coordinate, while going right on the X-axis increments your x coordinate.
Note that we, for the sake of simplicity, reduce space to a 2-dimensional ... well, space, here.
There is one last problem: Since my ship is already moving pretty fast, there is no way we can turn around (i.e. doing a 180° turn), so if the direction that the ship has to take is > (right) there is no way we can navigate < (left).
Success
Your code is successful, if it is able to produce navigation data to get the ship to the other side of the map, based on the direction it is facing (i.e. the last x coordinate if the ship is facing > (right)), without crashing into terrain.
Input
You can receive input in any reasonable format, as long it is able to contain the map data, including the ship coordinates.
You may assume that the input is always layed out in a way that the ship is able to pass through the entire map without turning around.
Output
You may directly output to stdout or return a string from a method, as you prefer. Note that your output may only contain directional characters (<, v, >, ^).
Rules

Standard loopholes are forbidden.
This is code-golf, so the shortest code in bytes, in any language, wins.
Only coding languages that were not created solely for this challenge may be used.

Example Cases
Input:
####      #####     ##
##          ##    ##
                 ####
>        ##     ####
       ######
      #######   ###
#     #####   ########

Solved Input:
####      #####     ##
##          ##    ##
        >>>>>>>v ####
>>>>>>>>^##    v####
        #####  >>>>>>>>
       ######   ###
#      #####  ########

Output: >>>>>>>>^>>>>>>>vv>>>>>>>>

Input:
##      ###      #
#      ####     ###
>     ###      ###
###    #  ###     ###
#####    ####    ####
######       ##
####      #######  ##

Solved Input:
##      ###      #
#      ####     ###
>>>>>v###>>>>>v###
###  v #>^### v   ###
#####>>>^#### >>v####
######       ## >>>>>
####      #######  ##

Output: >>>>>vv>>>^>^>>>>>vv>>v>>>>>

Input:
##    v        #######
#   ##  ##### ##########
    #     ###    ######
  #  ###     ###     #
 ##   #  ##   ##
####   #           ####

Solved Input:
##    v        #######
#   ##v ##### ##########
    # >>v ###    ######
  #  ###v    ###     #
 ##   # v##   ##
####   #v          ####

Output: vv>>vvvv

Thanks to Kevin Cruijssen for this testcase!
Input:
##       #
>   ###  #
#####    #
###   ###
 # # # # #
 #

Solved Input:
## ^>>>> #
>>>>###v #
#####<<v #
### <v###
 # #v# # #
 #  v>>>>>

Output: >>>>^>>>>vv<<v<vv>>>>>

Note: There may be some cases where multiple solutions are possible. A solution will be correct as long as the ship reaches its destination without crashing.
Good luck!

"You may assume that the input is always layed out in a way that the ship is able to pass through the entire map without turning around." Does this mean that it's guaranteed that < will never need to be used?

@marinus That depends on how the map is layed out. The ship doesn't always start on the left and doesn't always go to the right. (I'll add a test case.)

Could you add a test case where you'll have to get back a bit, so you'll use three navigation type instead of two like all your current test cases. Pastebin: This one perhaps.

@KevinCruijssen Added, thanks!

bfs ! !!! !!! !

@KevinCruijssen Huh, I don't even remember seeing that duplicate when it was originally posted. Something must have gone wrong with Stack Exchange's notifications...

@Neil Neither did I find it when I researched for duplicates, yet even after sandboxing it still is apparently. sigh

@Neil "Something must have gone wrong with Stack Exchange's notifications..." The duplicate flag was marked 29 minutes ago..

@KevinCruijssen Not the flag, the question which this duplicates.

@Neil Ah ok. Well, it has has been posted February 8th, and most people have noticed it. I even added a bounty for it at the start of July. :S


text:
Find the tangent of the sum of inverse tangents
Background
It can be shown that for any integer k >= 0, f(k) = tan(atan(0) + atan(1) + atan(2) + ... + atan(k)) is a rational number.
Goal
Write a complete program or function which when given k >= 0, outputs f(k) as a single reduced fraction (the numerator and denominator are coprime).
Test cases
The first few values are
f(0) = (0,1)
f(1) = (1,1)
f(2) = (-3,1)
f(3) = (0,1)
f(4) = (4,1)
f(5) = (-9,19)
f(6) = (105,73)

Rules

Standard loopholes are forbidden.
Input and output may be in any
convenient format. You may output f(k) as a string numerator/denominator, as a tuple of two integers, a fraction or rational object, etc. If you output a string, give two integers only, that is, output 3/2 instead of 1 1/2.
This is code-golf, the shortest answer (in bytes)
wins.

Can you further specify in your test cases what the input/output values are?

Can we output as a rational number instead?

Also it would be helpful to specify precisely which input corresponds to each output.

Are the integers in the range in degrees or radians?

OEIS: A180657

The atan(0) term is unnecessary.

@Adám If the atan(0) wasn't there, then f(0) wouldn't be defined; but for f(n); n > 0, yes, it doesn't change the answer.

@pizzapants184 f(0) = tan∑∅ = tan 0 = 0

@EriktheOutgolfer Neither. They are in unit circle units.

@EriktheOutgolfer: If you use tan and atan on same angle units, that is a non-problem.

M, 11 bytes
×C÷@+
R0;ç/

Try it online!
Uses the OEIS formula x(n) = (x(n-1)+n)/(1-n*x(n-1)) with x(0) = 0.

Python 2, 76 72 bytes
from fractions import*
f=lambda k:Fraction(k and(k+f(k-1))/(1-k*f(k-1)))

Use the identity:
tan(A + B) = (tan(A) + tan(B)) / (1 - tan(A) * tan(B))

We have:
f(k) = 0                                    if k = 0
     = (k + f(k - 1)) / (1 - k * f(k - 1))  if k > 0

Try it online!
Thanks to Luis Mendo, save 4 bytes.

Hope you do not mind: I added a TiO link.

@LuisMendo LGTM, Edited.

Mathematica, 28 bytes
Fold[+##/(1-##)&,0,Range@#]&

Try it online!
A longer, but more interesting approach (32 bytes):
Im@#/Re@#&@Product[1+n I,{n,#}]&

Try it online!

+1 o'_'o Mathematica and its built-ins o'_'o

@Mr.Xcoder Not really in this case. OP is using series summation cleverly (if I read the code right).

APL (Dyalog), 14 bytes
Requires ⎕FR←1287 (128 bit Floating-point Representation) for small input. Takes k as right argument.
1(∧÷,)3○¯3+.○⍳

Try it online!
⍳ integers one through k (zero is not needed as 0 = arctan 0)
¯3+.○ sum of arcus tangents
3○ tangent
1(…) apply the following tacit function with 1 as left argument and the above as right argument:
 ∧ the lowest common multiple (of 1 and the right argument); gives the numerator
 ÷ divided by
 , the concatenation (of 1 and the right argument); gives the numerator and the denominator

Haskell, 52 bytes
This uses the OEIS series expansion:
import Data.Ratio
f 0=0%1
f n|p<-f$n-1=(p+n)/(1-n*p)

Try it online!
Or a pointfree version:
(scanl1(\f n->(f+n)/(1-n*f))[0%1..]!!)

JavaScript (ES6), 80 bytes
f=n=>n?([a,b]=f(n-1),g=(a,b)=>a?g(b%a,a):b,c=g(d=b*n+a,e=b-n*a),[d/c,e/c]):[0,1]

Returns a [numerator, denominator] pair. Explanation: Let f(n-1) = a/b then f(n) = atan(tan(n)+tan(a/b)) = (n+a/b)/(1-n*a/b) = (b*n+a)/(b-n*a). It then remains to reduce the fraction to its lowest terms.
Online ES6 Environment

Octave, 30 bytes
format rat
tan(sum(atan(0:k)))

Try it online!

Casio-Basic, 35 bytes
tExpand(tan(sum(seq(tan⁻¹(n),n,0,k

tan-1 should be entered as the one on the Trig keyboard; or the -1 can be entered separately from the abc>Math keyboard. According to the fx-CP400's manual, it's a single two-byte character (764).
Function, 34 bytes for the code, +1 byte to add k as an argument.
Explanation
seq(tan-1(n),n,0,k) generates all the values for tan-1(n) from 0 to k.
sum adds them all together, then tan does the tangent function on them.
tExpand will then turn them into a single fraction.

@Adám This is Casio, not TI, so it's not done the same way.

According to Wikipedia, ⁻ and ¹ are two bytes each; E5CC and E5C1.

@Adám oh nice, I didn't realise that article existed! However, this is an fx-CP400, not the 9860G; I just checked the manual, and the superscript -1 is actually a single character, code 764; so it's a single two byte character.

Pari/GP, 36 bytes
n->imag(x=prod(i=0,n,1+i*I))/real(x)

Try it online!
Or the same length:
n->fold((x,y)->(x+y)/(1-x*y),[0..n])

Try it online!

05AB1E, 33 26 bytes
0X)Iƒ©`N*+®`sN*-‚D¿D_i\¤}/

Try it online!
Explanation
0X)                          # initialize stack with [0,1]
   Iƒ                        # for N in range [0 ... input] do:
     ©                       # store a copy of the current pair in the register
      `                      # push the pair separately to the stack
       N*                    # multiply the denominator with N
         +                   # add the numerator
          ®`s                # push the denominator then the numerator to the stack
             N*              # multiply the numerator by N
               -             # subtract it from the denominator
                D¿D          # get 2 copies of the greatest common divisor
                   0Qi  }    # if the gcd equals 0
                      \¤     # replace it with the denominator
                         /   # divide the pair with this number

Forth (gforth), 130 bytes
: g dup if tuck mod recurse then ;
: f 0 1 rot for 2dup i * + -rot swap i * - next
2dup g + abs over 0< 2* 1+ * >r i / swap r> / ;

Try it online!
Uses my own implementation of gcd, and the OEIS formula. Takes k from the stack and returns two integers denom num on the stack. It took a lot of effort (and bytes) to normalize the fraction.
: g ( x y -- gcd 0 )
  dup if tuck mod recurse then
;

: f ( k -- denom num )
  0 1               \ push initial fraction with num=0, denom=1
  rot for           \ ( num denom ) loop from k to 0 inclusive
    2dup i * + -rot \ ( denom*k+num num denom )
    swap i * -      \ ( denom*k+num denom-num*k )
  next
  2dup g + abs      \ ( num denom gcd ) evaluate positive gcd and remove 0
  over 0< 2* 1+ *   \ ( num denom gcd' ) negate gcd if denom < 0
  >r i / swap r> /  \ ( denom/gcd' num/gcd' )
;

Julia 0.6.0 40 bytes
k->rationalize(tan(sum(x->atan(x),1:k)))
It's a straightforward implementation of the question. The precision of rationalize can sometimes be weird but works fine 99% of the time.

source: Stack Exchange

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

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

sort: votes


text:
Will I make it out in time?
Inspired by this.
Background
The evil farmer has decided to burn your wheat field down in order to drive up the prices. To ensure total destruction, he has also soaked your field in gasoline. Even more unfortunately, you happened to be walking on the field when it was lit on fire, and you must get out quickly to survive.
Challenge
Given a field containing wheat, fire and your location, determine if you can make it out of the field in time.
A field consists of wheat (here represented by .) and fire (F). Here your location is marked with a O. For example:
...F...F
F.......
........
.F......
....O...
...F....
........
.F....F.

Every second you move to any adjacent cell (but not diagonally), and every fire spreads to every adjacent cell. If you can't move to a cell that will not be on fire, you die. If you make it out of the field, you survive. Let's see what happens in this example:
...F...F
F.......
........
.F......
....O...
...F....
........
.F....F.

..FFF.FF
FF.F...F
FF......
FFF.....
.F.F.O..
..FFF...
.F.F..F.
FFF..FFF

FFFFFFFF
FFFFF.FF
FFFF...F
FFFF....
FF.FF.O.
.FFFFFF.
FFFFFFFF
FFFFFFFF

FFFFFFFF
FFFFFFFF
FFFFF.FF
FFFFF.FF
FFFFFFFO
FFFFFFFF
FFFFFFFF
FFFFFFFF

FFFFFFFF
FFFFFFFF
FFFFFFFF
FFFFFFFF
FFFFFFFFO <-- you made it out and survived, barely
FFFFFFFF
FFFFFFFF
FFFFFFFF

Rules

Your input is the field as a grid. You may choose any input format, including a string with line separators or a 2D array.

You may not take as input the locations for fire and/or yourself.
You may use any 3 distinct values as wheat, fire and your position, including non-strings for array input.
Fields are always at least 1x1 in size, rectangular and contain no invalid characters.
Any field will contain exactly one of the value representing your location, and every other position may or may not be fire.

Your output is one of two distinct values for "you survive" or "you die", as usual in decision-problem.
Standard code-golf rules apply.

Test cases
Survived
O

....
.O..
....

FFFFF
.....
..O..
.....

FFFF
FFFO
FFFF

.F....
......
......
.F....
..O...
.FF...
.F....
..FF..

...F...F
F.......
........
.F......
....O...
...F....
........
.F....F.

Didn't survive
FFF
FOF
FFF

F.F
.O.
F.F

....F
.....
..O..
.....
F....

.F....F.
........
........
F..O....
........
.....F..

...F...F
F......F
........
.F......
....O...
...F....
........
.F....F.

F..F
.O..
FF..

This is kinda like the 'Meteor Showers' USACO problem

I don't see why someone downvoted

@OliverNi Probably because of the inspired by comment, instead of reading it they saw that thought it was a chameleon and down voted.

To both downvoters, please explain why my challenge is bad.

Why is there this restriction: "You may not take as input the locations for fire and/or yourself."? It just adds task to find O and Fs in input

@DeadPossum Because I feel like it would simplify the challenge too much and make it a bit too broad. Feel free to disagree, though; if others agree with you I might change the restriction.

I agree with Pietu1998, I also feel that the restriction is highly appropriate.

@Mr.Xcoder Any field will contain exactly one of your location

In all the truthy test cases you can escape following a straight line. Actually the general problem is more complicated if you have to consider non-straight paths. Since that seems to be the case, you should add a test case where you can escape but not following a straight path (or clarify that only straight paths need be considered)

@LuisMendo If it is possible to escape when the farmer turns, it's always possible for him/her to escape in a straight line. For instance, let's say the farmer is trying to escape to the right of the field. When the farmer moves one space down, some fire will spread downwards; then, the farmer's situation is the same as the initial position (plus more fire).

I, speaking as the evil farmer, would never soak the field in gasoline first.  I would tie you up, place you in the exact center of the field, and then start fires at the corners.  Then I would watch as the fire slowly moves toward you so I can enjoy your terror longer.  Much more evil that way.

Additionally, the above plan makes it impossible for you to get out alive, as you will be tied up.

@LuisMendo When writing the challenge I did notice that considering straight paths is sufficient. I thought about mentioning it, but I decided to let the answerers figure it out.

Snails, 15 bytes
\Oo!{.,fee7.,\F

Try it online!
1 means survival while 0 means death.
Since it is impossible to outrun the fire, it is never useful to try to go around it. The best route is always a straight line. So there are only four possible choices of escape route. To determine if a direction is safe, we check for any F in the "fire cone" pointing in that direction.

O_o Can you provide a testing link? This seems very short.

@Mr.Xcoder OK. It's a language specialized for [tag:grid] [tag:decision-problem]s after all.

The code is almost saying: "Oy!"... "phew"...

Because snails are the perfect choice for, you know, outrunning a fire...

@feersum In the "try it online" link, I tried the following 3-line wheat field, which should be death, but the program thinks you can survive it:  "F..F", ".O..", "FF.."

https://tio.run/##K85LzMwp/v8/xr9SsVpPJy21XE8nxu3/fzc9PTcuPX89PS43IBMA

@Xantix Good catch, my triangular search path had a hole in it. Fixed at the cost of 1 byte.

Python 2, 283 218 209 208 bytes
lambda F:f(F)&f(F[::-1])
def f(F):l=F.split();w=len(l[0])+1;i=F.index('O');x,y=i/w,i%w;r=range(len(l));return all('F'in''.join(n)for n in[[l[i][x+abs(i-y):]for i in r],[l[i][max(0,y+x-i):i+x-y+1]for i in r]])

Try it online!
Takes input as a newlines separated string, and returns True/False for Dead/Alive
Works by checking each direction(udlr) for Fire in by looking outward:
Example:
Input:
FFFFF
.....
..O..
.....

Fire checks:
Up:       Down:     Left:     Right:

FFFFF               F             F
 ...                ..           ..
  O         O       ..O         O..
           ...      ..           ..

If all directions contain fire you die, otherwise there is an escape.
Edit: Back to taking a string as input, and now only checks for up/right, but also checks the input backwards (giving down/left)
Saved a lot of bytes thanks to Mr. Xcoder and Felipe Nardi Batista

@FelipeNardiBatista thanks :)

Let us continue this discussion in chat.

JavaScript, 174 bytes
a=>+(t=>g=a=>t--?g(a.map((l,y)=>l.map((c,x)=>(h=v=>[(a[y-1]||[])[x],(a[y+1]||[])[x],a[y][x+1],a[y][x-1],c].includes(v),!c&&h()?p=1:[2,0,1].find(h))))):p)((p=a+'!').length)(a)

Input format:

Array of Array of Integers
2 for F, 1 for ., 0 for O

Output:

Truthy value (1) for survive
Falsy value (NaN) for die

Try It:

f=a=>+(t=>g=a=>t--?g(a.map((l,y)=>l.map((c,x)=>(h=v=>[(a[y-1]||[])[x],(a[y+1]||[])[x],a[y][x+1],a[y][x-1],c].includes(v),!c&&h()?p=1:[2,0,1].find(h))))):p)((p=a+'!').length)(a)
t=s=>f(s.trim().split('\n').map(x=>x.split('').map(n=>({F:2,'.':1,O:0}[n]))))

console.log(t(`
FFFFF
.....
..O..
.....
`))

console.log(t(`
FFFF
FFFO
FFFF
`))

console.log(t(`
.F....
......
......
.F....
..O...
.FF...
.F....
..FF..
`))

console.log(t(`
...F...F
F.......
........
.F......
....O...
...F....
........
.F....F.
`))

console.log(t(`
FFF
FOF
FFF
`))

console.log(t(`
F.F
.O.
F.F
`))

console.log(t(`
....F
.....
..O..
.....
F....
`))

console.log(t(`
.F....F.
........
........
F..O....
........
.....F..
`))

console.log(t(`
...F...F
F......F
........
.F......
....O...
...F....
........
.F....F.
`))

Consider a cellular automaton. There are 3 states for a cell O (reachable by people), F (catch fired), . (nothing just happened). The rule for create next generation is:
for each cell:
  me and my 4 neighborhoods,
    if anyone is `F` then result is `F`,
    otherwise, if anyone is `O` then result is `O`
    otherwise, keep state `.`

Once there is an cell on edge has O state, the people survive. If this not happened in enough amount generation, then the people died.
// check for all neighbors:
h=v=>[(a[y-1]||[])[x],(a[y+1]||[])[x],a[y][x+1],a[y][x-1],c].includes(v)
// if me == 'O' and i'm edge (neighbors contain _undefined_), then survive
!c&&h()?p=1
// Otherwise apply the given rule
:[2,0,1].find(h)

Octave, 71 bytes
@(a)(A=blkdiag(0,a,0))<3||any((bwdist(A>2,'ci')>bwdist(A==2,'ci'))(!A))

Try it online!
or
Verify all test cases!
Input format:

2D array of integers
1 for ., 2 for O and 3 for F

Output:

true and false

Explanation:
Explanation:
A=blkdiag(0,a,0)    % add a boundary of 0s around the array
A<3                 % return truthy when there is no fire
bwdist(A>2,'ci')    % city block distance transform of binary map of fire
bwdist(A==2,'ci')   % city block distance transform of binary map of your location
any(...)(!A)        % check if there is at least one element on the boundary of
                    % the fire distance map has its distance greater than
                    % that of distance map of your location

Retina, 243 bytes
^.*O(.|¶)*|(.|¶)*O.*$|(.|¶)*(¶O|O¶)(.|¶)*
O
m`^((.)*) (.*¶(?<-2>.)*(?(2)(?!))O)
$1#$3
m`^((.)*O.*¶(?<-2>.)*(?(2)(?!)))
$1#
T`p`\O`#| ?O ?
+m`^((.)*)[O ](.*¶(?<-2>.)*(?(2)(?!))F)
$1#$3
+m`^((.)*F.*¶(?<-2>.)*(?(2)(?!)))[O ]
$1#
}T`p`F`#|.?F.?
O

Try it online! Requires the background to be spaces rather than .s (or some other regexp-safe character could be used). Explanation:
^.*O(.|¶)*|(.|¶)*O.*$|(.|¶)*(¶O|O¶)(.|¶)*
O

If there is an O on any edge, delete everything else (survival case)
m`^((.)*) (.*¶(?<-2>.)*(?(2)(?!))O)
$1#$3

Place a # in any space above an existing O.
m`^((.)*O.*¶(?<-2>.)*(?(2)(?!)))
$1#

And a # in any space below an existing O.
T`p`\O`#| ?O ?

Change the #s to Os, and also any space to the left or right of an existing O.
+m`^((.)*)[O ](.*¶(?<-2>.)*(?(2)(?!))F)
$1#$3

Place #s above any existing Fs. These can overwrite Os as well as spaces.
+m`^((.)*F.*¶(?<-2>.)*(?(2)(?!)))[O ]
$1#

Place #s below any existing Fs, also overwriting Os as well as spaces.
}T`p`F`#|.?F.?

Change the #s to Fs, and also any O or space to the left or right of an existing F. Repeat until the Fs have consumed everything.
O

Return 1 for survival, 0 if not.

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


text:
Can I burn the farmers too?
Inspired by this and this which was inspired by the first question.
I've set my farmers' fields on fire, but unfortunately they saw me do it! If I don't deal with this situation they could report me and then I'd get arrested! So, that shouldn't be too hard. All I have to do is kill them with fire!
The field will be an m*n grid with odd m and n where both are one greater than a multiple of 4. The farmer starts out in the middle of the field. Each "tick", the farmer can move to an adjacent square (edge or corner) and any space on fire will ignite every grid adjacent to it in a 3x3 space (edge or corner again).
Note: fires and farmers can move diagonally.
The grid will be given as some 2D array of 3 unique values: Fire, .Wheat, and Human (Farmer). For example:
F...F
F...F
FFHFF
F...F
F...F

the farmer is doomed to DIE! >:-D
It would be easy if I could just light a fire right beside the farmer and set him on fire. However, he knows I am in the field with him and he has a gun. If he sees me, I'm dead. So, I can't light the fire within half of the distance between him and the edge, of him. Essentially, if you floordiv the width of the grid by 4, I must be within that many spaces from the edge, and same with the height.
I am immune to fire so I don't have to worry about getting myself out.
The question is:
Given a field with wheat, a farmer in the center, and potentially existing fires around the field, how many fires do I need to light to guarantee I can kill the farmer?
Test Cases
These test cases have input represented by a F . H grid and output as a single integer. You may take input in any other reasonable format and output a single integer.
FFFFF
F...F
F.H.F => 0, the farmer is doomed to die in 2 ticks anyway
F...F
FFFFF

FFFFF
F....
F....
F....
F.H.. -> 1 (just light a fire on the far right side of him)
F....
F....
F....
FFFFF

.....
.....
..H.. -> 4 (to ensure his demise, you would need to light 4 points around the perimeter (with rotational symmetry). Any 4 will do.
.....
.....

Rules

Standard Loopholes apply
You can take an array of 2 values if you would like, where you infer the farmer's position from the size (since the farmer will always be in the center)

tl;dr, +1 for title

Python 3, 672 bytes
e=enumerate;H='H';F='F'
def f(m):
	q=m[0];h=len(m);w=len(q);o=0;g=lambda m,c:{(k,l)for i,r in e(m)for j,v in e(r)for k in range(i-1,i+2)for l in range(j-1,j+2)if v==c and k>=0and k<h and l>=0and l<w};n=lambda m,c,d:[[c if(k,l)in g(m,c)-g(m,d)else m[k][l]for(l,v)in e(r)]for(k,r)in e(m)];s=lambda m:H in[q]+[m[h-1]]+[r[0]for r in m]+[r[w-1]for r in m];l=lambda m:all(H not in r for r in m)
	while 1:
		a=m
		while not(s(a)or l(a)):a=n(n(a,H,F),F,1)
		if l(a):return o
		else:o+=1;z(m,a,h,w)
def z(m,a,h,w):
	for i in(0,h-1):
		for j,v in e(a[i]):
			if v==H:m[i][j+(h-1)//2]=F;return
	for j in(0,w-1):
		for i,v in e(r[j] for r in a):
			if v==H:m[i+(w-1)//2][j]='F';return

Try it online!
It's very long (I've done my best to golf it), and the solution is not optimal. Here is the general idea:

First, let's see if the farmer burns in the original situation. The matrix a is filled with Fs when the fire grows and with Hs if the farmer can reach a position (a=n(n(a,H,F),F,1)).
If the farmer escapes (s(a)), look a the border of a. There must be at least a H. It takes (h-1)/2 ticks to reach the top or the bottom, and (w-1)/2 ticks to reach the left or right border. As soon as we find a H on the top, we put a fire at (h-1)/2 cases on its left. In (h-1)/2 ticks, an F will be there and it may also "burn" other Hs. The same applies for the left and right borders.

The solution is not optimal because:

there are some edge cases, in particular when a fire will burn two borders of the field.
considering top and bottom borders before right and left borders is not necessarily the best solution
going from left to right and top to bottom to find a H is not necessarily the best solution.


text:
Levenshtein Your Source

The Levenshtein edit distance between two strings is the minimum possible number of insertions, deletions, or substitutions to convert one word into another word. In this case, each insertion, deletion and substitution has a cost of 1.
For example, the distance between roll and rolling is 3, because deletions cost 1, and we need to delete 3 characters. The distance between toll and tall is 1, because substitutions cost 1.
Stolen from original Levenshtein question

Your task is to calculate the Levenshtein edit difference between an input string and your source. This is tagged quine, so cheating quines (for example, reading your source code) are not allowed.
Rules

The input will be non-empty and will be composed of ASCII, unless your source contains non-ASCII, in which case the input may include Unicode. Regardless, the Levenshtein distance will be measured in characters, not bytes.

The output is the minimum Levenshtein edit distance of the input and your source.

This is code-golf, so shortest answer, in bytes, wins.

Sandbox

I was going to suggest making the score the output of your program when run through itself, but then I realized...

Closely related.

Retina is so close to winning this with an empty program...

Python 2 + sequtils, 101 bytes
from sequtils import*;_='from sequtils import*;_=%r;print edit(_%%_,input())';print edit(_%_,input())

Python 2, 278 258 bytes
t=input();s,f='t=input();s,f=%r,lambda m,n:m or n if m*n<1else-~min(f(m-1,n),f(m,n-1),f(m-1,n-1)-((s%%s)[m-1]==t[n-1]));print f(len(s%%s),len(t))',lambda m,n:m or n if m*n<1else-~min(f(m-1,n),f(m,n-1),f(m-1,n-1)-((s%s)[m-1]==t[n-1]));print f(len(s%s),len(t))

Try it online!
This is just the usual quine in Python, mixed with the Levenshtein algorithm from this answer. Note that it gets quite extremely (thanks to Mr. Xcoder :P) slow.

Does this work for l(s%s,input()) (not sure)?

Vyxal D, 10 bytes
`:qp꘍`:qp꘍

Try it Online!
Thanks to Aaron Miller for this one.
`:qp `:qp  # Standard quine
    ꘍    ꘍ # Levenshtein distance

Vyxal D, 13 bytes
`q\`:Ė\`+꘍`:Ė

Try it Online!
`q\`:Ė\`+ `:Ė # Standard eval quine (see https://codegolf.stackexchange.com/a/232956/100664)
         ꘍    # Leveshtein distance with input

10 bytes in Vyxal 2.6, whiich hasn't been released yet

10 bytes using the other Vyxal quine

Haskell, 210 bytes
main=interact$show.((x++show x)%);x@(a:c)%y@(b:d)|a==b=c%d|1>0=1+minimum[x%d,c%y,c%d];x%y=length$x++y;x="main=interact$show.((x++show x)%);x@(a:c)%y@(b:d)|a==b=c%d|1>0=1+minimum[x%d,c%y,c%d];x%y=length$x++y;x="

Try it online!
Computes the levenshtein distance modified from here.  (I wrote the code there too)  This is combined with a standard quine mechanism.  Not much special here.
If you want to play around with it I suggest making edits towards the end of the string.  The algorithm is more or less \$O(n+m^4)\$ where \$n\$ is the location of the difference between the input and the source, and \$m\$ is the length of the string after the first difference.  So if you add a character to the front of this the compute time is exponential with the length of input and you won't see your result on tio.

Python 3.8 (pre-release), 135 bytes
exec(s:="l=lambda a,b:min(l(A:=a[1:],B:=b[1:])-(a[0]==b[0]),l(A,b),l(a,B))+1if b>''<a else len(a+b);print(l('exec(s:=%r)'%s,input()))")

Try it online!
took my solution of levenstein distance (https://codegolf.stackexchange.com/a/233868/103772) and adapted it to a quine. It is very (very) slow but it works

JavaScript, 113 bytes
This is a valid quine.
f=t=>[...t].map((v,j)=>x=x.map((w,k)=>q=k--?Math.min(q,w,x[k]-(v==u[k]))+1:j+1),x=[...[,...u=`f=${f}`].keys()])|q

f=t=>[...t].map((v,j)=>x=x.map((w,k)=>q=k--?Math.min(q,w,x[k]-(v==u[k]))+1:j+1),x=[...[,...u=`f=${f}`].keys()])|q

console.log(f('f=t=>[...t].map((v,j)=>x=x.map((w,k)=>q=k--?Math.min(q,w,x[k]-(v==u[k]))+1:j+1),x=[...[,...u=`f=${f}`].keys()])|q'));
console.log(f('%'));
console.log(f('12345'));

Idea stolen from other answer.

"This is a valid quine" - actually, I'm not sure there's any clear consensus in that meta thread you linked. And in fact, by a few votes, the "this is cheating" option is actually winning.


text:
Two interwoven chains
In this question I defined a "chain" function as a function that:

is a permutation, meaning that every value maps to and is mapped to by exactly one value.
and allows any value can be obtained from any other value by repeated applications of the function or its inverse.

There are a lot of functions that do this and some of them are pretty simple (see the answers on that question).  Now we are going to define a separate class of functions I am going to call "interwoven" functions.  An interwoven function is a function on a set A, that has two infinite partitions a0 and a1 such that the function is a chain function on both a0 and a1.
This means that no value in a0 can map to a value in a1 under the function or vice versa.
Task
Your task is to write a code that performs or defines an interwoven function on the positive integers.  Your function can be anything as long as it satisfies the criteria for being interwoven.  You should include a explanation as to why your function is interwoven in the answer.
This is a code-golf question so answers will be scored in bytes, with less bytes being better.

I think this could be considered a dupe of the last challenge you linked, as you just have to make an additional transfromation, i.e. enumerating all the even and all the odd numbers seperately. I don't think any of the answers you're getting here will provide anything substantially new.

@flawr You could do that, but it wouldn't be the best way.  I've done a little experimentation with this and there are some novel ways to perform these types of functions.

Python, 46 42 37 bytes
5 bytes saved thanks to @notjagan
lambda x:1<x<4and x*2%5or x-(x&2)*4+4

Try it online!
Iterates the even and odd numbers with steps of 4 and links on 2 and 3:
=> 22 => 18 => 14 => 10 => 6 => 2 => 4 => 8 => 12 => 16 => 20 => 24 =>
=> 23 => 19 => 15 => 11 => 7 => 3 => 1 => 5 => 9 => 13 => 17 => 21 =>

x86 32-bit machine code, 11 bytes
48 34 02 40 40 34 02 48 7E FA C3

Try it online!
Uses the regparm(1) calling convention – argument in EAX, result in EAX.
In assembly:
f:
    dec eax
    xor al, 2
    inc eax
repeat:
    inc eax
    xor al, 2
    dec eax
    jle repeat  # Jump back if pre-decrement value was ≤1
    ret

JavaScript, 30 24 bytes
a=>(a+=a&2?-4:4)<0?a*a:a

Sequences:

... 19 15 11 7 3 1 5 9 13 17 21 ...
... 18 14 10 6 2 4 8 12 16 20 24 ...

Code snippet

f=a=>(a+=a&2?-4:4)<0?a*a:a
console.log('23 19 15 11 7 3 1 5 9 13 17'.split` `.map(a=>f(a|0)).join` `);
console.log('22 18 14 10 6 2 4 8 12 16 20'.split` `.map(a=>f(a|0)).join` `);

Dyalog APL, 24 22 bytes
{x*1+0>x←4+⍵-8×2|⌊⍵÷2}

Try it online!
Same chains as my python answer.


text:
Bucket Brigade!
Inspired by this, this and this.
So, now that the evil farmer has set your field on fire, you naturally want to put it out.  You have a bunch of friends who all have buckets, and you want a program to figure out where to place everyone to save as much of your wheat as possible.
Your Task:
Write a program or function that takes as arguments the field, and the number of friends with buckets you have, and outputs the field with the optimal placement of friends with buckets.  The field will be represented by either a string, an array of strings, an array of arrays of characters, or any other method you deem appropriate.  The field consists of numbers representing how intense the fire is.  A 0 indicates that an area is not on fire.  1-4 represents the fire growing in intensity.  When the fire reaches stage 4, it spreads fires to all directly (not diagonally) adjacent areas that are not adjacent (directly or diagonally) to a bucket brigadier.  After stage 4, the fire dies, and becomes an "A", representing ashes.  In your output, friends with buckets are represented by a B.  They may be placed anywhere that does not contain flames.  When a friend is placed, any flames adjacent to them go out.
Input:
An integer representing the number of friends with buckets available, and an array or string representing the field.
Output:
The field, with friends placed to optimise the amount of wheat saved.  If you use a different set of characters than mentioned above, please include that information in your answer.
Test Cases:
1, 1001         10B0
   000000000 -> 000000000
      000000       000000

2, 1000000000010000101       100000000001B000101   Note that the friend on the second line could be placed in many other locations.
   00000000000000         -> 0000B000000000
                00000000                  00000000
                00000000                  00000000

Scoring:
This is code-golf, shortest solution in bytes wins!


text:
Implement the Cubically Cube
Cubically is a fairly new esoteric language capable of creating short, golf-like answers for a very specific subset of problems. It is unique in that it stores memory in the form of a 3x3 Rubik's cube, making calculations far less trivial than in most languages. In Cubically, the programmer must rotate the internal cube in order to manipulate the values stored on the faces, then use those values in their calculations. Calculations are performed on a single 32-bit integer stored on an imaginary face known as the "notepad". Additionally, Cubically can request user input and store it in an input buffer consisting of only a single integer value.
The Cube
The faces of the cube are Up, Down, Left, Right, Front, and Back:
   UUU
   UUU
   UUU
LLLFFFRRRBBB
LLLFFFRRRBBB
LLLFFFRRRBBB
   DDD
   DDD
   DDD

When the program starts, the cube is initialized such that each square on that face is equal to that face's 0-based index:
   000
   000
   000
111222333444
111222333444
111222333444
   555
   555
   555

Whenever a face is rotated, it is always rotated clockwise:
Cubically> F1

   000
   000
   111
115222033444
115222033444
115222033444
   333
   555
   555

The value of a face is defined as being the sum of every square on that face. For example, in the above cube, the value of face 0 is 3.
Syntax
Commands are executed by first loading a command into memory, then passing arguments to it to execute the command. For example, the command F1 will load the command F into memory, then call it with the argument 1. Additionally, F13 will load the command F into memory, then call it with the argument 1, then call it with the argument 3. Any non-digit character is treated as a command, and any digit is treated as an argument.
Your task
Your task is to implement Cubically's internal memory cube in a language of your choice. Your code should be able to execute a very small subset of the language.
Commands

R - Rotate the right face of the cube clockwise the specified number of times.
L - Rotate the left face of the cube clockwise the specified number of times.
U - Rotate the top face of the cube clockwise the specified number of times.
D - Rotate the bottom face of the cube clockwise the specified number of times.
F - Rotate the front face of the cube clockwise the specified number of times.
B - Rotate the back face of the cube clockwise the specified number of times.
% - Outputs the value on the given face. The value of a face is defined as the sum of all squares on that face.

Rules

You may use any language created before or after the date this challenge was posted to write a program or function capable of solving this challenge.
Input will be passed in either through STDIN, as a string, or as a character array (you choose, please specify).
Output must be passed either to STDOUT or as the output of the function, and it must be either an integer, a string containing only digits, or an array of digits. If your language requires you to output a trailing newline, you may do so.
The input will always be in the following format: ([UDLRFB]\d*)*%[0-5]. There will be no whitespace characters in the input.
The input for % will always use a 0-based index.

This is code-golf, so shortest answer in bytes wins.
Test Cases
%0 -> 0
%1 -> 9
%2 -> 18
%3 -> 27
%4 -> 36
%5 -> 45
R1%2 -> 27
RD3F2%5 -> 32
L1R23F1B5U9D2%3 -> 17

For more test cases, check out the TIO interpreter. If TIO isn't working, you may use the Lua interpreter instead.

Is this question a duplicate of this?

Related.

@TehPers I think it's very similar. For future challenges, I recommend leaving them in the sandbox for at least 24 hours, longer if you still have questions about it. (I had to learn this the hard way; my first challenges were not well-received at all. This isn't closed or downvoted yet so it's not bad, but had it been left in the sandbox for longer, other users might've noticed flaws that I didn't.)

@MDXF I'll keep that in mind for next time. Thanks!

Did you miss out a multiple of 4 between R and D in the example RD3F2%5 -> 30?

@JonathanAllan R is loaded into memory, but D overwrites it before it's called, meaning the R does nothing. Does this make sense now?

Oh OK, yes that makes sense, it's just the description did not say (I see now that the regex has a * too anyway!). Thanks.

@MDXF Oh, I'll fix that real quick. Thanks!

Python 2, 476 bytes
import re
c=[[i]*9for i in range(6)]
r=lambda f:[f[a+b]for a in(0,1,2)for b in(6,3,0)]
U=lambda c:[r(c[0])]+[c[j+1][:3]+c[j or 4][3:]for j in(1,2,3,0)]+[c[5]]
y=lambda c:[r(c[0])]+c[2:5]+[c[1],r(r(r(c[5])))]
z=lambda c:[c[2],r(r(r(c[1]))),c[5],r(c[3]),c[0][::-1],c[4][::-1]]
s=input()
exec("c="+"(c);c=".join("".join("zzzUz U zzUzz yyyzUzzzy zUzzz yzUzzzyyy".split()[ord(t)%11%7]*sum(map(int,n))for t,n in re.findall("([BUDLFR])(\d*)",s[:-2])))+"(c)")
print sum(c[int(s[-1])])

Try it online!
A port from my Simulate A Rubik's Cube answer. The revisit prompted me to golf that by 47 bytes.

Cubically, 1 byte
¶

Non-competing 'cause it's lame. Don't accept this.
¶  Read a line from stdin and evaluate

I added that this afternoon :P

Well, I think you have the shortest code.

@TehPers I do, but like I said, it's lame. Cubically can win other [tag:rubiks-cube] challenges with this builtin, it doesn't need to win this one.


text:
Parallelogram a Number
Now that we know how to properly square and triangle a number, we are going to learn how to parallelogram one.  To parallelogram a number, we first arrange it as a parallelogram by stacking it on top of itself a number of times equal to the number of digits it has, and adding spaces to make it a parallelogram.  So 123 would form:
   123
  123
 123

Now we take each horizontal and vertical number and add them, 123+123+123+1+12+123+23+3, which equals 531, which is the parallelogram of 123.
Your Task:
Write a program or function that, when given a number as input, returns the parallelogram of the number.
Input:
A non-negative integer, or a non-negative integer represented by a string.
Output:
The parallelogram of the integer.
Test Cases:
1234567 -> 10288049
123     -> 531
101     -> 417
12      -> 39

Scoring:
This is code-golf, lowest score in bytes wins!

Sandbox Post

Why the downvote?

MATL, 12 bytes
tnEXyPY+c!Us

Input is a string. Try it online!
Explanation
Consider input '123' as an example.
The code duplicates the input (t) and builds an identity matrix (Xy) of size twice the input length (nE):
1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1

then flips it upside down (P):
0 0 0 0 0 1
0 0 0 0 1 0
0 0 0 1 0 0
0 0 1 0 0 0
0 1 0 0 0 0
1 0 0 0 0 0

The input string, interpreted as ASCII codes of the digits, is equivalent to the numeric row vector
49 50 51

Full-size two-dimensional convolution (Y+) of the above vector and matrix gives
 0  0  0  0  0 49 50 51
 0  0  0  0 49 50 51  0
 0  0  0 49 50 51  0  0
 0  0 49 50 51  0  0  0
 0 49 50 51  0  0  0  0
49 50 51  0  0  0  0  0

Interpreting those numbers back as ASCII codes (c) gives the following char matrix, with char 0 represented as space:
     123
    123
   123
  123
 123
123

Transposition (!) transforms this into
     1
    12
   123
  123
 123
123
23
3

Interpreting each row as a number (U) gives the numeric column vector
  1
 12
123
123
123
123
 23
  3

and summing it (s) gives the final result, 531.

I smell... convolution

@Adnan What else? :-D

05AB1E,  12 11  8 bytes
I'm sure knew this can could be golfed further - tips welcome!
-1 byte thanks to Erik the Outgolfer (avoid wraps but using a concatenation)
and then...
-3 more bytes thanks to Adnan (avoid multiplication by length-1 by vectorising addition and subtracting the input off at the end)
.s¹η++Oα

Try it online!
How?
.s¹η++Oα - implicit input, say i      e.g.  123
.s       - suffixes                         [3,23,123]
  ¹      - push i                           123
   η     - prefixes                         [1,12,123]
    +    - addition of top two              [4,35,246]
     +   - addition (vectorises)            [127,158,369]
      O  - sum                              654
       α - absolute difference abs(123-654) 531
         - implicit print

You can use « to concatenate the suffixes and the prefixes: g<*¹.s¹η«O+

.s¹η++Oα should work for 8 bytes

Thanks @EriktheOutgolfer the two wraps did seem odd to me!

@Adnan - that's pretty sweet!

@JonathanAllan "tips welcome!" not sure if you'll get any anymore...

Retina, 22 bytes
.
$`;$&$';$_;
\d+
$*
1

Try it online! Link includes test cases. Explanation: The first stage splits the input number at each digit and includes all the exclusive prefixes and inclusive suffixes, giving the vertical numbers, plus also the original input number repeated for each digit, giving the horizontal numbers. The remaining stages then simply sum the resulting numbers.

Husk, 13 12 bytes
ṁit§+SRL§+ḣṫ

Try it online!
Explanation
              -- implicit input, say "123"
   §+         -- concatenate the results of the following two functions
     SR       --  ¹repeat the input n times, where n is the result of the next function
       L      --   length                                                  ["123","123"]
        §+   --  ²concatenate the results of the following two functions
          ḣ  --     prefixes                                              ["","1","12","123"]
           ṫ --     suffixes                                              ["123","23","3",""]
              -- inner concatenation                                      ["","1","13","123","123","23","3",""]
              -- outer concatenation                                      ["123","123","","1","13","123","123","23","3",""]
  t           -- all but the first element                                ["123","","1","13","123","123","23","3",""]
ṁ             -- map then sum
 i            --   convert to integer (where "" converts to 0)

Haskell, 90 78 76 71 64 63 59 57 bytes
g x=sum[x+div x(10^a)+mod x(10^a)|(a,_)<-zip[1..]$show x]

Try it online!

g x=sum[x+div x a+mod x a|(a,_)<-zip((10^)<$>[1..])$show x].

g x=sum[x+div x(10^a)+mod x(10^a)|(a,_)<-zip[1..]$show x] is a hair shorter still.

g x=sum[x+x`div`10^a+x`mod`10^a|(a,_)<-zip[1..]$show x].

Neim, 7 bytes
S

Beware. Contains snakes: S
Try it online!

"Beware. Contains snakes: S" Lol.. ``

Python 3, 85 70 Bytes
f=lambda n,r=1,i=int:n[r:]and i(n[r:])+i(n[:r])+f(n,r+1)+i(n)or i(n)*2

For input 12345:
Sums up slices of input 1+2345+12345, 12+345+12345, 123+45+12345, 1234+5+12345, by using string indexing to index (r) = 1,2,3,4 before casting to integer, and adds to 12345*2
Special Thanks to:
-14 Bytes @Jonathan Allen
-1 Byte @ovs
Try it online!

TIO links to wrong code. (len(n)+1) can be golfed to -~len(n) (~x is -1-x), and then that can save another byte by using -i(n)*~len(n). Then you can make it all an anonymous function: lambda n,i=int:sum(i(n[:r])+i(n[r:])for r in range(1,len(n)))-i(n)*~len(n) (74 bytes)

Even better make that function recursive for 71 bytes: f=lambda n,r=1,i=int:n[r:]and i(n[r:])+i(n[:r])+f(n,r+1)or-i(n)*~len(n)

70 bytes, based on Jonathan Allan's suggestion

I fixed your tio link.

Japt, 15 11 bytes
-4 bytes thanks to @Shaggy.
¬£iYç
cUz)x

Takes input as strings.
Try it online!
Explanation
¬£

Split the input array to digits (¬) and map by (£) the following function, where Y is the index.
["1", "2", "3"]
iYç

The input value (implicit) with Y spaces (ç) inserted (i) at the beginning. This is assigned to U.
["123", " 123", "  123"]
cUz1)x

Concatenate that with itself rotated 90° right (1 time). Then sum (x).
["123", " 123", "  123", "  1", " 12", "123", "23 ", "1  "] -> 531.

Exactly how I was trying to do it, but I couldn't quite get there, for some reason - nicely done :) Here's a 13 byte version.

11 bytes

@Shaggy Awesome, I knew there had to be a shorter way to prepend the spaces to each line. Thanks!

Japt, 31 18 bytes
-13 bytes thanks to @ETHproductions
This approach doesn't work well using Japt. Justin's solution is much better.
[U*Ål U¬£tYÃUå+]xx

Explanation:
[U*Ål U¬£tYÃUå+]xx
[              ]    // Create a new array
 U*Ål               // Push: Input * Input.slice(1).length()
                    // Push:
      U¬            //   Input, split into chars
        £tY         //   Map; At each char: .substr(Index)
            Uå+     // Push: Cumulative reduce Input; with addition
                xx  // Sum all the items, twice

Try it online!

That's it, I'm adding a shortcut for Ul  :P

Hmm... you don't need either of the Us in the functions, and the middle item in the array can be condensed to Uå+ x, which I think gets you down to 23 bytes.

@ETHproductions Thanks! I got it down another byte by rearranging the array items.

Can you change mx x to xx? :-)

@ETHproductions I sure can, thanks again :)

I think you can save one more byte by skipping V entirely: [UÅl *UU¬£tYÃUå+]xx

Actually, for the first one you can do U*Ål to save another byte :)

JavaScript, 77 74 bytes
Saved 3 bytes thanks to Value Ink

f=a=>[...a+a].map((_,b)=>a-=-z.substr((b-=n)>0?b:0,b+n),a*=n=(z=a).length)|a

console.log(f('123'));
console.log(f('101'));
console.log(f('12'));
console.log(f('1234567'));
console.log(f('102033'));

Ruby, 61 55+1 = 56 bytes
Uses the -n flag. Input from STDIN.
p (1..~/$/).sum{|i|[$_[i,~/$/],$_[0,i],$_].sum &:to_i}

Try it online!

For input 102033 your program prints 728714 while the correct value is 729702.

NOOOO! CURSE YOU OCTAL REPRESENTATIONS! (brb fixing, 02033 was the issue)

I supposed that octal numbers are the problem, but I was not sure (btw I don't know ruby). Thanks for clarifying :)

@ThePirateBay no problem; I was already working on a shorter, alternate solution that took string inputs, and even with the fixes needed I actually ended up saving bytes anyways :)

R, 168 162 103 bytes
-6 bytes by not using c()
-59 bytes thanks to @Giuseppe
function(n){k=nchar(n)
a=k*strtoi(n)
for(i in 1:k)for(j in i:k)a=a+(i==1|j==k)*strtoi(substr(n,i,j))
a}

Try it online!
Takes input as a string.
I'm absolutely certain there are improvements to be made, primarily in leveraging any of R's strengths... but in a challenge that's basically string manip, I'm struggling to see how.
Edit: Much better now that I'm not iterating on a bad idea!

103 bytes

@Giuseppe Ah thanks! That was a lot of wasted space from when I was still using an integer input. I like the strtoi(substr()) way, and the (a|b) trick is way smarter than I had. Thanks for the improvements! It's almost a different answer at this point...

That happens when you get another approach added! I couldn't figure out the loops myself, but I think you might be able to construct the indices for substr explicitly instead of looping, which would save a few bytes.

Pyth, 20 19 bytes
My current prefix approach (will hopefully golf further).
+*tlQsQssM+_M.__Q._

Test Suite or try an alternative approach with the same byte count.
Explanation
+*tlQsQssM+_M.__Q._  - Full program that reads a String from STDIN, with implicit input.

  tlQ                - Length of the input - 1.
     sQ              - The input converted to an integer.
 *                   - Product of the above two elements. We will call this P.
                 ._  - Prefixes of the input.
          +          - Concatenated with:
           _M.__Q    - The prefixes of the reversed input, reversed.
        sM           - Convert each to an integer.
       s             - Sum.
+                    - Addition of the product P and the sum above.

To understand the concept better, we shall take an example, say "123".

We first get the prefixes of the input. Those are ['1', '12', '123'].

Then, we get the prefixes of the reversed input, i.e: ['3', '32', '321'] and reverse each, hence we get ['3', '23', '123'].

We concatenate the two lists and convert each element to an integer, so we obtain [3, 23, 123, 1, 12, 123].

By summing the list, the result is 285.

The product P is the length of the input - 1 (i.e 2) multiplied by the integer representation of it (2 * 123 = 246).

In the end, we sum the two results: 285 + 246, hence we obtain 531, which is the correct result.

Pyth, 20 bytes
+*hlQsQsm+s>Qds<QdtU

Test Suite.
Explanation
Explanation to come after further golfing. I didn't succeed to golf this further for now (I have ideas though).
+*hlQsQsm+s>Qds<QdtUQ  - Full program. Reads from STDIN. Q means input, and is implicit at the end.

  hlQ                  - Length of the input + 1.
     sQ                - The input converted to an integer.
 *                     - Multiply the above. We'll call the result P.
        m         tUQ  - Map over [1...length of the input)
          s>Qd         - input[currentItem:] casted to an integer.
              s<Qd     - input[:currentItem] casted to an integer.
         +             - Sum the above.
       s               - Sum the list.
+                      - Add the sum of the list and P.

q/kdb+, 34 bytes
Solution:
{sum"J"$((c#c),c-(!)2*c:(#)x)#\:x}

Examples:
q){sum"J"$((c#c),c-(!)2*c:(#)x)#\:x}"1234567"
10288049
q){sum"J"$((c#c),c-(!)2*c:(#)x)#\:x}"123"
531
q){sum"J"$((c#c),c-(!)2*c:(#)x)#\:x}"101"
417
q){sum"J"$((c#c),c-(!)2*c:(#)x)#\:x}"12"
39

Explanation:
{sum"J"$((c#c),c-til 2*c:count x)#\:x} / ungolfed
{                                    } / lambda function
                                    x  / implicit input
                                 #\:   / apply take (#) to each-left element with the right element
        (                       )      / the left element
                       c:count x       / count length and save in variable c
                     2*                / multiply by 2 (e.g. 6)
                 til                   / range, so 0 1 2 3 4 5
               c-                      / vector subtraction, so 3 2 1 0 -1 -2
         (   )                         / do this together
          c#c                          / 3 take 3, so 3 3 3
              ,                        / join, so 3 3 3 3 2 1 0 - 1 -2
    "J"$                               / cast this "123", "123", "123" .. "23" to longs
 sum                                   / sum them up and return result

Jelly, 18 bytes
DµṚ;\U;;\ṖVS+Ḍ×¥L$

Try it online!

C (gcc), 95 84 81 bytes (78 + -lm compiler flag)
Hi! This is my first submission, I hope I didn't break any rule.
g,o,l;f(char*s){l=atoi(s);while(s[o++])g+=l/pow(10,o)+atoi(s+o);return g+l*o;}

Try it online!
Ungolfed, without warnings:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int g,o,l;

int f(char *s){
  l = atoi(s);

  while(s[o++]) {
    g+=l/pow(10,o)+atoi(s+o);
  }

  return g+l*o;
}

int main(void){
  printf("%d\n",f("1234567"));
  return 0;
}

Looks valid to me :)

Hmm, -lm for math functions is only needed for some C runtimes like e.g. glibc. Compiling e.g. with MinGW (using Microsoft's msvcrt.dll), it wouldn't be needed. So not sure it's required to add here? Anyways, if you add it, it would make 3 bytes ;)

Unfortunately, -lm is needed for the pow() function with gcc. I tried to work without it but couldn't find a solution using fewer than 6 bytes (pow + the compiler flag).
I couldn't find rules about how to include flags into the bytecount, and I know realize that I made a false assumption about the - character not beeing counted. I'm adding a +1 byte right now.

-lm is not required by gcc but by the fact that glibc doesn't include the math functions in the main library. msvcrt.dll does, so compiling on windows with gcc works without the -lm. This is nitpicking and I'm not entirely sure what the rules about this actually have to say.

Thanks for the heads up :)
I'm unable to try your proposal and tio doesn't seem to offer that possibility either, unfortunately

Swift 3, 213 bytes
func f(n:String){print((n.characters.count-1)*Int(n)!+(0..<n.characters.count).map{r in Int(n[n.index(n.startIndex,offsetBy:r)..<n.endIndex])!+Int(n[n.startIndex..<n.index(n.endIndex,offsetBy:-r)])!}.reduce(0,+))}

Cannot be tested online, because it is slow and times out. You can try it in Swift Playgrounds if you wish to test it.
Sample run
Input:

f(n:"123")
f(n:"101")
f(n:"1234567")

Output:

531
417
10288049

Jelly, 12 bytes
LḶṚ⁶ẋ;€µ;ZVS

Try it online!
Takes input as a string. Creates the "parallelogram" as a matrix of characters, then evaluates each row and column to get the numbers to sum.
Explanation
LḶṚ⁶ẋ;€µ;ZVS  Input: string S
L             Length
 Ḷ            Lowered range - [0, 1, ..., len(S)-1]
  Ṛ           Reverse
   ⁶          The char ' ' (space)
    ẋ         Create that many characters of each in the range
     ;€       Prepend each to S
       µ      Begin a new monadic chain
        ;     Concatenate with
         Z    Transpose
          V   Eval each string
           S  Sum

Java 8, 147 137 126 116 114 bytes
n->{Integer l=(n+"").length(),r=n*l,i=0;for(;++i<l*2;)r+=l.valueOf((n+"").substring(i>l?i-l:0,i<l?i:l));return r;}

-13 bytes (137 → 126 and 116 → 114) thanks to @OlivierGrégoire.
Explanation:
Try it here.
n->{                          // Method with integer as parameter and return-type
  Integer l=(n+"").length(),  //  Length of the input integer
      r=n*l,                  //  Result-integer (starting at `n*l`)
      i=0;                    //  Index-integer (starting at 0)
  for(;++i<l*2;               //  Loop from 0 through two times `l` (exclusive)
    r+=                       //   Add to the result-integer sum:
       l.valueOf((n+"").substring(
                              //    Substring of input, converted to integer:
        i>l?                  //     If `i` is larger than `l`:
         i-l                  //      Substring starting at `i-l`
        :                     //     Else:
         0,                   //      Substring starting at 0
        i<l?                  //     If `i` is smaller than `l`:
         i                    //      Substring ending at `i` (exclusive)
        :                     //     Else:
         l)                   //      Substring ending at `l` (exclusive)
  );                          //  End of loop
  return r;                   //  Return resulting sum
}                             // End of method

114 bytes: n->{Integer l=(n+"").length(),s=n*l,i=0;for(;++i<l*2;)s+=l.valueOf((n+"").substring(l<i?i-l:0,i<l?i:l));return s;}. It's a sliding window with min-max to reduce the number of calls to the expensive new Integer(....substring(...))

@OlivierGrégoire Thanks, and can even shortened some more by changing Math.max(0,i-l) to 0>i-l?0:i-l and Math.min(i,l) to i>l?l:i. Modifying it now. Ah, I see you've edited your comment after I had copied the 126 bytes answer. ;)

Yeah, sorry for editing, but I hadn't checked that ;)

Perl 5, 53 + 1 (-n) = 54 bytes
$r=$_*(@n=/./g);for$i(@n){$r+=$_+($t=(chop).$t)}say$r

Try it online!

Mathematica, 77 bytes
(s=IntegerDigits@#;t=Length@s;Tr[FromDigits/@Table[s~Take~i,{i,-t,t}]]+t#-#)&


text:
Make a lost RNG
Lost is a 2-D programming language where the start position and direction of the ip are entirely random.
This makes it very difficult to make deterministic Lost programs.  However today we are not writing a deterministic program, we are writing an RNG.
Write a Lost program that takes no input and outputs a single digit (0,1,2,3,4,5,6,7,8, or 9), with all digits having an equal probability of being output.  Since Lost's start location and direction is the only source of randomness, the only way to do this is to have every location in your source output a different number from 0 to 9 with an equal number outputting each digit.
You can calculate the probability of each digit by using the -Q flag and piping it into this python script
import sys
a=sys.stdin.read().split()[:-1]
for x in range(10):print x,':',a.count(`x`)
print[x for x in a if x not in list("1234567890")]

Try it online!
This is code-golf so answers will be scored in bytes with less bytes being better.

An overview of Lost
Lost is a wrapping implicit IO 2D language taking much from the mold of Klein.
Here is a quick cheatsheet of what lost commands do

\,/,| Mirrors the ip
<,^,>,v Points the ip in a direction
[ Reflects the ip if it is moving east; becomes ] if the ip is moving horizontally
] Reflects the ip if it is moving west; becomes [ if the ip is moving horizontally
! Skips the next operation
? Pops off the top of the stack and jumps if not zero
: Duplicates the top of the stack
$ Swaps the top two items of the stack
( Pops from the stack and pushes to the scope
) Pops from the scope and pushes to the stack
0-9 pushes n to the top of the stack
" Starts and ends a string literal.  During a string literal commands are not run and instead their character values are pushed to the stack.
+ Adds the top two numbers
* Multiplies the top two numbers
- Multiplies the top by -1
% Turns the safety off
# Turns the safety on
@ Ends execution if the safety is off (starts on)

What happens if you try to swap two values from the stack but there is only one value or try to pop from an empty stack?

@ppperry The stack is padded with implicit zeros.

Too low information about language. Does it wrap? What 'safety' means? Bracets description is misleading? How scope is used?

@DeadPossum I tried to keep it concise.  It does wrap.  Safety is already explained in the question.  I don't know what you mean about the brackets.  [] act as doors, <> point in directions and () store and recall from the scope.  Scope is used to store values.

@WheatWizard So safety is just condition for @ or does it have other usecases? About brackets, I don't understand this part: becomes ] if the ip is moving horizontally. Moving east is horizontally too, isn't it?

@WheatWizard Oh, and output. Am I right that it implicitly output whole stack and don't output scope?

@DeadPossum 1) Yes it is set by % and # and checked by @ nothing else interacts with it 2) Moving east is horizontal that is correct. 3) output is implicit

81 101 bytes
This might be golfable further ...
>%(0@>%(1@>%(2@>%(3@>%(4@>%(5@>%(6@>%(7@>%(8@>%(9@
^<<<<^<<<<^<<<<^<<<<^<<<<^<<<<^<<<<^<<<<^<<<<^<<<<

Try it online!

Interesting approach! I hadn't thought of that

Not sure if it is a problem, but this seems to occasionally double the output.

101 bytes that fixes the double print.  Just added a stack pop before the safety is turned off so if you hit the number at the start, it can pop it, push it again, then die.  I don't know if this is still technically a uniform random though...

I literally came up with the same idea at the same time ...

Your output isn't uniform.  0 has a 7/101 chance of being printed (any of the < or ^ underneath its block, plus the > and % symbol), 1-8 have a 10/101 chance, and 9 has a 11/101 chance.  Then it looks like there might be a chance it just goes on forever.

@WheatWizard Does Lost do any sort of wrapping if it goes off the end?  Or does the program just die if it walks off the end of the program?

It has to wrap, or otherwise this would terminate when it starts on the top line going up.

@ArnoldPalmer It wraps around the edges.

@ppperry In that case, just change the last section with 9 to follow the others (%(9@) and I think you're good.

Lost, 54 bytes
>%(0@>%(1@
@>%(2@>%(3
5@>%(4@>%(
(7@>%(6@>%
%(9@>%(8@>

Try it online!
Just copied from pppery's answer and do some random stuff. I know nothing about Lost language. And I even do not know what happening for above codes. Is this work? (I don't know)

Your code produces half as much output as ppperry's, I guess it's because of how -Q works? The output seems normally distributed anyway. It would have been nice to have a full spec of the language linked in the question.

@Aaron I should have explained how -Q works.  Since the language is random, verification is done by running all the possibilities.  -Q does this and prints all the results.  The shorter the program the less possibilities there are and the fewer outputs come from -Q.


text:
'abc' and 'cba'
Your task is simple, write a single code snippet that when executed in one language  outputs only the string 'abc' and when executed in another language outputs only the string 'cba'. The program should take no input.
This is a code-golf challenge.

I don't think this is a dupe at all. The fact that the string is reversed is different enough from printing two different strings. I won't (vote to) reopen, though, as that would have immediate effect

I voted to reopen this post, because IMO printing the reverse of a String and a String is much different than 2 different ones. No answer can trivially be modified to fit this challenge. My own answer uses a reverse symmetry techinque when compared to the answers there. I agree with @LuisMendo.

Reopening now, as it has two votes in addition to mine

Is a leading newline allowed?

Can you print ABC instead of abc

I vote to reopen, some answers use the fact cba is abc backwards; link, link, link, link, link, link, link, link, link

'ABC' and 'CBA' is ok, leading/trailing whitespace/newlines ok but must be the same for both outputs

@OliverNi Another reason it might not be considered a dupe is that the other question says "Different versions of the same language don't count", whereas that is allowed and indeed encouraged here

There are 8 Python 2/Python 3  answers to this question and somehow, all of them use different strategies?!

MATLAB / Octave, 41 bytes
disp(flip('abc',size(randsample(2,2),2)))

In MATLAB randsample(2,2) gives a 2×1 vector, so size(...,2) is 1. Thus flip is applied along the first dimension, which is a singleton, so the original string 'abc' is displayed:

In Octave randsample(2,2) gives a 1×2 vector, so size(...,2) is 2. Thus flip is applied along the second dimension, that is, the string is flipped from left to right:

I think this would be a few bytes shorter if you use the less interesting version variant.

@StewieGriffin Thanks. I think it's too late to change now. Maybe post it yourself?

Nah, it's a boring version of this one... Also, I don't have MATLAB anymore so I won't be able to test it.

05AB1E / Pyth, 5 bytes
_"abc

Try 05AB1E online!
Try Pyth online!
This also works in Pyke, outputting cba.
This also works in Recursiva, outputting cba.

Whitespace and Bash, 57 bytes

echo  cba

Try it online!

You can golf 3 bytes by removing the three trailing new-lines. Relevant Whitespace tip.

25 bytes
print(1/2and'cba'or'abc')

Try it online! (Python 2)
Try it online! (Python 3)

-1 byte by using exit instead of print (although this applies to every answer as of now).

@notjagan. exit prints to stderr, doesn't it? Not sure if it would be a valid answer.

@ThePirateBay Outputing to STDERR is allowed as per meta consensus.

The challenge says code snippet and print though, it's not using default rules.

Vim / Notepad.exe, 10 bytes
cbaabc<esc><backspace><backspace><backspace>

Notepad isn't a programming language, but +1.

it is cheating :(

-1 byte if I make ==0 into >0 but that's already another answer
Python 2, 26 bytes
print('acbbca'[1/2==0::2])

Try it online!

Python 3, 26 bytes
print('acbbca'[1/2==0::2])

Try it online!
1/2 gives 0 (floordiv) in Python 2 and 0.5 (truediv) in Python 3. Thus, 1/2==0 gives 1 in Python 3 and 0 in Python 2 (actually, booleans, but those are just integers), so 'acbbca'[1::2] => 'cba' is given for Python 3 and 'acbbca'[0::2] => 'abc' is given for Python 2.

Excel / Google Sheets, 41 28 27 24 Bytes
Anonymous worksheet formula that takes no input and outputs "ABC" to the calling cell in Excel and "CBA" to the calling cell in Google Sheets
=IfError(M("CBA"),"ABC")

In Google Sheets, M(...) is an alias for and autoformatted to T(...) (short for Text()). This call returns the text value of the passed variable, "CBA". "CBA" is not caught as an error, so "CBA" is returned by IfError(...,"ABC")
In Excel, there is no M(...) function, and M(...) is not an alias and therefore M("CBA") returns the formula not found error, #NAME?. This is  caught by IfError(...,"ABC"), which in turn returns "ABC".

Previous Versions, 27, 28, 41 Bytes
See edits for explanations
=If(IsErr(A()),"ABC","CBA")

=If(IsErr(GT()),"ABC","CBA")

=IfError(If(Info("NUMFILE"),"ABC"),"CBA")

Neat!  ....You can save 2 bytes by using iserr instead of iferror and 1 byte by using "SYSTEM" instead of "NUMFILE": =IF(ISERR(INFO("SYSTEM")),"cba","abc")

CJam / 05AB1E, 6 bytes
"abc"R

Try it online:

CJam;
05AB1E.

How it works in CJam
"abc"    Push this string
R        Push variable R, predefined to the empty string
         Implicitly display stack

How it works in 05AB1E
"abc"    Push this string
R        Reverse
         Implicitly display top of the stack

Also works in Foo instead of CJam.

With apologies to @HyperNeutrino for stealing most of his answer (I don't have the reputation to comment yet)
Python 2, 25 bytes
print('acbbca'[1/2>0::2])

Try it online!
Python 3, 25 bytes
print('acbbca'[1/2>0::2])

Try it online!

Umm it's actually <1 btw.

@EriktheOutgolfer No that's truthy for both languages

As @notjagan suggested, you can replace print with exit (which is allowed by our rules) and therefore save 1 byte.

You should add the second language to your answer (Python3 I assume)

@Zacharý Thanks, I didn't realize the problem had been updated (the original was only python 2 and pyhon 3)

JavaScript (NodeJS) and PHP, 46 bytes
<!--
strrev=console.log//--><?=
strrev("abc");

Prints abc in JS and cba in PHP.
Try the JS online!
Try the PHP online! (note that TIO doesn't hide the HTML comments (<!--...-->)

How is the <!-- interpreted in Node?

@Challenger5 It's apparently interpreted as a one-line comment, exactly like // (source). Works that way in browser JS as well.

That is weird...

--> blah blah is valid comment in some JavaScript interpreter, you may just remove //

@tsh That doesn't seem to work in any of the TIO JS interpreters; where does that act as a comment?

@JustinMariner I had tested on Node v8.1.3. And the behavior defined in ES6 specification Annex B, which means all browsers that support ES6 should accept it as comment.

Might as well link the spec. And that's definitely weird when used alone. Fortunately it only works on a line where's there's no statement (only whitespace and inline comments)

Python 2 and Python 3, 42 bytes
try:exec("print'abc'")
except:print('cba')

Try it online! (Python 2)
Try it online! (Python 3)
Thought I'd try something different...

I like this one, not the shortest but quite a generic framework, can be shortened a bit by using try:long;print('abc')

Or better still try:cmp;print('abc')

Hmm... It doesn't seem to work...

That's not what I wrote, parantheses () still required around print

Python / Befunge, 20 18 bytes
2 bytes saved thanks to @karhell
print("abc")# ,,,@

Try it online! for Python
Python sees print("abc") then a comment.
Try it online! for Befunge
Befunge, removing all nops and useless commands sees "abc",,,@ which puts a, b and c on the stack and then prints them (last in - first out).

A bit late, but you can shave off two bytes by replacing >:#,_@ by ,,,@

Save one more with #,,<@ instead

Excel/Google Sheets, 28 bytes
Inspired by @TaylorScott, who used a function that only exists in Excel, I found an even shorter function that only exists in Google Sheets.  Conveniently, it is designed to return strings:
=iferror(join(,"cba"),"abc")

How it works
In Google Sheets, join([arg1], arg2, arg3,...argk) will concatenate arg2 -> argk, optionally using the separator specified in arg1.  In this case, it successfully returns "cba."
Excel has no join function, so iferror sees a problem and returns "abc"

My first ever submission - hope I am doing it right....

Nice solution :)

Python 2 / Python 3, 28 bytes
print('abc'[::int(1/2*4)-1])

In Python 2 int(1/2*4)-1 evaluates to -1 and so prints cba. - TiO
In Python 3 it evaluates 1 so prints abc. - TiO

Welcome to Programming Puzzles and Code Golf

R/Cubix, 20 bytes
cat("abc")#u@o;o;o(;

R - Try it online!
Cubix - Try it online!
For R, cat("abc") then shameless abuse of comments.
For Cubix
    c a
    t (
" a b c " ) # u
@ o ; o ; o ( ;
    . .
    . .

"abc" Pushs a, b ad c onto the stack
)# Increment the c, pushs number of element in stack
u U-turn to the right
;( Remove the count, Decrement the c
o;o;o@ Output cba and exit

Pushs the number on in stack

I am strangely pleased by the way that cat( is totally ignored by Cubix.

C and C++, 115, 78, 58, 56 bytes
#include<stdio.h>
main(){puts(sizeof('x')>1?"abc":"cba");}

78 bytes, thanks to challenger5.
58 bytes, thanks to aschepler.
56 bytes, thanks to hvd
Try it - C++!
Try it - C!

You can collapse the two #ifdefs to make a single one. 2) You can remove the space in #include <stdio.h>. 3) You can change printf("%s", to puts(. Try it online!

Or there's always the good old sizeof('x')>1?"abc":"cba" trick.

@Challenger5 Thanks for the comment

@aschepler Thanks for the trick, i've made the changes 58 bytes :)

sizeof's operand does not need parentheses, it's not a function.

@hvd Thanks! You're right!

CJam and Gaia, 8 bytes
'c'b'a]$

Try it in CJam!
Try it in Gaia!
Explanation
In both languages this defines a list of characters.
In CJam, $ is sort, so it becomes abc.
In Gaia, $ joins the list into one string, giving cba.

I've added Gaia to the golfing language list; please let me know if I got any details wrong.

@ETHproductions Looks OK to me.

Java 8 & C, 95 bytes
//\
interface a{static void main(String[]s){System.out.print("abc"/*
main(){{puts("cba"/**/);}}

Try it in Java 8 - resulting in "abc".
Try it in C - resulting in "cba".
Explanation:
//\
interface a{static void main(String[]s){System.out.print("abc"/*
main(){{puts("cba"/**/);}}

As you can see in the Java-highlighted code above, the first line is a comment due to //, and the C-code is a comment due to /* ... */, resulting in:
interface a{static void main(String[]s){System.out.print("abc");}}

//\
interface a{static void main(String[]s){System.out.print("abc"/*
main(){{puts("cba"/**/);}}

Not sure how to correctly enable C-highlighting, because lang-c results in the same highlighting as Java.. But //\ will comment out the next line, which is the Java-code, resulting in:
main(){{puts("cba");}}

Japt 2.0/JavaScript, 11 10 bytes
"abc"
//Uw

Japt 2.0 outputs cba
JavaScript outputs abc

Vyxal/Hexagony, 19 bytes
ka3wiṘ,Qλa;b@;<λ;c/

Try it Online! (Vyxal)
Try it Online! (Hexagony)
The program is split into two main parts, ka3wiṘ,Q and λa;b@;<λ;c/. The first half is just basic Vyxal to print "cba" (though I cannot use `cba` because it messes with Hexagony's layout). The second part worked out really nicely, because in order to print in Hexagony, a semicolon is required, but in Vyxal, an unmatched semicolon gives an error. So to fix this, I use lambdas in order to match them, and it just so happened to fit into an exact 3x3 hexagon. Luckily, in Hexagony almost any character that isn't special is taken as its codepoint, so the lambda character is quickly overwritten by anything else that comes after it.

The lambdas are placed so each one proceeds a semicolon, even if they aren't used in the hexagony code (as indicated by the blue trail).

Python 3, 26 bytes
print('abc'[::-(1/2>0)|1])

Try it online!
Python 2, 26 bytes
print('abc'[::-(1/2>0)|1])

Try it online!
25-byte version with exit instead, which outputs to STDERR instead.
This is basically the same as print('abc'[::[1,-1][1/2>0]]), just that it's golfed.

Ly / ><>, 20 19 bytes
"abc"&&ov
;     oo<

Try it with ><>!
Try it with Ly!
These languages are very similar, as Ly is based off ><>. However, Ly does not have 2D execution and interprets & differently, which I took advantage of here.
Both languages will start by pushing abc to the stack.
For ><>, the & instruction moves values to and fro the register. Two in a row will push a value to the register and then take it straight back, essentially a NOP.
For Ly, & is a modifier that makes an instruction perform its function on the entire stack.
o means the same thing for both languages, but since it is modified by & in Ly, it will print the whole stack, outputting abc. In ><>, it will only output c (as it is printed from the top down)
v is a NOP in Ly, which skips it and goes straight to ;, ending execution. ><> will instead treat it as a pointer, sending the IP downwards.
It then hits another arrow, sending the IP left. Here, it meets two o signs, outputting b and a.
EDIT: Saved a byte (and fixed ><> crashing)

You can save a byte by moving the ; to the second line. This also has the benefit that the ><> IP doesn't wrap around and go through the second line again, which causes an error.

shouldn't there be a ; for ><>? it wouldn't take any more bytes, just replace one of the spaces

How about "abc"&&ooo;? It makes Ly crash, but only after printing "abc".

…or "abc"&&o!;o< for 1 extra byte, if you want to avoid crashing.

CJam and ><>, 12 bytes
"ooo;abc
"4>

What CJam sees:
"ooo;abc
"

String literal, which pushes the string ooo;abc (with a trailing newline) to the stack.
 4>

Slice off the first four characters of the string, leaving abc, which is output.
What ><> sees:
"

Begins a string literal.
 ooo;abc

Forms the contents of the string literal. The character codes of the characters in the string are pushed to the stack in reverse order (so c is on the top).
"

The IP wraps around, hitting the " a second time, which ends the string literal.
 ooo

Outputs the top three characters on the stack: cba
    ;

Terminates the program. Neither the abc nor any part of the second line is executed.
Solution with Error: 8 bytes
"abc"oo<

What CJam sees (Try it online!):
"abc"

Push a string literal to the stack.
    o

Output that string literal.
     o

Try to output again. The stack is empty, so the program crashes.
What ><> sees:
"abc"

Push three characters onto the stack in reverse order.
    o

Print one character: c
     o

Print another character: b
      <

Start moving backwards.
     o

Print the last character: a
    o

Try to print another character. Since the stack is empty, the program errors.

Python 2 and Foo, 16 bytes
print"abc"[::-1]

Python 2
print"abc"[::-1]

Try Python 2 online!
Explanation
print"abc"[::-1]

print             # print... (duh)
     "abc"        # the string "abc"...
          [::-1]  # backwards

Foo
"abc"

Try Foo online!
Explanation
"abc"

"abc"               print the string "abc"

C (gcc) C++ (g++), 59 bytes
#include<stdio.h>
main(){puts("abc\0cba"+(sizeof(' ')&4));}

Javascript / Ruby, 27 bytes
0?print('abc'):alert('cba')

A shorter version without prints for interpreters (14 bytes) :
0?'abc':'cba'

**Explanation**
NEW VERSION
0 is falsy for Javascript but truthy for Ruby, thanks to pxeger
OLD VERSION:
'' is falsy for Javascript, but truthy for Ruby.
OLD VERSION:
For Javascript, []+[] = "" as a string concatenation, since the + operand is only defined for numbers and strings, and the empty string is evaluated as false
Meanwhile, in Ruby, you can concatenate array using the + operand, and it is evaluated as true
(first participation in PCG ! :))

Can't you use 0 instead of ''?

You're right, thank you very much for your insight, I'll edit my answer :)

Fission / ><> , 11 bytes
!R"abc"ooo;

Try Fission Online
In Fission, a particle starts at R and prints abc.
Try ><> Online
In ><>, the IP starts at the top-left. ! skips the next instruction, and "abc" pushes [a,b,c] on the stack. ooo then pops and prints three times, giving cba.
Both programs end at ;

J/K (Kona), 30 bytes
NB. :`0:"ABC"
{}[] /.echo'CBA'

TIO - J & TIO - K kona

Julia and Python 3, 23 bytes
print(["abc","cba"][1])

Try Julia online!
Try Python online!
Julia uses 1-based indexing while Python uses 0-based indexing

05AB1E and 2sable, 6 bytes
…CBAžR

Prints ABC (OP said it was allowed) in 05AB1E and CBA in 2sable, using the fact that 2sable was similar to 05AB1E but the žR was added to 05AB1E after 2sable was abandoned.
Try it online! (05AB1E)
Try it online! (2sable)

The specification states that it must be "abc" or "cba". By my word, I'd say that this is invalid, but I can ask OP.

I asked the OP and he hasn't responded. If this turns out to be invalid, I will remove it.

@OliverNi Umm, if it's invalid you can just append a l btw.

PHP + JavaScript, 29 28 bytes
This works because PHP interprets '0' (same as the integer number 0) as being falsy, while JavaScript assumes it is simply a non-empty string which is truthy.

'0'?alert('cba'):print(abc);

This is meant to run with -r on PHP. In Javascript, just paste it in the console.

Thanks to @Justin Mariner for saving me 1 byte!

You could also use "0" instead of +![]: it becomes 0 (falsy) in PHP and is a string (truthy) in JS.

@JustinMariner You're right, but that's 1 byte longer.

Isnt it one byte shorter? +![]?print(abc):alert('cba'); -> "0"?alert('cba'):print(abc);

@JustinMariner OH!!! That way!!! Yes, it is 1 byte shorter. Thank you!

Julia and Octave/Matlab, 27 bytes
if'a'=="a""abc"else"cba"end

In Octave, both 'a' and "a" represent the same string, therefore 'a'=="a" is true. However, in Julia, 'a' is a single character while  "a" is a one-character string. In Julia, "cba" is the output.
Ungolfed version:
if 'a'=="a"
  "abc"
else
  "cba"
end

Braingolf and Lean Mean Bean Machine, 35 bytes
 O
""
#a
!!
""
#b
!!
""
#c
& ,&
@U;

Braingolf: Try it online!
LMBM: Try it online!
Outputs abc in LMBM, and cba in Braingolf.
Explanation
LMBM is a 2d language, which allows us to selectively execute the code we want.
Meanwhile Braingolf is a 1d language, meaning it starts at the top left, and goes across each line, executing code. It terminates upon reaching the end of the code.
In LMBM, a marble is spawned at every uppercase O when the program starts. Each tick it drops 1 character and executes the character. LMBM terminates once all marbles are destroyed.
A double quote " in LMBM sets the marble to char mode, meaning the next character to execute is interpreted as a 1 char string literal, and the marble's value is set to the codepoint of the character.
However " begins and terminates a string in Braingolf, automatically pushing the contents to the stack. Thankfully an empty string does nothing.
! in LMBM prints the marble's value as a char, however this is the silent modifier in Braingolf. Thankfully in braingolf v1, modifiers are only held through no-ops, meaning they will be dropped when braingolf hits the empty string, which doesn't use modifiers (unlike v2 where they are held until used) so we don't have to make sure to consume that modifier before we try to print the stack.
In Braingolf # is the char literal identifier, causing the codepoint of the next char to be pushed to the stack.
After passing through all of the characters (and in LMBM's case printing the first 2) we hit the last 2 lines.
The 2nd to last line does nothing in LMBM, as it simply drops through the space, a no-op.
In Braingolf however, the ampersand & is the greedy modifier. Modifiers in Braingolf are held through no-ops such as the space, until an operator consumes them, so the first ampersand is held through the space until it hits the comma , Braingolf's flip operator. The greedy modifier is consumed here to cause Braingolf to flip the entire stack, rather than the top 2 items. Then another greedy modifier is hit.
This one is held through the newline to the at @ sign, this prints the entire stack as ASCII.
Meanwhile LMBM simply drops through the space into the U, which prints the marble's value as ASCII and destroys the marble.
The U also has a function in Braingolf, it pops the top of the stack and pushes range(0...n), but the stack is empty because we just popped and printed everything, so this does nothing.

PHP / Brainf*ck, 31 bytes
using the -r flag,
PHP sees die(abc) and a comment, and since the compiler is forgiving, it outputs abc as a string instead of an empty variable.
Brainf*ck only sees the instruction characters, and the rest is seen as comments.
die(abc);#--[----->+<]>---.-.-.

Try it online! (PHP)
Try it online! (Brainf*ck)

FYI, you don't have to count -r

C / Common Lisp, 91 88 40 36 bytes
//(princ"abc")
;main(){puts("cba");}

Try it online – C
Try it online – Common Lisp
Both “normal” languages with very different syntax and semantics!
Explanation
For Common Lisp:
// is a special variable used in the Common Lisp REPL to give the result of the value preceding the previous one, initially equal to NIL. Then we prints abc. The following line starts with a semicolon, which is used to start one-line comments.
For C:
the first line is a comment, and the other is the program. Note that the semicolon before the definition of the main function is syntactically correct.
-1 byte thanks to @Zacharý

Would it be possible to remove the space after #include, since it's read as ;include? (Or at least from your explanation)

@Zacharý, yes, thanks!

Perl / Ruby, 18 bytes
Ruby
print'abc'.reverse

prints cba as we're calling .reverse on the string.
Try it online!
Perl
print'abc'.reverse

prints abc concatenated with the result of reverse which by default works on $_ which is empty and so makes no difference.
Try it online!

Python and Ruby, 30 bytes
print(['abc','cba'][(0 or 1)])

Ruby: the logical or short-circuits on 0, which is a truthy value.
Python: 0 is false, and the logical or yields 1.

Japt/Japt 2.0, 14 bytes
;AÊ?"abc":"cba

Japt outputs cba
Japt 2.0 outputs abc

MAWP / 1+, 71 bytes
1%(|"+1%+)1%()"+"+"+()();1%()"+"+"+()"+;1%()"+"+"+"+();77W2W1A!!;1M;2M;

Uses the % operator to remove all the stray 1's from the 1+ program. Rounded brackets are immediately skipped since there is no 0 in the stack for MAWP.
Try it! (MAWP)
Try it Online! (1+)

Ruby / C, 26 20 bytes
puts(0?"abc":"cba");

-6 from Dom Hastings.
Try it online! (Ruby)
Try it online! (C)
0 is a truthy value in Ruby, so it prints "abc", and C prints "cba".
puts is a function that works in both languages.

You can save 6 bytes with puts(0?"abc":"cba");!

I assumed that the ternary operator didn't work properly with strings in C. Yeesh.

JavaScript (V8), 65 bytes
console.log(parseInt('abc--[----->+<]>---.-.-.',16).toString(16))

Try it online!
brainfuck, 65 bytes
console.log(parseInt('abc--[----->+<]>---.-.-.',16).toString(16))

Try it online!

Python 2, 27 bytes
print(['abc','cba'][1/2>0])

Try it online!
Python 3, 27 bytes
print(['abc','cba'][1/2>0])

Try it online!

What is the purpose of posting another answer which is even more verbose than your first one?

@ThePirateBay It is a completely different approach

@ThePirateBay I think it's different enough. Besides, it's such a trivial task that (at least in my opinion), half of these answers are pretty much the same but reworded.

Python 2 and Python 3, 31 bytes
print(round(.5)and"abc"or"cba")

Uses the and/or trick from Erik the Outgolfer's answer, as well as the fact that Python 3 uses banker's rounding, while Python 2 does not.
Try it - Python 2!
Try it - Python 3!

Oh, thanks for having that as a note, I need to modify the MY interpreter now. And nice golf too!

@Zacharý is there any good reason to still support Python 2? :P

Yes. Because people still use Python2 (including me, since I have nltk and sympy on Py2)

Python 2, 28 bytes
print("abc"[::1/2and-1or 1])

Try it online!
Python 3, 28 bytes
print("abc"[::1/2and-1or 1])

Try it online!

JavaScript (ES8 & ES6), 24 bytes
_=>"".padEnd?"abc":"cba"

What about ES5 vs ES6 test [].keys

Or even ES5 vs ES3 test [].map...

@tsh; yeah, there's loads of options here. I went with this one 'cause it allowed me to use an arrow function, rather than an alert.

05AB1E and MY, 22 bytes
Try it online! (05AB1E)
Hex String in Python:
'"abc"?\x8e\x01\x06\x89(\x02\x06\x89(\x80\x03\x06\x89(\x80&'

Rendered in 05AB1E's codepage:
"abc"?Žʒε‰(αε‰(€βε‰(€&

Rendered in MY's unimplemented codepage:
_RrH_⌈≡16ǵ'26ǵ'+36ǵ'+←

How?
Here is what 05AB1E sees:
"abc"?Žʒε‰(αε‰(€βε‰(€&
"abc"                   -  The string "abc"
     ?                  -  Print (no newline)
      Ž                 -  Break on empty stack
       ʒε‰(αε‰(€βε‰(€&  - Unread junk

What MY sees (I added a feature which causes errors to produce 0, in addition to fixing the r command.):
_RrH_⌈≡16ǵ'26ǵ'+36ǵ'+←
_                       Negate (0)
 R                      Convert to binary ([0])
  r                     Convert from binary (0)
   H                    Convert to hex ("0")
    _                   Negate (errors, so 0)
     ⌈                  Ceiling (0)
      ≡                 Match (0 0=>1)
       16ǵ'             'a'
           26ǵ'+        Prepend 'b'
                36ǵ'+   Prepend 'c'
                     ←  Output without a newline

I could have used …, but I don't want to divide by 0 to result in 0.
(Use the file polyglot.py)

C/><>, 58 bytes
#include <stdio.h>//^
int main(){puts(/*/*/"abc"//ooo;
);}

JavaScript / Pascal, 40 bytes
JavaScript
Outputs "abc".

{alert`abc`/*}begin write('cba')end.{*/}

Pascal
Outputs "cba".
{alert`abc`/*}begin write('cba')end.{*/}

Try it online!

Pascal conveniently uses { } for block comments and, in JavaScript, { } are just scopes, which affect nothing in this context.

V/Vim, 6 bytes
iabcæ

Try it online!
V: cba
Vim: abc
V and Vim are backwards compatible, but V has many more commands mapped.  In V, æ means <M-f>lip where it's meaningless in Vim.

C and x86 DOS binary, 58 bytes
/* VX4!PZSXNN4s(D (D"5s@SCYAAA@!6cba*/main(){puts("abc");}

Pyth / Canvas, 14... bytes?
<4"abcｊｊｊ±" \┐

Try it in Pyth!
Try it in Canvas!

Pyth explanation:
<4                # All but the last 4 characters of:
  "abcｊｊｊ±"   　# String literal
               \┐ # Char literal, printing suppressed

Python 3 translation:
print("abcｊｊｊ±"[:-4])
"┐"

Canvas explanation:
Code               | Explanation                         | Stack
-------------------+-------------------------------------+----------------
<4"abc             | Push "<4\"abc" to the stack         | "<4\"abc"
      ｊｊｊ        |Remove first three characters of ToS | "abc"
           ±       | Reverse ToS                         | "cba"
             " \   | Push "\" \\" to stack               | "cba", "\" \\"
                 ┐ | Remove ToS                          | "cba"
                   | Print ToS (implicit)                |

I don't think this is valid unless you can provide a hexdump.

brainfuck / Jelly, 24 bytes
-[+[>+<<]>+]>+.+.+.
“CBA

“ is encoded as 0xFE in Jelly's codepage. Jelly's codepage is backwards compatible with printable ASCII, so all other characters are encoded the same.
To brainfuck
Try it online!
-[+[>+<<]>+]> sets a cell to 64. +.+.+. increments and outputs three times, printing ABC.
To Jelly
Try it online!
The first line is parsed as valid Jelly, but is ignored.
The second line is a string literal with content CBA. The last line of the file is the main link, so this is printed.

Swift / JavaScript, 34 bytes
/*/*/alert`cba`// */*/print("abc")

Try it Online! (Swift)
Testing snippet (JavaScript):

/*/*/alert`cba`// */*/print("abc")

This works by abusing nested block comments in Swift. Swift interprets the code as /*/* Comment */*/print("abc") while JavaScript interprets the code as /*Comment*/alert`cba`//Comment

Python 3 and Batch, 24 bytes
print('abc')#|echo cba

This program just takes advantage of operators in both languages.
What Python Sees
print('abc') # This is a comment, do not run
What Batch Sees
oh noes! errors! run this -> echo cba

Tcl, 79 bytes
#include<stdio.h>/*
proc M {} {puts cba}
#*/
#define M main(){printf("abc");}
M

Try it online!

C (gcc), 79 bytes
#include<stdio.h>/*
proc M {} {puts cba}
#*/
#define M main(){printf("abc");}
M

Try it online!

i knew someone was gonna (ab)use comment quirks

@mekb If you see other answers, lots of people are doing the same.

this was the first i saw

Pxem (ぬこ's intended specification) and Pxem (pxemi.7z: his actual implementation), 16 bytes.
Filename:
.wcba.p.d.aabc.p

Content is empty.
What it does
ぬこ, the designer of Pxem, originally intended that .w should NOT get into the loop when stack is empty, but his reference implementation does not satisfy it: it gets into the loop when stack is empty. This is why none of we, implementers, have ever complied his intended specification at all.

JScript, VBScript, 42 bytes
rem=1;a="abc"/*
a="cba"'*/
WScript.echo(a)

C / ><>, 33 bytes
#//;ooo"cba"
main(){puts("abc");}

What C sees
Try it online!
#

Begin empty preprocessor directive.

//;ooo"cba"

Single-line comment.

main(){puts("abc");}
Print abc.

What ><> sees
Try it online!

#

Reflect the code in the other direction.

       "cba"

String literal. Push the character codes of abc to the stack in order.

    ooo

Output each of those characters. Since c is at the top of the stack, it is output first.

   ;

End the program.

 //
main(){puts("abc");}

Never executed.

><> and Underload, 14 bytes
"(abc)S"}}ooo;

To ><>:
Try it online!
"(abc)S"

String literal. Push the character codes of (abc)S to the stack.
        }}

Move the TOS to the bottom twice.
          ooo

Output three characters (cba).
             ;

Halt.
To Underload:
https://tio.run/##K81LSS3KyU9M@f9fSSMxKVkzWKm2Nj8/3/r/fwA
"

Unrecognized
 (abc)

Push the string abc.
      S

Output it.
       "}}ooo;

More unrecognized characters.

Javascript and Japt, 18 15 bytes
$Pw=P="cba";$Pw

Outputs "abc" in Japt and "cba" Javascript.
Try it online!

This doesn't work in JS.

@Shaggy Works fine when run the same way as Oliver's answer, but I see where you're coming from. This is an old post and approaches to standard ways to answering were different back then.

Add++/Whispers v2, 29 bytes
x:"abc"
O
> "cba"
>> Output 1

Try Add++ online!
Try Whispers online!
This exits with an exit code of 1 when run in Add++.
How it works
Add++
Add++ goes through each line in a linear fashion, executing as it does so. The first line
x:"abc"

sets the x variable to the string abc. Then
O

outputs that string. Next
> "cba"
>> Output 1

(the Whispers code), compares the strings abc and cba lexicographically before throwing an error at the double >> on the fourth line.
Whispers
Whispers removes any lines which don't match one of it's five regexes, all of which only match lines beginning with >, making the code processed by Whispers
> "cba"
>> Output 1

Whispers' execution model is almost the exact opposite of Add++; it begins at the bottom line, and calls the lines indicated by the numbers as arguments.
>> Output 1

calls the function stored on line 1, then outputs the result. Line 1 is
> "cba"

, a nilad line which returns a single value and takes no arguments. Here, it returns the string cba, which is then outputted by the last line.

PHP & HTML, 15 bytes
<?die(abc)?>cba

PHP exits with printing abc; cba is ignored.
HTML sees the PHP code as unrecognized tag (and ignores it), then prints cba.

Bash / 05AB1E, 27 bytes
"printf" "abc\n" '#' r.ÁR¦¦

Try it online Bash
"printf" "abc\n" '#' r.ÁR¦¦
 │        │       └useless arguments
 │        └abc\n argument
 └printf command

Try it online! 05AB1E
"printf" "abc\n" '#' r.ÁR¦¦
 │        │       │ ││ │  └remove first two chars
 │        │       │ ││ └rotate stack 1 right
 │        │       │ │└reverse stack
 │        │       │ └push space character to stack
 │        │       └push # character to stack
 │        └push string "abc\n" to stack
 └push string "printf" to stack

Bash / 05AB1E, 24 bytes (without new line)
"printf" "abc" '#' r.ÁR?

Try it online Bash
"printf" "abc" '#' r.ÁR?
 │        │     └useless arguments
 │        └abc argument
 └printf command

Try it online!
"printf" "abc" '#' r.ÁR?
 │        │     │ ││ │ └print stack without newline
 │        │     │ ││ └rotate stack 1 right
 │        │     │ │└reverse stack
 │        │     │ └push space character to stack
 │        │     └push # character to stack
 │        └push string "abc\n" to stack
 └push string "printf" to stack

"printf" "abc" r.ÁR? seems to work for 20. But I don't know either Bash or 05AB1E.

A0A0 and FiM++, 123 bytes
(
>P97
P98
P99

)
Dear Princess Celestia: A!
Today I learned B.
I said "cba"!
That's all about B!
Your faithful student, C.

The parentheses at the top open a block comment in FiM++, so the A0A0 code in it is ignored by FiM++. A0A0 starts at the second line because of the preceding > and then print "abc", halting on the empty line after it.
FiM++ ignores the block comment and just executes a basic program that prints "cba". The first and last lines are for the class declaration, the second and fourth lines are for the main method, with the third line actually printing "cba".

authors: Евгений Новиков