text:
Swap the two given indices
Given an array of positive integers and two distinct valid indices, return the array with the two elements corresponding to the two indices swapped.
You may choose to use 0-indexing or 1-indexing, but the testcases below will be 0-indexed.
array        m n output
[1,2,3,4]    0 1 [2,1,3,4]
[5,8,9]      0 2 [9,8,5]
[11,13,15,3] 1 2 [11,15,13,3]
[11,13,15,3] 2 1 [11,15,13,3]
[11,15,15,3] 2 1 [11,15,15,3]

This is code-golf. Shortest answer in bytes wins. Standard loopholes apply.

Related, related.

Huh, this may well be a task that many golfing languages have a hard time with but most practical languages find easy. (Lists with mutable elements aren't a common thing for golfing languages to have.) If that is the case, it'll be quite interesting. (The golfing languages will probably still win, though, because they're so much terser they can get away with a more complex algorithm.)

Surprised this probably isn't a dupe, but this challenge is actually creative, since it's a real challenge for many golfing languages out there.

@LeakyNun I've got downvotes (and even delete votes) like that in the past, don't worry too much about it...

Can m and n be taken as an array?

Can the output not be in the form of a list (print the integers separated by a newline instead)?

Can functions return by modifying the original array in place?

@Okx I do not understand what you mean by m and n be taken as an array.

@Neil allowed by meta

@Mr.Xcoder I'm surprised that I can't find it on meta.

@ais523 I've added one more testcase.

Will the elements of the array be unique as they are in the test cases?

@Dennis nice observation. I've added one more testcase.

Full reentrancy should be a possible bonus!

C/C++, 53 50 39 bytes
f(a,m,n)int*a;{a[m]^=a[n]^=a[m]^=a[n];}

Try it online
Saved 11 bytes thanks to @Dennis

Operation Flashpoint scripting language, 98 95 bytes
f={t=_this;a=t select 0;b=+a;m=t select 1;n=t select 2;a set[m,b select n];a set[n,b select m]}

Modifies the array directly.
Explanation:
t=_this;                   // Give a shorter name for the array of arguments.

a=t select 0;              // Let 'a' be a pointer to the array that we modify.
                           // (The language doesn't have a concept of pointers really,
                           // yet its array variables are pointers to the actual array.)

b=+a;                      // Make a copy of the original array and save a pointer to it
                           // in the variable 'b'. This saves a few bytes later.

m=t select 1;              // Read the index arguments from the input array and save them
n=t select 2;              // to their respective variables.

a set[m,b select n];       // Do the swapping by reading the values from the copy and
a set[n,b select m]        // writing them to the original array. The last semicolon can
                           // be omitted because there are no more statements following
                           // the last statement.

Call with:
array = [1,2,3,4];
str = format["%1", array];
[array, 0, 1] call f;
hint format["%1\n%2", str, array];

Output:

JavaScript ES6, 36 32 bytes
Look, Ma, no temporary variable!
(a,m,n)=>[a[m],a[n]]=[a[n],a[m]]

4 bytes saved thanks to Neil bringing this consensus to my attention.

Try it
Enter a comma separated list of elements for a and 2 integers for m & n.

f=
(a,m,n)=>[a[m],a[n]]=[a[n],a[m]]
oninput=_=>o.innerText=(f(b=i.value.split`,`,+j.value,+k.value),b);o.innerText=(f(b=(i.value="5,8,9").split`,`,j.value=0,k.value=2),b)
*{font-family:sans-serif}input{margin:0 5px 0 0;width:100px;}#j,#k{width:50px;}
<label for=i>a: </label><input id=i><label for=j>m: </label><input id=j type=number><label for=k>n: </label><input id=k type=number><pre id=o>

Those instructions modify the array, which means you're allowed to not return the array, which will save you a few bytes.

@Neil: You're saying to just use (a,m,n)=>[a[m],a[n]]=[a[n],a[m]]? That would only output the 2 swapped elements without the rest of the array (e.g., [5,8,9],0,2 -> [9,5]).

@Neil: Right, which is why we need the a at the end to give us the complete, modified array. Or am I completely missing what you're trying to say?

@Neil: Hmm ... OK, I think I see what you'e getting at now (Sorry, trying to do too many things at the same time today). Thanks for the tip. Is there a consensus on that and, if so, would you have a link handy before I go searching for it myself?

https://codegolf.meta.stackexchange.com/a/4942/48934

Surely splicing is shorter?

@Downgoat, (a,m,n)=>a[m]=a.splice(n,1,a[m])[0] comes in at 35 bytes.

Jelly, 7 bytes
Ṛ,ḷyJ}ị

Try it online!
How it works
Ṛ,ḷyJ}ị  Main link. Left argument: [i, j]. Right argument: A (array)

Ṛ        Reverse; yield [j, i].
  ḷ      Left; yield [i, j].
 ,       Pair; yield [[j, i], [i, j]].
    J}   Indices right; yield all indices of A.
   y     Transliterate; replace j with i and i with j.
      ị  Index into A.

tfw the wrapper is almost as long as the program...

I never knew of the existence of y

I knew of y, but didn't think of using it here. That's a pretty clever answer.

This got me thinking... is Jelly valid Jelly code?

@M.Herzkamp It is. I doubt its exceptionally useful though.

Python 3, 41 32 bytes
-9 bytes thanks to @notjagan
def f(a,m,n):a[m],a[n]=a[n],a[m]

Try it online!
Modifies its argument, which is a valid output format.

It's funny how it's not even golfed that much comparing to idiomatic python code.

MATL, 7 6 bytes
yyP)w(

Indices are 1-based.
Try it online!
Explanation
Consider inputs [11 13 15 3], [2 3].
yy   % Take two inputs implicitly. Duplicate them
     % STACK: [11 13 15 3], [2 3], [11 13 15 3], [2 3]
P    % Flip
     % STACK: [11 13 15 3], [2 3], [11 13 15 3], [3 2]
)    % Reference indexing (pick indexed entries)
     % STACK: [11 13 15 3], [2 3], [15 13]
w    % Swap
     % STACK: [11 13 15 3], [15 13], [2 3]
(    % Assignment indexing (write values into indexed entries). Implicitly display
     % STACK: [11 15 13 3]

CJam, 4 bytes
{e\}

Try it online!

Japt, 17 16 bytes
hV(A=UgV UgW¹hWA

Try it online!
Saved a byte thanks to ETHproductions

Nice. Don't think you need the comma though.

@ETHproductions Thanks, you're right.

Alternative 16 byte implementation but I'm still convinced there's a shorter solution.

15 bytes

Common Lisp, 42 bytes
-2 bytes thanks to @coredump.
(lambda(a i j)(rotatef(elt a i)(elt a j)))

Try it online!
Quite straight forward, since there is a Common Lisp macro to swap: rotatef.

You could use ELT instead of AREF

@coredump Right, thanks!

C# (.NET Core), 48 43 31 bytes
(a,m,n)=>a[m]+=a[n]-(a[n]=a[m])

Try it online!
Swaps the numbers in the original array, no temporary variables used. Nonetheless I can't take credit for this answer as it has been Neil's idea.

@LeakyNun it does not seem to work, as that leaves a[m] with a value of 0. Try it yourself!

(a,m,n)=>a[m]+=a[n]-(a[n]=a[m]) seems to work though.

(These answers are all also valid in ES6 JavaScript, no?)

Javascript ES6, 36 34 bytes
(a,m,n)=>(x=a[m],a[m]=a[n],a[n]=x)

-2 Bytes because the function is altering the array. No need to return the array. Thanks to @Neil

Demo

f=

(a,m,n)=>(x=a[m],a[m]=a[n],a[n]=x)

let a1=[1,2,3,4], a2=[5,8,9], a3=[11,13,15,3]

f(a1,0,1);
f(a2,0,2);
f(a3,1,2);

console.log(JSON.stringify(a1)); //[2,1,3,4]
console.log(JSON.stringify(a2)); //[9,8,5]
console.log(JSON.stringify(a3)); //[11,15,13,3]

Those instructions modify the array, which means you're allowed to not return the array, which will save you a few bytes.

Shenzhen I/O, 735 Bytes
23¥, 810 Power, 48 Lines of Code
[traces]
......................
......................
......................
......................
......................
......................
.14.14.14.............
.94.14.14.............
.A........1C..........
.3554..95556..........
.9554.16..............
.A....................
.2....................
......................

[chip]
[type] UC6
[x] 4
[y] 2
[code]
  slx x0
  mov x1 acc
  mov x1 dat
  mov acc x3
  mov dat x3
  mov acc x3
  mov dat x3

[chip]
[type] UC6
[x] 8
[y] 5
[code]
  slx x2
  mov x2 x1
  mov x0 dat
  mov x2 x1
  mov x0 acc
  mov x2 x1
  mov dat

[chip]
[type] UC4X
[x] 2
[y] 6
[code]
  slx x0
  mov 0 x3
j:  mov x0 acc
  mov acc x2
  teq acc 0
- jmp j
  mov -999 x1

[chip]
[type] RAM
[x] 5
[y] 6

DISCLAIMER: Arrays are 0-terminated in this. Arrays are a pain in the ass to work with in Shenzhen I/O otherwise.
I actually made a steam level for this game. You can play it here.
EDIT: Aaand I just realized I said that the array in was ordered. Heck.

Welcome to the site This is really cool! do you think that you might be able to remove some of the whitespace in the file and still have Shenzhen IO accept the file?  I don't know how much you have fiddled with it, but you should try and see how flexible the format is.

I haven't played around with it! On the other hand, I am axing the header for the puzzle which contains the puzzle name and solution name, so I dunno if I should bother.

Brachylog, 19 bytes
iʰ{pᵗz=ᵗ!|}htI&h∋↙I

Try it online!
The process of writing this generator was fairly clumsy, so there's probably some further golfing to do. I may not have thought to use i if I hadn't initially thought I had some use for the value half of the pair it outputs! Takes input as [array, [m, n]].

Java 8 + InverseY, 27 bytes
java.util.Collections::swap

Just calls the swap function... this is a method reference of the type Consumer3<List, Integer, Integer>.
Try it online! (header and footer for boilerplate & copy of Consumer3 interface)

You don't need to add " + InverseY". It's valid in vanilla Java 8.

@OlivierGrégoire Agreed.

05AB1E, 10 bytes
D²è³ǝ¹³è²ǝ

Try it online!

Octave, 28 bytes
@(a,n){a(n)=a(flip(n)),a}{2}

Try it online!
Quite satisfied with this one actually :)
Takes input on the form: f([1,2,3,4],[1,2]), 1-indexed.
Explanation:
@(a,n)                         % Anonymous function that takes two 1-dimensional
                               % arrays as input
      {               , }      % Create a cell with two elements
       a(n)=a(flip(n))         % One element are the two number at indices given by
                               % the second input array. This will be a 1x2 array
      {a(n)=a(flip(n)),a}      % Place those two in a cell together with the entire array a
                               % a is now updated, thanks to Octave's inline assignment
      {a(n)=a(flip(n)),a}{2}   % Return the second element

Jellyfish, 7 bytes
p
ZRi
i

Takes a list and a pair of indices.
Try it online!
Explanation
Jellyfish happens to have a "modify items at indices" function, Z, which does exactly what we need.
The two is grab the inputs from STDIN.
Z takes as arguments the second input, the reversal function R, and the list.
Then Z performs the modification, and p prints the result.

R, 38 bytes
function(x,a,b){x[c(a,b)]=x[c(b,a)];x}

Feels rather long, but I can't get it much shorter. Sadly it requires the explicit returning through x, requiring {} around the function body. pryr::f() doesn't recognise the need for x as function argument so doesn't work :/.

I think function(x,i)replace(x,i,rev(i)) would work, even with pryr syntax.

@Giuseppe Ah, I was looking for a convenient function to do the swap, but was searching with the wrong terms. Feel free to post that as an own answer.

@Giuseppe I think you need to do replace(x,i,x[rev(i)]), else you'll place the indices instead of their values.

Java 8, 48 bytes
(a,b,c)->{int t=a[b];a[b]=a[c];a[c]=t;return a;}

Input:
int[] a
int b
int c

How do you do lambdas with three arguments in Java?

@LeakyNun I made a custom class for it.

The same logic (and byte count) can be achieved with currying and no custom classes. Try it online!

Those instructions modify the array, which means you're allowed to not return the array, which will save you a few bytes.

@Okx could you show your code for the custom class?

@LeakyNun I'm not Okx, but here is a Try it now example with Okx's current answer and custom interface.

And @Neil is right, you can get rid of the return: (a,b,c)->{int t=a[b];a[b]=a[c];a[c]=t;}

And based on Carlos Alejo's amazing C# answer (with @Neil's help), you can make it even shorter by getting rid of the temporary variable: (a,b,c)->a[b]+=a[c]-(a[c]=a[b]) (31 bytes)

