text:
Detriplicate a string
A lot of languages have built-in ways to get rid of duplicates, or "deduplicate" or "uniquify" a list or string. A less common task is to "detriplicate" a string. That is, for every character that appears, the first two occurrences are kept.
Here is an example where the characters that should be deleted are labelled with ^:
aaabcbccdbabdcd
  ^    ^ ^^^ ^^
aabcbcdd

Your task is to implement exactly this operation.
Rules
Input is a single, possibly empty, string. You may assume that it only contains lowercase letters in the ASCII range.
Output should be a single string with all characters removed which have already appeared at least twice in the string (so the left-most two occurrences are kept).
Instead of strings you may work with lists of characters (or singleton strings), but the format has to be consistent between input and output.
You may write a program or a function and use any of the our standard methods of receiving input and providing output.
You may use any programming language, but note that these loopholes are forbidden by default.
This is code-golf, so the shortest valid answer – measured in bytes – wins.
Test Cases
Every pair of lines is one test case, input followed by output.

xxxxx
xx
abcabc
abcabc
abcdabcaba
abcdabc
abacbadcba
abacbdc
aaabcbccdbabdcd
aabcbcdd

Leaderboard
The Stack Snippet at the bottom of this post generates a leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:
## Perl, 43 + 3 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

Singleton strings... stringletons?

Jelly, 6 bytes
Qx2œ&@

Try it online! or verify all test cases.
How it works
Qx2œ&@  Main link. Argument: s (string)

Q       Unique; deduplicate s.
 x2     Repeat each character.
   œ&@  Take the multiset intersection of s and the previous result.

JavaScript (ES6), 42 48
Edit A whopping 6 bytes saved thx @Neil
s=>s.replace(k=/./g,c=>(k[c]+=c)[11]?'':c)

Explanation: I use the properties 'a'...'z' of object k to store info for each character (object k is a regexp in this case just to save bytes).
These properties are initially undefined. In javascript adding a number to undefined gives NaN (quite sensible), but adding a string 'X' gives "undefinedX" - a string of length 10 (silly). Adding more characters you get longer strings. If the obtained string for a given character is longer than 11, that character is not copied to output.
Test

F=
s=>s.replace(k=/./g,c=>(k[c]+=c)[11]?'':c)

test=`

xxxxx
xx
abcabc
abcabc
abcdabcaba
abcdabc
abacbadcba
abacbdc
aaabcbccdbabdcd
aabcbcdd`.split`\n`
for(i=0;i<test.length;)
  a=test[i++],b=test[i++],r=F(a),
  console.log(r==b?'OK':'KO',a,'->',r,b)

Strictly speaking an empty line is one of the test cases.

@Neil ok added the empty string test

If you switch to array input and output, you can use .filter to save 12 more characters.  v=>v.filter(x=>!(v[x]+=x)[11]).  Kudos on the "undefined" hack.

@Grax thanx but too different. Should post it yourself

Python 2, 48 bytes
lambda s:reduce(lambda r,c:r+c*(r.count(c)<2),s)

c[r.count(c)/2:] is a same-length alternative to c*(r.count(c)<2) .

49 bytes:
r=''
for c in input():r+=c*(r.count(c)<2)
print r

Retina, 17 bytes
(.)(?<=\1.*\1.+)

Try it online!
Simple regex replace - match a character if it already appeared twice, and remove it.

I also tried a loop, and a repeated group with {2}, both with 18 bytes.

I've got 14 using a recently added feature. ;)

I knew there was something. I looked at limits, probably not that one. I'll check again.

Ah, I think I found Martin's answer. I had some trouble when I was trying before, I think because I didn't consider how deduplicate would work on a multi-line input. Spoiler (with 5 bytes added to enable per-line mode): http://retina.tryitonline.net/#code=JShHYApEYCguKSg_PD1cMS4rKQ&input=eHh4eHgKeHgKYWJjCmFiYwphYmNhYmMKYWJjYWJjCmFiY2RhYmNhYmEKYWJjZGFiYwphYmFjYmFkY2JhCmFiYWNiZGMKYWFhYmNiY2NkYmFiZGNkCmFhYmNiY2Rk

@FryAmTheEggman - Nice, I didn't find this one. Feel free to add an answer - I think this is too different from my answer and I didn't feel comfortable editing it in :P. Thanks!

Alright, (I think they are actually very similar, but) I've posted another answer :P

Brachylog, 25 bytes
.v|s.g:.z:1a
:2fl<3
he~t?

Try it online! or verify all test cases.
Explanation
This works because s - Subset will unify with bigger subsets first, thus e.g. for "aaa" it will try "aa" before "a".

Main predicate:
  .v         input = Output = ""
|          Or
  s.         Output is an ordered subset of the input
  g:.z       Zip each character of the output with the output itself
  :1a        Apply predicate 1 on each element of the zip

Predicate 1: Check that all characters only appear at most twice. Input = [String:Char]
:2f        Find all valid outputs of predicate 2 (i.e. one output per occurence
               of the char)
l<3        There are less than 3 occurences

Predicate 2: Get an occurence of a character. Input = [String:Char]
he         Take a character of the string in the input
  ~t?      That character is the char of the input

