text:
Aircraft Marshalling School
Given a string representing a series of aircraft marshalling hand signals, write a function or program to calculate the final position of an aircraft following these signals.
N.B.: Co-ordinates in this challenge are represented as a pair of Cartesian co-ordinates, plus a compass direction heading: (x, y, h) where x is the x-coordinate, y is the y-coordinate, and h is one of N, E, S, or W.
You start with an aircraft at (0, 0, N) on an imaginary grid, with engines off. Your input is a string containing comma-delimeted pairs of characters, where each pair represents one marshalling signal. You must follow each marshalling signal in turn, and output the co-ordinates in (x, y, h) form of the aircraft's final position.
If a signal requires your aircraft to move, assume it moves one unit in the required direction for each signal of that type that it receives. If a signal requires your aircraft to turn, assume it turns 90 degrees in the required direction for each signal of that type that it receives.
An aircraft cannot move if its engines are off. If your aircraft's engines are off and you receive a movement/turn signal, do not apply the movement/turn.
Signals
Each marshalling signal is represented by one pair of characters. The first of the pair represents the position of the marshaller's left arm, from the aircraft's point of view, and the second the right arm from the same POV. This handy chart of signals may help.
o/  —  START ENGINES (no movement, no turn)
-/  —  CUT ENGINES   (no movement, no turn)
-~  —  TURN LEFT     (no movement, left turn)
~-  —  TURN RIGHT    (no movement, right turn)
~~  —  COME FORWARD  (forward movement, no turn)
::  —  MOVE BACK     (backward movement, no turn)
/\  —  NORMAL STOP   (no movement, no turn)

This is not the complete list of marshalling signals, but it's all you're required to support.
Input
Input is a comma-delimeted string containing pairs of characters. This string will always be valid - you do not have to validate the input.
Output
Output is a set of co-ordinates as described above. You can return this in any convenient format - if your language supports multiple return values, you may use that; alternatively, you can use a string (the brackets surrounding the co-ordinates are non-compulsory), array, tuple, list, or whatever else you find convenient. The only rule is that it must contain x, y, and h values, in that order.
Test Cases
Input  —  Output
o/,~~,~~,~-,::  —  (-1, 2, E)
::,~-,o/,/\,~~,-~,~~,~~,~~  —  (-3, 1, W)
o/,::,-/,~~,o/,~-,~~,~~,~-  —  (2, -1, S)
o/,~-,~-,::,::,~-,~~,-~  —  (-1, 2, S)
~-,~-,o/,::,::,-/,~~,-~  —  (0, -2, N)

What do start engines and cut engines actually do? Will only those moves between start engines and cut engines be executed? Otherwise I fail to see the relevance.

@LevelRiverSt "An aircraft cannot move if its engines are off." I've been through that in the text.

if we write a function, can we take input as a list of instructions?

@Flp.Tkc Can you change the challenge to make it easier? No :)

I didn't realise using a builtin "split" function was so challenging. Having a rigid input format on code-golf is not advised; the standard is "take the input in any convenient format".

@Flp.Tkc Split isn't exactly difficult, but it's unfair to say you don't have to use it when everyone else does.

If the input format adds nothing to the challenge apart from a trivial function call such as "split", then it's generally not needed.

"Everyone else?" There's one answer. It's also possible to edit challenges.

@Flp.Tkc Yes, I'm familiar with how Stack Exchange works, thanks. This is how I've written the challenge; regardless of your opinions, I'm not going to change it unless you can give me a compelling reason to change the challenge and invalidate (partially) an existing answer.

Java 8, 505 bytes
Golfed (with help from @masterX244 for shaving a big chunk off)
class f{static boolean T(String u,String v){return u.equals(v);}public static void main(String[]a){java.util.Scanner q=new java.util.Scanner(System.in);String s=q.nextLine();int x=0;int y=0;int d=0;int[][]v={{0,1},{-1,0},{0,-1},{1,0}};int b=1;for(String r:s.split(",")){if(T(r,"o/")||T(r,"-/"))b=~1;if(b<0){if(T(r,"~-"))d=(d+3)%4;if(T(r,"-~"))d=(d+1)%4;if(T(r,"~~")){x+=v[d][0];y+=v[d][1];}if(T(r,"::")){x-=v[d][0];y-=v[d][1];}}}System.out.println("("+x+","+y+","+"NWSE".charAt(d)+")");}}

More readable
class f {
    static boolean T(String u,String v){return u.equals(v);}
    public static void main(String[] a) {
        java.util.Scanner q=new java.util.Scanner(System.in);
        String s=q.nextLine();
        int x=0;
        int y=0;
        int d=0;
        int[][] val = {
                {0,1},  // N
                {-1,0}, // W
                {0,-1}, // S
                {1,0}   // E
        };
        int b=1;
        for (String r: s.split(",")) {
            // toggle b if either start or stop engine
            if(T(r,"o/") || T(r,"-/"))
                b=~1;
            if(b<0){
                // right
                if(T(r,"~-")) d=(d+3)%4;
                // left
                if(T(r,"-~")) d=(d+1)%4;
                // come forward
                if(T(r,"~~")) {
                    x+=val[d][0];
                    y+=val[d][1];
                }
                // move back
                if(T(r,"::")) {
                    x-=val[d][0];
                    y-=val[d][1];
                }
            }
        }
        System.out.print("("+x+","+y+","+"NWSE".charAt(d)+")");
    }
}

some free bytes: class containing main() doesnt have to be public (see the golfing tips for java here) and quite a bunch of whitespace that can be optimized out (anything next to nonalphanumeric symbols can be stripped). also false can be writtten as 0>1

Also: replacing the bool with a int and comparing it for being greater or smaller than zero shaved some bytes off, too. (using *=-1 to toggle it) code in next comment. And always use print() over println when you only need one line outputted

class f{static boolean T(String u,String v){return u.equals(v);}public static void main(String[]a){java.util.Scanner q=new java.util.Scanner(System.in);String s=q.nextLine();int x=0;int y=0;int d=0;int[][]v={{0,1},{-1,0},{0,-1},{1,0}};int b=1;for(String r:s.split(",")){if(T(r,"o/")||T(r,"-/"))b*=-1;if(b<0){if(T(r,"~-"))d=(d+3)%4;if(T(r,"-~"))d=(d+1)%4;if(T(r,"~~")){x+=v[d][0];y+=v[d][1];}if(T(r,"::")){x-=v[d][0];y-=v[d][1];}}}System.out.print("("+x+","+y+","+"NWSE".charAt(d)+")");}}

@masterX244 thx I'm clearly a bit knew to this. Ill add in the edit for print

the import is also a spot to optimize. for one or 2 mentions a fully qualified reference on both is shorter than importing. (code i pasted in comment contains all optimizes i found)

Most stuff i mentioned is here: http://codegolf.stackexchange.com/questions/6671/tips-for-golfing-in-java

@masterX244 lol I don't know why I thought doing this in java would be good idea. The reference is really useful, thx for help :)