cough cough Collections::swap is 17 bytes... at least assuming this holds for this challenge...

@SocraticPhoenix yep, but... the full name is java.util.Collections::swap, so 27 bytes, not 17. Go ahead, post it :)

@OlivierGrégoire still shorter :)

@SocraticPhoenix Yeah, of course, that's why I said to post it! You'll get at least one +1, mine ;)

x86 Machine Code, 10 bytes
8B 04 8B 87 04 93 89 04 8B C3

This is a function written in 32-bit x86 machine code that swaps the values at the specified indices in a given array. The array is modified in-place, and the function does not return a value.
A custom calling convention is used, requiring the function's parameters to be passed in registers:

The address of the array (pointer to its first element) is passed in the EBX register.
The zero-based index of element A is passed in the ECX register.
(Assumed to be a valid index.)
The zero-based index of element B is passed in the EDX register.
(Assumed to be a valid index.)

This keeps the size down and complies with all formal requirements, but does mean that the function cannot be easily called from other languages like C. You'd need to call it from another assembly-language program. (You could rewrite it to use any input registers, though, without affecting the byte count; there's nothing magical about the ones I chose.)
Ungolfed:
8B 04 8B     mov  eax, DWORD PTR [ebx+ecx*4]   ; get value of element A
87 04 93     xchg eax, DWORD PTR [ebx+edx*4]   ; swap element A and element B
89 04 8B     mov  DWORD PTR [ebx+ecx*4], eax   ; store new value for element A
C3           ret                               ; return, with array modified in-place

R, 34 bytes
pryr::f(`[<-`(a,c(m,n),a[c(n,m)]))

JavaScript (ES2015), 66 57 49 bytes
A different (alas, longer) approach than previous JavaScript answers
(s,h,o,w=s.splice.bind(s))=>w(h,1,...w(o,1,s[h]))

Source
const swap = (arr, a, b, splice) => {
  splice(a, 1, ...splice(arr[b], 1, arr[a]))
}

(s,h,o,w=s.splice.bind(s))=>w(h,1,...w(o,1,s[h])) 49 bytes

Forgot about them default args. Thanks!

Mathematica, 32 bytes
(a=#;a[[{##2}]]=a[[{#3,#2}]];a)&

a[[{##2}]]==a[[{#3,#2}]] should be a[[{##2}]]=a[[{#3,#2}]] (using Set, not Equals)

Swift, 111 65 bytes (0-indexed)
Swift is already notorious for being one of the worst code-golf languages, but here is a function that makes use of ternary expressions:
func t(l:[Int],m:Int,n:Int){var r=l;r[m]=l[n];r[n]=l[m];print(r)}

Check it out!
- Usage: t(l:[1,2,3],m:0,n:1).

Using a default param for r would save you bytes and you can also just mutate the passed array (AFAIK swift array are pass by value)

Default parameter in Swift? How can I do that?

And parameters are constants in Swift @Downgoat

k (kona), 13 bytes
{x[y]:x@|y;x}

Pretty basic, but it works. Ex:
k){x[y]:x@|y;x}[1 2 3 4; 0 1]
2 1 3 4

Perl 5, 32 bytes
-3 bytes thanks to @Dom Hastings!
30 bytes of code + -pa flags.
@F[pop@p,@p]=@F[@p=<>];$_="@F"

Try it online!
Quite straight forward, using array slices.

Hey hey, tinkered with this a little and managed to save 3 bytes! @F[pop@p,@p]=@F[@p=<>];$_="@F".

@DomHastings Hmm, nice, as always! Thanks :)

C, 42 bytes
Modify the array in place with a temp value.
f(r,m,n){int*a=r;r=a[m];a[m]=a[n];a[n]=r;}

C, 60 58 bytes
A little more interesting, not using any temp value...
f(a,m,n)int*a;{a[m]+=a[n];a[n]-=a[m];a[n]*=-1;a[m]-=a[n];}

C, 49 bytes
Using XOR
f(a,m,n)int*a;{a[m]^=a[n];a[n]^=a[m];a[m]^=a[n];}

Heh, I was just about to post f(x,i,j,t)int*x;{t=x[i];x[i]=x[j];x[j]=t;}.

@Dennis you saved me two bytes on the other solution, thanks!

Wouldn't the second solution be shorter (and safer) with ^?

-1 for the XOR version using a define instead of a function #define X(x,y,z)x[y]^=x[z],x[z]^=x[y],x[y]^=x[z]

f(r,m,n){int*a=r;r=a[m];a[m]=a[n];a[n]=r;} is broken: SIGSEGV.

@BodoThiesen compile it for 32bits with -m32
Try it online!

-m32 only works if there is a 32 bit mode available. So, you should at least clarify, that your solution is a x86_32 only solution.

Pyth, 17 8 bytes
Saved 9 bytes thanks to Leaky Num.
@LQ.rUQE

Test it online!
This is 0-indexed, and the indices are provided as a tuple: (n, m).
Explanations
@LQ.rUQE

     UQ     # Generate [0, 1, 2, ..., len(input)]
       E    # Get the indices as the tuple (1, 2)
   .r       # Translate each element of UQ to its cyclic successor in E
            # Now the indices are permuted (e.g. [0, 2, 1, ..., len(input)]
@LQ         # For each index, get it's value. Implicit print

8 bytes: @LQ.rUQE

@LeakyNun It's so different I think you can post it for yourself!

I'm the OP; I don't post on my own challenge.

Julia 0.5, 20 bytes
x*t=x[t]=x[t[[2,1]]]

Try it online!

Mathematica, 20 bytes
#~Permute~Cycles@#2&

Pure function taking two arguments in the following 1-indexed (and possibly abusive) format: the second test case [5,8,9]; 0 2; [9,8,5] would be called as
#~Permute~Cycles@#2& [ {5,8,9} , {{1,3}} ]

(spaces are extraneous and just for visible parsing). Permute is the builtin function that applies a permutation to a list, and Cycles[{{a,b}}] represents the permutation that exchanges the ath and bth elements of a list and ignores the rest.

What do the ~ do?

~ is Mathematica's infix notation for a binary function: x~f~y means the same thing as f[x,y].

awk, 31 bytes
{c=$a;$a=$b;$b=c;a=$1;b=$2}NR>1

Try it online!
Takes input in the format
1 2
1 2 3 4

and outputs as
2 1 3 4

(1-indexed).
Explanation
The entire program is a missing pattern with an action followed by a pattern with a missing action.
Since a missing pattern runs on each line, the code inside the braces runs for both input lines. The c=$a;$a=$b;$b=c; part swaps the two values at indices a and b (through the temporary variable c). This only has an effect on the second line, since on the first line a and b are not yet defined. The a=$1;b=$2 part defines a to be the first field and b to be the second field, which sets the appropriate values for the first part to run on the second line.
Since a missing action is equivalent to {print}, the pattern prints every line it matches. This pattern in particular is NR>1: that is, print whenever the line number is greater than 1, which happens to be line 2. This runs after the swapping of values has taken place, thus completing the task.

Japt, 15 bytes
£gY¶V?W:Y¶W?V:Y

Test it

Explanation
       :Implicit input of array U and integers V & W
£      :Map over the array (with Y being the index of the current element), replacing each element with...
g      :  The element in the array at index...
Y¶V?W  :    W, if Y equals V
:Y¶W?V :    or V, if Y equals W
:Y     :    or just Y otherwise
       :Implicit output of modified array

Nice technique, looks a little verbose though... but I can't find a way to golf it.

@ETHproductions: yeah, I'm still convinced there's a shorter way, just haven't had the time to come back and find it and it looks like I won't until tomorrow :(

q/kdb+, 17 bytes
Solution:
{@[x;(|)y;:;x y]}

Example:
q){@[x;(|)y;:;x y]}[1 2 3 4;0 1]
2 1 3 4

Explanation:
A q version of the k answer by Simon. Apply the assign : function to x at indices reverse-y with value of x indexed at y. Broken down you can see more clearly:
q)x:1 2 3 4
q)y:0 1
q)x y
1 2
q)(|)y
1 0
q)x(|)y
2 1
q)@[x;(|)y;:;x y]
2 1 3 4

Powershell, 64 49 bytes
$f=$args;$t=$f[0];($t[$f[1]],$t[$f[2]]=$t[$f[2]],$t[$f[1]])>$;$t
param($a,$b,$c)($a[$b],$a[$c]=$a[$c],$a[$b])>$;$a

At least somewhat better solution.
Also I have no idea why redirecting to $ even works ^^

V, 10 bytes
ÀGYÀGVpVp

Try it online!
This takes input with each number to a line, and indices as program arguments. 1-indexed.

C, 42 bytes (one extra argument on function call)
f(a,m,n,t)int*a;{t=a[m];a[m]=a[n];a[n]=t;}

Try it online
C, 44 bytes
f(a,m,n)int*a;{int t=a[m];a[m]=a[n];a[n]=t;}


text:
Sink that Bismark! (Errr, pig)
Pig-latin is a made-up language that is translated into by moving the first letter of a word to the end and adding ay to the end. For example: hello translates into pig-latin as ellohay. Therefore, translating pig-latin back into English is dropping the ay at the end and moving the last letter to the start (like oodbyegay to goodbye). When writing it out, some people will put a - at the end before moving the first letter for clarity, so it reads (for example) ello-hay instead of ellohay for hello. We will use this hyphenated version for this challenge.
Objective
Undo a pig-latin string.
Instructions
Write a program/function that takes one argument, a single word in the form of a string. If that word is in pig-latin, the program/function must output (i.e. return or print it) the non-pig-latin word. If it isn't pig-latin, output the word as-is.
Pig-latin for this challenge will be in the following format:
ello-hay

If the word ends in -*ay, it is pig-latin, where the * is a single wildcard character.
Non-letter characters should be treated as a normal letter. For multiple dashes, ignore all except the last.
Examples
Using fictitious unpig() Python function for demo.
unpig("ello-hay")    #=> hello
unpig("hello-world") #=> hello-world
unpig("hello")       #=> hello
unpig("pple-aay")    #=> apple
unpig("apple")       #=> apple
unpig("ig-Stay")     #=> ig-Stay (+1 to ETHproductions for noticing.)
unpig("ello----hay") #=> hello---
unpig("la$s-gay")    #=> gla$s
unpig("ig-pay-yay")  #=> yig-pay

Rules

Standard loopholes apply
This is code-golf, so shortest code wins.
Built-in functions (specifically for this purpose) are not permitted.
Use header # Language, XX bytes

Leaderboard

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

JavaScript (ES6), 34 bytes
s=>s.replace(/(.*)-(.)ay$/,'$2$1')

Test cases