><>, 22 bytes
i:0(?;::9g:}2(?o{1+$9p

Try it online! Uses the codebox to keep track of counts so far.
i                       Read a char c of input
 :0(?;                  Halt if EOF
      :                 Make a copy - stack has [c c] at the top
       :9g              Get count stored at (c, 9)
          :}            Copy the count and move to bottom of stack
            2(?o        If the count is less than 2, output c
                {1+     Move the count back to the top of the stack and increment
                   $9p  Update cell at (c, 9)
                        [Instruction pointer moves to start as ><> is toroidal]

J, 20 15 bytes
#~(3>[+/@:={:)\

This defines a monadic function that takes and returns a string. Try it here. Usage:
   f =: #~(3>[+/@:={:)\
   f 'abaacbb'
abacb

Explanation
I switched to the same algorithm that some other solutions use, since it turned out to be shorter...
#~(3>[+/@:={:)\  Input is y.
  (          )\  For each prefix of y:
          =        compute the equality vector
     [     {:      of the prefix and its last element, and
      +/@:         take its sum. Now we have a vector r such that y[i] has its
                   r[i]'th occurrence at position i.
   3>              Mark those coordinates where r[i] < 3.
#~               Remove the non-marked characters from y.

Haskell, 40 39 bytes
foldl(\s c->s++[c|filter(==c)s<=[c]])""

Usage example: foldl(\s c->s++[c|filter(==c)s<=[c]])"" "aaabcbccdbabdcd" -> "aabcbcdd".
Keep the next char c if the string of all cs so far are lexicographical less or equal the singleton string [c].
Edit: @xnor saved a byte by switching from list comprehension to filter. Thanks!

Your alternative could do filter(==c)s<=[c] to save a byte.

Perl, 22 bytes
21 bytes code + 1 for -p.
s/./$&x(2>${$&}++)/ge

Usage
perl -pe 's/./$&x(2>${$&}++)/ge' <<< 'aaabcbccdbabdcd'
aabcbcdd

C, 57 bytes
Call f() with the string to detriplicate. The function modifies its parameter. Requires C99 because of the for-loop declaration.
f(char*p){for(char*s=p,m[256]={0};*s=*p;s+=++m[*p++]<3);}

Can't you put the declaration of s into the first statement of the for?

In C99 you can. I just didn't because I like to keep golfs C89 compatible.

JavaScript (ES6), 35 bytes
s=>s.filter(c=>(s[c]=(s[c]|0)+1)<3)

Takes an array of characters as input and returns the detriplicated array.

Nice. You could do c=>(s[c]=-~s[c])<3 to save a few bytes.

I'd missed that you could use arrays as input and had written a function using map. Golfed it looked essentially like yours. the main difference was the assignment, which if you'll switch it around will save a few bytes. Try s.filter(c=>(s[c]=s[c]+1|0)<3) for 33 bytes. EDIT: Whoops, missed the comment above me, that's even better :)

Retina, 14 bytes
D`(.)(?<=\1.*)

Verify all test cases. (The % enables per-line mode)
Uses the new "Deduplicate" stage to save a couple bytes over Kobi's approach. Deduplicate gathers a list of all matches to the regex and replaces all but the first with the empty string. The regex matches a character that already appears once in the string, meaning that the first two will be kept.

MATL, 8 bytes
t&=Rs3<)

Try it online!
Explanation
t      % Input string implicitly. Push another copy
&=     % Matrix of all pairwise equality comparisons of string elements
R      % Keep only upper triangular part, making the rest of the entries zero
s      % Sum of each column. This gives a vector with number of occurrences
       % of the current character up to the current position
3<     % True for entries that are less than 3
)      % Use as logical index into initial copy of the input. Display implicitly

Example
Assuming input 'aaababbc', the stack contains the following after the indicated statements:

t
'aaababbc'
'aaababbc'

t&=
'aaababbc'
[ 1 1 1 0 1 0 0 0;
  1 1 1 0 1 0 0 0;
  1 1 1 0 1 0 0 0;
  0 0 0 1 0 1 1 0;
  1 1 1 0 1 0 0 0;
  0 0 0 1 0 1 1 0;
  0 0 0 1 0 1 1 0;
  0 0 0 0 0 0 0 1 ]

t&=R
'aaababbc'
[ 1 1 1 0 1 0 0 0;
  0 1 1 0 1 0 0 0;
  0 0 1 0 1 0 0 0;
  0 0 0 1 0 1 1 0;
  0 0 0 0 1 0 0 0;
  0 0 0 0 0 1 1 0;
  0 0 0 0 0 0 1 0;
  0 0 0 0 0 0 0 1 ]

t&=Rs
'aaababbc'
[ 1 2 3 1 4 2 3 1 ]

t&=Rs3<
'aaababbc'
[ true true false true false true false true ]

t&=Rs3<)
'aabbc'

PowerShell v2+, 31 bytes
$args-replace'(.)(?<=\1.*\1.+)'

Uses the same regex as in Kobi's Retina answer, just encapsulated in the PowerShell -replace operator. Works because both are using .NET-flavor regex in the background.
Alternatively, without regex, 56 bytes
$b=,0*200;-join([char[]]$args[0]|%{"$_"*($b[$_]++-lt2)})

Creates a helper array $b pre-populated with 0s. Casts the input string $args[0] as a char-array, pipes it through a loop |%{...}. Each iteration outputs the current character $_ as a string "$_" multiplied by a Boolean that is only $TRUE (implicitly cast to 1 here) if the appropriate point in the helper array is less than 2 (i.e., we haven't seen this char twice already). The resultant collection of strings is encapsulated in parens and -joined together to form a single output string. That's left on the pipeline and output is implicit.

regex is unbeatable. :) I beleave a hashtable is better then an array for the variant without regex: $b=@{};-join($args|% t*y|?{++$b.$_-lt3}).

@mazzy For the variant without regex and your code, it would need to be a newer version than PowerShell 2. As a result, I think I'll keep this answer without change. You can post your code as a separate answer, though!

did the hashtable appear in the version 3.0? Ok. Thanks.

Mathematica, 39 bytes
Fold[If[Count@##<2,Append@##,#]&,{},#]&

Anonymous function. Takes a character list as input, and returns the detriplicated list as output. Uses the method of folding over the list and rejecting triplicate elements, it's not too complicated.

05AB1E, 12 bytes
vyˆ¯y¢O3‹iy?

Explanation
v            # for each char in input
 yˆ          # push to global array
   ¯y¢O3‹i   # if nr of occurrences are less than 3
          y? # print it

Try it online

K, 18 Bytes
  g:{x{?x@<x}@,/2#'=x}
  g "abc"
"abc"
  g "aaabcbccdbabdcd"
"aabcbcdd"

  /k4 request test vectors from internet
  R:"GET /raw/ftHe0bpE HTTP/1.0\r\nHost: pastebin.com\r\n\r\n"
  t:+0N 2#t@1_&|\(0=#:)'t:1_"\r\n"\:`:http://pastebin.com:80 R

  /k4 no internet? use a file called "t.txt" in current directory
  t:+0N 2#0:`:t.txt

  /k6?
  t:+0N 2#0:"t.txt"

  /visually inspect test cases
  g't[0]
(();"xx";"abcabc";"abcdabc";"abacbdc";"aabcbcdd")

  /do all tests pass?
  |/ t[1] {$[0=#x;0=#y;x~y]}' g't[0]
1b

K4 is available for free download; K6 is in development. If you've downloaded KDB, you can get into K with backslash.
It may be easiest to see this broken apart, but first some syntax: g:x sets g to x. {x+1} is a function which takes an argument x. In K the first argument to a function is x (the second is y and the third is z. Don't need a fourth).
Now:
x:"aaabcbccdbabdcd"

=x means group x, which produces:
"abcd"!(0 1 2 10;3 5 9 11;4 6 7 13;8 12 14)

2#' means two taken(from) each which produces
"abcd"!(0 1;3 5;4 6;8 12)

As you can see, these are the offsets of the first two matches of each character. The 2 could be generalised.
,/ means join each and is often called raze. It's going to get us just the values of our dictionary. Thus, ,/"abcd"!(0 1;3 5;4 6;8 12) produces:
0 1 3 5 4 6 8 12

which we need to sort. {x@<x}@ is an idiom K programmers often see (Q calls it asc), which says x at grade-up x. Breaking it apart:
  <0 1 3 5 4 6 8 12
0 1 2 4 3 5 6 7

returned the indices of the sorted array, which we want taken from the original array. x@y means x at y so this indexes the array with the indices of the sort (if that makes any sense).
  {x@<x}@0 1 3 5 4 6 8 12
0 1 3 4 5 6 8 12

which we simply now index into our original array. We could say x@ here, but K supports a really powerful concept which we can take advantage of here: function application is indexing. That means that a[0] could be looking up the
zeroth slot of a or it could be applying the 0 to the function called a. The reason we needed the @ previously in {x@<x} is because x<y means xs less than ys: Operators in K have a dyadic form (two-argument) and a monadic form (one-argument) that comes from APL. Q doesn't have this "ambivalence".

Welcome to PPCG! Great first answer. :)

I have a couple of questions. 1. Is K4 the same language as the one you link to (Q/kdb+)? 2. Could you show how to call your function on an input or how the items in testVectors.txt should be formatted?

@Dennis 1. Yes. Press backslash to get from Q to K. 2. Just as they appear in the question: http://pastebin.com/ftHe0bpE example call: g"aaabcbccdbabdcd"

OK, thanks. Couldn't get the file part working, but g"..." does the trick. Unfortunately, your code returns aabbcc for input abc.

@Dennis You might have done something wrong: {x{?x@<x}@,/2#'=x}"abc" definitely returns "abc". It would return "aabbcc" if you missed the ? distinct.

\:testVectors.txtis a handle to the filetextVectors.txtand not a file called:testVectors.txt` NB the handle begins with the syntax backtick-colon.

I'm not sure how or why, but I executed the code from the revision history. The current version does indeed work. Apologies. I specified the correct filename (without a colon) but it didn't work. That doesn't matter though. A few suggestions: 1. We don't require functions to be named. {x{?x@<x}@,/2#'=x} is a valid submission. 2. You should set the actual submission apart from the test run so one can see clearly where the byte count comes from. 3. For K noobs like me, a test run that shows how to drop to K and doesn't involve a file would be helpful.

@Dennis - 1. I wasn't counting the characters in the assignment. 2. I've expanded the introduction and would appreciate feedback on it; can you figure it out now? 3. I've added language about how to get into K4 by providing a link to the documentation.  If you want help with K, the #kq IRC channel on freenode is usually helpful.

Let us continue this discussion in chat.

Pyke, 16 bytes
F~kR/2<Ii?+k(K~k

Try it here!

Java 8 lambda, 90 characters
i->{int[]o=new int[128];String r="";for(char c:i.toCharArray())if(++o[c]<3)r+=c;return r;}

Ungolfed version:
public class Q86503 {

    static String detriplicate(String input) {
        int[] occurences = new int[128];
        String result = "";
        for (char c : input.toCharArray()) {
            if (++occurences[c] < 3) {
                result += c;
            }
        }
        return result;
    }
}

Creates an array for all ascii characters. If a character occurs the corresponding counter will be increased. If it is over 2 the character won't be appended to the result string. Very easy, very short ;)

Python 2, 51 bytes
f=lambda s:s and f(s[:-1])+s[-1]*(s.count(s[-1])<3)

Test it on Ideone.

Perl 6, 27 bytes
{.comb.grep({++%.{$_} <3})}

Explanation:
{.comb.grep({++%.{$_} <3})}
{                         } # a function
 .comb                      # get all the characters in the argument
      .grep({           })  # filter
               %.           # an anonymous hash (shared between calls to grep)
             ++  {$_}       # increment the value at the current key (current letter).
                            # if the key doesn't exist, it defaults to 0 (then gets incremented)
                      <3    # return True if it wasn't seen 3 times

(Note: Perl 6 isn't as "golf-oriented" as its sister Perl 5 ... So yes, that space before the < is necessary. The %.{} is an anonymous hash).

24 bytes

SmileBASIC, 77 72 69 68 bytes
DIM R[#Y]READ S$WHILE""<S$Q=ASC(S$)INC R[Q]?SHIFT(S$)*(R[Q]<3);
WEND

Explained:
DIM R[128] 'array to store letter frequencies
READ S$ 'get input string
WHILE""<S$ 'much shorter than LEN(S$)
 Q=ASC(S$) 'get ascii value of first character in S$
 INC R[Q]
 ?SHIFT(S$)*(R[Q]<3); 'remove the first character of S$, and print it if there are less than 3 occurrences.
WEND

Welcome to ppcg! Nice first post!

Ruby, 79 62 57 bytes
This is pretty unwieldy, but I'm not sure I can golf this much better at the moment. Any golfing suggestions are welcome. Try it online!
Edit: -17 bytes thanks to Value Ink by suggesting a golfier way to remove triplicate characters. -5 bytes from removing the .uniq method.
->s{s.chars.map{|a|s[s.rindex a]=""while s.count(a)>2};s}

Ungolfed:
def g(s)
 s.chars.each do |a|
  while s.count(a) > 2
   i = s.rindex(a)
   s[i] = ""
  end
 end
 return s
end

62 bytes: ->s{s.chars.uniq.map{|a|s[s.rindex a]=""while s.count(a)>2};s}

Common Lisp, 127
(lambda(s)(map()(lambda(x)(flet((p(b)(1+(position x s :start b))))(setf s(remove x s :start(p(p 0))))))(remove-duplicates s))s)

Pretty-printed
(lambda (s)
  (map nil
       (lambda (x)
         (flet ((p (b)
                  (1+ (position x s :start b))))
           (setf s (remove x s :start (p (p 0))))))
       (remove-duplicates s))
  s)

K, 27 Bytes
    f:{x{x@<x}@,/{?2#&x}'x~'/:?x}
    testList:("xxxxx";"abcabc";"abcdabcaba";"abacbadcba";"aaabcbccdbabdcd")
    f'testList
("xx";"abcabc";"abcdabc";"abacbdc";"aabcbcdd")

Q, 52 Bytes
q)f2:{x asc raze{distinct 2#where x}each x~'/:distinct x}
q)f2 each testList
"xx"
"abcabc"
"abcdabc"
"abacbdc"
"aabcbcdd"
q)

JavaScript, 30 bytes
v=>v.filter(x=>!(v[x]+=x)[11])

Using the method that @edc65 came up with for counting but with an array filter.  First time character appears, the object value gets "undefined" plus the character (i.e. "undefinedx").  The next time the object value becomes "undefinedxx".
After that, v[x][11] returns true and when combined with the not operator, false, meaning characters that have already appeared twice will be filtered.

Kotlin, 50 bytes
{it.filterIndexed{i,c->it.take(i).count{it==c}<2}}

Try it online!

PHP, 42 bytes
Loop through the string, count each character in an array, only echo if the letter hasn't reached a count of 3 yet.
while($e=$argn[$x++])if($s[$e]++<2)echo$e;

Try it online!

Nice answer! You can save a couple of bytes using${$e} instead of $s[$e] and using the && shortcircuit too! Try it online!

C (gcc), 85 bytes
int f(char*i){int v[255]={};int x,y;x=y=0;do++v[i[x]]<3?i[y++]=i[x]:0;while(i[x++]);}

Try it online!
de-golfed version:
int f(char* i)
{
    int v[255]={};
    int x,y;
    x=y=0;
    do
    {
        ++v[i[x]]<3?i[y++]=i[x]:0;
    }while(i[x++]);
}

Takes input as an array of characters and outputs by updating it in-place.

You can remove the return type declaration of f, and combine the declarations of v with x and y: Try it online!

Can save even more with for over do while and eliminating one of x/y: Try it online!

Pure Zsh, 35 bytes
eval ';1=${(I:3:)1//'{a..z}\}
<<<$1
Attempt This Online!
Explanation:

eval {a..z}:  for each letter:

$1: in the input:
{//}: replace all matches of that letter
(I:3:): but only replace starting with the third match
;1=: and update the input to that new string

<<<$1: print the variable $1

Javascript (using external library) (80 bytes)
This was a good one! Didn't win but it was fun
n=>{a={};return _.From(n).Where(x=>{b=a[x]?a[x]++:a[x]=1;return b<2}).Write("")}

Link to lib: https://github.com/mvegh1/Enumerable/
Code explanation: Method accepts a string, library parses it as a char array, and the Where clause is a complex filtering predicate that checks the 'a' hashmap for presence of the current char. If exists, increment counter, else set to 1. If < 2, the predicate (and current char) passes, else fail

You can avoid using a return but making your function a comma-separated list of a expressions in parentheses: n=>(a={},_From(n)....). The last expression is the return value. In your Where function, you can eliminate the intermediate b entirely by comparing against the result of the assignment or increment: x=>(a[x]?a[x]++:a[x]=1)<2.

Finally, you can avoid using an external library at all (and save bytes) using the string-split ellipsis and filter with join: [...n].filter(...).join(""). Flip the true/false logic when changing Where to filter.

Ahh good observations! Ill take a closer look later at your suggestion

Clojure, 72 bytes
#(apply str(reduce(fn[r c](if(<(count(filter #{c}r))2)(conj r c)r))[]%))

So many bytes...

Pascal (FPC), 103 bytes
var a:array['a'..'z']of word;c:char;begin repeat read(c);inc(a[c]);if a[c]<3then write(c)until eof end.

Try it online!
Explanation:
var a:array['a'..'z']of word; //used for counting occurences of characters in the input
                              //array indices are accessed by chars
    c:char;
begin
  repeat
    read(c);                  //read a character from input
    inc(a[c]);                //increment the count of that character (its number in array)
    if a[c]<3 then write(c)   //if this is character's 1st or 2nd occurence, output it
  until eof                   //go back to reading if input is not read completely
end.

sed (with -r), 25 bytes
:x;s/((.).*\2.*)\2/\1/;tx

Try it online!
Takes input from STDIN, outputs to STDOUT. Very straightforward implementation: does a regexp match for triple characters, deletes the last one, and loops until it didn't find anything else.

Bash + GNU sed, 18 bytes
sed -es/{a..z}//3g

Try it online!
Way better than my pure sed answer. I marked it as GNU sed because POSIX sed doesn't define the result of supplying both a number and g as flags to the s command. GNU sed, as an extension, takes this to mean "replace all matches starting with the third", which is just what we want.

05AB1E, 7 bytes
ʒIN£y¢!

Try it online!

APL (Dyalog Unicode), 19 bytes
{⍵/⍨i∨≠0@(⍸i←≠⍵)⊢⍵}

Try it on TryAPL (because this doesn't work in TIO)
≠ is the unique mask function when used monadically. It returns an array of ones and zeroes (ones where the first occurrence of an element is found, zeroes where there are duplicates). i ← ≠⍵ assigns the unique mask of ⍵ (the argument to this function) to i.
i gives us ones where the first occurrence of each element is found, but we also need ones where the second occurrence of each element is found. To do that, we use ≠ again, but first we clear all the unique elements from ⍵. ⍸ tells us the indices of the ones in its argument, so ⍸i gives the indices of unique elements in ⍵. (0 @ (⍸i)) ⍵ replaces the elements in ⍵ at these indices to 0 (so now they're all duplicates, and they don't conflict with the other lowercase letters in ⍵). Running ≠ on that gives ones where the second occurrence of each element is, along with a one as the first element.
∨ (or) combines these two masks so there are zeroes only at the indices where triplicates are. / is can take a mask on its left and keep only the elements in its right argument that correspond to a 1 in the mask. ⍨ just swaps its order so we don't need parentheses.

Jelly, 7 bytes
Ġḣ€2FṢị

Try it online!
A byte longer than Dennis' but a unique approach as far as I can tell
How it works
Ġḣ€2FṢị - Main link. Takes a string s on the left
Ġ       - Group the indices of s by their values
  €     - Over each group:
 ḣ 2    -   Take the first 2
    F   - Flatten
     Ṣ  - Sort
      ị - Index back into s

TCC, 5 4 bytes
$~;2

Try it online!
     | Print (implicit)
$~   | Limit char occurence
     | of input (assumed if not given)
  ;  | seperator
   2 | to 2

Do you have a link to the language specification as well?

Nope. I just know Lua, so I learned the language myself, but I can't find a specification anywhere. You can find the Lua source at https://www.ccode.gq/projects/tcc.lua

This language appears to be lost to time, but I don't think it deserved this many downvotes


text:
Array Escape - get out of there
One day you awake only to find yourself caught in an array. You try to just walk out of there, taking one index at the time, but it seems there are other rules:
The array is completely filled with natural numbers.

If you find yourself on an index n, you go to the index array[n], except:
If you find yourself on an index n which is a prime number, you take array[n] steps back

Example:
You start on index 4, in this array (start index is 0):
array = [1,4,5,6,8,10,14,15,2,2,4,5,7];
-----------------^ you are here

As the value of the field you are on is 8, you go to the index 8 as the first step. The field you land on contains the value 2. You then go to index 2 as your second step. As2is a prime number, you take 5 steps back, which is your third step. As there is no index -3, you successfully escaped the array in a total of 3 steps.
Your task is:
To write a program or function, which accepts an array and a start index as parameter, and outputs the amount of steps to escape the array. If you can't escape the array (e.g. [2,0,2] with start-index 2 => you constantly go from index 2 to 0), output a falsy value. You may use one-based indexing or zero-based indexing, but please specify which you use.
Test cases
Input: [2,5,6,8,1,2,3], 3
Output: 1
Input: [2, 0, 2], 2
Output: false
Input: [14,1,2,5,1,3,51,5,12,3,4,41,15,4,12,243,51,2,14,51,12,11], 5;
Output: 6
The shortest answer wins.

Welcome to PPCG! This is a decent first challenge. :) Can we use 1-based indexing as well? Also it might be good to have a few more test cases. For future challenges you can also consider using the sandbox where you can get feedback from the community before a challenge goes live.

Thanks for the feedback - to be honest I didn't read through the page much, so thanks for the sandbox advice, will do that next time :) I'll do an edit shortly.

Based on your second last paragraph I think I know the answer, but just in case: does "natural numbers" here mean > 0 or >= 0?

@Sp3000 It means >= 0

Can you put a testcase which outputs 0? Or, is the start index guaranteed to be valid?

You're speaking of natural numbers N and you use 0 in your test cases, so I assume you mean the set N= {0,1,2,...}, right? Is it correct that we have to assume N={1,2,3,...} for 1-based indexing? Can you add some 1-based indexing testcases?

@LeakyNun yes, you can expect that the startIndex is valid. @flawr: no, it's N={0,1,2,3..} for 1-based indexing aswell. You will have escaped the array if you land on index 0 however.

@LeakyNun no, you take array[n] steps back, so the value which is in index 2. In the example above this is the number 5

@LeakyNun you're right, pasted the wrong array, it's fixed now

@MichaelKunst Please add some 1-indexed testcases.

Very closely related

@Martin Ender it's not related to the question... but me as a mobile user find it impossible to use the sandbox. What should I do to get a feedback on my questions before actually posting them?

What would using 1-based indexing look like? Does it affect only the initial index or all elements of the array? Would a value of 3 mean we go to the (1-based) index 3, but still go three steps back? If so, the current test cases don't cover 1-based indexing at all...

I am confused.  The third test case says start on index 5 which has the value 3 which is prime and since you can't take 3 steps back because this is the first step the answer should be 1 step, right?  So how is the answer 6 and why am I the only one that is confused?

@JerryJeremiah why can't you take 3 steps back? you'll land on index 2 if you start at 5 and take 3 steps back

@user902383 going to index 2, which is prime, so we do 2 steps back and go to index 0, which is not prime. The value at index 0 is 2, so we go to index 2, which is prime ... repeat

Ahhh.  So "X steps back" means "X indexes toward zero"?    I read "As the value of the field you are on is 8, you go to the index 8 as the FIRST STEP. The field you land on contains the value 2. You then go to index 2 as your SECOND STEP." which clearly (to me) equated "step" with "move" so "X steps back" would mean "back to the index you were on X moves ago".  I still think using "first step" to mean "first move" and "second step" to mean "second move" and "steps back" to mean "indexes toward zero" is confusing but at least I understand now.

Pyth, 31 Bytes
KlQ%tl-.u?}NUK?P_N-N@QN@QNKQEKK

The test cases
It uses zero to indicate a false value, the number of hops otherwise.

Python, 161 138 bytes
Credits for factorial.
g=lambda x:0**x or x*g(x-1)
f=lambda a,i,n=0,l=[]:(i<0)+(i>=len(a))and n or(0 if i in l else f(a,[a[i],i-a[i]][i and-g(i-1)%i],n+1,l+[i]))

Ideone it!
How it works
Wilson's theorem is used for prime checking.
Loop detection by storing seen indices to an array (l) and checking whether current index is in l.

Python, 107 bytes
import sympy
f=lambda a,i,n=0:0if n>len(a)else f(a,[a[i],i-a[i]][sympy.isprime(i)],n+1)if 0<=i<len(a)else n

Usage: f(list, start) ex: f([2,5,6,8,1,2,3], 3)
Returns 0 for loops (detected when n > len(a))

Matlab, 138 bytes
This a straighforward approach, using 1-based indices because Matlab uses 1-based indices by default. To count the number of steps we use a for loop counting from 1 to infinity(!). For the case were we cannot escape the array, we use a vector v to keep track of which entries we already visited. If we visit an entry twice, we know we are stuck in an unescapeable cycle. To see check whether we are outside of an array, we use the try/catch structure, which also catches out of bounds exceptions.
function r=f(a,i);v=a*0;v(i)=1;for k=1:Inf;if isprime(i);i=i-a(i);else;i=a(i);end;try;if v(i);r=0;break;end;v(i)=1;catch;r=k;break;end;end

05AB1E, 32 bytes
ï[U¯Xåi0,q}²gL<Xå_#X²XèXDˆpi-]¯g

Explanation
ï                                 # explicitly convert input to int
 [                            ]   # infinite loop
  U                               # store current index in X
   ¯Xåi0,q}                       # if we've already been at this index, print 0 and exit
           ²gL<Xå_#               # if we've escaped, break out of infinite loop
                   X²XèXDˆpi-     # else calculate new index
                               ¯g # print nr of indices traversed

Try it online

CJam, 44 bytes
Expects index array on the stack.
:G\{_G,,&{G=_L#)0{_L+:L;_mp3T?-F}?}L,?}:F~o@

Try it online!
My first CJam answer, hence why it's so terrible and imperative...
:G\{_G,,&{G=_L#)0{_L+:L;_mp3T?-F}?}L,?}:F~o@
:G                                              Store the array as G
  \                                             Put the index first
   {                                  }:F~      The recursive F function
     G,,                                        Generate a 0..length(G) sequence
    _   &                            ?          Check that the index is contained
         {                        }             If so, then...
          G=                                    Get the value at the index
            _L#)                 ?              If the value is in L (`-1)` gives `0` which is falsy)
                0                               Return 0 (infinite loop)
                 {              }               Otherwise...
                  _L+:L;                        Store the value we're accessing in L (infinite loop check)
                        _mp3T?-                 Remove 3 if the number is prime
                               F                Then recursively call F
                                   L,           We escaped! Return the size of "L" (number of steps)
                                          o     Print the top value of the stack
                                           @    Tries to swap 3 elements, which will error out

(it is considered okay to crash after the correct output as printed, which is what the program here does)

JavaScript (ES6), 100
Index base 0. Note: this function modifies the input array
(a,p)=>eval("for(s=0;1/(q=a[p]);++s,p=p>1&&p%i||p==2?p-q:q)for(a[p]=NaN,i=1;p%++i&&i*i<p;);q==q&&s")

Less golfed
(a,p)=>
{
  for(s = 0;
      1/ (q = a[p]);
      ++s)
  {
    a[p] = NaN; // mark visited position with NaN to detect loops
    for(i = 1; p % ++i && i*i < p;); // prime check
    p = p > 1 && p % i || p == 2 ? p-q : q;
  }
  return q==q && s // return false if landed on NaN as NaN != NaN
}

Test

F=
(a,p)=>eval("for(s=0;1/(q=a[p]);++s,p=p>1&&p%i||p==2?p-q:q)for(a[p]=NaN,i=1;p%++i&&i*i<p;);q==q&&s")

;[
 [[2,5,6,8,1,2,3], 3, 1]
,[[2, 0, 2], 2, false]
,[[14,1,2,5,1,3,51,5,12,3,4,41,15,4,12,243,51,2,14,51,12,11], 5, 6]
].forEach(t=>{
  var [a,b,k]=t, i=a+' '+b,r=F(a,b)
  console.log(r==k?'OK':'KO',i+' -> '+r)

})

JAVA, 229 218 Bytes
Object e(int[]a,int b){Stack i=new Stack();int s=0;for(;!(a.length<b|b<0);s++){if(i.contains(b))return 1>2;i.add(b);b=p(b)>0?b-a[b]:a[b];}return s;}int p(int i){for(int j=2;j<i/2;j++)if(i%j<1)return 0;return i<2?0:1;}

Thanks to Kevin, 11 bytes bites the dust.

A few things to golf it down some more: Stack<Integer>i=new Stack<>(); can be changed to Stack i=new Stack(); and return 1==2; can be changed to return 0>1;. Also, you might want to mention it's Java 7 instead of Java in general.

@KevinCruijssen I'm not sure is it point to mention that it is java 7, as especially now this solution is compatible with most java versions.

Well, in Java 8 you can use a lambdas which is shorter: a,b->{...} instead of Object e(int[]a,int b){...}, which is why I personally mention Java 7 to let people know I purposely haven't used Java 8 lambdas, but it's up to you.

@KevinCruijssen fair enough, when I'm using lamda, I'm specifying java version, but when solution works with java 7, it's usually works with java 8 as well, so it was pointless to add version. But you might be right, i should specify minimum version.

Racket, 183 156 bytes
Probably more bytes savable with further golfing, but that's it for me. :)
(require math)(define(e l i[v'()][g length])(cond[(memq i v)#f][(not(< -1 i(g l)))(g v)][else(e l((λ(a)(if(prime? i)(- i a)a))(list-ref l i))(cons i v))]))

Complete module with test suite with cleaner function:
#lang racket

(require math)

(define (e l i [v'()] [g length])
  (cond
    [(memq i v) #f]
    [(not (< -1 i (g l))) (g v)]
    [else (e l
             ((λ (a) (if (prime? i)
                         (- i a)
                         a))
              (list-ref l i))
             (cons i v))]))

(module+ test
  (require rackunit)
  (define escape-tests
    '((((2 5 6 8 1 2 3) 3) . 1)
      (((2 0 2) 2) . #f)
      (((14 1 2 5 1 3 51 5 12 3 4 41 15 4 12 243 51 2 14 51 12 11) 5) . 6)))
  (for ([t escape-tests])
    (check-equal? (apply e (car t)) (cdr t) (~a t))))

Run it like raco test e.rkt
Major kudos for @cat discovering the undocumented prime? function.

C, 121 bytes
Function f accepts array, starting index (0-based) and number of elements in the array, since there is no way how to test the end of an array in C (at least I don't know any).
p(n,i,z){return--i?p(n,i,z*i*i%n):z%n;}c;f(a,i,n)int*a;{return i<0||i/n?c:c++>n?0:i&&p(i,i,1)?f(a,i-a[i],n):f(a,a[i],n);}

Try it on ideone!
Note: function p(n) tests if n is prime or not. Credit for this goes to @Lynn and his answer for Is this number a prime?

@raznagul nonsense, you can't determine the length of an input parameter array. See answer 2 on the same question

@edc65: Sorry, I should have read beyond the first answer.

@Jasmes - In code golf, a function should be able to be called multiple times to get the same output. Your code requires resetting c to call the function again.

JavaScript, 121 132 bytes
p=n=>t=i=>n%i&&n>i?t(i+1):(0<n&&n<=i?1:0),c=-1,a=>r=s=>(++c,0<=s&&s<a.length?(p(s)(2)?r(s-a[s]):0||([a[s],s]=[0,a[s]])[1]?r(s):0):c)

f=(p=n=>t=i=>n%i&&n>i?t(i+1):(0<n&&n<=i?1:0),c=-1,a=>r=s=>(++c,0<=s&&s<a.length?(p(s)(2)?r(s-a[s]):0||([a[s],s]=[0,a[s]])[1]?r(s):0):c));

let test_data = [[[1,4,5,6,8,10,14,15,2,2,4,5,7],4],
                 [[2,5,6,8,1,2,3],3],
                 [[2,0,2],2],
                 [[14,1,2,5,1,3,51,5,12,3,4,41,15,4,12,243,51,2,14,51,12,11],5]];
for (test of test_data) {
    c = -1;
    console.log(f(test[0])(test[1]));
}

edit 1: oops, missed the bit about returning number of steps. fix coming soonish.
edit 2: fixed

Java, 163 160 bytes
boolean p(int n){for(int i=2;i<n;)if(n%i++==0)return 0>1;return 1>0;}
int f(int[]a,int n){return n<0||n>=a.length?1:p(n)?n<a[n]?1:1+f(a,a[n-a[n]]):1+f(a,a[n]);}

p(n) is for prime testing, f(a,n) is for the escape function. Usage:
public static void main(String[] args) {
    int[] array = {14,1,2,5,1,3,51,5,12,3,4,41,15,4,12,243,51,2,14,51,12,11};
    System.out.println(f(array, 5));
}

Ungolfed version:
static boolean isPrime(int n) {
    for (int i = 2; i < n; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

static int escape(int[] array, int n) {
    if (n < 0 || n >= array.length) {
        return 1;
    } else if (isPrime(n)) {
        if (n < array[n]) {
            return 1;
        } else {
            return 1 + escape(array, array[n - array[n]]);
        }
    } else {
        return 1 + escape(array, array[n]);
    }
}

Perl 6, 85 bytes
->\n,\a{{.[+a].defined??0!!+$_}(lazy n,{.is-prime??$_- a[$_]!!a[$_]}...^!(0 <=* <a))}

Explanation:
lazy n, { .is-prime ?? $_ - a[$_] !! a[$_] } ...^ !(0 <= * < a)

This is a lazy sequence of the indices traversed according to the rule.  If the index eventually exceeds the input array bounds (the !(0 <= * < a) condition), the sequence is finite; otherwise, the indices cycle infinitely.
That sequence is fed to the internal anonymous function:
{ .[+a].defined ?? 0 !! +$_ }

If the sequence is defined at the index given by the size of the input array, it must have entered an infinite cycle, so 0 is returned.  Otherwise, the size of the sequence +$_ is returned.

Perl 5, 107 + 1 (-a) = 108 bytes
for($i=<>;!$k{$i}++&&$i>=0&&$i<@F;$s++){$f=0|sqrt$i||2;1while$i%$f--;$i=$f?$F[$i]:$i-$F[$i]}say$k{$i}<2&&$s

Try it online!
0-based list.  Returns false (blank) if the list is unescapable.

source: Stack Exchange

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

sort: votes


text:
Output a Magical 8 Trapezium
Your task is to output a Magical 8 Trapezium:
        1 × 8 + 1 = 9
       12 × 8 + 2 = 98
      123 × 8 + 3 = 987
     1234 × 8 + 4 = 9876
    12345 × 8 + 5 = 98765
   123456 × 8 + 6 = 987654
  1234567 × 8 + 7 = 9876543
 12345678 × 8 + 8 = 98765432
123456789 × 8 + 9 = 987654321

Output in your chosen language in the fewest bytes possible.
Note the number of spaces at the start of each line to maintain the trapezium shape.
Trailing spaces are allowed.
You can use × or the letter x - whichever you prefer.

Related. (slightly...)

Middle spaces are required, yes?

@KevinLau-notKenny it is, but you could always post an alternative too if it's significant.

It's 6 bytes corresponding to the 6 spaces in the middle, so no, I don't think it's significant enough.

Python 2, 59 bytes
a=i=1
exec"print'%9d x 8 +'%a,i,'=',a*8+i;i+=1;a=a*10+i;"*9

The numbers a and i the equation a * 8 + i are generated arithmetically. Each line, i is incremented, and a has the next digit appended via a=a*10+i. For example, if a=12345, i=5, then i becomes 6, so the new a is 12345*10 + 6 which is 123456.
Storing these as numbers rather than strings lets us compute the RHS as given by the equation a*8+i, which is shorter than string reversing.

+1 for seeing this for what it is - a sum that can be generated

V, 37 bytes
i¸ 1 X 8 + 1 = 98ñYp|Eylp^Xf+$ylp

Try it online!
This contains unprintable, so here is a hexdump:
00000000: 69c2 b820 3120 5820 3820 2b20 3120 3d20  i.. 1 X 8 + 1 =
00000010: 391b 38c3 b159 707c 4579 6c70 015e 5866  9.8..Yp|Eylp.^Xf
00000020: 2b01 2479 6c70 18                        +.$ylp.

PHP, 105 89 60 57 bytes
my first golf try here (thanks to manatwork & user55641)
for(;$i++<9;)printf("%9s x 8 + $i = %s
",$s.=$i,$s*8+$i);

59
for(;$i++<9;)printf("%9s x 8 + $i = %s
",$s.=$i,$t.=10-$i);

89 (my own try)
for(;@++$i<=9;){printf("%9s x 8 + %s = %s\n",join(range(1,$i)),$i,join(range(9,10-$i)));}

105 (first)
for($j='123456789';@$j[$i++];){printf("%9s x 8 + %s = %s\n",substr($j,0,$i),$i,strrev(substr($j,-$i)));}

No need for the braces around a single statement. The $i alone better interpolate directly in the string without format specifier.

You can drop 23 more bytes with a few tricks:
Changing @++$i<=9 to $i++<9 saves 2 bytes. You don't need to silence notices as they don't stop execution and under standard PPCG rules you can ignore stderr if you want to.
Changing the \n to an actual newline character saves a byte.
Changing the join(range(...)) bits to $s.=$i and $t.=10-$i saves 15 bytes. This works because assignments return the value assigned  and is pretty much the most valuable trick I've found for golfing php.
The last 5 bytes are detailed by manatwork above

You can drop 2 more bytes by replacing $t.=10-$i with $s*8+$i. https://tio.run/##K8go@G9jXwAk0/KLNKxVMrW1bSytNQuKMvNK0jSUVC2LFSoULBS0FVQyFWwVVIu5lHRUivVsVTKBlJaFtkqmpvX//wA

That´s 59 bytes. And $s*8+$i instead of $t.=10-$i saves two more.

Pyth, 32 bytes
VS9ss[*dK-9NSN" x 8 + "N" = "r9K

Try it online!
VS9ss[*dK-9NSN" x 8 + "N" = "r9K
VS9                                  # For N in 1..9
   s                                 # Join without delimiter
    s[                               # Reduce the array on + (flattens)
      *dK-9N                         # - Space, repeated K=(9-N) times
            SN                       # - The string sequence 1..N
              " x 8 + "              # - This string literal
                       N             # - N itself
                        " = "        # - This string literal
                             r9K     # - The string sequence 9..K

Thanks to @FryAmTheEggman for saving 2 bytes.
Thanks to @KennyLau for saving 3 bytes.

s does not join with space - it joins with no delimiter.

@isaacg hah, and now I'm thinking I could save a byte by joining with space

The byte-count would be the same.

05AB1E, 32 31 30 28 bytes
Code:
TG9N-ð×NLJðN"x8+ÿ="€ðJžmN£J,

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

.c isn't usable here?

@carusocomputing It is, but that postdates the challenge.

Ahhh... Did not see the timestamp.

CJam, 39 38 36 bytes
Thanks to Optimizer for saving 2 bytes.
9{)_,:)9Se[" x 8 + "@S'=S9_,fm4$<N}/

Test it here.
Same byte count:
9{)_,:)9Se[]"x8+"+:\'=9_,f-Y$<]S*n}/

This requires the latest version, available on Try it online!

@Optimizer lived up to his name, then!

Python 2, 87 84 78 75 bytes
s="123456789"
n=1
exec'print"%9s"%s[:n],"x 8 + %s ="%n,s[::-1][:n];n+=1;'*9

Try it online
A previous version uses some string magic.
R=range(1,10)
for n in R:print" "*(9-n)+`R`[1:n*3:3]+" x 8 + %d = "%n+`R`[-2:27-3*n:-3]

Casting range(1,10) to a string gives [1, 2, 3, 4, 5, 6, 7, 8, 9], and this is nice since every number is only a single digit. So getting the string 123456789 from this is simple with `range(1,10)`[1::3]. The reversed range is  `range(1,10)`[-2::-3]. Then, to get only as far as I want each iteration, I slice it off at either 3*n, or at 3*(9-n) (27-3*n) for the reversed digits.

You can do for n in range(1,10):print"%9s"%s[:n]+" x 8 + %s = "%n+s[::-1][:n] for 80 bytes.

s="123456789";n=1;exec'print"%9s"%s[:n],"x 8 + %s ="%n,s[::-1][:n];n+=1;'*9 saves three more! Down to 75.

Nice, thanks for the help! Too bad I had to double-slice the second time...

Ruby, 77 73 65 60 bytes
Try it online~
Major revamps from @manatwork
Another overhaul from @xsot
a=i=0;9.times{puts"%9d x 8 + %d = %d"%[a=a*10+i+=1,i,a*8+i]}

Seems to be shorter with format string: puts'%9d x 8 + %d = %d'%[k=[*1..i]*'',i,k.to_i*8+i].

(1..9).map → 1.upto(9)

Ah, I didn't know about %9d being a formatting option to pad integers like that

60: a=i=0;9.times{puts"%9d x 8 + %d = %d"%[a=a*10+i+=1,i,a*8+i]}

@xsot that's great! Didn't think of calculating the initial number like that.

Java 10, 151 133 130 129 126 110 bytes
v->{String p="\n",r="";for(int n=123456789,i=9;i>0;n/=10,p+=" ")r=p+n+" x 8 + "+i+" = "+(n*8+i--)+r;return r;}

Try it online.
Explanation:
v->{                   // Method with empty unused parameter and String return-type
  String p="\n",       //  Prefix-String, starting at a newline
         r="";         //  Result-String, starting empty
  for(int n=123456789, //  Multiply-number, starting at 123456789
      i=9;i>0          //  Loop `i` in the range [9, 0):
      ;                //    After every iteration:
       n/=10,          //     Remove the last digit from the integer
       p+=" ")         //     Append a space after the prefix
    r=...+r;           //   Prepend the following to the result-String:
      p                //    The prefix-String
      +n               //    Followed by the integer
      +" x 8 + "       //    Followed by the literal String " x 8 + "
      +i               //    Followed by the loop-index `i`
      +" = "           //    Followed by the literal String " = "
      +(n*8+i--)       //    Followed by the result of that equation
  return r;}           //  Return the result-String

I think you could save bytes by using x instead of the multiplication sign.

You can save a couple of bytes by initializing s to "\n" and removing "\n"+ from the for loop

@wizzwizz4 Thanks. Should have known × is 2 bytes instead of 1 like x..

Aren't you adding s to the result on each iteration as well?

I know this is old, but can't you do return o instead of System.out.print(o)? Also, you can change to Java 10 and save with var and lambdas

@EmbodimentofIgnorance Done. This is indeed one of my earliest answers. :) Not even sure why I had the print instead of return.. xD PS: I cannot use var since there are two Strings. I could use something like var p="\n";var r="";, but that would be 1 byte longer instead of shorter.

Perl, 49 bytes
printf"%9s x 8 + $_ = %s
",$@.=$_,$_+8*$@for 1..9

Usage
perl -e 'printf"%9s x 8 + $_ = %s
",$@.=$_,$_+8*$@for 1..9'

C#, 113 bytes
void f(){for(int n=1,i=1;i<10;n=10*n+ ++i)Console.WriteLine(new string(' ',9-i)+n+" x "+"8 + "+i+" = "+(n*8+i));}

if you have anyway to improve this solution feel free to share.

You can save 1 byte by removing a space: ;n=10*n+ ++i in the for-loop can be changed to ;n=++i+10*n. Also, +" x "+"8 + "+ can be changed to +" x 8 + "+. to save 3 more bytes.

void f(){for(int n=1,i=1;i<10;n=++i+10n)Console.WriteLine($"{new string(' ', 9-i)}{n} x 8 + {i} = {(n8+i)}");}
------------ saved you a byte!

Batch, 117 bytes
@echo off
set a=         12345678987654321
for /l %%i in (1,1,9)do call echo %%a:~%%i,9%% x 8 + %%i = %%a:~17,%%i%%

Yes, that is 16 % signs on one line; that's Batch for you!

J, 51 bytes
(|."1|.\p),.' x 8 + ',"1]p,.' = ',"1]\|.p=:u:49+i.9

Creates the string 123456789 and then operates on prefixes and suffixes of it to create the output.
Usage
   (|."1|.\p),.' x 8 + ',"1]p,.' = ',"1]\|.p=:u:49+i.9
        1 x 8 + 1 = 9
       12 x 8 + 2 = 98
      123 x 8 + 3 = 987
     1234 x 8 + 4 = 9876
    12345 x 8 + 5 = 98765
   123456 x 8 + 6 = 987654
  1234567 x 8 + 7 = 9876543
 12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321

JavaScript ES6 (88)
Taking advantage of the new repeat method, backticks and templating...
i=10;for(y="";--i;)console.log(`${" ".repeat(i)+(y+=(x=10-i))} x 8 + ${x} = ${y*8+x}\n`)

nice job bro , you should consider to remove some space and use alert instead of console.log, it can save some bytes!

Given I answered this just before midnight I figure I was close to half asleep... I'll post an update on this soon. LOL

PowerShell v2+, 85 64 58 57 52 bytes
8..0|%{" "*$_+-join(1..++$i+" x 8 + $i = "+9..++$_)}

Loops from 8 to 0 8..0|%{...} via the range operator. Each iteration, we output a string concatenation consisting of (the appropriate number of spaces " "*$_), plus a -joined string of (a range from 1 to a pre-incremented helper number ++$i, plus the middle bit " x 8 + $i = ", plus the final range from 9 to the current number $_ pre-incremented).
One big trick here is we leverage the "left-preference" for typecasting, which allows us to "add" arrays together inside the -join parens, meaning we use only one -join operator.
Example
PS C:\Tools\Scripts\golfing> .\magical-8-trapezium.ps1
        1 x 8 + 1 = 9
       12 x 8 + 2 = 98
      123 x 8 + 3 = 987
     1234 x 8 + 4 = 9876
    12345 x 8 + 5 = 98765
   123456 x 8 + 6 = 987654
  1234567 x 8 + 7 = 9876543
 12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321

%{ Are your eyes alright?

@gcampbell If your eyes looked like that, you'd be frowning, too.

Depends on how your font renders percents.

Haskell, 92 bytes
s=(show=<<)
[1..9]>>= \x->([x..8]>>" ")++s[1..x]++" x 8 + "++s[x]++" = "++s[9,8..10-x]++"\n"

How it works:
s=(show=<<)                   -- helper function that turns a list of numbers into
                              -- a string without delimiters, e.g. [1,2] -> "12"

[1..9]>>=                     -- for each number 1 to 9
     ([x..8]>>" ")            -- take length of [x..8] copies of a space
     s[1..x]                  -- the digits from 1 to x
     " x 8 + "                -- a string literal
     s[x]                     -- the digit of x
     " = "                    -- another string literal
     s[9,8..10-x]             -- the digits from 9 down to 10-x
     "\n"                     -- an a newline

Pyke, 30 29 bytes
9Fd*~utj+9<\x8\+9i-\=ji>_dJ)X

Try it here!
9F                         )  -  for i in range(9):
  d*                          -       " " * i
        +                     -      ^ + V
       j                      -       j = V
    ~ut                       -        "123456789"
         9<                   -     ^[:9]
           \x8\+9i-\=         -    [^, "x", 8, "+", (9-i), "=", V]
                        _     -     reversed(V)
                     ji>      -      j[i:]
                         dJ   -   " ".join(^)
                            X - print(reversed(^))

Retina, 66 bytes
Byte count assumes ISO 8859-1 encoding. The leading linefeed is significant.

123456789!9 = 987654321
+`^((.)+)\B.!.(.+).
 $1!$2$3¶$&
!
 x 8 +

Try it online!

MATL, 38 36 35 bytes
9:"9@-Z"@:!V' x 8 + '@VO61O58@:-v!D

Try it online!

C, 74 bytes
d(i,n){for(i=n=1;i<10;n=++i+n*10)printf("%9d x 8 + %d = %d\n",n,i,n*8+i);}

R, 107 103 bytes
a=1;for(i in 2:10){cat(rep("",11-i),paste(a,"x",8,"+",(i-1),"=",strtoi(a)*8+(i-1)),"\n");a=paste0(a,i)}

Ungolfed :
a=1

for(i in 2:10)
    cat(rep("",11-i),paste(a,"x",8,"+",(i-1),"=",strtoi(a)*8+(i-1)),"\n")
    a=paste0(a,i)

Result :
        1 x 8 + 1 = 9
       12 x 8 + 2 = 98
      123 x 8 + 3 = 987
     1234 x 8 + 4 = 9876
    12345 x 8 + 5 = 98765
   123456 x 8 + 6 = 987654
  1234567 x 8 + 7 = 9876543
 12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321

96 bytes

APL (Dyalog Unicode), 61 52 39 bytesSBCS
↑(⍳9)((¯9↑↑),' x 8 +',⊣,'= ',↑∘⌽)¨⊂1↓⎕D

Try it online!
-9 bytes by using the 10⊥ trick to parse the number, instead of a reduction.
Thanks to @Adám for -13!
Explanation:
↑    ((¯9↑↑),' x 8 +',⊣,'= ',↑∘⌽)¨⊂1↓⎕D
                                     ⎕D  ⍝ Numbers from 0 to 9
                                   1↓    ⍝ Drop the 0
 (⍳9)(                          )¨⊂      ⍝ Do 9 times, N=current
                             ↑∘⌽         ⍝ Reverse the string (9..1) and cut off N elements
                      ⊣                  ⍝ N itself
      (   ↑)                             ⍝ Drop N elements off the 1..9 string...
      (¯9↑ )                             ⍝ ...then pad it back with spaces
            ,' x 8 +', ,'= ',            ⍝ Join with a few constant strings
↑                                        ⍝ Format

Brainfuck, 232 bytes
++++++++[->+>+>+++++[->+>+>+>+>+>+++<<<<<<]>->>+>++>+++<<<<<<<<]>++>+>>>+++>>>---<<<<<<[-[-<<+>>>>.<<]>+[-<+>>>>+.<<<]>.>>>>>.<<<<<.>>>.<<<.>.<.>>.<<.>>>>.<<<<.<<<<[->>>+>>>+<<<<<<]>>[-<<+>>>>>>.-<<<<]>[->>>-<<<<+>]<<<[->>>+<<<]>.>]

Try it online!
Can be golfed much further...

Javascript (using external library) (143 bytes)
n=>_.Range(1,9).WriteLine(v=>_.Range(0,10-v).Write("",x=>" ")+_.Range(1,v).Write("")+" x 8 + " + v + " = "+_.Range(10-v,v).Reverse().Write(""))

Link to lib: https://github.com/mvegh1/Enumerable/
Explanation of code: Create range 1 to 9, and for each value, write a line corresponding to the complex predicate. The predicate is passed the current integer value, and creates a range spanning 10-currentValue elements, in order to create that many spaces. Those spaces are concatenated with the formula part of the line, and then that is concatenated with the tailend of the range matching the number of elements as the frontend, in reverse order.
Note: In the image, the first line is off by one space because the console added a quotation mark since the return value is a string. The actual value is formatted correctly

JavaScript (ES6), 99 bytes
_=>[...Array(9)].map((n,i)=>`${n="        123456789".substr(i,9)} x 8 + ${++i} = ${n*8+i}`).join`\n`
_=>".........".replace(/./g,(n,i)=>`${n="        123456789".substr(i,9)} x 8 + ${++i) = ${n*8+i}\n`)

Where \n represents a literal newline character. The second version outputs a trailing newline. I came up with a formula for the numbers ('1'.repeat(9-i)+0+i)/9 but the padding was easier to do this way.

05AB1E, 24 bytes
9Lε©LJ'x8'+®'=T®L-Jðý}.c

Try it online!
Uses a newer version than the challenge, which is now allowed.

It's not much, but in the even newer version of 05AB1E you can remove the ©, and change the ® to y to save a byte.

@KevinCruijssen Eh, I don't generally "update" old answers like that. Also, the "newer version" is a totally different language (different implementations).

Canvas, 20 bytes
９｛Ｒ⤢x∙8∙+¹=¹◂±ｍ） ＊］ｒ

Try it here!

VBA (Excel), 51 bytes
Using Immediate Window
For z=1To 9:a=a &z:?Spc(9-z)a" x 8 +"z"="a*8+z:Next

k (77 bytes)
Could probably be shortened a bit more
-1@'((|t)#\:" "),'(t#\:n),'" x 8 + ",/:n,'" = ",/:(t:"I"$'n)#\:|n:"123456789";

Example:
k)-1@'((|t)#\:" "),'(t#\:n),'" x 8 + ",/:n,'" = ",/:(t:"I"$'n)#\:|n:"123456789";
         1 x 8 + 1 = 9
        12 x 8 + 2 = 98
       123 x 8 + 3 = 987
      1234 x 8 + 4 = 9876
     12345 x 8 + 5 = 98765
    123456 x 8 + 6 = 987654
   1234567 x 8 + 7 = 9876543
  12345678 x 8 + 8 = 98765432
 123456789 x 8 + 9 = 987654321

golflua, 56 characters
p=""~@i=1,9p=p..i; w(S.q("%9s x 8 + %d = "..p*8+i,p,i))$

Sample run:
bash-4.3$ golflua -e 'p=""~@i=1,9p=p..i; w(S.q("%9s x 8 + %d = "..p*8+i,p,i))$'
        1 x 8 + 1 = 9
       12 x 8 + 2 = 98
      123 x 8 + 3 = 987
     1234 x 8 + 4 = 9876
    12345 x 8 + 5 = 98765
   123456 x 8 + 6 = 987654
  1234567 x 8 + 7 = 9876543
 12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321

Object Pascal (FPC), 156 127  103 bytes
Trivial solution, using the Format library func. Shaved some more bytes by using only integers and no strings. Reduced in size thanks to @manatwork (for teaching me some basic stuff about writeln).
var i,c:int64;begin i:=0;for c in[1..9]do begin i:=i*10+c;WriteLn(i:9,' x 8 + ',c,' = ',i*8+c);end;end.

Try it online!
Ungolfed:
var
  i, c: int64;
begin
  i := 0;
  for c in [1..9] do
  begin
    i := i*10+c;
    WriteLn(i:9, ' x 8 + ', c, ' = ', i*8+c);
  end;
end.

Nice, but why you use Format? WriteLn(i:9,' x 8 + ',c,' = ',i*8+c); And with the price of a compiler warning you can remove i:=0;. (Yes, will not be compatible with some ancient Pascal versions.)

@manatwork Because I didn't know about the : operator... Will change it later today

I'm afraid, the : is not operator. Is Write/WriteLn specific field width specifier.

@manatwork Yeah thats what I meant, didn't know about it.

///, 149 bytes
/:/ x 8 + //-/ = //0/1234//_/9876//|/  /||||1:1-9
||| 12:2-98
|||123:3-987
|| 0:4-_
||05:5-_5
| 056:6-_54
|0567:7-_543
 05678:8-_5432
056789:9-_54321

Try it online!

dc, 79 bytes
1[32P]sS[d0<S1-d0<R]sR[dZ9r-lRxrdn[ x 8 + ]PdZn[ = ]Pdd8*rZ+prd10*dZ+dZA>M]dsMx

Try it online!
Somewhat better than I expected. Started with a solution that juggled stack and an incremental register before realizing I only need to keep the left-most number around - since the value to be added is the number of digits the left-most number has, this can be determined via Z and the result can just be calculated according to the formula.
[32P]sS[d0<S1-d0<R]sR feels wasteful, but I couldn't come up with a much better way to handle the indentation. The main macro, [dZ9r-lRxrdn[ x 8 + ]PdZn[ = ]Pdd8*rZ+prd10*dZ+dZA>M]dsMx should be fairly self-explanatory based on my above description. The initial 1 just seeds the whole thing.

Pyth - 30 bytes
First attempt, working on optimization.
VS9+*dK-9Njd[jkSN\×8\+N\=jkr9K

Try it online.

Forth (gforth), 76 bytes
: f 0 10 1 do cr 10 * i + dup 9 .r ."  x 8 + "i . ." = "dup 8 * i + . loop ;

Try it online!
Explanation
Start a value at 0. Starts a loop from 1 to 9. Each iteration:

Multiply value by 10 and add the loop index
output this value right-aligned
output " x 8 + "
output the loop index
output " = "
calculate results and output

Code Explanation
: f                  \ start word definition
  0                  \ set up counter/value
  10 1 do            \ start a counted loop from 1 to 9
    cr               \ output a newline
    10 * i +         \ calculate the next value for the first term
    dup 9 .r         \ make a copy and then output in a right-aligned space of 9 characters
    ."  x 8 + "      \ output " x 8 +"
    i .              \ output the loop index
    ." = "           \ output " ="
    dup 8 * i +      \ perform the actual calculation
    .                \ output result
  loop               \ end the counted loop
;                    \ end the word definition

Perl 6, 58 bytes
my $a;printf "%9s x 8 + $_ = %s\n",$a~=$_,$a.flip for 1..9

Try it online!

Vyxal C, 24 bytes
`%x8+%=%`Ṅ9ɾ:ṅḂ"v¦$wY∩v%

Try it Online!
`%x8+%=%`                 # Take the string "%x8+%=%"
         Ṅ                # Join by spaces
                       v% # Replace %s in this with each of...
                      ∩   # Transposed..
                     Y    # Interleave...
           9ɾ:     $w     # 1...9 and...
           9ɾ ṅ           # "123456789"
               Ḃ"v¦       # Prefixes and reversed suffixes

JavaScript, 70 bytes

alert = console.log; // for less frustration

for(n='1';m=n%10;n+=++m)alert(n.padStart(9)+` x 8 + ${m} = `+(n*8+m));

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

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


text:
Brute force my code lock
The code lock for my garage has 5 buttons, labeled "1 2", "3 4", "5 6", "7 8", and "9 0". To open the garage door, you have to enter the correct 4-digit PIN.
As you can see, every button represents two numbers. Thus some PINs, like "1357" and "2367", are essentially identical because they require the same sequence of button presses.
Further, there is no "open" button so the lock always just takes the last 5 digits that were entered. For example, pressing "135791" would open the door for the PINs "1357", "3579", and "5791" (as well as all their equivalents).
Your task is to write a piece of code that outputs or returns a string of digits or list of numbers that, if entered, is guaranteed to open my garage door. Remember: when your result includes "1458", you don't need to output "2367" anymore. You can use all 10 digits, but using only odd or even digits is sufficient.
The shortest result sequence wins (measured in digits, 629 (4+5^4) is the theoretical minimum). If equal, the shortest code in bytes wins.

I'm voting to close this question as off-topic because I think this challenge would do better on Puzzling rather than here

@muddyfish It's not actually difficult to find an optimal solution, so I don't think this is interesting from a puzzling perspective.

@FryAmTheEggman Since when is "shortest code in bytes wins" not a competition on this site?

Sorry, I missed the tie-breaker. However, that makes it seem like the initial winning criterion is rather pointless?

@FryAmTheEggman I could have written "output most not be longer than 629 digits" instead, and made it a pure code golf. I wanted to allow answers that are not "perfect" to make it a bit easier to get started.

Alright, it's just that the first part (finding the shortest value) is very strongly related to this challenge, if I'm not mistaken. There are well known ways to generate the shortest sequences that will match every permutation.

If it's not a duplicate of the one that Fry linked, it's possibly a duplicate of this one.


text:
Missing Integer Sequence Detection -- Filesystem
The challenge is to detect missing integer sequences of files or directories. You have a directory filled with files/directories that are named as integers.
The files/directories are generated from multiple threads yet the job did not complete - there are therefore gaps in the sequence.
The input is two integers a start and an end, and your task is detect the starting integer of the next missing sequences. You may presume that all files and directories in the directory where run have only integer named files or directories.
Acceptable answer forms: functions, code snippets - they must run on the command line.
Acceptable start/end input: included on the command line, env variables/argv are okay, parameters to functions, user input is okay.
Shortest code wins.
Update -- Although I managed to squeeze out this one, there were many interesting answers. The idea in apricotboy's Bash answer was used in part to help me design my 35 Byte Bash answer. Best of luck on the next one.
E.g. Presume files 1,2,3,4,7,8,9,10,18 are present, start is 1, end is 20:

The output should be:
5
11
19

Can I input an array instead of reading my own files?

It seems a rather pointless extra requirement to me.

@A.Danischewski I find the real-world background here is too much of a narrow reference to justify the file requirement.

Can I just delete all files and print 1?

This is absolutely a chameleon challenge - the requirement to take input as file names and/or directories makes this challenge more about working with the filesystem than actually filling in the holes.

You all complain too much whenever there's a challenge requiring any functionalities other than shuffling integers or strings around.

Related, possibly a dupe target since it's mostly the same challenge, but without the unnecessary requirement of doing filesystem I/O.

@feersum We complain when challenges arbitrarily require extra functionality (like filesystem I/O) that don't add anything to the actual challenge.

@Mego How do you determine whether a thing is a thing or not a thing?

@feersum How is finding missing integers in sequence related to finding files in directory?

May we output a list of missing names?

Can any of the arguments be negative?

Ok so do we have to write IO code or not? I solved the non-IO part of the problem...

Python 2, 101 bytes
2 bytes thanks to @xnor.
import os
t=-1
for n in range(input(),input()+1):
 if~-os.path.isfile(str(n)):
  if~t+n:print n
  t=n

I detected 2 trailing spaces after your import os that you should take out.

@KevinLau-notKenny Thanks.

I think if~-n!=t: can be if~t+n:.

Ruby, 74 60 45 bytes
Input is in command line, run it like ruby f.rb 0 20. Only works in current directory.
-1 byte from unpacking the ARGV into variables, and -13 bytes from replacing the select and grep with a set subtraction.
V3: -5 bytes from using a substitution for Dir.glob in an old Ruby answer to another filesystems challenge, as suggested by @PatrickOscity. -10 from remembering some quirks in Ruby's String#next function.
a,b=$*
f=[*a..b]-Dir[?*]
puts f-f.map(&:next)

Dyalog APL, 25 24 or 36 bytes
Prompts for lower bound, then upper bound.
It seems from comments to other answers  that the OP wanted as short sequences as possible.
{⍵/⍨~⍵∊⍨⍵-1}((⍳⎕)~⍳⎕-1)~⍎¨⎕SH'dir/b'

{
    ⍵/⍨ those where it is
    ~ not true
    ⍵∊⍨ that the set contains
    ⍵-1 their predecessor
} of
(
    (⍳⎕) of the integers until n
    ~ except
    ⍳⎕-1 integers until n-1
)~ except
⍎¨ the evaluation of each of
⎕SH'dir/b' the bare list of names in the current directory

Old answer which returns length-1 sequences:
(⍕¨(⍳⎕)~⍳⎕-1)~⎕SH'dir/b'

(
    ⍕ string representation
    ¨ of each
    (⍳⎕) of the integers until n
    ~ except
    ⍳⎕-1 integers until n-1
)~ except
⎕SH'dir/b' the bare list of files in current directory
Only works on Windows. A cross platform solution:
(⍕¨(⍳⎕)~⍳⎕-1)~0⎕NINFO⍠1⊢'*'

0 just the filename(s)
⎕NINFO of the Native file(s) INFOrmation
⍠1 using wildcards
⊢'*' on all files

I'm getting       (⍕¨(⍳⎕)~⍳⎕-1)~0⎕NINFO⍠1⊢'*'
Unknown APL character: ⍠ (U+2360)
Non-APL character

@A.Danischewski Which APL are you using?

@A.Danischewski Dyalog APL

@A.Danischewski Specifically version 15.0+, which is free, and downloadable with the link I provided.

Let us continue this discussion in chat.

@A.Danischewski Please continue in chat.

Perl 6, 47 bytes
{my \c;.say if .IO.e??(c=0)!!!c++ for $^a..$^b}

Explanation:
{my \c;.say if .IO.e??(c=0)!!!c++ for $^a..$^b}
{                                               } # A function. Arguments: $^a and $^b (implicitly)
 my \c;                                           # A variable without prefix (\ is needed only here)
                                  for $^a..$^b    # For each number between $^a and $^b
       .say if                                    # Print the number if the result is truthy:
               .IO.e??(c=0)!!!c++                 # If the file exists, reset the sequence (don't print this one), otherwise, return the `!(c++)` result (is it the first time we're incrementing)

Tried to use flipflops. Didn't manage to :P.

this is a function. just put parentheses with the arguments after the closing }.

yep :-). hoping to see more people using Perl 6 everywhere, even in golfing!

PHP, 64 bytes
<?=implode("\n",array_diff(range($argv[1],$argv[2]),glob("*")));

Run like this:
php -f golf.php 1 20

Note:

Only does the current directory.
No trailing newline on the output.
This requires the <?= to be allowed in php.ini. Which I think is default but I'm not sure.

Bash, 31 bytes
a(){(seq $@;ls)|sort|uniq -u;}

Run as a 1 20. Again, only does the current dir.
Can I submit two? Hope so. This is my first post to Code Golf so I'm not too sure of the etiquette. Hope I'm counting my bytes correctly, too.

You can submit multiple solutions, but unless they are trivial derivatives of each other, each solution should be in a separate answer.

You're only supposed to print the first element of each missing range, but the PHP code looks like it would print all of the missing numbers, is this correct?

Ah, my bad. I misunderstood it and just aimed to get the output in the question, without reading into it enough. Should I take my submission down?

I see now this is an old question, but still, I like it...
PowerShell, 70 bytes
for($m,$n=$args;$m-le$n;$m++){$w=$a;$a=Test-Path $m;if(!$a-and$w){$m}}

Run as a script from the command line, eg .\misso.ps1 1 20.

PowerShell v4+, 62 bytes
param($x,$y)$x..$y|?{$_-notin($a=(ls ".\").Name)-and$_-1-in$a}

Save as a script in the desired directory and call it locally (see example below). Takes input $x and $y and constructs a range .., then pipes that to a Where-Object (the |?{...}) which is basically a filter. Here we're only selecting items where the current element $_ is -notin the .Name collection of the current directory, but the previous element is -in that collection (i.e., only the start of a missing range).
The ls is an alias for Get-ChildItem and is basically what you'd expect. Requires v4 for the encapsulation-select of .Name, otherwise you'd need $a=ls ".\"|select Name.
Example
PS C:\Tools\Scripts\golfing\misd> ls .\

    Directory: C:\Tools\Scripts\golfing\misd

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         7/26/2016   7:48 AM          8 1
-a---         7/26/2016   7:48 AM         10 10
-a---         7/26/2016   7:54 AM          0 18
-a---         7/26/2016   7:48 AM          8 2
-a---         7/26/2016   7:48 AM          8 3
-a---         7/26/2016   7:48 AM          8 4
-a---         7/26/2016   7:48 AM         10 7
-a---         7/26/2016   7:48 AM          8 8
-a---         7/26/2016   7:48 AM          8 9
-a---         7/26/2016   8:18 AM        365 misd.ps1

PS C:\Tools\Scripts\golfing\misd> .\misd.ps1 1 20
5
11
19

Groovy, 53 bytes
{f,s,e->(s..e)-f.listFiles().collect{it.name as int}}

I had an explanation and screenshots, but I didn't post that version and left the page... Either that or I posted the answer to a random S.O. thread about the "best way to stat a directory in Groovy".


text:
Convert exponents into ASCII art
Task
Your task is to convert strings like this:
abc^d+ef^g + hijk^l - M^NO^P (Ag^+)

To strings like this:
   d   g       l    N P    +
abc +ef  + hijk  - M O  (Ag )

Which is an approximation to abcd+efg + hijkl - MNOP (Ag+)
In words, raise the characters directly next to carets to the upper line, one character for one caret.
Specs

Extra trailing whitespaces in the output are allowed.
No chained carets like m^n^o will be given as input.
A caret will not be followed immediately by a space or by another caret.
A caret will not be preceded immediately by a space.
All carets will be preceded by at least one character and followed by at least one character.
The input string will only contain printable ASCII characters (U+0020 - U+007E)
Instead of two lines of output, you are allowed to output an array of two strings.

To those who speak regex: the input string will match this regex:
/^(?!.*(\^.\^|\^\^|\^ | \^))(?!\^)[ -~]*(?<!\^)$/

Leaderboard

var QUESTION_ID=86647,OVERRIDE_USER=48934;function answersUrl(e){return"http://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"http://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

Is the input a single line, or are multi-line strings possible?

@TimmyD "The input string will only contain printable ASCII characters (U+0020 - U+007E)"

Why stop at exponents? I want something that handles H_2O!

@Neil Make your own challenge then, and I may close this challenge as a duplicate of that one. :)

Based on your example I'd say they are superindices, not necessarily  exponents

Those who speak regex hail from a highly regular country where expression is tightly constrained. The leading cause of death is catastrophic backtracking.

Only printable ASCII, sure, but \n is composed of two printable characters ;-)

@TimmyD Then it is \n, not the linefeed.

V, 15 14 bytes
ÄÒ +òf^xxé kPj

Try it online!
A fairly straightforward solution. The perfect challenge for V!
Explanation:
Ä                "Duplicate this current line
 Ò               "Replace this line with spaces
   +             "Move to the beginning of the next line
    ò         ò  "Recursively (The second ò is implicit):
     f^          "  Find a caret
       xx        "  Delete two characters. The second will be saved into the main register
         é       "  Insert a space
           k     "  Move up
            P    "  Paste from the main register
             j   "  Move down

Conveniently, based on how the recursion works, this will run once for every single caret.

vim is perfect language for this challenge. +1

Cheddar, 77 72 67 bytes
l->l.chars.vfuse.replace("^\n"," ").lines.map(j->"%-2s"%j).turn(3)

No regex!
I love this answer as it is a wonderful demonstration of Cheddar's abilities. Mainly thanks to the replace function added by Conor. The PR to dev was never made so the replace function only exists on this branch (update: I made the PR and now it's on the latest beta branch which you can install with npm install -g cheddar-lang)
I have found a way to golf it but unfortunately an oversight results in this happening when item lengths are not the same:
["   denifednud   denifednug       denifednul    denifednuN denifednuP    denifednu+ ", "abcdenifednu +efdenifednu  + hijkdenifednu  - Mdenifednu Odenifednu  (Agdenifednu )"]

I could have saved a lot of bytes using regex, and in fact I just made regexes for Cheddar... the only problem is that there are no regex functions :/
Explanation
l->                    // Function take input as `l`
   l.chars             // Get array of chars in input
   .vfuse              // Join with newlines
   .replace("^\n"," ") // Replace `^\n` with a space globally
   .lines              // Get the lines (see below for more details on what this returns)
   .map(j->            // Loop through each "line" `j` is arg
       "%-2s"          // C-like printf format.
                       // think of as: padRight(j, " ", 2)
                       // see below for more details
        % j            // Pass j as the string to insert
   ).turn(3)           // Turn the string 270 degrees (see below)
   .vfuse              // Vertically fuse to get result (this is not needed as we can output an array of the lines)

To get a better understanding. This is what .lines returns for 1^2
["1", " 2"]

the .turn with rotate this:
1
 2

into:
 2
1

Another example which will make it more clear:
1
 2
2
 2

becomes:
 2 2
1 2

Why format?
What the %-2s is doing is pretty simple. % specifies we are starting a "format", or that a variable will be inserted into this string at this point. - means to right-pad the string, and 2 is the max-length. By default it pads with spaces. s just specifies it's a string. To see what it does:
"%-2s" % "a"  == "a "
"%-2s" % " a" == " a"

:D I always upvote cheddar.

@DrGreenEggsandIronMan :D thank you

Cheddar have a turn method for strings?

-1 this language's name always makes me hungry.

@TùxCräftîñg only for 2D arrays, which is why i used .lines to get the lines.

That's a lot of "."s

Perl, 21 + 1 = 22 bytes
say'';s/\^(.)/♥[A\1↓/

Run with the -p flag. Replace ♥ with a raw ESC byte (0x1b), and ↓ with a vertical tab (0x0b).
The vertical tab is Martin Ender’s idea. It saved two bytes! Thanks.

Wouldn't you need to move the cursor down a line at the start so that the exponents don't overlap the last console prompt?

I wasn't sure about that, yeah. I made the assumption of having as much space as I need, but maybe that’s a bit cheaty. (In general, I’m not very proud of using cursor movements to solve this kind of problem, but it’s the first thing that came to mind...)

I think it's a fine solution but the result should be visually indistinguishable from printing the string as intended.

What a lovely solution

JavaScript (ES6), 56 55 bytes
s=>[/.(\^(.))?/g,/\^.(())/g].map(r=>s.replace(r,' $2'))

Regexps to the rescue of course. The first one replaces all characters with spaces, unless it finds a caret, in which case it deletes the caret and keeps the character after it. (These characters are guaranteed to exist.) The second is the obvious one to replace each caret and its following character with a space.
Edit: Saved 1 byte thanks to @Lynn who devised a way to reuse the replacement string for the second replace allowing the replace to be mapped over an array of regexps.

Looks like s=>[/.(\^(.))?/g,/\^.(())/g].map(r=>s.replace(r,' $2')) is a byte shorter.

@Lynn That's a really cunning stunt!

Python 3, 157 101 98 85 83 74 bytes
This solution keeps track of whether the previous character was ^, then decides whether to output to the first or second line based on that.
Outputs as an array of ['firstline', 'secondline'].
a=['']*2
l=0
for c in input():x=c=='^';a[l]+=c*x;a[~l]+=' '*x;l=x
print(a)

Saved 13 15 bytes thanks to @LeakyNun!
Saved 7 bytes thanks to @Joffan!

Nice finite-state automaton.

Would it be better to have a=['',''] and concatenate ' ' and c directly into a[l] and a[~l]?

Python 2, 73 bytes
l=['']*2;p=1
for c in input():b=c!='^';l[p]+=c*b;l[~p]+=' '*b;p=b
print l

No regex. Remembers if the previous character was ^, and put the current character in the top or bottom line based on that, and a space in the other one.

Ruby, 47 + 1 (-n flag) = 48 bytes
puts$_.gsub(/\^(.)|./){$1||" "},gsub(/\^./," ")

Run it like so: ruby -ne 'puts$_.gsub(/\^(.)|./){$1||" "},gsub(/\^./," ")'

I think you can save 1 byte using $_=$_.gsub(/\^(.)|./){$1||" "}+gsub(/\^./," ") and -p instead of -n.

@DomHastings regardless of if it works or not, your code doesn't seem to have a newline, and adding +$/ means it's not going to save bytes. puts throws in the newline for you automatically when the , is present between arguments.

Oh... I tested using ruby -p ... <<< 'input' but I agree, if it's missing the newline it's no good! Actually, I might have had a newline appended in my tests earlier... It was at work though so I can't check!

@DomHastings Looking at it again, my guess is that it's because gets includes the trailing newline most of the time, but if you pipe in a file that doesn't contain the trailing newline, then it won't appear and the output will be wrong. Test your code with ruby -p ... inputfile since Ruby redirects the gets to the file if it's a command line argument.

Got it, makes perfect sense. I guess a trailing newline in the file would also fix the problem. I'm not a proficient Rubyist by any means so I feel like I've learnt a little more about it today. Thanks!

Pyth, 17 bytes
CcsmX~Z1j;d;cQ\^2

             Q      input string
            c \^    split on '^'
   m                map for sections d:
    X      ;          insert a space at index:
     ~Z1                the old value of Z (initially 0), before setting Z to 1
                      into:
        j;d             the section joined on spaces
  s                 concatenate
 c              2   chop into groups of 2
C                   transpose

Returns an array of 2 strings.  (Prepend j to join them with a newline.)
Try it online.

I can’t stop wondering how your last name is pronounced. :D

MATL, 18 bytes
94=t1YSt~&vG*cw~Z)

Try it online!
94=    % Take input implicitly. Create logical array of the same size that contains
       % true for carets, false otherwise
t      % Push a copy of this array
1YS    % Circularly shift 1 unit to the right. This gives an array that contains true
       % for the elements right after a caret (superindices), and false for the rest
t~     % Push a copy and negate
&v     % Concatenate vertically. This gives a 2D, 2-row array
G*     % Push the input again, multiply with broadcast. This gives a 2D array in
       % which the first row contains the superindices (characters after a caret)
       % and 0 for the rest; and the second row contains the non-superindices and
       % 0 for the superindices
c      % Convert to char
w      % Swap. Brings to top the array containing true for carets and false otherwise
~      % Negate
Z)     % Use as logical index to remove rows that contain carets. Display implicitly

Python (2), 76 68 67 Bytes
-5 Bytes thanks to @LeakyNun
-3 Bytes thanks to @KevinLau-notKenny
-1 Byte  thanks to @ValueInk
-0 bytes thanks to @DrGreenEggsandIronMan
import re
lambda i,s=re.sub:[s("(?<!\^).\^?"," ",i),s("\^."," ",i)]

This anonymous Lambda function takes the input string as its only argument and returns the two output lines separated by a newline. To call it give it a name by writing "f=" before it.
Pretty straightforward regex: The first part replaces the following by a space: any character and a carrot caret or only a char, but only if there is no caret before them. The second part replaces any caret in the string and the char after it by a space.

@LeakyNun: I was for some reason wondering if 1. also holds if i import libraries. Was copying 2. into this question right now when i saw your comment. Thanks to you and Kevin!

You could take one byte off with from re import*

@DrGreenEggsandIronMan This seems to use exactly the same numer of bytes. (see above)

Keep the old import statement and do lambda i,s=re.sub:[s("(?<!\^).\^?"," ",i),s("\^."," ",i)] for -1 byte

Convex, 24 bytes
®(?<!\^).\^?"SòNê®\^."Sò

Try it online!

Retina, 16 bytes
S`^
\^(.)
♥[A$1↓

A port of my Perl answer, pointed out by Martin Ender. Replace ♥ by a raw ESC byte (0x1b) and ↓ with a vertical tab (0x0b).

Haskell, 74 56 55 bytes
g('^':c:r)=(c,' '):g r
g(c:r)=(' ',c):g r
g x=x
unzip.g

Returns a pair of strings. Usage example: unzip.g $ "abc^d+e:qf^g + hijk^l - M^NO^P: (Ag^+)" -> ("   d     g       l    N P     + ","abc +e:qf  + hijk  - M O : (Ag )")
g makes a list of pairs, where the first element is the char in the upper line and the second element is the char in the lower line. unzip turns it into a pair of lists.
Edit: @xnor suggested unzip which saves 18 bytes. @Laikoni found one more byte to save. Thanks!

Can you do j=unzip.g?

@xnor: oh, how stupid of me not to see that myself! Thanks a lot!

You can replace g[]=[] with g x=x to save one byte.

@Laikoni: Well spotted! Thanks!

shell+TeX+catdvi, 51 43 bytes
tex '\empty$'$1'$\end'>n;catdvi *i|head -n2

Uses tex to typeset some beautiful mathematics, and then uses catdvi to make a text representation. The head command removes junk (page numbering, trailing newlines) that is otherwise present.
Edit: Why do the long, proper, thing and redirect to /dev/null when you can ignore sideeffects and write to a single letter file?

Example
Input: abc^d+ef^g + hijk^l - M^NO^P (Ag^+)
TeX output (cropped to equation):

Final output:
   d   g     l  N P   +
abc +ef +hijk -M O (Ag )

Assumptions: Start in empty dir (or specifically a dir with no name ending in "i"). Input is a single argument to the shell script. Input is not an empty string.
Someone tell me if this is rule abuse, especially catdvi.

Perl, 35 bytes
34 bytes code + 1 for -p
$_=s/\^(.)|./$1||$"/ger.s/\^./ /gr

Usage
perl -pe '$_=s/\^(.)|./$1||$"/ger.s/\^./ /gr' <<< 'abc^d+ef^g + hijk^l - M^NO^P (Ag^+)'
   d   g       l    N P    +
abc +ef  + hijk  - M O  (Ag )

Note: This is exactly the same as Value Ink's answer which I spied afterwards. Will remove if needed as this doesn't really add to the Ruby solution.

Java 8 lambda, 132 128 112 characters
i->{String[]r={"",""};for(char j=0,c;j<i.length();j++){c=i[j];r[0]+=c==94?i[++j]:32;r[1]+=c==94?32:c;}return r;}

The ungolfed version looks like this:
public class Q86647 {

    static String[] printExponents(char[] input) {
        String[] result = {"",""};
        for (char j = 0, c; j < input.length(); j++) {
            c = input[j];
            result[0] += c == 94 ? input[++j] : 32;
            result[1] += c == 94 ? 32 : c;
        }
        return result;
    }
}

Outputs as an array, simply checking whether there is a caret and if so the next character will be put in the upper row, else there will be a space.

Updates
Replaced characters with their ascii values to save 4 characters.
Thanks to @LeakyLun for pointing out to use a char array as input instead.
Also thanks to @KevinCruijssen for switching the int to char to save some more characters.

You can try to input char[] and use for(char c:i) to see if the byte-count can be reduced.

You can golf it down a bit to 110 bytes by using: i->{String[]r={"",""};for(char j=0,c;j<i.length;j++){c=i[j];r[0]+=c==94?i[++j]:32;r[1]+=c==94?32:c;}return r;} with "abc^d+ef^g + hijk^l - M^NO^P (Ag^+)".toCharArray() as input. (Ideone of these changes.)

Coconut, 122 114 96 bytes
Edit: 8 26 bytes down with help from Leaky Nun.
def e(s,l)=''==l and s or"^"==l[0]and l[1]+e(s+' ',l[2:])or' '+e(s+l[0],l[1:])
f=print..e$('\n')

So as I learned today python has a ternary conditional operator, or in fact two of them: <true_expr> if <condition> else <false_expr> and <condition> and <true_expr> or <false_expr> with last one coming with one char less.
A python conform version can be ideoned.

First attempt:
def e(s,l):
 case l:
  match['^',c]+r:return c+e(s+' ',r)
  match[c]+r:return' '+e(s+c,r)
 else:return s
f=print..e$('\n')

Calling with f("abc^d+ef^g + hijk^l - M^NO^P (Ag^+)") prints
   d   g       l    N P    +
abc +ef  + hijk  - M O  (Ag )

Anyone tried golfing in coconut yet? It enriches python with more functional programming concepts like the pattern matching and function concatenation (with ..) used above. As this is my first try at coconut, any tips would be appreciated.
This could definitely be shortened as any valid python code is also valid coconut and shorter python answers have been posted, however I tried to find a purely functional solution.

I think you can use ternary operators (x and y or z) to replace the case.

You can even use s[0]=="^" instead of match['^',c]+r in l

@LeakyNun When I replace match['^',c]+r with s[0]=="^", then c and r are no longer bound. How would this help?

You can use s[1] to replace c and s[2:] to replace r.

then you can use ternary now.

Gema, 42 41 characters
\^?=?@set{s;$s }
?=\ @append{s;?}
\Z=\n$s

Gema processes input as stream, so you have to solve it in one pass: first line is written immediately as processed, second line is collected in variable $s, then output at the end.
Sample run:
bash-4.3$ gema '\^?=?@set{s;$s };?=\ @append{s;?};\Z=\n$s' <<< 'abc^d+ef^g + hijk^l - M^NO^P (Ag^+)'
   d   g       l    N P    +
abc +ef  + hijk  - M O  (Ag )

Dyalog APL, 34 bytes
{(0 1=⊂b/¯1⌽b){⍺\⍺/⍵}¨⊂⍵/⍨b←⍵≠'∧'}

It returns a two-element vector with the two lines
Sample run (the uparrow in front is to format the two-el. vector for human consumption):
      ↑{(0 1=⊂b/¯1⌽b){⍺\⍺/⍵}¨⊂⍵/⍨b←⍵≠'∧'}'abc∧d+ef∧g + hijk∧l - M∧NO∧P (Ag∧+)'
   d   g       l    N P    +
abc +ef  + hijk  - M O  (Ag )

To your comment on my question about code doing nothing: yes, that code you put counts.

PowerShell v2+, 88 83 bytes
-join([char[]]$args[0]|%{if($c){$_;$b+=' '}elseif($_-94){$b+=$_;' '}$c=$_-eq94});$b

A little longer than the others, but showcases a little PowerShell magic and a little different logic.
Essentially the same concept as the Python answers -- we iterate over the input character-by-character, remember whether the previous one was a caret ($c), and put the current character into the appropriate spot. However, the logic and method for determining where to output is handled a little differently, and without a tuple or separate variables -- we test if the previous character was a caret, and if so output the character to the pipeline and concatenate a space onto $b. Otherwise we check if the current character is a caret elseif($_-94) and so long as it's not, we concatenate the current character onto $b and output a space to the pipeline. Finally, we set whether the current character is a caret for the next go-round.
We gather those characters from the pipeline together in parens, encapsulate them in a -join which turns them into a string, and leave that along with $b on the pipeline. Output at the end is implicit with a newline inbetween.
For comparison, here's a direct port of @xnor's Python answer, at 85 bytes:
$a=,''*2;[char[]]$args[($l=0)]|%{$a[!$l]+="$_"*($c=$_-ne94);$a[$l]+=' '*$c;$l=!$c};$a

Cinnamon Gum, 21 bytes
0000000: 5306 6533 bd92 d1db 8899 8381 a2f8 8f8c  S.e3............
0000010: 1230 249e a1                             .0$..

Non-competing. Try it online.
Explanation
I'm not much of a regex golfer so there's probably a better way to do this.
The string decompresses to:
S(?<!\^)[^^]& &\^&`S\^.&

(note the trailing space)
The first S stage receives input and uses a negative lookbehind to replace all characters other than carets with no preceding caret with a space, then deletes all carets. Then it immediately outputs the modified input string with a newline and removes that S stage. Since STDIN is now exhausted and the previous stage didn't provide any input, the next S stage receives the last line of STDIN again and then replaces all carets followed by any character with a space and outputs that.
In Perl psuedo-code:
$first_stage_sub_1 = ($input =~ s/(?<!\^)[^^]/ /gr);
$first_stage_sub_2 = ($first_stage_sub_1 =~ s/\^//gr);
print $first_stage_sub_2, "\n";

$second_stage_sub = ($input =~ s/\^./ /gr);
print $second_stage_sub, "\n";

J, 28 27 bytes
0|:t#]{."0~_1-_1|.t=.'^'~:]

Try it online!
                  t=.'^'~:]    0 for ^, 1 for the rest, define t
              _1|.             Shift right, now zeroes are for superscripts
     ]{."0~_1-                 Prepend that many spaces to each character
   t#                          Remove the rows with carets
0|:                            Transpose

There must be a better way...