Found another shave-off on that intboolean-hack (replacing the *-1 with =~b class f{static boolean T(String u,String v){return u.equals(v);}public static void main(String[]a){java.util.Scanner q=new java.util.Scanner(System.in);String s=q.nextLine();int x=0;int y=0;int d=0;int[][]v={{0,1},{-1,0},{0,-1},{1,0}};int b=1;for(String r:s.split(",")){if(T(r,"o/")||T(r,"-/"))b=~1;if(b<0){if(T(r,"~-"))d=(d+3)%4;if(T(r,"-~"))d=(d+1)%4;if(T(r,"~~")){x+=v[d][0];y+=v[d][1];}if(T(r,"::")){x-=v[d][0];y-=v[d][1];}}}System.out.println("("+x+","+y+","+"NWSE".charAt(d)+")");}}

oops fixing now...

Befunge, 201 185 bytes
p10p2p3pv
~/3-*95~<v:+-"/"
  v!:-*53_v
 #_7-:v v0-1
vv!:-3_100>p
 _69*-:v NESW v+g01g
v v-*93_g10g\->4+4%10p
v<_100g >*:10g:1\-\2%!**03g+03p10g:2\-\2%**02g+02p
>>~65*`#v_2g.3g.10g9+5g,@

Try it online!
Befunge doesn't have a string type as such, so to make the signals easier to compare, each character pair is converted into an integer using the formula (c1 - 45)/3 + c2 - 47. This can mean we'll get false matches on invalid input, but that's doesn't matter if the input is guaranteed to be valid.
The rest of the code is based around the manipulation of four "variables": the engine state (1 or 0), the heading (0 to 3 for NESW), and the x and y positions. The calculations for each signal are then as follows:
Start engine: engine = 1
Cut engine: engine = 0
Turn left: heading = (heading - engine + 4) % 4
Turn right: heading = (heading + engine) % 4
Movement: (where dir is 1 for forward and -1 for backwards)
y += dir*engine*(1-heading)*!(heading%2)
x += dir*engine*(2-heading)*(heading%2)
Once we reach the end of the input sequence, it's then just a matter of outputting the x, y, and heading (converted to a char with a simple table lookup).

Python 2.7.12, 295 bytes
from operator import*
l=[0,0]
m=[['N',[0,1]],['E',[1,0]],['S',[0,-1]],['W',[-1,0]]]
n=0
x=raw_input()
for c in x.split(','):
 if'o/'==c:n=1
 if'-/'==c:n=0
 if n:
    if'-~'==c:m=m[-1:]+m[:-1]
    if'~-'==c:m=m[1:]+m[:1]
    if'~~'==c:l=map(add,l,m[0][1])
    if'::'==c:l=map(sub,l,m[0][1])
print l+[m[0][0]]

The first level of indentation after for uses a single \s. The indentation of the second level uses a single \t. (the wysiwyg replaces \t with multiple spaces so please keep this in mind when testing for size)

There's a lot of extraneous whitespace you can remove here.

Not just white space but other easy to fix inefficientcies.  Try the tips for golfing in python for specific examplrs.

Note that in code-golf you don't have to have any input prompt: you can just do raw_input().

This code errors for me on line 15: TypeError: Argument to map() must support iteration (I'm using Python 2.7.12).

@Qwerp-Derp, I believe I fixed the map() error.

You have a couple of places where you write if c=="<string>".  These can be replaced with if"<string>"==c.  Also everywhere you double nest if statements you could probably save bytes with an and.

You can also use from operator import* to import add and sub in less bytes.  It will import other things but it doesn't look like that would be a problem.  And since no one else has said it, Welcome to the site, hope you have a good time here.

@Wheat Wizard, Thank you for the comments!

If you are going to add ands instead of the nested ifs could I recomend using python's binary operation &.  The first one would be if(c=="-~")&n.  Unfortunately the parens are necessary but it still uses less bytes than a regular and

You can save an extra 3 bytes by putting an if n: around all the if statements that have &n at the end, and getting rid of the parens.

@Qwerp-Derp Thank you for the tip. This only reduces by 1 byte because the nested if statements require more indentation.

@ArtOfCode does the comma separated input have whitespace? ex. item1, item2 If not, I can save 13 bytes.

@Eric No, it doesn't.

You haven't gotten rid of the unnecessary parents around the if statements after the "if n" bit.

Python 2, 142 bytes
s=raw_input()
e=p=0;d=1
while s:exec'd-=e d+=e p+=1j**d*e e=0 0 e=1 p-=1j**d*e 0'.split()[ord(s[0])+ord(s[1])*2&7];s=s[3:]
print p,'ESWN'[d%4]

Example:
% python2.7 ams.py <<<'o/,~~,~~,~-,::'
(-1+2j) E

This prints complex numbers, which should be okay, I think? The x, y, h order is still there, and the 'j' doesn’t cause any confusion. Tell me if I should change it.


text:
The Squaring Sequence
Each term in the squaring sequence, \$x_n\$, is created by taking \$x_{n-1}\$, squaring it, and removing all but the first four digits.
The sequence always begins with \$x_1 = 1111\$. Squaring this yields \$1234321\$, so \$x_2 = 1234\$
The first few terms are:
1111
1234
1522
2316
5363
...

The Challenge
Your task is to, given a non-negative integer \$n\$, calculate \$x_n\$. You may submit a full program which performs I/O, or a function which takes \$n\$ as a parameter.
Your solution can be zero or one indexed, as long as you specify which.
Because all the terms in this sequence are shorter than 5 digits, your code should be as short as possible too. Standard code-golf loopholes apply.
May the best golfer win!

Test Cases
Note: These are 1-indexed.
1   -> 1111
8   -> 6840
15  -> 7584
20  -> 1425
80  -> 4717

Here's a related link :)

This sequence could find use as a pseudo-random number generator (although it's not very secure).

May we output as a string?

@ophact IO is flexible.

Any OEIS link for this?

05AB1E, 8 7 bytes
Code:
$Fn4×4£

Explanation:
$        # Push 1 and the input
 F       # Input times do...
  n      #   Square the number
   4×    #   Repeat that string 4 times
     4£  #   Take the first four characters
         # Output the last computed number

Uses the CP-1252 encoding. Try it online!

Beat me by 20 seconds :(.

×4£ can be ∍ now for -2 bytes.

JavaScript (ES7), 44 43 36 bytes
f=n=>--n?(f(n)**2+f).slice(0,4):1111

This is a great example of abusing type coercion: ** converts both its arguments to numbers, and + converts both its arguments to strings unless they're both numbers. This means that f(n)**2+f first converts f(n) to a number and squares it, then concatenates the result with the string representation of f. We can then use .slice to retrieve the first 4 chars of the string.
Here are a few alternate approaches that don't use strings:
f=(n,x=1111)=>x<1e4?--n?f(n,x*x):x:f(n,x/10|0)
f=n=>--n?(x=f(n))*x/(x>3162?1e4:1e3)|0:1111

Test snippet

let f=n=>--n?(Math.pow(f(n),2)+f).slice(0,4):1111
<input id=I type="number" step="1" min="1" value="1"><button onclick="console.log(f(I.value))">Run</button>

Note: this uses Math.pow because ** isn't supported in all browsers.

If we can output as a string, then n=>n?(''+f(n-1)**2).slice(0,4):1111 should work for 35 bytes

Python 2, 51 46 44 Bytes
I'd like to get rid of the clunky if if possible, but I think an exec could be shorter.. Turns out for the moment that exec is shorter. Wrong again! The recursive function returns. This is one-indexed.
f=lambda n:1111*(n<2)or int(`f(n-1)**2`[:4])

An aleternative 46-byte solution with exec:
s=1111;exec's=int(`s*s`[:4]);'*input();print s

An alternative 49-byte recursive solution:
f=lambda n,s=1111:s*0**n or f(n-1,int(`s*2`[:4]))

Thanks to Flp.Tkc for saving a byte by reminding me that squaring doesn't need exponentiation :)

Another 46 bytes solution: f=lambda n:1111if n<2else int(`f(n-1)**2`[:4])

@daHugLenny that can actually be 45: https://repl.it/EejD

@Flp.Tkc And that can actually be 44 ;)

Haskell, 40 bytes
((iterate(read.take 4.show.(^2))1111)!!)

It's a 0-based sequence. Usage example: ((iterate(read.take 4.show.(^2))1111)!!) 79 -> 4717.
How it works:
iterate (   ) 1111               -- repeatedly apply a function starting
                                 -- with 1111 and collect the results in a list
                                 -- the function is
           (^2)                  -- square
        show                     -- turn into string
     take 4                      -- take the first 4 chars
  read                           -- turn back to number
                     !!          -- finally pick the nth element from the list

V, 19 bytes
4é1Àñ|C="*"
5|D

Try it online!
This uses 0-based indexing.
Of course, since numbers aren't exactly V's forte, this isn't very golfy. However, it does show one nice advantage V has over vim. You can run a macro 0 times, which is not possible in vim since '0' is a command not a count.
This contains many unprintable characters, so here is a hexdump:
0000000: 34e9 31c0 f17c 4312 3d12 222a 1222 0a1b  4.1..|C.=."*."..
0000010: 357c 44                                  5|D

And here is a readable version:
4é1Àñ|C<C-r>=<C-r>"*<C-r>"
<esc>5|D

Explanation:
4                           " 4 times:
 é1                         " Insert a '1'
   Àñ                       " Arg1 times:
     |                      "   Move to the first character on this line
      C                     "   Delete this whole line and enter insert mode
       <C-r>=               "   Insert the following evaluated as vimscript:
             <C-r>"         "     Insert what we just deleted
                   *        "     Times
                    <C-r>"  "     What we just deleted
<esc>                       "   Escape to normal mode
     5|                     "   Move to the fifth column on this line
       D                    "   And delete until the end of this line
                            " The second 'ñ' is added implicitly

Perl, 37 bytes
36 bytes of code + -p flag.
$\=1x4;$\=substr$\*$\,0,4while--$_}{

To run it:
perl -pe '$\=1x4;$\=substr$\*$\,0,4while--$_}{' <<< 80

Jelly, 12 9 bytes
-3 bytes thanks to Dennis using 1-based indexing and the ṁ mold/reshape atom. Golfing suggestions welcome! Try it online!
²Dṁ4Ḍ
1Ç¡

Ungolfing
Helper link
²       Square.
 D      Integer to decimal (a list of digits).
  ṁ4    Mold/reshape list_of_digits to be 4 digits long.
    Ḍ   Decimal to integer.

Main link: implicit left argument n
1     Start with the nilad 1.
 Ç¡   Call the helper link n times.

This saves 3 bytes with 1-based indexing.

Uh, I don't think you can use 1 instead of ⁽¡n.

@EriktheOutgolfer How come?

@Sherlock9 Oh, you seem to 1-index this sequence? Hm, looks like the code is a bit tricky to understand...

Mathematica, 48 bytes
Nest[⌊10^(3-⌊t=2Log[10,#]⌋+t)⌋&,1111,#]&

Unnamed function taking an integer argument; 0-indexed. Uses four three-byte characters ⌊⌊⌋⌋: Mathematica uses either Floor[x] or ⌊x⌋ to round a real number down to an integer, and the latter is generally one fewer byte. The command names in Mathematica for converting integers to strings are too long, so instead we do a mathematical calculation to find the first four digits of x^2: we take the base-10 logarithm of x^2, subtract its integer part, raise 10 back to that power, and multiply by 1000 and round down.
tl;dr: logarithms ftw

APL (Dyalog Extended), 13 bytes
-2 (changing the input method) thanks to @Razetime
{⍎4⍴⍕⍵*2}⍣⎕⊢1

Explanation:
{⍎4⍴⍕⍵*2}⍣⎕⊢1     ⍝ apply the dfn input times
            1     ⍝ .. with initial argument 1
     ⍵*2          ⍝ current value squared
 ⍎4⍴⍕             ⍝ take first 4 digits

Try it online!

-2

Powershell, 73 55 bytes
Huge thanks to TimmyD for shaving off 18 bytes!
Code:
for($A=1111;$args[0]---1;$A=-join"$(+$A*$A)"[0..3]){}$A
$A=1111;1..($n=2)|%{[string]$B=[math]::pow($A,2);$A=$B.substring(0,4)};$A
$n is n in xn-1
Explanation and exploded code:
$A=1111                            #starting number
$n=4                               #n in formula
for($i=0; $i -lt $n;$i++)          #loop n times
{
    [string]$B=[math]::pow($A,2)   #create a new string $B and set it to $A raised to the power of 2
    $A=$B.substring(0,4)           #set $A to the first 4 characters of $B
}
$A                             #print $A

Some notes:

Powershell lets you assign variables in the same statements where you reference them. For example, 1..($n=4)|% will set $n to 4 and then start a loop that runs $n times. 1 can be changed to any integer and it will loop $n-[your integer]+1 times.
The default data type when using [math]:: in Powershell is a double. In the code above, we have to explicitly cast $B to a string so that we can call .substring() on it because there is no .substring() function for doubles in Powershell.

Python 2,  44   41 bytes
-3 bytes thanks to xnor (use an integer division to avoid and)
f=lambda n:int(1/n*1111or`f(n-1)**2`[:4])

repl.it
1-based recursive function.
When n>1 the integer division, 1/n, results in 0, then 0*1111=0 which is falsey, so the right of the or is evaluated, which takes the first four characters of the representation of the square of the n-1th result; this is then cast to an int.
When n=1 the integer division, 1/n, results in 1, then 1*1111=1111, which is truthy, and the int 1111 cast to an int is 1111.

Good one, ninja'd me by one byte!

I just looked for your answer and then realised you wrote the challenge! Nice job.

Nice idea with taking the int outside. If you 1-index, you can do the base case shorter with g=lambda n:int(1/n*1111or`g(n-1)**2`[:4]).

@xnor very neat!

"Crossed out 44 still looks like 44 :("

@Flp.Tkc not as much as it does without the  s!

Javagony - 153 bytes
Javagony is a restricted version of Java, that doesn't allow any control flow except recursion and try-catch, no for loops, while loops, or if's. Coding in it is a pretty fun exercise, but frustrating. Not that regular Java isn't nearly as frustrating by itself.
int a(int i){return a(i-1,1111);}int a(int i,int n){try{int x=1/i;return a(i-1,Integer.parseInt((n*n+"").substring(0,4)));}catch(Exception e){return n;}}

Groovy, 49 bytes
{x=1111;(it-1).times{x="${x**2}"[0..3] as int};x}

PHP, 55 52 bytes
Saved 3 bytes thanks to @user59178
for($i=1111;$argv[1]--;)$i=substr($i**2,0,4);echo$i;

Run from command line, zero-indexed.
Thanks for not caring about what type my variables are, PHP! Here we simply square the number and trim off everything past the first 4 digits, casually alternating between number and string without a care in the world.

You could save 3 bytes by using $argv[1]-- as the loop counter.

MATL, 14, 13 bytes
1111G:"UV4:)U

Try it online!
Explanation:
1111            % Push 1111
    G           % Push input
     :"         % Input times:
       U        %   Square the top of the stack
        V       %   Convert it to a string
         4:)    %   Take the first four digits
            U   %   Convert it back to a number
                % Implictly display

You can use U (square, for numeric input) insted of t*

@LuisMendo Thanks for reminding of the function I recommended! :P

Pyke, 10 bytes
1RVX`4*4<b

Try it here!

R, 58 56 55 53 bytes
x=3334;for(e in N<-scan():1)x=x^2%/%10^(3+(x>3162));x

Takes N from stdin. 3334 is practically X_0, which is needed because the for-loop needs to be executed at least once (it would be longer to skip).
R really is a terrible language for taking the first four digits of a number, but since the number of cases are limited, we only have to worry about the squares of x<3163 and x>3162, the former yield a 6 digit number, the latter a 7 digit number.
The rest is pretty straightforward, %/% divides and ignores the remainder. x is printed to stdout.
Saved 2 bytes thanks to @ETHproductions

This is so notrivial. Brilliant!

Nice one! What would happen if you started with 3334 (or perhaps 3333)?

@ETHproductions 3333^2 = 11108889 so would yield 1110, and .... as im checking this I see 3334 would work :| . Not sure why I didn't check that anymore.

Pushy, 20 bytes
1111@:2esL4-:.;Kjk;#

Try it online!
Note this is 1-indexed.
            % Implicit: N is on stack
1111@       % Push 1111, and then reverse stack to get [1111, n]
:           % N times do: (this consumes N)
 2e         %   Square last term
 s          %   Split into individual digits
 L4-:.;     %   Get stack length -4, pop that many times
 Kj         %   Join remaining digits (Uses flag "K" for whole stack)
 k          %   Set "K" flag to false, so operations only affect last item
;           % End loop.
#           % Output final calculated term

cQuents, 14 bytes
=1111:(ZZ)[:4]

Try it online!
1-indexed.
Explanation
=1111           first term is 1111
     :          given n, output nth term, otherwise output full sequence
                each term equals
      (ZZ)                       previous term * previous term
          [:4]                                                 [:4] (python slicing)

Really nice showcase of this language's abilities!

Brachylog, 18 bytes
,1111:?:{^@[.l4,}i

Try it online!
This answer is 0-indexed.
Explanation
,1111:?:{       }i      Iteratively call Input times the predicate in brackets starting with
                          input 1111:

         ^                  Square
          @[.               Output is a prefix of the square
            .l4,            Its length is 4

C#, 64 60 bytes
Saved 4 bytes by following Olivier Grégoire's comment on a Java answer!
n=>{int x=1111;for(;n-->1;)for(x*=x;x>1e4;x/=10);return x;};

Previous version (64 bytes):
n=>{int x=1111;while(n-->1){x*=x;while(x>9999)x/=10;}return x;};

Full program with ungolfed method and test cases:
using System;

namespace SquaringSequence
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int, int> f = n =>
            {
                int x = 1111;
                while (n-- > 1)
                {
                    x *= x;
                    while (x > 9999)
                        x /= 10;
                }
                return x;
            };

            // test cases:
            Console.WriteLine(f(1));    // 1111
            Console.WriteLine(f(8));    // 6840
            Console.WriteLine(f(15));   // 7584
            Console.WriteLine(f(20));   // 1425
            Console.WriteLine(f(80));   // 4717
        }
    }
}