let unpig =

s=>s.replace(/(.*)-(.)ay$/,'$2$1')

console.log(unpig("ello-hay"))    // => hello
console.log(unpig("hello-world")) // => hello-world
console.log(unpig("hello"))       // => hello
console.log(unpig("pple-aay"))    // => apple
console.log(unpig("apple"))       // => apple
console.log(unpig("ig-Stay"))     // => ig-Stay

Is this a function? I don't do JS (ES6).

I literally had the exact same solution, except using double quotes instead of single quotes

Nvm. Great start!

@juniorRubyist Its an anonymous function that can be assigned to any variable(in this case 'unpig').

Seems pretty unbeatable.

PHP, 61 bytes
function f($v){echo preg_replace("#(.*)-(.)ay$#","$2$1",$v);}

Try it online!
PHP, 46 bytes
without a function

<?=preg_replace("#(.*)-(.)ay$#","$2$1",$argn);

Try it online!

Must be a function. Invalid.

@CalculatorFeline fixed

Actually, 22 minutes ago, your 46 byte solution became valid.

Python 2, 48 46 bytes
-2 bytes thanks to xnor.
These are anonymous lambda functions that can be assigned to, say unpig.
lambda s:[s,s[-3]+s[:-4]][s[-4]+s[-2:]=="-ay"]

Try it online!
Regex solution, 49 bytes
lambda s:re.sub('(.*)-(.)ay',r'\2\1',s)
import re

Try it online!

You don't need to use and/or when short-circuiting isn't required. Selecting from a list works and is shorter.

Python 2.7, 68 55 52 bytes
def up(s):print(s,s[-3]+s[:-4])[s[-4]+s[-2:]=="-ay"]

Uses a ternary-like operator.
-13 bytes thanks to officialaimm and an update in rules.
-3 Changed ternary operator. See https://stackoverflow.com/a/470376/3210045.

s[0:len(s)-4] can be replaced by just s[:-4]. And few spaces can be avoided by squeezing ]if and "else

05AB1E, 15 bytes
D'-¡θ¦„ayQi¨¨Á¨

Try it online!
θ is replaced by ®è on TIO since it hasn't been pulled there yet.

Best golfing! You win.

Lexurgy, 29 bytes
p:
([]+)$1 \- []$2 ay=>$2 $1

Python 3, 59 60 bytes

1 byte added thanks to @Erik the Outgolfer: $ to ensure ig-payyay outputs the same and not yig-pa

lambda a:a[-3]+a[:-4]if re.search("-.ay$",a)else a
import re

Try it online!

Japt, 18 17 bytes
Just the same RegEx replacement as everyone else, first posted by Arnauld.
r"(.*)-(.)ay$"ÏiZ

Try it

I had q$/-(.)ay/$ w q for 15 but unfortunately that fails on inputs containing multiple copies of -<char>ay (it corrects them all rather than just the last). Oh well...

Jelly, 22 17 bytes
ṖṖṙ-Ṗµṣ”-ṪḊ⁼⁾ayµ¡

Try it online!

Perl 6, 22 bytes
{S/(.+)\-(.)ay$/$1$0/}

Basic regular expression solution.

Java (OpenJDK 8), 146 bytes
s->{Matcher m=Pattern.compile("(.*)-(.)ay").matcher(s);String g="";while(m.find())g=m.group(1);return (g!=""?s.charAt(s.lastIndexOf('-')+1)+g:s);}

Try it online!

05AB1E, 15 14 bytes
I know there already is a 15-bytes 05AB1E answer. I haven't found anything shorter yet, but since I found two 15-byters with a different approach, I figured I'd post them as well EDIT: Found a 14-byter. But I'll still mention the two 15-byters either way:
œ6è…-ayÅ¿i¨¨Á¨