+1 for the dark goes-to-operator n-->1

Batch, 82 bytes
@set n=1111
@for /l %%i in (1,1,%1)do @set/an*=n&call set n=%%n:~0,4%%
@echo %n%

Like Perl, integers are strings, but unlike Perl I can only take the substring of a variable, and taking substrings inside a loop is somewhat awkward.

I think you can leave out the space after @for.

@YourDeathIsComing 'for' is not recognised as an internal or external command, operable program or batch file.

Pyth, 13 12 bytes
Thanks to @Jakube for -1 byte
us<*4`*GG4Q1

A program that takes input of a 1-indexed integer and prints the result.
Test suite
This uses a similar approach to @Adnan's answer.
How it works
us<*4`*GG4Q1  Program. Input: Q
u         Q1  Execute the following Q times, starting at 1, with variable G:
      *GG      Yield G*G
     `          Convert to string
   *4           Repeat 4 times
  <      4      Yield first 4 characters
 s              Convert to integer
              Implicitly print

*GG instead of ^G2<space>

C, 56 bytes
a;s(n){for(a=1111;--n;)a=a*a/(a>3162?1e4:1e3);return a;}

One-indexed.

I have a feeling that you can go for recursion...

Clojure, 76 bytes
(defn s[n](if(= n 1)1111(read-string(subs(str(*(s(dec n))(s(dec n))))0 4))))

First Clojure golf (seems like a nice language). This is 1-indexed.
Will explain the code later.

Ruby, 47 bytes
First golf! Saves bytes with -n option (but still count as 1! :)).
a=1111;$_.to_i.times{a="#{a*a}"[0,4].to_i};p a

0-indexed.
To run it:
ruby -ne 'a=1111;$_.to_i.times{a="#{a*a}"[0,4].to_i};p a' <<< 80

Welcome to the site, and nice first answer! One nitpick though, technically this is 47 bytes because of our policy of counting command line flags towards the byte count. Other than that, it looks good to me!

Thanks! Didn't know the rules, answer changed!

GolfScript, 15 bytes
~1111\{.*`4<~}*

Try it online!
0-indexed
~                 # Parse n to a number
 1111             # Push 1111
     \{      }*   # Execute this block n times
       .*         # Square the number
         `        # Parse it to a string
          4<      # Get the first 4 digits
            ~     # Parse it back to a number

Nice answer. Is it not possible to take integer input directly?

@Razetime No, in the input and output section of http://www.golfscript.com/golfscript/tutorial.html , it says: "all input from stdin is read first and placed as a string onto the stack". But this site also doesn't mention that the numbers can be complex, so maybe there is a way. If there is, it cannot be shorter than ~.

Japt -mh, 9 bytes
T=Â4î1wT²

Try it
T=Â4î1wT²     :Implicit map of range [0,input)
T=            :Assign to variable T (initially 0)
  Â           :Bitwise NOT of bitwise NOT of (i.e., cast to an integer)
   4î         :Mould to length 4 string
     1w       :  Maximum of 1 and
       T²     :  T squared
              :Implicit output of final result

No Flags, 12 10 bytes
1-indexed, returning a string
@4îX*X}g1ì

Try it
@4îX*X}g1ì     :Implicit input of input of integer U
@              :Function taking an integer X as argument
 4îX*X         :  Mould X*X to length 4
      }        :End function
       g       :Repeatedly take the last element of the following array, pass it through that function, push the result and return the Uth element
        1ì     :  Convert 1 to digit array

Vyxal, 6 5 bytes
Ṫ(²4Ẏ

Try it online, or verify all test cases.
Explanation:
Ṫ      # Pop, push 1 then the input
 (     # [Input] times:
  ²    #   Square
   4Ẏ  #   Get the first 4 digits

With a newly added overload, 1? can just be Ṫ.

@Steffan Thanks, I was wondering if there wouldd be something like that, I saw that 05AB1E had it.

You can decrease it to 4.375 bytes using the = flag to compress it using Vyncode.

@Hippopotomonstrosesquipedalian Yeah but we shouldn't be going around old posts just changing it to use Vyncoder

@tybocopperkettle oh...

TI-Basic, 31 bytes
Input N
1111
For(I,2,N
int(Ans²/₁₀^(-3+int(log(Ans²
End
Ans

1-indexed input. - represents the negative symbol.

Excel VBA, 42 bytes
v=1111:For i=2To[A1]:v=Left(v^2,4):Next:?v

Input is in cell A1 of the active sheet. Code is run in the immediate window. Output is to the immediate window. Here's the result for 80 as an input:

Java, 79 67 66  64 bytes

Version 2.2/64 bytes:

Thanks to @Oliver Grégoire.
int a(int i){i=i<2?1111:a(--i);for(i*=i;i>1e4;)i/=10;return i;}

Version 2.1/66 bytes:

Thanks to @ETHProduction.
long a(long i){i=i<2?1111:a(--i);for(i*=i;i>1e4;)i/=10;return i;}

Version 2.0/67 bytes:

Replaced substring and stuff with the idea from @Xanderhall
long a(long i){i=i<2?1111:a(--i);i*=i;for(;i>1e4;)i/=10;return i;}

Version 1.0/79 bytes:

Although there are shorter solutions I wanted to post one recursive:). And I am the shortest "real" function:). Edit: Seems like I am the shortest now:)))
long a(long i){i=i<2?1111:a(--i);return Long.valueOf((i*i+"").substring(0,4));}

Can you do for(i*=i;i>1e4;)i/=10;? That would save a byte.

Hmmm... Regarding your claim about the shortest Java function, this function would like to have some words ;-)

Hmmm, thinking about it, why do you even use longs? You can kill two bytes by using ints.

I missed that when I updated to 2.0

Perl, 36 bytes
A different approach from the other Perl solution, leading to slightly shorter code. No command-line arguments are needed (other than the usual version selection argument, -M5.010, which doesn't count against the byte count), meaning that this is the same amount of code but with fewer penalties, giving a better overall score.
say+eval'($&*$&||1x4)=~/(....)/;'x<>

We create a loop Underload-style via repeating and eval-ing a string; I experimented with starting the string in the middle, but starting it at the start turns out to be shortest. We multiply $& (the result of the last regex match) by itself to square it; if the result's zero, we use 1x4 (i.e. 1111; Perl has an operator for repeating things, including digits of a number) instead of the result. Then we regex the first four characters. The whole thing runs in list context due to being inside say, thus the final result of the eval will be the contents of the parentheses of the final match.

Java 8, 82 59 bytes
Saved 23 bytes thanks to help from commenters @adrianmp and @OlivierGrégoire
n->{int x=1111;while(--n>0)for(x*=x;x>1e4;x/=10);return x;}

Each iteration, we square the number, then loop and shrink it by factors of 10 until it's a 4 digit number. Repeat this process n times and return.

You can save some bytes by using x*=x; instead of Math.pow.

and put that whole stuff in for loops instead of while loops.

Taking your algorithm and fixing a lot, I get 60 bytes: n->{int x=1111;for(;--n>0;)for(x*=x;x>1e4;x/=10);return x;}. I removed the y since we can decrease n, I used for loops, removed the braces and the biggest winner is what @adrianmp said, of course. Oh, and I made the problem 1-indexed, just like in the question, instead of 0-indexed as in your answer ;)

you know, I honestly forgot that squaring a number was just x*x. I'm too used to the exponentiation operator in PHP ** and using Math.pow in Java. Also, my choice of while loops is usually if it doesn't change the byte count, like the first for loop

CJam, 15 bytes
'14*ri{i2#s4<}*

Uses 0-based indexing.
Try it online!

Java 8, 77 93 74 71 69 78 bytes

int n=1111;int m=1;while(x>m++){n=Integer.parseInt((n*n+"").substring(0,4));}

x->{int n=1111;int m=1;while(x>m++){n=Integer.parseInt((n*n+"").substring(0,4));}return n;}

x->{int n=1111;for(;--x>0;){n=Integer.parseInt((n*n+"").substring(0,4));}}

x->{long n=1111;for(;--x>0;){n=Long.valueOf((n*n+"").substring(0,4));}}

x->{long n=1111;for(;--x>0;)n=Long.valueOf((n*n+"").substring(0,4));return n;}

Each repetition makes n the first 4 characters of n*n.
Try Java online!
Post history:

77 bytes: initial code (incomplete)
+16 bytes, by Olivier Grégoire: completed code by making it a Lambda function.
-19 bytes: replace while with for cycle.
-4 bytes: used longs instead of ints
-2 bytes, by Roman Gräf: removed unnecessary brackets
+9 bytes, missing return statement

Thanks to @OlivierGrégoire and @RomanGräf for pointing out some issues!
Wait, Java beats... (drumroll) Clojure and Matlab here! A big applause to Java please!

This answer is incomplete. x isn't declared. This should be a function or full program. Not a code snippet.

@NonlinearFruit I was going for  the function. Seems I missed this out. Do you mean I should just replace x with a number?

What @NonlinearFruit said is that your answer, with your current code, sould be: x->{int n=1111;int m=1;while(x>m++){n=Integer.parseInt((n*n+"").substring(0,4));}return n;} (for a total byte count of 91). This is because snippets aren't allowed: only functions or full programs.

@OlivierGrégoire Isn't that 93 bytes? And thanks for pointing out lambda funcions.

You're right, it's 93 bytes, I must have checked from a previous, defect version. However, all I did was wrapping so that your program would be a valid entry. Now you can golf the hell out of it! For instance, here's a golfed version of your program for only 75 bytes: x->{Long n=1111;for(;--x>0;)n=n.valueOf((n*n+"").substring(0,4));return n;}, with several techniques used (used Long to be able to use Long.valueOf with less bytes, it's not recommended in normal programming, but totally in golfing; removed m as it's unnecessary if we decrease x instead, removed unneeded braces)

@OlivierGrégoire I didn't read your comment as the program wouldn't be mine, but rather yours. I'll try to golf it myself first.

@OlivierGrégoire I'm done golfing. Now when I see your code, I don't think it works: n=n.valueOf throws an error; I used n=Long.valueOf instead. Also, return n; throws an error, and the program works without it.

You can remove the brackets around n=Long.... Also you probably should add a return or the n would be useless.

@RomanGräf it seems to work without it. But thanks for the tips!

Yes but how do get the result back?

@RomanGräf You mean print it? I just put a System.out.println later.

I don't see your point. If you add the System.out.print() call in the function you have to add that to the byte count.

@RomanGräf It's not in the function, it's where the function is called

Then you need a return

@RomanGräf you mean x->{long n=1111;for(;--x>0;)n=Long.valueOf((n*n+"").substring(0,4));return n}? It seems to work for me without it.

Lets say you want to assign long i=... to SquareSequence[n]. How would ... look like?

@RudolfL.Jelínek You are right, I made 1 mistake in my suggestion: Long n=1111L: I should have appended L (for 1 more byte than advertized). The rest is OK and works fine. Also, make sure to use Long and not long.

Also, to be complete, it's still your code: I haven't changed your algorithm for a bit. Same for the other Java answer which I got down to 60 bytes. I didn't do the main algorithm, so it's not my solution either. I only optimized the presentation of the algorithm itself, just like I suggested for your solution. I don't consider either of suggestions mine.

@OlivierGrégoire You could post that golfed-down code as your own answer, get a few upvotes, and leave my partial answer as is. You didn't. Thanks.

Perl 6, 36 bytes
{(1111,{+$_².substr(0,4)}...*)[$_]}

Explanation:
{                                 } # bare block lambda
  1111,                  ...        # sequence generator
                            *       # without a limit
       {                }           # lambda used to generate the next value
         $_²                        # start by squaring the previous value
            .substr(0,4)            # take only the first four digits
        +                           # make it numeric ( not necessary )
 (                           )[$_]  # return the requested value

Test:
say {(1111,{+$_².substr(0,4)}...*)[$_]}( 1,8,15,20,80 X- 1 ).perl
# (1111, 6840, 7584, 1425, 4717)

GNU Awk, 41 bytes
Pretty straightforward since you can easily mix math and string manipulations.
{for(x=1111;--$1;x=substr(x*x,1,4));}$1=x

Accepts zero or more positive numbers n (1-indexed), one number per line, on stdin. Outputs results xn, one result per line, on stdout.
Sample input/output:
% awk -f sqrseq.awk
1
1111
8
6840
15
7584
20
1425
80
4717
%

Matlab, 79, 78 Bytes
function a=s(n)
if n<2;a=1111; else f=s(n-1);a=fix(f^2/10^(3+(f>1e7^.5)));end

Test cases:
s(79) = 2172
s(49) = 8059
s(6)  = 2876

Not an amazing solution. I'm sure there must be a better way to truncate to 4 digits but I don't know today.
Edit: Shaved a byte by setting 0.5 -> .5

Husk, 11 bytes
¡öd↑4d□1111

Try it online!

Stax, 8 bytes
å\S∩♪öH╠

Run and debug it

JavaScript, 35 bytes
n=>n?(''+f(n-1)**2).slice(0,4):1111

Zero-indexed. Outputs a string if n >= 0 and the number 1111 if n == 0.

><> (Fish), 59 bytes
1e4f*+f*+$v /a,:1%-11!.|
:*:$v!?:-1<$^?)+*f+*f+*f2e6a
 ;n$<

Try it

Explanation
Red loop repeatedly squares. Blue subloop divides by 10 while the value is greater than or equal to 10000.
1e4 is 1111 encoded as base 15. Then repeated f*+ sums it.
a6e2 is 10000 encoded as base 15.
I'm not sure if my base 15 encoding is optimal. Maybe some string encoding with base 255 would be better? But then how to properly add the elements? Hmm this could be a metagolf challenge.

Could you perhaps save some bytes by encoding the a6e2 as U+2710"✐"?

MathGolf, 8 bytes
1kÆ²░4<i

Try it online.
Explanation:
1         # Push 1
 k        # Push the input-integer
  Æ       # Pop and loop that many times, using 5 characters as inner code-block:
   ²      #  Square the current integer
    ░     #  Convert it to a string
     4<   #  Pop and leave the first 4 characters/digits
       i  #  Convert it back to an integer
          # (after the loop, the entire stack is joined together and output implicitly)

Go, 79 bytes
func f(n int)int{i,a:=0,1111
for;i<n;i++{for s:=a*a;s>999;s/=10{a=s}}
return a}

Attempt This Online!

Thunno 2, 8 bytes
«¥[s{²4ɱ

Attempt This Online!
0-indexed.
Explanation
«¥[s{²4ɱ  # Implicit input
«¥[       # Push compressed integer 1111
   s{     # Repeat input number of times:
     ²    #  Square top of stack
      4ɱ  #  Take the first four characters
          # Implicit output

Julia 1.0, 42 bytes
!x=parse(Int,("$(1(x<2||!~-x)^2)"^4)[1:4])

Try it online!

RProgN, 19 Bytes
~{2^''.4m14¢}\*1\C

RProgN continues to be amazing average! Although it easily passes the score of verbose languages, it still chokes in comparison to other golfier languages.
Explained
~{2^''.4m14¢}\*1\C  # Main link
~                    # Zero Space Segment
 {          }       # Define anonymous function
  2^                # Square the top of the stack
    ''.             # Convert to a string.
       4m           # Repeated 4 times.
         14¢        # Push back only the first 4 letters.
             \*     # Multiplied by the implicit input, Creating another anonymous function that calls this one n times.
               1\C  # Push 1 to the stack, and call the chained function.

Try it Online!

Retina, 77 bytes
Sequence is zero-indexed. Doesn't work for n > 1 in TIO because of memory constraints. Byte count assumes ISO 8859-1 encoding.
$
¶1111
{`(?!0¶).+
$*
(?<=1¶(1*))1(?=(1*))
1$1$2
^1