Very slow for larger inputs.
Try it online or verify all test cases. (The test suite uses S6.IJ instead of œ6è, since it's A LOT faster, but basically does the same. Unfortunately, builtin .I doesn't work on strings - apparently.)
4(è«…ay-Å¿i¨¨Á¨

Try it online or verify all test cases.
`«ŠŠ«…ay-QiJÁëI

Try it online or verify all test cases.
Explanation:
œ               # Get all permutations of the (implicit) input-string
 6è             # Only leave the 7th one (0-based 6th)
   …-ayÅ¿i      # If this permutation ends with "-ay":
          ¨¨    #  Remove the last two characters from the (implicit) input-string ("ay")
            Á   #  Rotate it once towards the right
             ¨  #  Rotate the last character ("-")
                #  (after which it is output implicitly as result)
                # (implicit else)
                #  (implicitly output the implicit input unchanged)

4(è             # Get the 0-based -4'th character of the (implicit) input
   «            # Append it to the (implicit) input
    …ay-Å¿i     # If this string ends with "ay-"
           ¨¨Á¨ #  Same as above

`               # Push all characters of the (implicit) input separately to the stack
 «              # Merge the last two together
  ŠŠ            # Triple-swap the last three items twice (a,b,c to b,c,a)
    «           # Merge the top two together
     …ay-Qi     # If this is equal to "ay-":
           J    #  Join the other characters on the stack together
            Á   #  And rotate it once towards the right
          ë     # Else:
           I    #  Push the input
                # (after which the top of the stack is output implicitly as result)

Pip, 18 bytes
a~`-(.)ay$`?$1.$`a

Try It Online!
Explanation
a~`-(.)ay$`?$1.$`a
a                   First command-line argument
 ~                  Find first match
  `-(.)ay$`         of this regex (capture the letter in group 1)
           ?        If a match was found:
            $1        Contents of group 1
              .       Concatenated with
               $`     Portion of the string before the match
                    Else:
                 a    The string unchanged

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:
Convert phones to calculation
Introduction
OnePlus is a Chinese smartphone manufacturer founded in December 2013. Their latest phone, OnePlus 5, was unveiled on June 20, 2017.
I am sure you have seen that the name of the phone can easily be translated to a sum.
OnePlus can be written like 1+ thus OnePlus 2 = (1+ 2) = 3
Input
The name of one OnePlus phone. The above list in the only possible input
OnePlus 1
OnePlus 2
OnePlus X
OnePlus 3
OnePlus 3T
OnePlus 5

Output
The sum of the name (a number not a string)
OnePlus 1 => 2
OnePlus 2 => 3
OnePlus X => an integer
OnePlus 3 => 4
OnePlus 3T => 27 (T = Today = 23 thus 1+3+23=27)
OnePlus 5 => 6

Rules
The input can be written in different versions. This applies to every names. For example
OnePlus 1
OnePlus1
One+ 1
One+1
1+ 1
1+1

The output for OnePlus X is an integer that should be different from the other phones names. Whatever you want except 2,3,4,27,6
The T in OnePlus 3T will always be 23 which is the day I am posting this.
This is code-golf, so the shortest solution (in bytes) wins.

Is One case-sensitive? What about inputs like One                    +   1(arbitrary number of spaces between the tokens)?

Do we have to support all different versions?

@officialaimm One and Plus are case-sensitive. You only have to rely to the provided format

@EriktheOutgolfer All the versions provided in the rules sections. Not less, Not more

@Downvoter Can I have an explanation ?

Can the being considered advertisement? Or Spam?

@sergiol If this is the case, I will remove my post. I was just trying to find a good challenge. In anyway, I am linked to the OnePlus company

Didn't understand. You are linked or not linked? => @Weedoze

@sergiol I am not linked. Sorry for the bad English hehe

How are there answers to this? Am I missing something or just stupid?

"The input can be written in different versions" has two issues. Firstly it's not clear whether this is a restriction (your code must handle all of them) or a concession (you choose which one to handle). Secondly, specification by example is not specification.

05AB1E, 10 bytes
0Uθ.VT26:>

Try it online!
θ has been replaced by ®è on TIO since it hasn't been pulled there yet. Alternatively, ¤ would work too.
Explanation:
0Uθ.VT26:> "Accepts a single line from STDIN"\
0          "Push 0"\
 U         "Assign to X"\
  θ        "(implicit input)"\ "Take the last element"\
   .V      "Eval as 05AB1E code"\
     T     "Push 10"\
      26   "Push 26"\
        :  "Infinitely replace"\
         > "Increment"\

Though the question is not so clear, in your solution, OnePlus 4T is outputting same as OnePlus 3T

@officialaimm I don't think we'll ever get such input.

Retina, 26 16 bytes
-10 bytes thanks to @MartinEnder
O
1
T
995
.
$*
1

Try it online!

The best way to write a test suite is to put %(G\`` in the header, which simply applies the program to each line individually. You can shorten \D\n\n\dto.and the final stage to a simple1`: https://tio.run/##K0otycxL/K@q4Z7w35/LkCuEy9LSlEuPS0WLy/D/f/@81ICc0mIFQy4YywjOioCzjBGsEDjTFAA

@MartinEnder thanks a lot.

Perl 5, 21 bytes
20 bytes of code + -p flag.
$_=/\d$/?$&+1:27*/T/

Try it online!
If the input ends with an integer (/\d$/), then we add one to it ($&+1) and outputs it. Otherwise, we output 27*/T/ which is 27 if the inputs contains a T, and 0 otherwise.

C# (.NET Core), 138 bytes
using System.Linq;s=>s.Replace("One","1").Replace("Plus","+").Replace("T","+23").Replace("X","9").Split('+').Select(e=>int.Parse(e)).Sum()

Try it online!

It's a lot shorter to just check the last character of the input. Is it a digit: output that digit + 1; is it T: output 27; else / is it X: output an unique digit like 0 or 9.

Java 8, 79 61 bytes
s->{int x=s.charAt(s.length()-1);return x<58?x-47:x<85?27:9;}

Explanation:
Try it here with all possible test cases.
s->{                             // Method with String parameter and integer return-type
  int x=s.charAt(s.length()-1);  //  Get the last characters of the input
  return x<58?                   //  If it's a digit:
          x-47                   //   Return that digit + 1
         :x<85?                  //  Else if it's a 'T':
          27                     //   Return 27
         :                       //  Else (it's a 'X')
          9;                     //   Return 9 (unique digit other than 2,3,4,6,27)
}                                // End of method

C (gcc), 65 63 48 bytes
f(char*s){s+=strlen(s)-1;s=*s?*s^84?*s-47:27:9;}

Try it online!

Excel VBA, 87 51 bytes
Anonymous VBE immediate window function that takes input from cell [A1] and outputs OnePlus math to the VBE immediate window
i=Asc(Right([A1],1)):?IIf(i<58,i-47,IIf(i<85,27,9))

Old Version
Anonymous VBE immediate window function that takes input from cell [A1] that and outputs OnePlus math to the VBE immediate window
?Application.Evaluate("="&Replace(Replace(Replace([A1],"One",1),"Plus","+"),"T","+23"))

Input/Output
As a result of the Application.Evaluate call this solution is afforded access to all of the Excel WorkSheet Functions
[A1]="OnePlus 3T"
?Application.Evaluate("="&Replace(Replace(Replace([A1],"One",1),"Plus","+"),"T","+23"))
 23

[A1]="OnePlusPi()"
?Application.Evaluate("="&Replace(Replace(Replace([A1],"One",1),"Plus","+"),"T","+23"))
 4.14159265358979

[A1]="One+Day(Now())"
?Application.Evaluate("="&Replace(Replace(Replace([A1],"One",1),"Plus","+"),"T","+23"))
 26

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


text:
Does this line pass through that square?
Divide the first quadrant (including the positive x-axis, the positive y-axis, and the origin) into 1x1 grids, with each grid labelled by the coordinates of its bottom-left corner, as demonstrated below:

Note that each grid contains its boundaries and its vertices. Using mathematical symbols, the grid labelled (m,n) would represent the square {(x,y) | m ≤ x ≤ m+1, n ≤ y ≤ n+1}.

Given a straight line in the form of ax+by+c=0 with integers a, b, and c, and a grid represented by (m,n), output whether the line passes through the grid, i.e. whether any point in the given grid is on the line.

a  b  c m n output
1  1  0 0 0 true
1  1  0 1 1 false
1  1  0 0 2 false
1  1 -3 0 1 true
1  1 -3 0 0 false
2 -1  0 1 1 true
2 -1  0 1 0 false
2 -1  0 0 2 true
2 -1  0 0 1 true
2 -1  0 1 2 true
2  0 -1 0 0 true
2  0 -1 0 1 true
2  0 -1 0 2 true
2  0 -1 1 0 false
2  0 -1 1 1 false
0  2 -1 0 0 true
0  2 -1 1 0 true
0  2 -1 2 0 true
0  2 -1 0 1 false
0  2 -1 1 1 false
1  0 -1 0 0 true
1  0 -1 0 1 true
1  0 -1 0 2 true
1  0 -1 1 0 true
1  0 -1 1 1 true

Please suggest more testcases in the comments.

This is code-golf. Shortest answer in bytes wins. Standard loopholes apply.

Of course we should be able to assume that not both a and b are 0, since then if c is zero there can be infinite lines while if c is non-zero there can be no line at all.

Can I get input as two or more arrays, say [a, b, c] (the line) and [m, n] (the square)?

@EriktheOutgolfer I'm surprised that isn't in meta.

Related

Strongly related.

Is it ok if input is required to be a float (ex. 2.0 instead of 2)

@Dopapp no, it is not.

Python 3, 84 66 bytes
First golf, first fail (maybe).
Thanks to Rod for shaving off 18 bytes by using a function instead of direct input.
def f(a,b,c,m,n):f=-(a*m+c)/b;g=f-a/b;print(min(f,g)<=n<=max(f,g))

Try it online!
Explanation:
Basically we calculate the value of the line function for m and m+1, if n is inbetween the values, then the list must pass through it at some point.
Would be much better if the language had some simpler way to input multiple integers.

You can use a function instead input()

Welcome to PPCG!

Doesn't this need to check against n+1 as well as m+1?

Division by zero when b is 0.

Also, it doesn't pass several test cases highlighted by Leaky Nun.

@OlivierGrégoire which test cases did I highlight?

@LeakyNun all of them, they're all in another background color :p Ok... maybe "highlighted" isn't the appropriate word, but all in all, several test cases fail with this method. Using the TIO and repeating the print function for each test case shows that.

wrapper

@LeakyNun, I'm confused, do you agree that this does not pass all the test cases?

@Dopapp yes, I agree.

In addition to Olivier Grégoire's observation, wouldn't dividing by b give incorrect results whenever b is not a factor of a*m+c because of int vs. float division?

Jelly, 10 bytes
ż‘{Œpæ.ṠE¬

Try it online!
Background
Like other answers before mine, this relies on the fact that a straight line divides the plane into two semi-planes. The rectangle is either contained in one of these semi-planes (no intersection with the line) or intersects both semiplanes (and thus the line that separates them.
How it works
ż‘{Œpæ.ṠE¬  Main link. Left argument: [m, n]. Right argument: [a, b, c]

 ‘{         Increment left; yield [m+1, n+1].
ż           Zipwith; yield [[m, m+1], [n, n+1]].
   Œp       Cartesian product; yield [[m, n], [m, n+1], [m+1, n], [m+1, n+1]].
     æ.     Take the dot products with [a, b, c], mapping each [x, y] to ax+by+c.
       Ṡ    Take the signs.
        E   Test the signs for equality.
         ¬  Logical NOT.

Python 2, 59 bytes
lambda a,b,c,m,n:min(0,a,b,a+b)<=-a*m-b*n-c<=max(0,a,b,a+b)

Try it online!
We can tell which side of the line a point is by the sign of a*x+b*y+c. The line passes through the square (counting touching) unless all four vertices (m,n),(m,n+1),(m+1,n),(m+1,n+1) are strictly on the same side of the line. We can plug these values in an extract out the constant a*m+b*n+c that appears in all four:
a*m+b*n+c
a*m+b*n+c+a
a*m+b*n+c+b
a*m+b*n+c+a+b

So, the line passes through the square unless these four values are all positive or all negative. So, it suffices for their minimum to be <=0 and maximum to be >=0.
min(a*m+b*n+c,a*m+b*n+c+a,a*m+b*n+c+b,a*m+b*n+c+a+b)<=0<=max(a*m+b*n+c,a*m+b*n+c+a,a*m+b*n+c+b,a*m+b*n+c+a+b)

Subtracting the common a*m+b*n+c from each part gives the code.
A slightly longer approach is to check whether the set of signs (+,0,-) has length at least 2.
Python 2, 62 bytes
lambda a,b,c,m,n:len({cmp(a*m+b*n+c,-d)for d in(0,a,b,a+b)})>1

Try it online!

Mathematica, 60 55 bytes
Solve[m#+n#2==-#3&&#4<=m<=#4+1&&#5<=n<=#5+1,{m,n}]!={}&

-5 bytes thanx to @MartinEnder
input form

[a,b,c,m,n]

Ah, I wish every language had a Solve function...

Batch, 66 bytes
@cmd/cset/a"q=%1*%4+%2*%5+%3,((-(q+%1)*(q+%2)&-q*(q+%1+%2))>>31)+1

Explanation: We consider the values taken by the equation at the four corners of the cell. If the line does not intersect the cell, then all four values have the same sign, but if it does intersect the cell, then at least one value will be zero or the opposite sign. The comparison is simplified by multiplying pairs of opposite corners, then if both values are positive then the line does not intersect the cell. Some bit-twiddling then converts the multiplications into an overall result.

Python, 54 bytes
lambda a,b,c,m,n:abs(2*(a*m+b*n+c)+a+b)<=abs(a)+abs(b)

Try it online!
(Thanks to xnor for the testing script.)
How it works
The line goes through m + 1/2 + x, n + 1/2 + y if and only if
a⋅(m + 1/2 + x) + b⋅(n + 1/2 + y) + c = 0
⇔ 2⋅(a⋅m + b⋅n + c) + a + b = −2⋅a⋅x − 2⋅b⋅y.
This is possible for some |x|, |y| ≤ 1/2 if and only if |2⋅(a⋅m + b⋅n + c) + a + b| ≤ |a| + |b|.

Java (OpenJDK 8), 71 bytes
(a,b,c,x,y)->(0<a?0:a)+(0<b?0:b)<=(x=-a*x-b*y-c)&x<=(0>a?0:a)+(0>b?0:b)

Try it online!
Port of xnor's Python solution.
Original solution, using Java's shape/line intersection built-in (108 bytes)
(a,b,c,x,y)->b==0?x<=-c/a&-c/a<=x+1:new java.awt.Rectangle(x,y,1,1).intersectsLine(x,c=(c+a*x)/-b,x+1,c-a/b)

Try it online!
Credits

-8 bytes thanks to ceilingcat

Mathematica, 50 bytes
-4<Tr@Sign[Tuples@{{#,#+1},{#2,#2+1}}.{##4}+#3]<4&

Try it online!
Takes m, n, c, a, b as input in that order.
Explanation: Tuples@{{#,#+1},{#2,#2+1}} makes a list of the coordinates of the four corners of the square, then taking the dot product with .{##4} (which means {#4, #5}) and adding +#3 computes ax + by + c for x,y at each corner. If the line passes through the point, this is zero; if the line is further from the origin, it's negative; and if the line is nearer to the origin, it's positive — therefore we check the Signs of these four values. The line passes outside the square if and only if all four values are 1 or all four are -1, so we check that their sum is strictly between -4 and 4.
(This answer is vaguely inspired by my answer to this question.)

Python 2, 147 110 bytes
def f(a,b,c,m,n):
 if b:d=sorted((-a*x-c)/float(b)for x in(m,m+1));return d[0]-1<=n<=d[1]
 return m<=-c/a<=m+1

And a huge thanks to Leaky Nun!
TIO.

131 bytes

121 bytes

@LeakyNun, wow awesome!

114 bytes

110 bytes

@LeakyNun, I'm speechless.


text:
Plant trees in a park - As fast as you can!
This challenge is inspired by this app. The test cases are borrowed from that app.

This is a fastest-code challenge, where the objective is to solve the largest test cases in the least amount of time. There are provided some smaller test cases, so that people might test their algorithms faster.

You'll be given a square input grid, of dimensions n-by-n where 9 <= n <= 12. This grid will be divided into n areas, where the cells of each area has a unique identifiers (I'll use lower case letters from a-l in the the text here, but you may choose whatever you like, for instance integers 1-12).
The input may look like this (optional input format):
aabbbbbcc
adddbbbcc
adeeecccc
adddefgcc
hhhdifggg
hdddifffg
hhhiifffg
hihiifffg
iiiiiiggg

Or, easier to visualize:

Challenge:
You are to place 2*n trees in this park, according to the following rules:

There shall be exactly 2 trees per column, and 2 trees per row
All areas shall have exactly 2 trees.
No trees can be adjacent to another tree, vertically, horizontally or diagonally

The solution to the layout above is:

Note: There is only one solution to each puzzle
Additional rules:

The input and output formats are optional

The output might for instance be a list of indices, a grid with 1/0 indicating if there's a tree in that position, or a modified version of the input where the trees are indicated

The execution time must be deterministic
The program must finish withing 1 minute at @isaacg's computer

Specs: 4 CPUs, i5-4300U CPU @ 1.9 GHz, 7.5G of RAM.

In case your program can't solve the two largest test case in one minute each then the time for the second largest (n=11) will be your score. You'll lose against a solution that solves the largest case.

Test cases:
I might edit this list if submissions seems to be customized to fit these test cases.
12-by-12:
--- Input ---
aaaaabccccdd
aaaaabccccdd
aaaaabbbbddd
eeeafffgbghh
eeaafffgbghh
eefffffggghh
eeefijffghhh
iieiijjjjkhh
iiiiijjjjkhk
lljjjjjjjkkk
llllllkkkkkk
llllllkkkkkk
--- Solution ---
aaaaabcccCdD
aaaaaBcCccdd
aAaaabbbbdDd
eeeaffFgBghh
eeAaFffgbghh
eefffffGgGhh
EeefijffghhH
iiEiIjjjjkhh
IiiiijjjjkHk
lljJjJjjjkkk
lLllllkkKkkk
lllLllKkkkkk

11-by-11:
--- Input ---
aaaaaaabbcc
adddabbbbcc
edddbbbbbbc
eddddbbbbbb
effffggghhh
effffgghhii
eefffjjhhii
eeeejjjhhii
eeejjjjkiii
jjjjjjkkiii
jjjjjkkkiii
--- Solution ---
aaAaaaabbCc
adddAbBbbcc
eDddbbbbbbC
eddDdBbbbbb
effffggGhHh
eFfffGghhii
eefFfjjhHii
EeeejjjhhiI
eeEjjjjKiii
JjjjJjkkiii
jjjjjkKkIii

10-by-10
--- Input ---
aaaaabccdd
aeaabbbccd
aeaabfbgcd
eeeaafggcd
eeeaafghcd
eeeiifghcd
ieiiigghcd
iiijighhcd
jjjjighhcd
jjjggghhdd
--- Solution ---
aaAaabccdD
aeaaBbBccd
aEaabfbgcD
eeeaaFgGcd
eEeAafghcd
eeeiiFghCd
IeiIigghcd
iiijigHhCd
JjJjighhcd
jjjgGghHdd

9-by-9
--- Input ---
aabbbbbcc
adddbbbcc
adeeecccc
adddefgcc
hhhdifggg
hdddifffg
hhhiifffg
hihiifffg
iiiiiiggg
--- Solution ---
aAbBbbbcc
adddbbBcC
adEeEcccc
AdddefgCc
hhhDiFggg
hDddifffG
hhhiIfFfg
HiHiifffg
iiiiiIgGg
--- Input ---
aaabbbccc
aaaabbccc
aaaddbcce
ffddddcce
ffffddeee
fgffdheee
fggfhhhee
iggggheee
iiigggggg
--- Solution ---
aaAbBbccc
AaaabbcCc
aaaDdBcce
fFddddcCe
fffFdDeee
fGffdheeE
fggfHhHee
IggggheeE
iiIgggGgg

"The input and output formats are optional, but should be the same" What does that mean? Can't I output a list of lists containing 1s and 0s for trees and non trees without caring about outputting the areas?

@Fatalize, edited. I think outputting a list of indices or a grid with 1/0 as you suggest is a good idea.

Information (if I calculate correctly): There are 3647375398569086976 configurations to put 24 trees in a 12*12 grid satisfy only (1): There shall be exactly 2 trees per column, and 2 trees per row, so a brute-force is probably impossible.

"shouldn't be a big problem": I personally think that it is. My current implementation solves the first test case in ~150ms and the 3rd one in 5s but fails to solve the last one (which is 'only' 11x11) in any reasonable amount of time. It would probably require some much more aggressive forward pruning -- and therefore a significant amount of additional code -- to complete within 1 minute.

@Arnauld, I changed the maximum to 11 since that's the largest test case. You may post your solution (as a valid, competing submission), but it will not win if someone posts a solution that solves all test cases, regardless of code length. Fair?

Stewie, we need bigger test cases. We have multiple answers in the smaller numbers of milliseconds.

@isaacg, I'm not sure I'm able to make larger test cases that are guaranteed to have only one unique solution while not being trivial :/ I'll see what I can come up with... Suggestions are appreciated.

Stewie, you might be able to make use of the solvers that have been made to check for uniqueness. Ask the people who made them if they can be adapted that way. Knowing whether something was unique would probably help composition.

Do you think 20x20 is a good fit? (Still not sure if I can make one, but I'll try :) )

JavaScript (ES6), 271 bytes
Takes input as an array of arrays of characters. Returns an array of bitmasks (integers) describing the position of the trees on each row, where the least significant bit is the leftmost position.
f=(a,p=0,r=[S=y=0],w=a.length)=>a.some((R,y)=>a.some((_,x)=>r[y]>>x&1&&(o[k=R[x]]=-~o[k])>2),o=[])?0:y<w?[...Array(1<<w)].some((_,n)=>(k=n^(x=n&-n))<=x*2|k&-k^k|n&(p|p/2|p*2)||r.some((A,i)=>r.some((B,j)=>A&B&n&&i<y&j<i))?0:(w=r[y],f(a,r[y++]=n,r),r[--y]=w,S))&&S:S=[...r]

Formatted and commented
f = (                                           // given:
  a,                                            //   - a = input matrix
  p = 0,                                        //   - p = previous bitmask
  r = [                                         //   - r = array of tree bitmasks
        S = y = 0 ],                            //   - S = solution / y = current row
  w = a.length                                  //   - w = width of matrix
) =>                                            //
  a.some((R, y) => a.some((_, x) =>             // if there's at least one area with more
    r[y] >> x & 1 && (o[k = R[x]] = -~o[k]) > 2 // than two trees:
  ), o = []) ?                                  //
    0                                           //   abort right away
  :                                             // else:
    y < w ?                                     //   if we haven't reached the last row:
      [...Array(1 << w)].some((_, n) =>         //     for each possible bitmask n:
        (k = n ^ (x = n & -n)) <= x * 2 |       //       if the bitmask does not consist of
        k & - k ^ k |                           //       exactly two non-consecutive bits,
        n & (p | p / 2 | p * 2) ||              //       or is colliding with the previous
        r.some((A, i) => r.some((B, j) =>       //       bitmask, or generates more than two
          A & B & n && i < y & j < i            //       trees per column:
        )) ?                                    //
          0                                     //         yield 0
        :                                       //       else:
          (                                     //
            w = r[y],                           //         save the previous bitmask
            f(a, r[y++] = n, r),                //         recursive call with the new one
            r[--y] = w,                         //         restore the previous bitmask
            S                                   //         yield S
          )                                     //
      ) && S                                    //     end of some(): return false or S
    :                                           //   else:
      S = [...r]                                //     this is a solution: save a copy in S

Test cases
This snippet includes an additional function to display the results in a more readable format. It is too slow to solve the last test case.
Expected runtime: ~5 seconds.

f=(a,p=0,r=[S=y=0],w=a.length)=>a.some((R,y)=>a.some((_,x)=>r[y]>>x&1&&(o[k=R[x]]=-~o[k])>2),o=[])?0:y<w?[...Array(1<<w)].some((_,n)=>(k=n^(x=n&-n))<=x*2|k&-k^k|n&(p|p/2|p*2)||r.some((A,i)=>r.some((B,j)=>A&B&n&&i<y&j<i))?0:(w=r[y],f(a,r[y++]=n,r),r[--y]=w,S))&&S:S=[...r]

format = (a, w) => a.map(n => [...('0'.repeat(w) + n.toString(2)).slice(-w)].reverse().join('')).join('\n')

console.log(format(f([
  [..."aabbbbbcc"],
  [..."adddbbbcc"],
  [..."adeeecccc"],
  [..."adddefgcc"],
  [..."hhhdifggg"],
  [..."hdddifffg"],
  [..."hhhiifffg"],
  [..."hihiifffg"],
  [..."iiiiiiggg"]
]), 9));

console.log(format(f([
  [..."aaabbbccc"],
  [..."aaaabbccc"],
  [..."aaaddbcce"],
  [..."ffddddcce"],
  [..."ffffddeee"],
  [..."fgffdheee"],
  [..."fggfhhhee"],
  [..."iggggheee"],
  [..."iiigggggg"]
]), 9));

console.log(format(f([
  [..."aaaaabccdd"],
  [..."aeaabbbccd"],
  [..."aeaabfbgcd"],
  [..."eeeaafggcd"],
  [..."eeeaafghcd"],
  [..."eeeiifghcd"],
  [..."ieiiigghcd"],
  [..."iiijighhcd"],
  [..."jjjjighhcd"],
  [..."jjjggghhdd"]
]), 10));

OP's note: This submission was made when the challenge was a code-golf challenge. It is therefore perfectly valid, even though it isn't optimized for the current winning criterion!

Timing: Takes over a minute on 11x11.

We're in a pickle, maybe you can help. Can you think of any way to generate nontrivial larger puzzle instances?

C, official time: 5ms for 12x12
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <omp.h>

#define valT char
#define posT int

#ifndef _OPENMP
#  warning Building without OpenMP support
#  define omp_get_max_threads() 1
#  define omp_get_num_threads() 1
#  define omp_get_thread_num() 0
#endif

#define MIN_THREADED_SIZE 11

static void complete(posT n, valT *workspace) {
    const posT s = n * 3 + 2;

    const valT *regions = workspace;
    valT *output = &workspace[n*2+1];

    for(posT y = 0; y < n; ++ y) {
        for(posT x = 0; x < n; ++ x) {
//          putchar(output[y*s+x] ? '*' : '-');
            putchar(regions[y*s+x] + (output[y*s+x] ? 'A' : 'a'));
        }
        putchar('\n');
    }

    _Exit(0);
}

static void solveB(const posT n, valT *workspace, valT *pops, const posT y) {
    const posT s = n * 3 + 2;

    const valT *regions = workspace;
    const valT *remaining = &workspace[n];
    valT *output = &workspace[n*2+1];

    for(posT r = 0; r < n; ++ r) {
        if(pops[r] + remaining[r] < 2) {
            return;
        }
    }

    for(posT t1 = 0; t1 < n - 2; ++ t1) {
        posT r1 = regions[t1];
        if(output[t1+1-s]) {
            t1 += 2;
            continue;
        }
        if(output[t1-s]) {
            ++ t1;
            continue;
        }
        if((pops[t1+n] | pops[r1]) & 2 || output[t1-1-s]) {
            continue;
        }
        output[t1] = 1;
        ++ pops[t1+n];
        ++ pops[r1];
        for(posT t2 = t1 + 2; t2 < n; ++ t2) {
            posT r2 = regions[t2];
            if(output[t2+1-s]) {
                t2 += 2;
                continue;
            }
            if(output[t2-s]) {
                ++ t2;
                continue;
            }
            if((pops[t2+n] | pops[r2]) & 2 || output[t2-1-s]) {
                continue;
            }
            output[t2] = 1;
            ++ pops[t2+n];
            ++ pops[r2];
            if(y == 0) {
                complete(n, &workspace[-s*(n-1)]);
            }
            solveB(n, &workspace[s], pops, y - 1);
            output[t2] = 0;
            -- pops[t2+n];
            -- pops[r2];
        }
        output[t1] = 0;
        -- pops[t1+n];
        -- pops[r1];
    }
}

static void solve(const posT n, valT *workspace) {
    const posT s = n * 3 + 2;

    valT *regions = workspace;
    valT *remaining = &workspace[n];
    valT *pops = &workspace[n*s];
//  memset(&remaining[n*s], 0, n * sizeof(valT));

    for(posT y = n; (y --) > 0;) {
        memcpy(&remaining[y*s], &remaining[(y+1)*s], n * sizeof(valT));
        for(posT x = 0; x < n; ++ x) {
            valT r = regions[y*s+x];
            valT *c = &remaining[y*s+r];
            valT *b = &pops[r*3];
            if(*c == 0) {
                *c = 1;
                b[0] = y - 1;
                b[1] = x - 1;
                b[2] = x + 1;
            } else if(x < b[1] || x > b[2] || y < b[0]) {
                *c = 2;
            } else {
                b[1] = b[1] > (x - 1) ? b[1] : (x - 1);
                b[2] = b[2] < (x + 1) ? b[2] : (x + 1);
            }
        }
//      memset(&output[y*s], 0, (n+1) * sizeof(valT));
    }
    memset(pops, 0, n * 2 * sizeof(valT));

    posT sz = (n + 1) * s + n * 3;
    if(n >= MIN_THREADED_SIZE) {
        for(posT i = 1; i < omp_get_max_threads(); ++ i) {
            memcpy(&workspace[i*sz], workspace, sz * sizeof(valT));
        }
    }

#pragma omp parallel for if (n >= MIN_THREADED_SIZE)
    for(posT t1 = 0; t1 < n - 2; ++ t1) {
        valT *workspace2 = &workspace[omp_get_thread_num()*sz];
        valT *regions = workspace2;
        valT *output = &workspace2[n*2+1];
        valT *pops = &workspace2[n*s];

        posT r1 = regions[t1];
        output[t1] = pops[t1+n] = pops[r1] = 1;
        for(posT t2 = t1 + 2; t2 < n; ++ t2) {
            posT r2 = regions[t2];
            output[t2] = pops[t2+n] = 1;
            ++ pops[r2];
            solveB(n, &regions[s], pops, n - 2);
            output[t2] = pops[t2+n] = 0;
            -- pops[r2];
        }
        output[t1] = pops[t1+n] = pops[r1] = 0;
    }
}

int main(int argc, const char *const *argv) {
    if(argc < 2) {
        fprintf(stderr, "Usage: %s 'grid-here'\n", argv[0]);
        return 1;
    }

    const char *input = argv[1];
    const posT n = strchr(input, '\n') - input;
    const posT s = n * 3 + 2;

    posT sz = (n + 1) * s + n * 3;
    posT threads = (n >= MIN_THREADED_SIZE) ? omp_get_max_threads() : 1;
    valT *workspace = (valT*) calloc(sz * threads, sizeof(valT));
    valT *regions = workspace;

    for(posT y = 0; y < n; ++ y) {
        for(posT x = 0; x < n; ++ x) {
            regions[y*s+x] = input[y*(n+1)+x] - 'a';
        }
    }

    solve(n, workspace);

    fprintf(stderr, "Failed to solve grid\n");
    return 1;
}

Compiled with GCC 7 using the -O3 and -fopenmp flags. Should have similar results on any version of GCC with OpenMP installed.
gcc-7 Trees.c -O3 -fopenmp -o Trees

Input and output format are as given in the question.
On my machine this takes 0.009s 0.008s 0.005s for the 12x12 example, and 0.022s 0.020s 0.019s to run all the examples. On the benchmark machine, isaacg reports 5ms for the 12x12 example using the original (non-threaded) version of the code.
Usage:
./Trees 'aaabbbccc
aaaabbccc
aaaddbcce
ffddddcce
ffffddeee
fgffdheee
fggfhhhee
iggggheee
iiigggggg'

Just a simple brute-force solver, working on one row at a time. It runs at a good speed by recognising impossible situations early (e.g. no region cells remaining, but less than 2 trees in the region).
The first update improves cache hits by putting related data close together in memory, and makes the possible-trees-remaining-in-segment calculations slightly smarter (now accounts for the fact that trees cannot be adjacent). It also extracts the outermost loop so that fewer special cases are needed in the hottest part of the algorithm.
The second update makes the outermost loop run in parallel across the available processors (using OpenMP), giving a linear speed boost. This is only enabled for n >= 11, since the overhead of spawning threads outweighs the benefits for smaller grids.

Official timing: 5ms for 12x12. If anyone else gets close, we'll need bigger test cases.

We're in a pickle, maybe you can help. Can you think of any way to generate nontrivial larger puzzle instances?

@isaacg Well from the illustrated example, it seems the original grids were made by placing trees first (in a knight pattern with minor changes in that example, but I guess any pattern with 2 trees per row & column would work) then fitting regions around them so that each region contains 2 trees. Seems like that should be a simple enough method for a human to follow for arbitrarily large grids.

In fact, looking again, it's not a knight pattern with minor changes, but a wrapping pattern where each tree is offset (1,2) from the previous. Once you have a pattern, you can permute rows and columns to make less structured solutions, just as long as it doesn't leave trees adjacent.

Java (OpenJDK 8), Official Timing: 1.2s on 12x12
edit: no longer code golf
import java.util.*;

// Callable method, takes an int[][] and modifies it
static void f(int[][] areas){
    List<List<BitSet>> areaBitSets = new ArrayList<>();
    List<List<BitSet>> areaTreeBitSets = new ArrayList<>();
    for(int i = 0; i < areas.length; i++){
        areaBitSets.add(new ArrayList<BitSet>());
        areaTreeBitSets.add(new ArrayList<BitSet>());
    }

    // Add a bitset to our list representing each possible square, grouped by area
    for(int i=0; i < areas.length; i++){
        for(int j=0; j < areas.length; j++){
            BitSet b = new BitSet();
            b.set(i*areas.length + j);
            areaBitSets.get(areas[i][j]).add(b);
        }
    }

    // Fold each set onto itself so each area bitset has two trees
    for(int i=0; i < areas.length; i++){
        for(int j=0; j<areaBitSets.get(i).size()-1; j++){
            for(int k=j+1; k <areaBitSets.get(i).size(); k++){
                if(canFoldTogether(areaBitSets.get(i).get(j),areaBitSets.get(i).get(k), areas.length)){
                    BitSet b = (BitSet)areaBitSets.get(i).get(j).clone();
                    b.or(areaBitSets.get(i).get(k));
                    areaTreeBitSets.get(i).add(b);
                }
            }
        }
    }

    // Starting with area 0 add each area one at a time doing Cartesian products
    Queue<BitSet> currentPossibilities = new LinkedList<>();
    Queue<BitSet> futurePossibilities = new LinkedList<>();
    currentPossibilities.addAll(areaTreeBitSets.get(0));

    for(int i=1; i < areaTreeBitSets.size(); i++){
        while(!currentPossibilities.isEmpty()){
            BitSet b= (BitSet)currentPossibilities.poll().clone();

            for(BitSet c: areaTreeBitSets.get(i)){
                if(canFoldTogether(b,c,areas.length)){
                    BitSet d=(BitSet)b.clone();
                    d.or(c);
                    futurePossibilities.add(d);
                }
            }
        }
        currentPossibilities.addAll(futurePossibilities);
        futurePossibilities.clear();
    }

    // Get final output and modify the array
    BitSet b = currentPossibilities.poll();
    for(int i=0; i<areas.length*areas.length; i++){
        areas[i/areas.length][i%areas.length] = b.get(i)?1:0;
    }
}

// Helper method which determines whether combining two bitsets
// will still produce a valid output
static boolean canFoldTogether(BitSet a, BitSet b, int size){

    // See if there are trees too close to each other
    int c=-1;
    while((c=a.nextSetBit(c+1))>=0){
        int d=-1;
        while((d=b.nextSetBit(d+1))>=0){
            int r1=c/size;
            int r2=d/size;
            int c1=c%size;
            int c2=d%size;

            int rDifference = r1>r2 ? r1-r2 : r2-r1;
            int cDifference = c1>c2 ? c1-c2 : c2-c1;
            if(rDifference<2 && cDifference<2)
                return false;
        }
    }

    // Check for row and column cardinality
    BitSet f,g;
    for(int i=0; i<size; i++){
        f = new BitSet();
        f.set(i*size,(i+1)*size);
        g=(BitSet)f.clone();
        f.and(a);
        g.and(b);
        f.or(g);
        if(f.cardinality()>2){
            return false;
        }

        f=new BitSet();
        for(int j = 0; j<size; j++){
            f.set(j*size+i);
        }
        g=(BitSet)f.clone();
        f.and(a);
        g.and(b);
        f.or(g);
        if(f.cardinality()>2){
            return false;
        }
    }

    return true;
}

Try it online!
TIO link is for the 12x12 test case.  TIO reports 2.429s for the run time.
Takes an array of integers as the input and modifies the array to contain 1s for trees and 0s for non-trees.
This runs for all testcases.  The largest testcase runs on my machine in less than a second, although I have a pretty powerful machine
Test code for the 12x12, can modify for others
public static void main(String[] args){
    int[][] test = {{0,  0,  0,  0,  0,  1,  2,  2,  2,  2,  3,  3},
            {0,  0,  0,  0,  0,  1,  2,  2,  2,  2,  3,  3},
            {0,  0,  0,  0,  0,  1,  1,  1,  1,  3,  3,  3},
            {4,  4,  4,  0,  5,  5,  5,  6,  1,  6,  7,  7},
            {4,  4,  0,  0,  5,  5,  5,  6,  1,  6,  7,  7},
            {4,  4,  5,  5,  5,  5,  5,  6,  6,  6,  7,  7},
            {4,  4,  4,  5,  8,  9,  5,  5,  6,  7,  7,  7},
            {8,  8,  4,  8,  8,  9,  9,  9,  9,  10,  7,  7},
            {8,  8,  8,  8,  8,  9,  9,  9,  9,  10,  7,  10},
            {11,  11,  9,  9,  9,  9,  9,  9,  9,  10,  10,  10},
            {11,  11,  11,  11,  11,  11,  10,  10,  10,  10,  10,  10},
            {11,  11,  11,  11,  11,  11,  10,  10,  10,  10,  10,  10}};

    long l = System.currentTimeMillis();
    f(test);
    System.out.println("12x12: " + (System.currentTimeMillis() - l) + "ms");

    for(int[] t : test){
        System.out.println(Arrays.toString(t));
    }

}

Produces this on my machine:
12x12: 822ms
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1]
[0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0]
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0]
[0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]
[0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0]

OP's note: This submission was made when the challenge was a code-golf challenge. It is therefore perfectly valid, even though it isn't (only) optimized for the current winning criterion!

@StewieGriffin thanks for the comment. When I get a chance I'll work on cleaning it up some since it's no longer code golf and see if I can optimize it for some speed

Official timing: 1.2 seconds on 12x12.

We're in a pickle, maybe you can help. Can you think of any way to generate nontrivial larger puzzle instances?

Clingo, ≈ 7 ms for 12×12, 116 bytes
{t(X,Y):c(X,Y,Z)}=2:-Z=1..n.
:-X=1..n,{t(X,1..n)}!=2.
:-Y=1..n,{t(1..n,Y)}!=2.
:-t(X,Y),t(X+1,Y;X+1,Y+1;X,Y+1;X-1,Y+1).

(Newlines are optional and not counted.)
Run with clingo plant.lp - -c n=<n> where <n> is the grid size.  The input format is a list of c(X,Y,Z). statements for each cell (X, Y) colored Z, with 1 ≤ X, Y, Z ≤ n, separated by optional whitespace.  The output includes t(X,Y) for each tree at (X, Y).
The time is pretty meaningless as it’s basically just startup time, so consider this a vote for larger test cases.
Demo
$ clingo plant.lp -c n=12 - <<EOF
> c(1,1,1). c(2,1,1). c(3,1,1). c(4,1,1). c(5,1,1). c(6,1,2). c(7,1,3). c(8,1,3). c(9,1,3). c(10,1,3). c(11,1,4). c(12,1,4).
> c(1,2,1). c(2,2,1). c(3,2,1). c(4,2,1). c(5,2,1). c(6,2,2). c(7,2,3). c(8,2,3). c(9,2,3). c(10,2,3). c(11,2,4). c(12,2,4).
> c(1,3,1). c(2,3,1). c(3,3,1). c(4,3,1). c(5,3,1). c(6,3,2). c(7,3,2). c(8,3,2). c(9,3,2). c(10,3,4). c(11,3,4). c(12,3,4).
> c(1,4,5). c(2,4,5). c(3,4,5). c(4,4,1). c(5,4,6). c(6,4,6). c(7,4,6). c(8,4,7). c(9,4,2). c(10,4,7). c(11,4,8). c(12,4,8).
> c(1,5,5). c(2,5,5). c(3,5,1). c(4,5,1). c(5,5,6). c(6,5,6). c(7,5,6). c(8,5,7). c(9,5,2). c(10,5,7). c(11,5,8). c(12,5,8).
> c(1,6,5). c(2,6,5). c(3,6,6). c(4,6,6). c(5,6,6). c(6,6,6). c(7,6,6). c(8,6,7). c(9,6,7). c(10,6,7). c(11,6,8). c(12,6,8).
> c(1,7,5). c(2,7,5). c(3,7,5). c(4,7,6). c(5,7,9). c(6,7,10). c(7,7,6). c(8,7,6). c(9,7,7). c(10,7,8). c(11,7,8). c(12,7,8).
> c(1,8,9). c(2,8,9). c(3,8,5). c(4,8,9). c(5,8,9). c(6,8,10). c(7,8,10). c(8,8,10). c(9,8,10). c(10,8,11). c(11,8,8). c(12,8,8).
> c(1,9,9). c(2,9,9). c(3,9,9). c(4,9,9). c(5,9,9). c(6,9,10). c(7,9,10). c(8,9,10). c(9,9,10). c(10,9,11). c(11,9,8). c(12,9,11).
> c(1,10,12). c(2,10,12). c(3,10,10). c(4,10,10). c(5,10,10). c(6,10,10). c(7,10,10). c(8,10,10). c(9,10,10). c(10,10,11). c(11,10,11). c(12,10,11).
> c(1,11,12). c(2,11,12). c(3,11,12). c(4,11,12). c(5,11,12). c(6,11,12). c(7,11,11). c(8,11,11). c(9,11,11). c(10,11,11). c(11,11,11). c(12,11,11).
> c(1,12,12). c(2,12,12). c(3,12,12). c(4,12,12). c(5,12,12). c(6,12,12). c(7,12,11). c(8,12,11). c(9,12,11). c(10,12,11). c(11,12,11). c(12,12,11).
> EOF
clingo version 5.1.0
Reading from plant.lp ...
Solving...
Answer: 1
c(1,1,1) c(2,1,1) c(3,1,1) c(4,1,1) c(5,1,1) c(6,1,2) c(7,1,3) c(8,1,3) c(9,1,3) c(10,1,3) c(11,1,4) c(12,1,4) c(1,2,1) c(2,2,1) c(3,2,1) c(4,2,1) c(5,2,1) c(6,2,2) c(7,2,3) c(8,2,3) c(9,2,3) c(10,2,3) c(11,2,4) c(12,2,4) c(1,3,1) c(2,3,1) c(3,3,1) c(4,3,1) c(5,3,1) c(6,3,2) c(7,3,2) c(8,3,2) c(9,3,2) c(10,3,4) c(11,3,4) c(12,3,4) c(1,4,5) c(2,4,5) c(3,4,5) c(4,4,1) c(5,4,6) c(6,4,6) c(7,4,6) c(8,4,7) c(9,4,2) c(10,4,7) c(11,4,8) c(12,4,8) c(1,5,5) c(2,5,5) c(3,5,1) c(4,5,1) c(5,5,6) c(6,5,6) c(7,5,6) c(8,5,7) c(9,5,2) c(10,5,7) c(11,5,8) c(12,5,8) c(1,6,5) c(2,6,5) c(3,6,6) c(4,6,6) c(5,6,6) c(6,6,6) c(7,6,6) c(8,6,7) c(9,6,7) c(10,6,7) c(11,6,8) c(12,6,8) c(1,7,5) c(2,7,5) c(3,7,5) c(4,7,6) c(5,7,9) c(6,7,10) c(7,7,6) c(8,7,6) c(9,7,7) c(10,7,8) c(11,7,8) c(12,7,8) c(1,8,9) c(2,8,9) c(3,8,5) c(4,8,9) c(5,8,9) c(6,8,10) c(7,8,10) c(8,8,10) c(9,8,10) c(10,8,11) c(11,8,8) c(12,8,8) c(1,9,9) c(2,9,9) c(3,9,9) c(4,9,9) c(5,9,9) c(6,9,10) c(7,9,10) c(8,9,10) c(9,9,10) c(10,9,11) c(11,9,8) c(12,9,11) c(1,10,12) c(2,10,12) c(3,10,10) c(4,10,10) c(5,10,10) c(6,10,10) c(7,10,10) c(8,10,10) c(9,10,10) c(10,10,11) c(11,10,11) c(12,10,11) c(1,11,12) c(2,11,12) c(3,11,12) c(4,11,12) c(5,11,12) c(6,11,12) c(7,11,11) c(8,11,11) c(9,11,11) c(10,11,11) c(11,11,11) c(12,11,11) c(1,12,12) c(2,12,12) c(3,12,12) c(4,12,12) c(5,12,12) c(6,12,12) c(7,12,11) c(8,12,11) c(9,12,11) c(10,12,11) c(11,12,11) c(12,12,11) t(1,7) t(1,9) t(2,3) t(2,11) t(3,5) t(3,8) t(4,10) t(4,12) t(5,5) t(5,8) t(6,2) t(6,10) t(7,4) t(7,12) t(8,2) t(8,6) t(9,4) t(9,11) t(10,1) t(10,6) t(11,3) t(11,9) t(12,1) t(12,7)
SATISFIABLE

Models       : 1+
Calls        : 1
Time         : 0.009s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time     : 0.000s

To make the input/output format easier to deal with, here are Python programs to convert from and to the format given in the challenge.
Input
import sys
print(' '.join("c({},{},{}).".format(x + 1, y + 1, ord(cell) - ord('a') + 1) for y, row in enumerate(sys.stdin.read().splitlines()) for x, cell in enumerate(row)))

Output
import re
import sys
for line in sys.stdin:
    c = {(int(x), int(y)): int(z) for x, y, z in re.findall(r'\bc\((\d+),(\d+),(\d+)\)', line)}
    if c:
        t = {(int(x), int(y)) for x, y in re.findall(r'\bt\((\d+),(\d+)\)', line)}
        n, n = max(c)
        for y in range(1, n + 1):
            print(''.join(chr(ord('aA'[(x, y) in t]) + c[x, y] - 1) for x in range(1, n + 1)))
        print()

Looks like we're gonn'a need a bigger test case. Btw, you'd be winning the golf version of this question — just needs the 2s changing to 1s.

Official timing is 18 milliseconds on 12x12, I apologize. 1 character typo, that's the trouble with abbreviations.

We're in a pickle, maybe you can help. Can you think of any way to generate nontrivial larger puzzle instances?


text:
Create a stem-and-leaf plot
Related: Validate a stem-and-leaf plot
Input
A non-empty list of positive integers. If needed, they can be taken as strings. You cannot assume it is sorted.
Output
A stem-and-leaf plot of the numbers. In a this stem-and-leaf plot, numbers are ordered into stems by tens, then all numbers that fit into that stem have their ones value placed into the stem, and then all are sorted. In this challenge, newlines separate the stems, and spaces separate the stems from the leaves.
You may either include or exclude all empty stems that are between non-empty stems.
Test Cases
(lists can be taken in your language's list default, I used JSON for the below)
Including empty stems:
[1, 2, 3, 3, 3, 3, 3, 10, 15, 15, 18, 1, 100]

0 11233333
1 0558
2
3
4
5
6
7
8
9
10 0

[55, 59, 49, 43, 58, 59, 54, 44, 49, 51, 44, 40, 50, 59, 59, 59]

4 034499
5 0145899999

[10000, 10100]

1000 0
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010 0

Excluding empty stems:
[1, 2, 3, 3, 3, 3, 3, 10, 15, 15, 18, 1, 100]

0 11233333
1 0558
10 0

[55, 59, 49, 43, 58, 59, 54, 44, 49, 51, 44, 40, 50, 59, 59, 59]

4 034499
5 0145899999

[10000, 10100]

1000 0
1010 0

Sandbox

It need to be sorted and/or preserve the input order?

@Rod by definition, it sorts the input by tens, then by ones. Input order doesn't matter.

The output format MUST be like that? Is my answer valid?

@Rod I believe your answer is invalid - you are separating stems from stems with the same delimiter as stems from leaves, if I am seeing it correct

changed a bit, is it better now?

Do the leaves have to be sorted? And my answer outputs a list of tuples, is that okay?

@totallyhuman tuples are OK, but yes, the leaves need to be sorted, that's the whole point of the plot, to visualize patterns and distributions

R, 12 bytes
stem(scan())

Try it online!
Explanation:
s               # imports RAND's "Million Random Digits"
  e  )          # cooks a pound of spaghetti and places it on the stack
 t              # transposes the output 42 times
       can      # goes for a pee
   m(           # grows moustache, turns head to side and frowns
      s   (     # implicitly ignores all criticism
           )    # makes a stemplot of the input

I think just stem would be sufficient, as it takes an array as input.

That was the only way I could get an example to actually work on TIO. And I guess I'm used to the "program or function" style of answering, and am unsure about other formats.

Like this

Agree with @Giuseppe, the answer should be just stem :)

Python 2, 78 75 79 bytes
s=-1
for i in sorted(input()):
 if i/10^s:s=i/10;print'\n%d-'%s,
 print`i`[-1],

Try it online!

Jelly, 17 bytes
Ṣµ:©⁵Ġṁ@%⁵®Q¤żK€Y

Try it online!

Retina, 38 30 bytes
Thanks to Neil for saving 2 bytes, and to Leo for saving another 6.
Byte count assumes ISO 8859-1 encoding.
O#`
.\b
 $&
\B
0
D$`¶?.+
$*

Input is a linefeed-separated list of integers. Output omits empty prefixes.
Try it online!

(?<=(\b.+ ).)¶\1 saves you two bytes.

Bytes can be saved by using a deduplication stage instead of a replacement one as the last stage (you must then deal with the first line though) https://tio.run/##K0otycxL/K@qEZyg899fOYFLLyaJS0FFjSvGSYHLQIErjuvQNi6XhEPb9LQV/gcnqPw31DHSMYZDQwMdQ1MwstAxBPIMuExNdUwtdUyAyFjH1ALENjXRMTEBiZgaghkGOqYGYHEQ4gLqMQAaYgCkAQ

@Leo Thanks, I'm going with a slight variant that doesn't end up with a leading linefeed.

Python 2, 146 140 133 124 120 118 109 107 90 86 84 91 82 81 70 63 bytes
-6 bytes thanks to Rod. -9 bytes thanks to ovs.
lambda l:{i/10:[j%10for j in sorted(l)if j/10==i/10]for i in l}

Try it online!
Okay, something is slightly wonky. As all Python programmers should know, dicts are unordered, meaning the original order of the key-value pairs is not preserved. However, in my current code, I do not sort the resulting dict at all. Yet, I have tested multiple times, checking for equality and order every single time, and the dict always comes out right. If anybody either disproves that it always comes out right or knows why this works, I'd love to know.
Input as a python list and output as a dict. Example:
Input:
[1, 2, 3, 3, 3, 3, 3, 10, 15, 15, 18, 1, 100]

Output:
{0: [1, 1, 2, 3, 3, 3, 3, 3], 1: [0, 5, 5, 8], 10: [0]}

you can replace the try/except with bitwise validation

r[i/10]=r.get(i/10,'')+\i%10`` for 82 bytes

I think dicts are sorted by default? just not in the original order

JavaScript (ES6), 89 bytes
a=>a.sort((a,b)=>a-b).map(e=>r[d=e/10|0]=(r[d]||d+` `)+e%10,r=[])&&r.filter(e=>e).join`
`

Mathematica, 103 bytes
Code taken from @user202729's deleted answer
Grid[Table[{Keys[#][[i]],""<>ToString/@#[[i]]},{i,Length@#}]]&@(GroupBy[Sort@#,⌊#/10⌋&]~Mod~10&@#)&

><>, 84 bytes
1&0\n~a7+3.
 :}<$?)@:$@:v!?
r~&^?-l&:+1&/&:,a-%a::
&=?v~&1+:&ao>n" "o:?!;::a%:@-a,&:

Try it online, or at the fish playground!
Assumes the input numbers are already on the stack.
Explanation: First, we sort the stack using a bubble sort, with this bit of code:
1&0\
 :}<$?)@:$@:v!?
   ^?-l&:+1&/

Next, we compute the integer-quotient of the first thing in the stack by 10 using ::a%-a,, put that in the register, and go through the stack printing the last digits of the numbers until their first digits aren't the same as the register, then incrementing the register and continuing. When we reach the end of the list, marked with a 0, we stop.

PostgreSQL, 53 bytes
SELECT n/10,json_agg(n%10ORDER BY n)FROM t GROUP BY 1

The list of integers must reside in an integer column n of an existing table t. The result is a two-column table: each row consists of a "stem" column and a "leaves" column. The "leaves" column is in JSON array format. (As noted in the comments, it is not necessary to adhere exactly to the format shown under "Test Cases".)
Though the order of stems is not guaranteed (to save 10 bytes, ORDER BY 1 is omitted from the end of the query), in my testing, the stems did seem to end up in the correct order.
View result on SQL Fiddle


text:
Divinacci Sequence
Divinacci (OEIS)
Perform the Fibonacci sequence but instead of using:
f(n) = f(n-1)+f(n-2)

Use:
f(n) = sum(divisors(f(n-1))) + sum(divisors(f(n-2)))

For an input of n, output the nth term, your program should only have 1 input.

First 14 terms (0-indexed, you may 1-index; state which you used):
0  | 0     # Initial               | []
1  | 1     # Initial               | [1] => 1
2  | 1     # [] + [1]              | [1] => 1
3  | 2     # [1] + [1]             | [1,2] => 3
4  | 4     # [1] + [1,2]           | [1,2,4] => 7
5  | 10    # [1,2] + [1,2,4]       | [1,2,5,10] => 18
6  | 25    # [1,2,4] + [1,2,5,10]  | [1,5,25] => 31
7  | 49    # [1,2,5,10] + [1,5,25] | [1,7,49] => 57
8  | 88    # [1,5,25] + [1,7,49]   | [1, 2, 4, 8, 11, 22, 44, 88] => 180
9  | 237   # [1,7,49] + [180]      | [1, 3, 79, 237] => 320
10 | 500   # [180] + [320]         | [1, 2, 4, 5, 10, 20, 25, 50, 100, 125, 250, 500] => 1092
11 | 1412  # [320] + [1092]        | [1, 2, 4, 353, 706, 1412] => 2478
12 | 3570  # [1092] + [2478]       | [1, 2, 3, 5, 6, 7, 10, 14, 15, 17, 21, 30, 34, 35, 42, 51, 70, 85, 102, 105, 119, 170, 210, 238, 255, 357, 510, 595, 714, 1190, 1785, 3570] => 10368
13 | 12846 # [2478] + [10368]      | [1, 2, 3, 6, 2141, 4282, 6423, 12846] => 25704
Etc...

You may choose whether or not to include the leading 0. For those who do: the divisors of 0 are [] for the purpose of this challenge.
It's code-golf lowest byte-count wins...

All natural numbers divide 0, thus its divisor sum is +∞.

@Dennis finally someone who doesn't think that 1 + 2 + 3 + ... = -1/12.

@Dennis We can get rid of the 0 and make this valid though :P. Or you can just submit a Mathematica answer of Infinity if you want.

The Jelly answer would be shorter. :P You can either change the sequence (the answer probably would need tweaking as well) or change its description (start with base values 0, 1, 1).

@Dennis The Jelly answer could've been just ÷...with input getting fed from STDIN.

Why should we assume that the divisors of 0 are []? Just make 2 -> 1 an Initial as Dennis suggested...problem solved. ;)

@EriktheOutgolfer 7 answers already, you sure it affects none of them?

@carusocomputing If it doesn't change the sequence, how can it affect answers?

Alternatively, relaxing the rules is always possible (i.e. making it optional whether the zero is included in the sequence or not).

@MartinEnder is this worded correctly? I'm just genuinely confused on what you guys want me to edit specifically, if you could suggest an edit that'd be awesome.

That edit works.

@LeakyNun excuse me, you saying it isn't?

@tox123 happy april fools

05AB1E, 9 bytes
XÎFDŠ‚ÑOO

Try it online!
Explanation
XÎ          # initialize stack with 1,0,input
  F         # input times do
   D        # duplicate
    Š       # move down 2 places on the stack
     ‚      # pair the top 2 elements on the stack
      Ñ     # compute divisors of each
       OO   # sum twice

Tons of swapping going on heh! Interesting.

I like how the last couple bytes are forcefully yelling at the reader.

You won this by 2 minutes lol.

Mathematica, 45 40 bytes
If[#<3,1,Tr@Divisors@#0[#-i]~Sum~{i,2}]&

Mathematica's divisor related functions Divisors, DivisorSum and DivisorSigma are all undefined for n = 0 (rightly so), so we start from f(1) = f(2) = 1 and don't support input 0.
Defining it as an operator instead of using an unnamed function seems to be two bytes longer:
±1=±2=1
±n_:=Sum[Tr@Divisors@±(n-i),{i,2}]

*7 bytes longer unless ± is 1 byte in a Mathematica supported encoding.

@CalculatorFeline It is. (The default setting for $CharacterEncoding on Windows machines is WindowsANSI, i.e. CP 1252.)

Good to know. .

Perl 6, 58 bytes
{my&d={sum grep $_%%*,1..$_};(0,1,{d($^a)+d $^b}...*)[$_]}

Try it online!

Haskell, 55 bytes
f n=sum[a|n>1,k<-f<$>[n-1,n-2],a<-[1..k],mod k a<1]+0^n

Try it online!
One-indexed.

Jelly, 10 9 bytes
ð,ÆDẎSð¡1

Try it online!
Thanks to Dennis for -1.

9 bytes

@Dennis The 0 was implicit?

When you take the number of iterations from STDIN, you get a niladic chain, and 0 is the implicit argument of niladic chains.

@Dennis So ¡ and others will just try to take an argument from everywhere, even with a Ɠ? That's quite unexpected...

Unless specified explicitly, ¡ et al. take the last command-line argument and, if there aren't any, reads a line from STDIN.

Python 3, 88 83 81 bytes
f=lambda n:+(n<3)or g(f(n-1))+g(f(n-2))
g=lambda n,i=1:n>=i and(n%i<1)*i+g(n,i+1)

Try it online!
Excludes the 0

Python 2, 76 bytes
f=lambda n:sum(a for k in[1,2][:n]for a in range(1,3**n-8)if f(n-k)%a<1)or n

Try it online!
Ridiculously slow.

MATL, 16 15 bytes
Oliq:",yZ\s]+]&

This solution uses 0-based indexing.
Try it at MATL Online
Explanation
O        % Push the number literal 0 to the stack
l        % Push the number literal 1 to the stack
i        % Explicitly grab the input (n)
q        % Subtract 1
:        % Create the array [1...(n - 1)]
"        % For each element in this array...
  ,      % Do the following twice
    y    % Copy the stack element that is 1-deep
    Z\   % Compute the divisors
    s    % Sum the divisors
  ]      % End of do-twice loop
  +      % Add these two numbers together
]        % End of for loop
&        % Display the top stack element

Haskell, 64 60 bytes
d n=sum[a|a<-[1..n],mod n a<1]
f=0:scanl((.d).(+).d)1f
(!!)f

Try it online!

PHP, 97 bytes
for($f=[0,$y=1];++$i<$argn;$x=$y,$y=$r)for($f[]=$r=$v=$n=$x+$y;--$v;)$n%$v?:$r+=$v;echo$f[$argn];

Try it online!
PHP, 101 bytes
for($f=$d=[0,1];$i<$argn;$d[]=$r)for($f[]=$r=$v=$n=$d[$i]+$d[++$i];--$v;)$n%$v?:$r+=$v;echo$f[$argn];

Try it online!

Pari/GP, 39 bytes
f(n)=if(n<3,1,sum(i=1,2,sigma(f(n-i))))

Based on Martin Ender's Mathematica answer.
Try it online!

R, 81 bytes
f=function(n,a=1,b=1,d=numbers::divisors)`if`(n-1,f(n-1,b,sum(d(a))+sum(d(b))),a)

1-indexed, and excludes the 0 at the start of the sequence. That zero gave me a lot of trouble to implement, because the builtin numbers::divisors doesnt handle it well.
The rest is a modified version of the standard recursive function that implements the fibonacci sequence.
> f(1)
[1] 1
> f(2)
[1] 1
> f(3)
[1] 2
> f(5)
[1] 10
> f(13)
[1] 12846

Vyxal, 9 bytes
1{~"vKf∑…

Try it Online!
Prints the sequence forever.
1         # Push 1
 {        # Forever...
  ~"      # Grab top two elements, without popping
    vK    # Get divisors of each
      f∑  # Deep sum
        … # Print that without popping

Julia, 47 44 bytes
~n=(n.%(r=1:n).<1)'r
!N=N<3||~!(N-1)+~!(N-2)
Attempt This Online!
-3 bytes thanks to Czylabson Asa. (I forgot how a'*b worked)

gives true for N=1,2

@CzylabsonAsa true == 1, so I think it's ok

oh, really. just a short note, your ~ can be
~m=(r=1:m;r'*(m.%r.<1)),
not shorter, but a little bit different.

thanks, I knew I could do better but I forgot about how finicky a'*b was to get a number instead of a 1x1 matrix

w/similar method i got 6th (20220615) at https://code.golf/abundant-numbers :-)

Husk, 11 bytes
!¡ȯΣṁḊ↑_2ŀ2

Try it online!
Explanation
!¡ȯΣṁḊ↑_2ŀ2
         ŀ2 array [0,1]
 ¡          iterate on the array, expanding it:
  ȯ         using the following 4 functions:
      ↑_2   get last 2 elements
    ṁḊ      get divisors of both
   Σ        sum them
!           Get element at index n

Factor + math.primes.factors math.unicode, 53 bytes
[ 0 1 rot [ tuck [ divisors Σ ] bi@ + ] times drop ]

Try it online!
0-indexed.

C (gcc), 93 87 86 bytes
f(n){return n<2?n:s(f(n-1))+s(f(n-2));}s(n,c,i){for(c=i=0;n/++i;)c+=n%i?0:i;return c;}

Try it online!
A simple recursive solution that finds divisors by brute force.
Thanks to @ceilingcat for -6 bytes on the for loop and -1 on some superfluous parens.

Burlesque, 23 bytes
0 1 2{fc++jfc++.+}C~j!!

Try it online!
0 1   # Initial
2     # Keep top 2 stack elements
{
 fc++ # Factors, Sum
 j    # Swap stack
 fc++ # Factors, Sum
 .+   # Sum
}C~   # Continue forever
j!!   # Get input element

05AB1E, 7 bytes
1λè‚Ñ˜O

Outputs the 1-based \$n^{th}\$ value.
Try it online.
With some small modifications, we could output:

7 bytes: The first 1-based \$n\$ values by replacing è with £: try it online.
5 bytes: The infinite 1-based sequence by removing the 1 and è: try it online.
Or with 0-based sequence by adding Ý after the 1:

8 bytes: 0-based \$n^{th}\$: try it online.
8 bytes: 0-based first \$n\$ values: try it online.
7 bytes: 0-based infinite sequence: try it online.

So with default sequence rules, this could have been 5 bytes.
Explanation:
 λ       # Start a recursive environment,
  è      # to output the a(input)'th value
         # (which is output implicitly at the end)
1        # Starting at a(0)=1
         # And where every following a(n) is calculated as:
   ‚     #  Pair the (implicit) previous two terms together: [a(n-2),a(n-1)]
         #  (a(n-2) is unknown in the first iteration, so will default to 0)
    Ñ    #  Get the divisors of both inner values
     ˜   #  Flatten this list of lists of integers
      O  #  Sum them together

Explanation of the 5-bytes infinite 1-based sequence:
λ        # Start a recursive environment,
         # to output the infinite sequence
         # (which is output implicitly at the end)
         # Implicitly starting at a(0)=1
         # And where every following a(n) is calculated as:
 ‚Ñ˜O    #  See above

Scala, 123 bytes
Golfed version. Attempt it online!
def f(n:Int):Int=if(n<3)1 else{def g(n:Int,i:Int=1):Int=if(n>=i)if(n%i<1)i+g(n,i+1)else g(n,i+1)else 0;g(f(n-1))+g(f(n-2))}

Ungolfed version. Attempt it online!
object Main {
  def main(args: Array[String]): Unit = {
    val sequence = (1 to 10).map(f).toList
    println(sequence)
  }

  def f(n: Int): Int = {
    if (n < 3) 1
    else g(f(n - 1)) + g(f(n - 2))
  }

  def g(n: Int, i: Int = 1): Int = {
    if (n >= i) {
      if (n % i < 1) i + g(n, i + 1)
      else g(n, i + 1)
    } else 0
  }
}

Japt, 11 bytes
Starts with 0 and outputs the nth term, zero-indexed. Replace g with h to output the first n terms instead.
@Zo2 câ x}g

Try it