M%`1
}`(\d{4}).*$
$1
0¶

Try it online
Explanation:
$                           # Append a newline and the starting number
¶1111
{`(?!0¶).+                  # Begin loop. If counter is not zero, convert numbers to unary
$*
(?<=1¶(1*))1(?=(1*))        # If the counter >= 1, replace each digit with entire number
1$1$2                       #   (This squares the number)
^1                          # Counter -= 1

M%`1                        # Convert each line's numbers back to decimal
}`(\d{4}).*$                # Keep only first four digits. End loop
$1
0¶                          # Remove the counter

C, 53 52 bytes
a;s(n){return n?(a=s(n-1))*a/(a>3162?1e4:1e3):1111;}

Zero based.
First timer - This is a recursive variation on the earlier solution (expressed in the same way), as requested.

Welcome to PPCG! Can you remove the outermost parentheses to save a byte? a;s(n){return n?(a=s(n-1))*a/(a>3162?1e4:1e3):1111;}

you can make it one indexed for -2 bytes

Scala, 44 bytes
Stream.iterate(1111)(n=>n*n+"" take 4 toInt)

This is an expression which evaluates to a Stream[Int], which is an infinte sequence of integers. In scala, Stream[A] extends (Int => A), which means that a Stream is a function from an index to the element at that index.
Explantion:
Stream.iterate( //create an infinite Sequence,
    1111        //starting with 1111,
  )(            //by calculating the next element with the following function:
    n=>
      n*n       //square the previous element
      +""       //convert it to a string
      take 4    //take the first 4 characters and drop the rest
      toInt     //convert the string back to an int
  )

Swift, 80 Bytes
func s(i:Int)->Int{var c=1111;for _ in 0..<i{c*=c;while c>9999{c/=10}};return c}

Ungolfed
func squaringSequence(index: Int) -> Int {
    var currentNum = 1111

    for _ in 0 ..< index {
        currentNum *= currentNum

        while currentNum > 9999 {
            currentNum /= 10
        }
    }

    return currentNum
}

Due to the pretty-verbose nature of string manipulation in Swift, in which converting an Int to a String, getting the first four characters, and converting back might look something like this:
let str = String(num);
num = Int(str[str.startIndex ..< str.index(str.startIndex, offsetBy: 4)])!

I'm opting to get the first four digits by dividing by 10 as needed.

Clojure, 70 bytes
#(first(drop %(iterate(fn[i](read-string(subs(str(* i i))0 4)))1111)))

Zero-based indexing. Iterates a function which returns first 4 characters of the string representation of the squared integer value.

QBIC, 43 41 bytes
#1111|:[a-1|f=!A! A=$LEFT$|(!f*f/z$,5)]?A

Way too much going on in here... Time to implement Substring in QBIC.
Explanation:
#1111|                     Define string constant A$ as '1111'
:                          Get CMD line param for N, called 'a'
[a-1|                      FOR 'b' = 1 to 'a'-1
  f=!A!                    Make 'f' be A$ cast to num

             f*f/z         Square 'f', and since we only want the first 4 digits,
                           divide it by 10 (z=10). This prevents that QBASIC
                           switches to E^ notation because f^2 is too large
    $LEFT$|(!       $|,5)  Cast it to string, take the first 5 positions (QBASIC
                           adds a leading space on cast-to-num...)
  A=                       And assign to A$
]                          END FOR
?A                         Print the latest value of A$, end

Verified for all test cases.

Wonder, 28 bytes
@:^#0(genc@><""tk4^#0 2)1111

Usage:
(@:^#0(genc@><""tk4^#0 2)1111)79

Simply gets the n th item from an infinite list of squaring sequence numbers. Zero-indexed.
More readable:
@
  iget #0
    (
      genc@
        join "" tk 4 ^ #0 2
    ) 1111

Pip, 13 bytes
Lao:(o*o)@<4o

1-indexed. Takes input as a command-line argument. Try it online!
Explanation
Same algorithm as most of the 1-indexed golflang answers.
               Implicit: a is 1st cmdline arg; o is 1
La             Loop a times:
  o:             Assign this expression to o:
         @<4     Leftmost four characters of
    (o*o)        o squared (parens necessary for precedence)
            o  Print final value of o

The first step, from 1 to 1111, works without any explicit string repetition: string slicing in Pip repeats the string as necessary until the slice index is valid. So "leftmost four characters of 1" gives 1111.

Minkolang v0.15, 43 40 33 bytes
'1111'nd?C[2;6ZrI4-[x]r6$Z]N.CxN.

0-indexed
Try it online! (for n=2)
Explanation
'1111'                            push this number
      n                           push input as number
       d                          duplicate
        ?                         check if it is 0:

If input is 0: (the reason 0 has to be handled specially is that otherwise Minkolang gets confused with the for-loops and 0iterations that you get an error)
         C                        start comment
           ... C                  end comment
                x                 delete value at top of stack (ie 0)
                 N.               output as number and end program

If input is > 0:
         C                        gets jumped over (since input is true)
          [               ]       start for-loop with the input as the number of iterations
           2;                      pushes 2, and raises the number by 2 (ie squares it)
             6Z                    converts number to string
               r                   reverses it
                I4-                pushes the length of the stack (ie the string value of the number) and subtracts it by 4 (so we now how many of the string to discard of)
                   [x]             discard the top of the stack by that many times
                      r            reverses stack
                       6$Z         converts it to a number
                                   for-loop ends
                           N.     output stack as number and end program

Python 3, 67 Bytes
Indexed at 1
a=1111
for _ in range(int(input())-1):a=str(int(a)**2)[:4]
print(a)

I was originally going to do this as a list comprehension, but I realised that I couldn't receive the last item in the list in order to square it.

Please note that there's already a python answer here.

@Flp.Tkc I realise that, but both that one and [this one][1] are using python 2, whereas this is python 3, which, i believe, counts as a separate language to the python 2 language, due to slightly different syntax rules. [1]: http://codegolf.stackexchange.com/a/101964/53336

Yes, they're different languages, but there's no point posting a python 3 solution when the python 2 one could just be trivially modified.

@Flp.Tkc I agree that the Python 2 answers could be modified easily to create a Python 3 answer, but A) This is python, so none of these answers are going to come close to winning (The smallest amount of Bytes that i've seen so far is 7). B) Before posting this answer I didn't look through the current answers, because I do these challenges just to keep my skills up, and I don't want to be influenced by other peoples answers, so I hadn't noticed there were already python answers here

C++ (clang), 52 bytes
void s(int&n){n=--n?s(n),n*n/1e3/(n<3163?:10):1111;}

Port of Lynn's C answer using recursion, is 1 indexed and returns via out parameter.
Try it online!

brev, 66 bytes
(fn(eif x(strse*((fn(* x x))(f(- x 1)))"^...."(m 0)0)1111))

There's no square unless I import the math lib so (fn(* x x)) had to do. Using a regex to yank the first four digits.
This is zero-indexed.

J-uby, 28 bytes
0-indexed.
(~:**&2|S|~:[]&4&0|Z)+[1111]

Attempt This Online!
Explanation
(~:** & 2 | S | ~:[] & 4 & 0 | Z) + [1111]

(                               ) + [1111]  # Iterate n times starting with initial value 1111
 ~:** & 2 |                                 #   Square, then
            S |                             #   Convert to string, then
                ~:[] & 4 & 0 |              #   Get first 4 characters, then
                               Z            #   Convert to int

q, 26 bytes
{"J"$4#string x*x}/[;1111]

k, 18 bytes
{.:4#$x*x}/[;1111]

Python 3, 76 bytes
x=1111
n=int(input())
for y in range(n-1):
    x=int(str(x**2)[:4])
print(x)

Try it online!

><>, 40 36 bytes
"e"b*>$1-:@?!n:*v
%1:,av?  (*"dd":<-

Try it online!
Explanation
                   # we call the input n
"e"b*              # initialize number as 1111
     >$1-:@?!n     # calculate n-1, if 0 then print number
              :*v  # else, square and move to row 2
     v?  (*"dd":<- # if number is less than 10000, move to row 2
%1:,a              # else divide by 10 and mod away the decimals to get an int

source: Stack Exchange

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

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

sort: votes


text:
Create a version series
The Definition
Given an integer x, a version series is a set of digits (base 10) from which any x-length subset of consecutive members is unique compared to all other possible subsets of the same length (a unique "version").
The Task
Write a function which, when passed some subset length x, produces a version series, considering a scoring determined by the sum of the total number of characters outputted by inputs 1 through 10 (so, f(1) + f(2) + ... + f(10)).
Further rules

The output must always be the same for a specific x.
Please do not change your algorithm (except for corrections) after posting and try to avoid using others' work.

Examples
Let f(x) be the function which returns the version series.
>>> f(3)
0010111

Note that this is a valid version series as all possible consecutive subsets of length 3 (001, 010, 011, 111) are unique. This would obviously be a terrible score, however.
>>> f(3)
0123456789876543210

This is another valid version series, with a slightly better score. This is valid for the same reasoning as before.
>>> f(3)
001010011110111

This is clearly not valid; the subsets 001, 010, 101, 111 all occur more than once.
Trivia
I have referred to this as a version series as it may be used to identify a range of compatible versions by taking a larger subset of consecutive values within the full set to identify a range of compatible versions that lie therein.
Verifier (in Java)
import java.util.Scanner;
import java.util.ArrayList;

public class Checker {
    public static void main(String[] args) throws Exception {
        int substringLength = Integer.parseInt(args[0]);

        Scanner sc = new Scanner(System.in);
        sc.useDelimiter("");

        ArrayList<Character[]> active = new ArrayList<Character[]>();

        Character[] current = new Character[substringLength],
            compare, prev;

        for (int i = 0; i < substringLength; i++) {
            current[i] = sc.next().charAt(0);
        }

        for (int index = 0; sc.hasNext(); index++) {
            for (int k = 0; k < index; k++) {
                boolean differ = false;
                compare = active.get(k);
                for (int j = 0; j < substringLength; j++) {
                    differ = differ || compare[j].compareTo(current[j]) != 0;
                }
                if (!differ)
                    throw new Exception("Match found for subset " + index);
            }
            active.add(current);
            prev = current;
            current = new Character[substringLength];
            for (int k = 1; k < substringLength; k++) {
                current[k - 1] = prev[k];
            }
            current[substringLength - 1] = sc.next().charAt(0);
        }

        System.out.println("Input is a valid version series.");
    }
}

Compile this as Checker.java, and call with program <x> | java Checker <x>, where x is your input (obviously, the input to your program is flexible).
If you are unable (or unwilling) to use Java, you may implement your own verifier, as long as you post it with your answer and show that it works.

I think the first example is missing the 101 from the middle.

Related.

Thanks for the challenge! It was fun to solve even if there was an optimal solution and I was FGITW.

Python 2, score: 11111111155
Score: sum(10**x+x-1 for x in range(1,11))
This program obtains the maximum possible score for any given x.
def f(x):
    s="0"*x
    while 1:
        for c in "1234567890":
            p=s+c
            if p[len(p)-x:]not in s:
                s=p
                break
        else:
            break
    return s

Try it online
This takes a long time to run for large inputs (like 6), because it's building strings thousands or millions of characters long. It also maintains a set of substrings and checks if a possible next substring is contained in it. It's not very efficient. I first tried a recursive solution, as well as a solution with a fixed number of iterations or something, but this was my working one.
Explanation:
I solved this by recognizing a pattern in the optimal solutions for x=1,2, which I created by hand as below. I roughly implemented the method I used to create f(2) in the function above, except that I just did zero last altogether.
1   0123456789
2   00102030405060708091121314151617181922324252627282933435363738394454647484955657585966768697787988990

This algorithm tries every number in order, with zero last. Failing to do zero last will result in an early termination. f(2), for example, would stop at 00102030405060708090, because all possible values starting with 0 have been exhausted. When doing this by hand, I simply started with f(1), added zeros between each digit, then went to every combination starting with a 1 (leaving out zero), then twos (leaving out zero and one), etc. Essentially, the algorithm must try the digit that you started with last.
The score is sum(10**x+x-1 for x in range(1,11)).
I used this formula to compute the score, because the output for all values 1-10 would probably take many days (months?) to complete. The highest I received the output for was f(6), which took ~10-15 minutes. It'd take at least 10000 times that for f(10). The lengths of s and p go from 1 to 10**x. The for loop runs exactly 10 times, no matter what.
Output:
They are slightly different than above because zeros are done last:
1   0123456789
2   00112131415161718191022324252627282920334353637383930445464748494055657585950667686960778797088980990
3   000111211311411511611711811911012212312412512612712812912013213313413513613713813913014214314414514614714814914015215315415515615715815915016216316416516616716816916017217317417517617717817917018218318418518618718818918019219319419519619719819919010210310410510610710810910022232242252262272282292202332342352362372382392302432442452462472482492402532542552562572582592502632642652662672682692602732742752762772782792702832842852862872882892802932942952962972982992902032042052062072082092003334335336337338339330344345346347348349340354355356357358359350364365366367368369360374375376377378379370384385386387388389380394395396397398399390304305306307308309300444544644744844944045545645745845945046546646746846946047547647747847947048548648748848948049549649749849949040540640740840940055565575585595505665675685695605765775785795705865875885895805965975985995905065075085095006667668669660677678679670687688689680697698699690607608609600777877977078878978079879979070870970088898808998908098009990900

I was going to make a pastebin of f(6), but it's past the maximum size limit a guest can create.
Validator - Counts how many unique subsets there are. If the result is 10**x, it's correct.

well okay then.

BruteForce
Tries to brute force every single possible combination using luck. Note that it does use the same seed all the time, so output is the same. Takes a single input in the args array to specify i.
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class BruteForce {
    private static Random rand = new Random(123);
    public static void main(String[] args) throws Exception {
        int length = Integer.valueOf(args[0]);
        List<List<Character>> used = new ArrayList<>();
        StringBuilder out = new StringBuilder();
        List<Character> put2 = new ArrayList<>();
        for(int i = 0; i < length-1; i++) {
            char one = (char) rand(48, 57);
            out.append(one);
            put2.add(one);
        }
        used.add(put2);
        long last;
        last = 0;
        for(int i = length-1; ; i++) {
            last = System.currentTimeMillis();
            List<Character> put = new ArrayList<>();
            do {
                if(last+1000 < System.currentTimeMillis()) {
                    System.out.println(out.toString());
                    return;
                }
                put.clear();
                for(int j = i-1; j >= i-length+1; j--) {
                    put.add(out.charAt(j));
                }
                put.add((char) rand(48, 57));
            } while(used.contains(put));
            used.add(put);
            out.append(put.get(length-1));
        }
    }
    public static int rand(int min, int max) {
        return rand.nextInt((max - min) + 1) + min;
    }
}

Do you know what the score is, or if this produces the optimal result?

It will produce the optimal result, eventually.

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


text:
Parse a raw IRC message
In the IRC protocol, raw messages look similar to this:
command arg1 arg2 :arg3 with spaces :arg4 with spaces :arg5

In a shell environment (e.g. bash), that would be equivalent to:
command arg1 arg2 "arg3 with spaces" "arg4 with spaces" arg5

The format specification is as follows:

Raw messages will only contain printable ASCII characters (ordinals 32-126).
Raw messages will start with a command, which will not contain any spaces.
Any number of arguments may follow a command. Arguments are delimited by one or more spaces followed by a colon (<space>: and <space><space>: are both valid delimiters).

Any arguments that do not contain spaces may omit the colon from the delimiter so long as all previous arguments (if any) have omitted the colon.

Colons will not appear within arguments or commands.
Arguments will not begin with a space.

For example, these are all valid raw messages:
join #foo #bar #baz
msg person hi
msg #channel :hello world
help :how do I use IRC
foo bar :baz bip :abc def :ghi

These are all invalid raw messages:
error :n:o colons within arguments
error ::need spaces between colons
:error no colons in commands
error non-ASCII character Ω

Given a valid raw IRC message as input, output a list containing the command and the arguments, properly parsed.
Test Cases
"join #foo #bar #baz" -> ["join", "#foo", "#bar", "#baz"]
"msg person hi" -> ["msg", "person", "hi"]
"msg #channel :hello world" -> ["msg", "#channel", "hello world"]
"help :how do I use IRC" -> ["help", "how do I use IRC"]
foo bar :baz bip :abc def :ghi :xyz -> ["foo", "bar", "baz bip", "abc def", "ghi", "xyz"]

Could the final argument end with spaces?

@JonathanAllan Yes

Can we assume that input will be valid?

@Titus Yes, that was the goal of defining what constitutes valid input.

Does the output have to be a flat list?

@BradGilbertb2gills What do you have in mind?

(("foo", "bar"), ("baz bip", "abc def", "ghi", "xyz"))

@BradGilbertb2gills No, you need to preserve the spaces in arguments

I was asking about the (), that is ((0,1),(2,3,4,5)) vs (0,1,2,3,4,5). If you look you will see "baz bip" which means it is a string with a space in the middle.

@BradGilbertb2gills Oh, I missed that. Blame mobile and tiny screens. I'm still going to say flat lists only.

Jelly, 19 bytes
;⁷œṣ⁾ :µḢḲ;œr€⁶ỴF$€

A monadic link that returns a list.
Note: As a full program the implicit print that Jelly performs may be a little confusing in this case, since a list containing strings (really lists of characters in Jelly) is printed as if it were a single string. So, for completeness here are test harnesses employing the quick Ç which calls the previous link monadically:

Ṿ shows the Jelly representation of a list of character lists;
Y joins the list with line feeds;
ŒṘ shows the underlying Python representation (showing the actual lists of characters).

How?
Handling the edge case of possible trailing spaces for the ultimate argument (the only one which may have trailing spaces) is quite an expense at 6 bytes; maybe there is a shorter way?
;⁷œṣ⁾ :µḢḲ;œr€⁶ỴF$€ - Link expecting a single list of characters as input
;                   - concatenate
 ⁷                  - a line feed (to avoid right trimming spaces from ultimate argument)
  œṣ                - split on sublists equal to
    ⁾ :             -     two character list [' ',':']
       µ            - monadic chain separation (call the split result z)
        Ḣ           - head - pop first element (modifies z)
         Ḳ          - split at spaces
          ;         - concatenate with z
              ⁶     - space
           œr€      - right-strip from €ach
                 $€ - last two links as a monad for €ach
               Ỵ    -     split on line feeds
                F   -     flatten (removes the line feed from the beginning)

How does this handle <space><space>:?

@isaacg - thanks for pointing that out, I have fixed it up, although it opened up an edge case I had to address too.

I think you can add the Ṙ×0 test harness too.

PHP, 87 bytes
$a=($s=preg_split)("# +:#",$argv[1]);array_splice($a,0,1,$s("# +#",$a[0]));print_r($a);

The first regex splits the argument by one or more spaces followed by a colon.
The second regex splits the first element by one or more spaces with no colon.
array_splice replaces the first element with the result of the second preg_split.
print_r prints the resulting array.
function version for testing
$cases=[
    "join #foo #bar #baz" => ["join", "#foo", "#bar", "#baz"],
    "msg person hi" => ["msg", "person", "hi"],
    "msg #channel :hello world" => ["msg", "#channel", "hello world"],
    "help :how do I use IRC" => ["help", "how do I use IRC"],
    "foo bar :baz bip :abc def :ghi :xyz" => ["foo", "bar", "baz bip", "abc def", "ghi", "xyz"],
];
function i($argv_1_){$a=($s=preg_split)("# +:#",$argv_1_);array_splice($a,0,1,$s("# +#",$a[0]));return $a;}
foreach($cases as$x=>$e)
{
    $y=i($x);
    echo "case '$x': ['",join("','",$y),'"]: ',($y<>$e?"FAIL. Expected: ['". join("','",$e)."']":OK),"\n";
}

what should i learn from that downvote?

I'm not sure why whoever downvoted did as they did, but maybe it didn't work for all test cases?

@Downgoat Or maybe someone just doesn´t like my nose. It doesn´t check the input for correctness; but I don´t see that required anywhere.

Retina, 24 bytes
M!`:.+?(?=\s+:|$)|\S+
:

(note there is a trailing newline)
Try it online!

Added that new line. Could you pop an explanation in at some point?

PowerShell v2+, 43 34 bytes
$a,$b=$args-split' +:';-split$a;$b

This -splits the input string $args on the regex +: (i.e., one or more spaces and a colon), stores the left-most (i.e., first result) into $a and any remaining results into $b. We then need to -split $a on spaces (here done by leveraging that whitespace is the default for unary -split), and that's left on the pipeline. We then simply put $b on the pipeline. Output via implicit Write-Output inserts a newline between elements.
Test cases
PS C:\Tools\Scripts\golfing> .\parse-raw-irc.ps1 'join #foo #bar #baz'
join
#foo
#bar
#baz

PS C:\Tools\Scripts\golfing> .\parse-raw-irc.ps1 'msg person hi'
msg
person
hi

PS C:\Tools\Scripts\golfing> .\parse-raw-irc.ps1 'msg channel :hello world'
msg
channel
hello world

PS C:\Tools\Scripts\golfing> .\parse-raw-irc.ps1 'help :how do I use IRC'
help
how do I use IRC

PS C:\Tools\Scripts\golfing> .\parse-raw-irc.ps1 'foo bar :baz bip :abc def :ghi :xyz'
foo
bar
baz bip
abc def
ghi
xyz

Python 2, 64 60 bytes
import re;a=re.split(' +:',input());print a[0].split()+a[1:]

Edit:
Requires quoted input to use input.
Preserves trailing spaces on last argument.

Since we allow input to be wrapped in quotes, you can use input() instead of raw_input()

Needs to handle the edge case of the final argument having trailing spaces

Perl 6,  49  47 bytes
{m/(<-[\ :]>+)+%%" "+":"?(.+?)*%[" "+":"]$/.flat}

Perl 6 version of the Python answer
{$/=.split(/" "+":"/);|$0.split(" "),|$/[1..*]}

The to |s are there to flatten the list.
the first entry expanded:
{    # bare block lambda with implicit parameter ｢$_｣

  m/               # regex match implicitly against ｢$_｣

      (               # capture
        <-[\ :]>+     # at least one non-space non-colon character
      )+              # at least once

    %%                # separated (with optional trailing separator)

      " "+            # by at least one space

    ":"?              # optionally match a colon ( needed for rest of regex )

      (               # capture
        .+?           # at least one character as short as possible
      )*              # any number of times

    %                 # separated (no optional trailing separator)

      [ " "+ ":" ]    # by at least one space, and a colon

    $                 # match end of string (needed because of ｢.+?｣)
  /

 .flat         # flatten the captures
}

C, 140 bytes (excluding sample usage)
void p(char*m){char*c=strchr(m,':');if(c) {*c=0;c++;}
char*n=strtok(m," ");while(n) {puts(n);n=strtok(NULL," ");}
if(c){puts(c);}}

Sample usage:
#include <string.h>
#include <stdio.h>
void parse(char*msg){char*c=strchr(msg,':');if(c) {*c=0;c++;}
char*n=strtok(msg," ");while(n){puts(n);n=strtok(NULL," ");}
if(c){puts(c);}}
main(){char msg[]="sample : abcnsjd hajs";parse(msg);}

Try me: http://codepad.org/GQ51MO4l

Welcome to PPCG! :)   First of all, you should format your golfed code the same way as your 'sample usage' code. You could turn every name that is over 1 characters to 1, ex. parse to p and msg to m. Useless whitespaces could be removed from after if(c) (both cases) and while(n).

I count 131 bytes, and there's still extraneous whitespace.

JavaScript (ES6), 59 57 56 49 bytes
This is my first entry on PPCG, any input appreciated!
(s,[a,...b]=s.split(/ +:/))=>a.split` `.concat(b)

EDIT History:

Thanks @Mego for saving 2 bytes by making it an anonymous function.
Replaced \s with   to save 1 byte.
Thanks @BassdropCumberwubwubwub for showing me the split` ` syntax and the [a,...b]=array_expression_here syntax. I didn't know these were possible, thank you very much! Very clever!

Test snippet

let f = (s,[a,...b]=s.split(/ +:/))=>a.split` `.concat(b)
<input id=I type="text" size=70 value="command arg1 arg2 :arg3 with spaces :arg4 with spaces :arg5"><button onclick="console.log(f(I.value))">Run</button>

Welcome to PPCG! The only improvement I see is that you can drop the f= to make it an anonymous function, which are allowed on the site by default.

You can write split(" ") as split\ `` to save 2 bytes

Actually, even shorter like this (s,[a,...b]=s.split(/ +:/))=>a.split\ `.concat(b)`

Mathematica, 44 bytes
Flatten@MapAt[s=StringSplit,#,1]&@s[#," :"]&


text:
Manhattan distance of rotation sequence
I though this would be a good challenge : http://adventofcode.com/2016/day/1
Task description
Given a sequence of rotations and distances following the pattern (L|R)[1-9][0-9]*, give the manhattan distance between the start and the ending points, that is the minimal number of vertical and horizontal moves on a grid.
Examples
For example, if we assume you started facing North:
Following R2, L3 leaves you 2 blocks East and 3 blocks North, or 5 blocks away.
R2, R2, R2 leaves you 2 blocks due South of your starting position, which is 2 blocks away.
R5, L5, R5, R3 leaves you 12 blocks away.
Technical details
You can choose the separator between the moves (e.g. : "\n", ", ", or ",").
You must give the answer as an integer in base 10.
Not a duplicate!
It is not a duplicate for multiple reasons :

The moves are not the same. Here they are rotations, not directions.
I want the Manhattan distance, not the euclidian.

You should include a description of what the Manhattan distance is in your question.  Just posting a link is kind of tacky.

It's very different ! We only have rotations !

@Labo I agree. Its not just about the fact that the answer here is in Manhattan distance whereas the other one is in Euclidean distance. This has turtle style movement while the other one specifies compass directions NSEW (the fact that it calls them UDLR is irrelevant.)

For the moment, I have this :
Python 3, 108 chars http://pastie.org/private/2v1jeiylbfjbezemquqcpq

I've voted to reopen.

Is it okay to assume separators between the direction and the distance? (i.e. can the input be a rectangular array like {{"R", 2}, {"L", 3}})

Is the first character always R or L, so that the first move is always east or west?

Some test cases?

@GregMartin: It doesn´t matter what direction your first move goes; the Manhattan distance stays the same.

That's true isn't it. Just checking the specification tho

Can the input be a space-separated string such as "R2 L3"?

@JHM no, the moves have to be of the mentioned pattern.

@Sherlock9 Yes!

I have 104 bytes in Python 3 : http://pastie.org/private/9maphu3wzk3gxzamjgja

Please use the Sandbox in the future to get feedback on your challenges before posting them to the main site.

@Mego Sorry, although I did read and answered a lot of challenges, it's my first post, and I didn't know about the Sandbox!

@Labo That's fine, we don't expect new users to know all the ins and outs of this site immediately. It's just a gentle suggestion for next time. :)

@Mego Could you please explain (you or somebody) how I am supposed to choose a winner?

I have a 38 bytes Pyth solution : https://goo.gl/67nrqW

Python 3, 109 99 104 101 bytes
This is a simple answer that uses complex numbers, with input as a space-separated string or a newline-separated string. Golfing suggestions welcome!
Edit: -13 bytes thanks to Labo. +5 bytes for converting to an int.
d=p=0
for r in input().split():d+=1-2*(r<'R');p+=1j**d*int(r[1:])
print(int(abs(p.real)+abs(p.imag)))

Ungolfing
def manhattan_rotation(seq, nsew=0, pos = 0):
    for rot in seq.split():
        # change direction
        if rot[0] == "L":
            nsew += -1
        else:
            nsew += 1
        # move in that direction rot[1:] times
        pos += 1j ** nsew * int(rot[1:])
    return int(abs(pos.real)+abs(pos.imag))

1-2*(r[0]<'R') will save you 2 bytes :)

Don't make a function, reading from the input make you save more chars!

Assign 2 variables in the same line to save 2 bytes : d=p=0

I golfed again your answer and it makes 99 chars ! http://pastie.org/private/hm7lejqosdqnkgo000u7q

@Labo Was just adding all of that as you typed it :D

But I can't approve your answer, you give a float and not an int :( I though base 10 was clear, I edited the description. You can add a conversion though.

@Labo I'm not sure you can edit the specification in a way that would invalidate existing answers, but let me ask some mods.

Ok. Anyway, you win for Python :)

Actually, you can save 3 more bytes if you use r<'R' !

Python 2, 86 bytes
x=y=0
for d in input().split():c=cmp(d,'M');x,y=int(d[1:])-y*c,x*c
print abs(x)+abs(y)

Tracks the current x and y coordinates. When turning, instead of updating the direction, rotates the current value so that the motion is always in the x-positive direction. Complex numbers were too costly to extract the coordinates from.

PHP, 93 bytes
while($m=$argv[++$i])${chr(80|3&$d+=(P<$m)-(M>$m))}+=substr($m,1);echo abs($P-$R)+abs($Q-$S);

breakdown
while($m=$argv[++$i])       // loop through arguments:
    ${                      // 5. use as variable name
        chr(                // 4. cast to character (P,Q,R,S)
        80|                 // 3. add 80
        3&                  // 2. modulo 4
        $d+=(P<$m)-(M>$m)   // 1. change direction depending on letter
    )}+=substr($m,1);       // 6. add number to variable
echo abs($P-$R)+abs($Q-$S); // calculate distance, print

Python 2, 103 102 bytes
l=c=0
for i in input().split():c+=cmp(i[0],'N');l+=1j**c*int(i[1:])
print int(abs(l.imag)+abs(l.real))

repl.it
Input is a string of space delimited directions, e.g. "R5 L5 R5 R3".
Prints out the Manhattan distance between the starting location and the destination.
How?
Starts at the origin of the complex plane, l=0;
With a cumulative quarter-right turn counter, c=0;
For each instruction, i, the rotation is parsed is by comparing the first character of the direction to the character 'N', and c is adjusted accordingly.
The distance to travel is parsed with int(i[1:]) and the instruction is enacted by taking that many block sized steps in the direction given by taking the cth power of 0+1j with 1j**c.
The final Manhattan distance is the sum of the absolute distances from the origin in the two directions - imaginary and real; achieved with abs(l.imag)+abs(l.real)

@Sherlock9 - Oh, um answer convergence. Save 2 bytes by switching to Python 2 and using cmp like my answer, let me know and I will delete.

JavaScript (ES2016), 98 100
2 bytes saved thx @Neil
d=>d.replace(/.(\d+)/g,(d,l)=>(o+=d>'M'||3,l*=~-(o&2),o&1?x-=l:y+=l),x=y=o=0)&&(x*x)**.5+(y*y)**.5

100 bytes for ES6
d=>d.replace(/.(\d+)/g,(d,l)=>(o+=d>'M'||3,l*=~-(o&2),o&1?x-=l:y+=l),x=y=o=0)&&(x>0?x:-x)+(y>0?y:-y)

Less golfed
d => d.replace(/.(\d+)/g,
  (d,l)=>( // L or R in d, distance in l
    o += d>'M' || 3, // orientation in o, used %4
    l *= ~-(o&2), // convert to number and change sign if needed
    o&1 ? x -= l : y += l // move based on orientation
  ), x = y = o = 0)
&& (x>0?x:-x) + (y>0?y:-y)

Test (ES6)

F=
d=>d.replace(/.(\d+)/g,(d,l)=>(o+=d>'M'||3,l*=~-(o&2),o&1?x-=l:y+=l),x=y=o=0)&&(x>0?x:-x)+(y>0?y:-y)

function update() {
  O.textContent=F(I.value)
}

update()
<input id=I value='R5, L5, R5, R3' oninput='update()'>

My ES6 answer was originally 106 bytes; copying your intermediate variable saved me 3 bytes; switching from match to your replace saved me 2 bytes, and copying your processing the direction and distance at the same time saved me a final byte, resulting in this: s=>s.replace(/.(\d+)/g,(c,n)=>(d+=c<'R'||3,n*=~-(d&2),d&1?x+=n:y+=n),x=y=d=0)&&(x<0?-x:x)+(y<0?-y:y), which is now two bytes shorter than your ES6 answer, thanks to the c<'R'||3 and n*=~-(d&2) tricks.