text:
Pointers, pointers, pointers!
Introduction
In the error outputs of some languages such as Java, a pointer is shown to give the programmer an idea of exactly where the error went wrong.
Take this example on Ideone:
Main.java:12: error: ';' expected
    Invalid Java!
                ^

Notice the caret shows where the invalid code is?
Challenge
Your challenge is: given number N and string S, place a pointer on the Nth character in S.
Examples
Input: 2, "Lorem ipsum, dollar sit amet."
Output:
Lorem ipsum, dollar sit amet.
 ^

Rules

Input is received via STDIN or function parameters
Output is printed out to the console or returned
Trailing new lines, spaces etc are allowed in the output
The pointer character must be a ^ caret and must be on a new line.
This is code golf, so the shortest answer wins. Good luck!

I feel like this is an extremely simple problem, so I am not certain it will be received overly well. You might want to try the sandbox once you have enough rep.

I think this could have been made a bit more interesting if the input had multiple lines, so that you had to insert a newline, spaces, and carat at the correct position(s). Honestly, the spec doesn't really say it will be a single line, but I think enforcing that now will invalidate a few answers unfairly, since there's no example that shows this.

@Geobits Can I add that now? People may need to change their answers.

Like I said, the cat's probably out of the bag on this one. Rule changes after valid answers are posted usually don't work out well. Live and learn ;)

Oh well. Thanks anyway! I'll make sure to use complete & solid rules before I post.

The Sandbox link in the other comment is a great idea, too.

@Geobits Yeah, I will use the Sandbox now I have enough reputation.

@SohamChowdhury I'll just pretend that was intentional ;) Do you want me to fix it?

While this may be very simple, you've certainly done well for a first challenge! You have +16/-0 votes, 1,300 views, and 28 answers (as of this writing) and you've made the Hot Network Questions list. Nice job!

@FryAmTheEggman and again the value of a question can be measured by the quality of the answers. Very good ones in this challenge.

So are the quotes and comma necessary?

@kirbyfan64sos The quotes around the string output aren't required.

@fridgefish I meant the input.

@AlexA. I agree. I'm surprised how well the question went. Thank you!

+1 for the carrot (even though it's been edited out now)

Can I get S as command-line argument and N in unary, using any digit I want?

C 33
If just a function is allowed, then even c can compete.
(For the record, 2 bytes saved thx to @Cool Guy. Mt thx comment is unexpectedly evaporated.)
1 more char saved thx @Mig
f(a,c){printf("%s\n%*c",a,c,94);}

C can always compete, it just can't always win. ;)

@AlexA.  looks like its winning to me ;-)

Save 1 char : f(a,c){printf("%s\n%*c",a,c,94);}

If I were a cynical person, I'd say that it's still about 4 times as long as the shortest answer in a golfing language. Which is about business as usual. ;) This is clever, though. I think I had seen the * option in the format string before, but had completely forgotten about it. Might come in handy for some of the ascii art challenges in the future.

Brainf*ck - 133 bytes
+++++>>+>>+++>>+++++++++<<<<<<[[->++++++++++<]>>]<++++<<++<<<<--<,>[->+<<->]>>>,<<[->>-<<]<<[->>>>++++++++++<<<<]>>+[,.]>.>[->.<]>>>.

Expects input as [0-9]{2}.* e.g. "02Hello world!!!" would produce

Hello world!!!
 ^

Welcome to Programming Puzzles and Code Golf! This is a great first post, nice job! :D

The problem is, no-one knows if this is even valid code, let alone solves the problem :)

Yeah I think there is an off-by-one error here. The caret should be under the e in the example. At the cost of 1 byte this can be fixed by adding a - in front of [->.<]

@FryAmTheEggman you're right -- see the edit. I originally had it under the e as it is now, but I got confused by using two IDEs with different fonts.

IA-32 machine code, 24 bytes
Hexdump:
66 b8 5e 00 42 38 22 75 fb 66 c7 02 0d 0a 42 42
c6 02 20 e2 fa 89 02 c3

It's a function (using MS fastcall convention) which updates the string in-place:
__declspec(naked) void __fastcall carrot(int n, char* s)

Assembly code:
    mov ax, '^'; // ah = 0, al = '^'

mystrlen:
    inc edx;
    cmp [edx], ah;
    jne mystrlen;

    mov word ptr [edx], '\r\n'; // append a newline
    inc edx;

mymemset:
    inc edx;
    mov byte ptr [edx], ' ';
    loop mymemset;

    mov [edx], eax; // append a caret and terminate the string
    ret;

It uses WORD-sized (16-bit) data in a few places. This has a penalty (1-byte prefix) in 32-bit code, but makes the code smaller anyway - using 32-bit data would put two zero bytes into code!
At the end, it writes 4 bytes (eax) instead of 2 bytes (ax) - the code is smaller that way, and 2 extra bytes of junk go after string termination, so no one notices them.
Usage:
int main()
{
    char s[100] = "Lorem ipsum, euro sit amet.";
    carrot(2, s); // credit to Digital Trauma for the name
    puts(s);
}

The instruction 66 b8 5e 00 moves 0x5e to al, not to ah, and zero to ah instead of al, so your comment in assembly code is misleading.

@Ruslan Thanks! Fixed. That was a remnant from a previous version.

Why is naked in there? And why is it the first thing I saw?

It's Microsoft that decided to put the naked in front: https://msdn.microsoft.com/en-us/library/h5w10wxs.aspx

Pyth, 8
zp\^*tQd

This solution no longer works, since the commit after the one I've linked to as the language name changed p to have arity 1. There are several other ways of achieving a similar score in Pyth that still work today, like zp+*dQ\^.
If the string needs quotes, adding v to the beginning of the code works. If it has to be comma separated, it goes up to 10 bytes:
eQp\^*dthQ

I think this is the shortest one so far. Well done.

The algorithm seems wrong to me, I think ^ will always be under the first character. And by the way the input parameters are given in the wrong order to the online interpreter (so it fails executing).

@Jim This answer used an older version of pyth, where p had arity 1. This caused the first line of the output to be printed first and then the caret on the next line followed by the spaces. Now you could do z+*dQ\^ for a shorter score but with a trailing newline, or add a p before the + to remove it. I'm unsure what to do here, since people upvoted this version of the answer, I think I will try to find the version it worked on.

T-SQL, 90
While a fairly simple question, it's always interesting to try these in languages that really don't tend to support them well or golf well for that matter.
This answer is almost guaranteed to be the longest one.
This creates an inline table function for SQL Server that takes @n and @ as parameters and returns the results as a column.  The carriage return is significant, otherwise I would need to use char(13).
CREATE FUNCTION G(@N INT,@ VARCHAR(MAX))RETURNS TABLE RETURN SELECT @+'
'+SPACE(@n-1)+'^'R

It's used in the following manner
SELECT R
FROM (VALUES
    (1,'This is test 1'),
    (2,'This is test 2'),
    (3,'This is test 3'),
    (4,'This is test 4'),
    (5,'This is test 5')
    )T(n,S)
    CROSS APPLY G(n,S)

And returns
R
---------------
This is test 1
^
This is test 2
 ^
This is test 3
  ^
This is test 4
   ^
This is test 5
    ^

Very creative use of a language not really designed for golfing ;) +1

Python, 27
lambda n,s:s+'\n%%%dc'%n%94

This uses two levels of string formatting.
And here's a 25 byte solution partly stolen from feersum's answer (with the argument order reversed):
lambda*p:'%s\n%%%dc'%p%94

Bash, 27
printf %s\\n%$[$1-1]s^ "$2"

Output
$ ./carrot.sh 2 "Lorem ipsum, dollar sit amet."
Lorem ipsum, dollar sit amet.
 ^$

Carrot? Also, what's the dollar at the end?

The Dollar seems to be the shell's prompt.

@Scimonster Carrot was my attempt at a joke - see my edit to the question.  And yes, the $ at the end is the shell prompt.  The question specifies that trailing newlines are allowed, but doesn't say they're necessary.

sed, 16
2y/1/ /;2s/ $/^/

This is something of a testcase of this meta answer.  Specifically I am requiring that the number N is input in unary. E.g. for the caret in position 2, the input for N would be 11.  Also it is not strictly specified which order S and N should be, so here S goes first, followed by unary N on a new line, all through STDIN.
Output:
$ { echo "Lorem ipsum, dollar sit amet."; echo 11; } | sed '2y/1/ /;2s/ $/^/'
Lorem ipsum, dollar sit amet.
 ^
$

2y/1/ /;2s/ $/^/

@manatwork Good call!

Python, 29
lambda n,s:s+'\n'+' '*~-n+'^'

Concatenates the string, a newline, n-1 spaces, and a ^.

If only rjust wasn't so long...

Ah, the tadpole operator.

JavaScript (ES6): 63 62 56 52 32 bytes
Thanks to nderscore for greatly reducing the size of the code.
p=(a,b)=>b+`\n${' '.repeat(a)}^`

Version that works across more browsers (47 bytes):
p=function(a,b){return b+`\n${' '.repeat(a)}^`}

The question uses 1-based indexing, so you need Array(a-1). 2. Anonymous function are allowed by default, so you don't need point=. 3. For the ES6 version, you can get rid of the return statement and the braces. Just use (a,b)=>b+"\n"+Array(a-1).join(" ")+" ^".

33 bytes: (replace \n with an actual newline) p=(a,b)=>b+\\n${' '.repeat(a-1)}^``

@dennis The indexing works perfectly for me: https://i.stack.imgur.com/Tdejc.png

@Dennis Array(1).join(' ') results in an empty string :)

@nderscore I can't find a way to use an actual newline without it causing a line break in the code snippet, and the indexing follows the given example: https://i.stack.imgur.com/Tdejc.png

As long as each line is prepended with 4 spaces, it will maintain the code formatting.

@nderscore My mistake. I didn't realize there was a space before the caret, so it should have been Array(a).join(" ")+"^". The caret is still off for me. That might be an issue with my interpreter, but is ' '.repeat(1) really supposed to return an empty string?

@Dennis No, that trick only works for Array.join.

@darkness3560 The caret is at the third character, just that the quote from implicitly returning the function pushes the first line one character to the right. You need a-1 for a correct answer. Try logging the result instead of just returning it and you'll see. Also like already mentioned, adding an explicit newline instead of \n would shave one byte.

CJam, 9 bytes
q~N@(S*'^

Try it online.
How it works
q~  e# Read the input from STDIN and interpret it.
    e# This pushes the integer and the string on the stack.
N@  e# Push a linefeed an rotate the integer on top of it.
(S* e# Subtract 1 and push a string consisting of that many spaces.
'^  e# Push a caret.

Python, 29

Here's a more fun way to do it in 29:
lambda*p:'%s\n%*s'%(p+('^',))

Example usage:
>>> f=lambda*p:'%s\n%*s'%(p+('^',))
>>> print f('lorem',5)
lorem
    ^

TI-BASIC, 10 (?) bytes
Disp Ans
Output(3,N,"^

Input is given in the variable N, as the question asks, but you can't use the letter var S as a string. In place of that, it takes string input from Ans, so to run the example in the OP: 2->N:"Lorem ipsum, dollar sit amet.":prgm<program name>.
I'm aware that that probably doesn't count, though, as each colon-delimited segment is technically a separate statement; here's a 46-byte program that takes input as N "S" (2 "Lorem ipsum, dollar sit amet.")
Input Str1
2+inString(Str1,"
//^there's a space after the quote
Disp sub(Str1,Ans,length(Str1)-Ans
Output(4,expr(sub(Str1,1,1)),"^

Both of these assume that the screen has been cleared before running.

You'd be better off taking input from Input for the number and Ans for the string.

The first one also doesn't work if the program name, assignment, and string combined are longer than 16 chars.

@ThomasKwa 26, actually, since I have a color calculator :P It technically does work, if you count overwriting part of the input as 'working'.

The first one does work if you add a ClrHome:Input N, because the current vote on meta for mixing I/O methods is at +7.

dc, 19
?pr256r^255/32*62+P

Input is from STDIN.  dc strings are macro definitions and contained in [ ].  The string of spaces is generated by calculating the number that when expressed as a base 256 byte stream gives the string we need.  The calculation is ((n ^ 256) / 255) * 32).  This gives n spaces (ASCII character 32), but we need n-1 followed by ^, so we simply add 62 to the last base 256 digit.
Output
$ dc -e '?pr256r^255/32*62+P' <<< "2 [Lorem ipsum, dollar sit amet.]"
Lorem ipsum, dollar sit amet.
 ^$

C, 59 57 47 bytes
f(a,c){for(puts(a);--c;putchar(32));puts("^");}

Pretty straightforward. Ungolfed version:
f(char* a,int c){
    puts(a);        //Print the string first

    for(;--c;)      //Until number-1 is not 0
        putchar(32);//Print a space
    puts("^");      //Print a caret
}

Test it here
Thanks to @anatolyg for saving 10 bytes!

It's more beautiful to move puts(a) and putchar(32) into the parentheses of the for loop - there are exactly 2 empty places there! Also, I don't think you need to declare the type of a and c - just use the implicit int for them - will work if you don't do #include <stdio.h>.

@anatolyg , Thanks! I did not think that omitting the types would work, but to my surprise, it did.

C# 55
A function, concept similar to my C answer, but this time return is shorter than output.
string f(string a,int b){return a+'\n'+"^".PadLeft(b);}

K, 21 bytes
{y,"\n",1_|"^",x#" "}

Example:
ryan@DevPC-LX:~/golf/caret$ rlwrap k
K Console - Enter \ for help

  `0:{y,"\n",1_|"^",x#" "}[2;"Lorem ipsum, dollar sit amet."]
Lorem ipsum, dollar sit amet.
 ^

Explanation (x is the number, y is the string):
{                   }   enclosing function
               x#" "    repeat the space `x` times
           "^",         prepend the caret
          |             reverse the string to put the caret at the end
        1_              drop the extra space
   "\n",                prepend a newline
 y,                     prepend the text

SAS, 35 bytes
%macro a(n,s);put &s/@&n."^";%mend;

That is the SAS equivalent of a naked function; to add the data step to call it (equivalent to C main function to call it) would be a bit more (9 more bytes - Ty Alex), but I think that's not necessary for this purpose.  How it would be called:
data;
%a(3,"My String");
run;

There is a macro-only implementation but it's much longer, even if you allow it to give a warning about invalid parameters on n=1.
If we could use pre-defined parameters, SAS would be quite short comparatively on this one, which is a rarity for a language most definitely not intended to be short.

If a dataset is allowed to be the source of input, which is how you would 'do it' in SAS (or by %let statements), but is probably not permitted, this is even shorter (27 bytes, which actually could be 25 if you guaranteed the dataset was constructed immediately prior to running this [as you could then just use set;]):
(pre-existing dataset)
data b;
  n=3;
  s="My String";
run;

(actual code)
data;set b;put s/@n"^";run;

Good to see SO's resident SAS expert here on PPCG. :)

I'm fairly sure some of the old timers who know DM scripting could best this score... And my cmdmac skills suck.

I always forget that DM even exists, and I don't even know what cmdmac is! Btw, when you're counting bytes for the whole data step, you don't need data a;, you can just do data; which will save 2 bytes. But as you said, it's not necessary for this purpose anyway.

Yeah, my SAS ingrained reflexes don't let me use that intuitively I guess :). Thanks.

Speaking of old timers, I think you could save a couple bytes by defying all SAS intuition and using an old-style macro. I can't recall whether they can accept parameters though.

That's what I mean by CMDMAC.

I can't figure out a way to golf this using old-style macros, because I can't figure out a way to make old-style macros use parameters.  Maybe they do (I see some few indications they may have, though almost all do not) but I can't get it to work.  Might have been broken in 9.4, who knows.

Yeah I was looking into that the other day and I also can't seem to find a way to get old-style macros to accept parameters. Oh well, 35 is a great golfing score for SAS.

Matlab/Octave, 41
@(n,s)sprintf('%s\n%s^',s,ones(1,n-1)+31)

This is an anonymous function that returns the string. This produces a warning, which can be suppressed by previously calling warning off.

Do you mean the editor warning, or does it actually print a warning for you? Also, I beat you by 16 characters ;-) But mine does print the ans = bit, so after fixing that, it's only 10 characters difference.

@Oebele it prints a warning, but the returned string is unaffected.

Python3, 38 36 bytes
def f(s,i):return s+'\n'+' '*~-i+'^'

# OR

def f(s,i):print(s+'\n'+' '*~-i+'^')

Test it here
Thanks to @Dennis for saving 2 bytes!

(i-1) -> ~-i

I'm weak with bit operations and math.... Thanks anyway! :-D

R, 49 48 46
As an unnamed function that outputs to STDOUT.  Thanks to @Flounderer for the improvement.
uses strwrap now to ident the caret to n-1.  cat uses a seperator of \n rather than empty string.
function(n,s)cat(s,strwrap('^',,n-1),sep='\n')

Test run
> f=function(n,s)cat(s,strwrap('^',,n-1),sep='\n')
> f(29,'The caret should point here v hopefully')
The caret should point here v hopefully
                            ^
>

function(n,x)cat(x,"\n",rep(" ",n-1),"^",sep="") is 48 characters

@Flounderer Thanks for that ... my original idea was similar to that, but I didn't do it as nicely

If I am allowed two initial spaces, this works: function(n,x)cat(" ",x,"\n",rep("",n),"^") and saves a few characters

@Flounderer I suspect not.  strwrap also has some possibilities but it would probably end up longer.

That's nice! I've never seen the strwrap function before. Is there a simple way of saying what it does? I can't figure it out from the documentation.

@Flounderer First time I used it or noticed it yesterday.  Simply put it is a simplistic paragraph formatter.  Given a long string it will chop it up into strings of no more than w width and indent/exdent as require.  New strings are returned in a vector

Forth (gforth), 32 31 bytes
: b type cr 1- spaces 94 emit ;

Try it online!
Input is given as <number>  s" <string>" b.
Note the required space after s".
-1 byte from Bubbler.
Shorter than MAWP lol

1 - has a shortcut 1-.

Julia, 27 bytes
(n,s)->s*"\n"*" "^(n-1)*"^"

This creates an unnamed function that accepts an integer and string as input and returns a string. To call it, give it a name, e.g. f=(n,s)->....
All that's happening here is we're appending a newline, n-1 spaces, and the caret. String concatenation is performed using * and string repetition with ^.
Ungolfed:
function f(n, s)
    s * "\n" * " "^(n-1) * "^"
end

Example:
julia> println(f(2, "Lorem ipsum, dollar sit amet."))
Lorem ipsum, dollar sit amet.
 ^

PHP (CLI) - 42
<?=sprintf("%s\n%$argv[1]s",$argv[2],'^');

Call it from the command line:
php pointer.php 2 "Lorem ipsum, dollar sit amet."

I've only noticed now. But your answer is exactly like my 2nd option. I'm offering it to you: <?printf("$S\n%{$P}s",'^');. Replace the \n with a real newline. The total is 5 bytes. That only works on PBP4.1 and below.

Wow, so many mistakes in that comment... I meant that it is 26 bytes long and that only works on PHP4.1. And it is yours!

My first shot at codegolf
Java, 133 65
String g(int i,String s){for(s+="\n";--i>0;)s+=" ";return s+"^";}

I'm sure it can be reduced even more.
Old code
public void go(int i,String s){System.out.println(s);IntStream.range(1,i).forEach(j->System.out.print(" "));System.out.println("^");}

Can you store System.out somwhere?

No need for public. And change IntStream.range(1,i).forEach(j->System.out.print(" ")); to for(;--i>0;)System.out.print(" ");

@CoolGuy aha! sometimes simple is better

Can you move the s+="\n" inside the for() initialization to use the semicolon there?

@ThomasKwa 1 byte less

Matlab, 25
This one is extremely cheeky. Apparently displays prints non-printable characters as spaces. The following code defines a function named ans, that meets the specs.
@(N,S)[S 10 ones(N-1) 94]

so calling this function like this:
ans(2, 'Lorem ipsum, dollar sit amet.')

gives the output:
ans =

Lorem ipsum, dollar sit amet.
 ^

I always dislike the ans = part in Matlab answers. If this is a problem, I need to add 6 bytes... but I have always seen it like this in Matlab answers.
Note that running this code overwrites the variable ans, so you need to redefine the function if you want to use it a second time!

Very nice! I didn't know putting a string in a vector worked like that. My understanding was that since this is a function, the string it returns it the meaningful value, and MATLAB's repl environment just happens to print it out. i.e. if you do x=ans(2, 'asdf'); you don't get an ans = thing.

Pascal: 57 characters
procedure p(n:Byte;s:string);begin
Write(s,#10,'^':n)end;

Just to demonstrate Pascal's cute little output formatting. The rest is depressing.

Swift, 41
It is disappointing that Swift does not have operator * on Array or String.
{$1+reduce(0..<$0,"\n",{$0.0+" "})+"^"}

For Swift 2.0: {$1+(0..<$0).reduce("\n"){$0.0+" "}+"^"}

MAWP v1.02, 37 53 bytes
%|0~[;]25W3M;@~(%)~_1A[1A~25WWM~]~1A[1A84W;]85W7M2W;.

Takes input as [S][a], with no spaces between S and n.
Since the online interpreter takes only one line of input, the string and number are printed together.
Try it!

Spaces no longer compute as NaN! :)

Yay! I fixed the code to take in multi digit numbers

As for multiline input, i've been thinking about that and how it will work with the current input functions. Ill open an issue for further discussion

Python 3, 29 bytes 31
lambda N,S:S+'\n'+' '*~-N+'^'

Try it online!
A Plain Comprehensible snippet, used function lambda function and concatenation

(N-1) can be ~-N. You can also use f-strings for 28 bytes

@JoKing Thank you for your opinion

If you are using a def function declaration, you have to include it in the byte count (right now this is neither a full program nor a function).

@JoKing Sorry, my mistake. Thank you once again.

Perl 5 -p, 16 bytes
$_.=$"x<>;s; $;^

Try it online!

Perl 5 -p, 16 bytes
$\=$"x(<>-1)."^"

Try it online!

Integral, 7 6 Bytes

▼8gv^►

Try it!
-1 thanks to @petStorm

Save a byte (▼8gv^► (6 bytes)) by using the v instruction.

Hexagony, 37 bytes (Side Length 4)
?},$;}<..0~\>(</,<}.>/>;/@\'$'65;\94\

    ? } , $
   ; } < . .
  0 ~ \ > ( <
 / , < } . > /
  > ; / @ \ '
   $ ' 6 5 ;
    \ 9 4 \

Input is of the form: "[number] [string]"
ex: 3 Hello World!
would output:
Hello World!
  ^

In terms of pictures, I've split it up into:
Most of the program, and the End

Red: ?},$
  `?}` gets the pointer num and moves the MP
  `,` skips the space
  `$` creates a jump to the for loop

Red / Orange ,<;
  `,` gets the next byte from stdin
  `<` goes out of loop if byte is <= 0
  `;` prints the byte

Green ~0;56'$
  `~0` when Hexagony reads an empty byte, it puts a -1 in memory,
       I then flip that to 1 and append a 0 to get 10
       This saves 1 char over `*10` which I needed to save
  `;` prints the newline
  `56` appends a 56 to the 10 to get 1056
       taken modulo 256, it comes out to 32 which is ascii
       for space; this also saves 1 char over `*32`
  `'` moves the MP back to the pointer num
  `$` jumps into the space printing loop

Green / Blue (<};'
  `(` decrements by 1 before checking if 0 so that it
      prints pointer val - 1 spaces
  `<` loops if counter > 0
  `};'` moves to the memory value containing the space,
        prints it, then moves back

Purple }'94
  `}'` the `'` was already in the path, so I used } to move it forward
       so it would move back
  `94` puts ascii `^` into memory

Starting from where purple left off, I was lucky that the program basically worked itself out. It ends up not changing the 94 in memory until it prints it, and then eventually makes its way to a blank space that hadn't been used and so I put the stopping point there and it all worked out. Fun challenge!
Try it online!

APL (Dyalog Unicode), 23 bytes
⊣,(⎕UCS 10),'^',⍨' '⍴⍨⊢

Try it online!
Explanation:
⊣,(⎕UCS 10),'^',⍨' '⍴⍨⊢
⊣,(⎕UCS 10)              ⍝ original line + linefeed
            '^',⍨' '⍴⍨⊢  ⍝ generate the pointer

Explaining the generator by example:
               ('^',⍨' '⍴⍨⊢)
               {'^',⍨' '⍴⍨⍵}
               {(' '⍴⍨⍵),'^'}
               {(⍵⍴' '),'^'}
                (⍵⍴' ')          ⍝ generate ⍵ spaces
                        '^'      ⍝ append the pointer

I think you need to output the original line as well.

oh true that, let me fix it

alright, should work now

{↑⍺('^',⍨⍵⍴'')} or ↑⊣,⍥⊂'^',⍨''⍴⍨⊢ with the latter being ↑⊣⍮'^',⍨''⍴⍨⊢ in Extended.

Perl 5, 31
sub{"$_[0]
"." "x($_[1]-1)."^"}

You can save 2-3 characters.  Drop the final newline as it's not required, then change the first newline to a literal newline.  (Perl is okay with multi-line strings)

@Mr.Llama thanks, those are good.

F#, 31 characters
let p n s=s+"\n"+"^".PadLeft(n)

SpecBAS - 34
1 INPUT n,s$: PRINT s$'TAB n-1;"^"

Apostrophe in PRINT forces a new line, then just have to move the cursor to correct position.

GolfScript 11
n@~(' '*'^'

Test here.

JavaScript - 52 bytes
Here's mine, it's pretty simple.
function f(n,s){return s+"\n"+Array(n).join(" ")+"^"}

Usage:
$ console.log(f(7, "Any string at all"))

Any string at all
      ^

It points at the seventh character.

Nice save Scimonster O_O

You can write it like alert((P=prompt)()+"\n"+Array(P()+1).join(" ")+"^"). And you save 2 bytes. Also, you can make it into a stasksnippet to showcase the code running. That expects the string to come first, then the position

Perl, 45
This is a pretty horribly golfed answer, but it's my first attempt at code golf.
<>=~/(.*), "(.*)"/;print"$2
"." "x($1-1)."^";

Welcome to PPCG! If you enjoy Perl, reading Tips for golfing in Perl? is a must. Using the -p switch (counted as 1 byte), you can eliminate <>=~ and replace print with $_=. If you take a few liberties with the input format on top of that, you can shorten your code to /\d+ /;$_=$'.$"x($&-1)."^".

Ruby, 17 23 22
->s,n{s+$/+?\s*~-n+?^}

This is as short as I can go from something like this:
# Lambdas are like Procs, except with a fixed num of arguments
lambda do |sourceLine, offset|
    # The last expression is returned as the lambda's return value.
    # Multiplying a string by N will repeat it N times.
    sourceLine + "\n" + " " * (offset - 1) + "^"
end

And where are you outputting/returning the source code line to which the caret points?

The rules say: "Output is printed out to the console or returned". I am returning the output.

The accent was not on the action but on the subject: your proc neither receives nor returns the source code.

Oh, sorry! Edited the code.

You can save 1 char by replacing ?\n with $/.

C, 60 49
f(n,s){puts(s);while(n-=1)putch(' ');putch('^');}

First post, so I guess it's not that good.

Scala (49 42 bytes)
def p(i:Int,s:String)=s+"\n"+" "*(i-1)+"^"

scala> def p(i:Int,s:String)=s+"\n"+" "*(i-1)+"^"
p: (i: Int, s: String)String

scala> p(2, "Lorem ipsum, dollar sit amet.")
res0: String =
Lorem ipsum, dollar sit amet.
 ^

Perl, 20
After seeing @Digital Trauma's answer, I wanted to port his answer to Perl to show an another example of accepting the input numbers as unary as a default. This is based on the meta discussion.
$i++&y/1/ /&s/ $/^/

19 characters +1 for -p flag.
Run with:
{ echo "Lorem ipsum, dollar sit amet."; echo 111; } | perl -pe'$i++?y/1/ /&&s/ $/^/:1'

The ternary operator seems pointless here as you only have instruction for the “then” branch: $i++&y/1/ /&s/ $/^/.

@manatwork good call! updated answer

J, 19
Including parentheses!
The verb:
(],:'^',~' '#~<:@[)

Use:
9 (],:'^',~' '#~<:@[) 'Invalid Java!'
Invalid Java!
        ^

This is my first code golf, but here I go.
Haskell, 36
f s n=s++'\n':replicate(n-1)' '++"^"

The regular version being
placeCaret :: String -> Integer -> String
placeCaret s n = s ++ '\n' : replicate (n - 1) ' ' ++ "^"

So, not really much change. Clearly, the replicate is wasting the most space here, but as far as I know there are no alternatives in Prelude. I played a bit with other things which could have been cool tricks, but they all ended up being the same length.
Example usage:
Prelude> putStrLn $ f ['a'..'z'] 7
abcdefghijklmnopqrstuvwxyz
      ^

putStrLn is needed so that the newline will be displayed as a newline instead of "\n" (in GHCi only).
I know I'm VERY late to this party, but whatever.

Straw, 13 bytes
<#<>
> ,}*>^>

Try it online!
^ is the only non-alphanumeric character (with \) to not be assigned to a command, so no need for a string literal to push it.

Common Lisp, 40 35
(format t"~A
~VT^"(read)(1-(read)))

-5 bytes thanks to PrzemysławP.

(format t"~A<enter>~VT^"(read)(1-(read))) saves 5 bytes

@PrzemysławP Thanks, I edited the answer; I was pretty busy, sorry for the delay

Haskell, 30 bytes
s!n=s++'\n':([1..n]>>" ")++"^"

05AB1E, 7 bytes
'^I<ú‚»

Try it online!
Explantion
'^       # push caret
  I<ú    # prepend with input-1 spaces
     ‚   # pair with second input
      »  # join by newline

6 bytes by taking the inputs in reversed order.

C++ (with the standard library) - 159 121 bytes (-38 by Riley)
#include<iostream>
using namespace std;int main(int c,char**v){cout<<string(v[2])<<endl<<string(stoi(v[1])-1,' ')<<"^";}

Gets input from the command line args.
Example usage: ./a.out 8 "hello, world"
This is my first ever code golf, so if you have any tips, that would be great!

Unless specified, you can assume the input will be correctly formatted. That lets you skip the exit part. 2. You shouldn't need to assign p and s. I think you can just put stoi(...) and string(...) right in the cout. 3. I don't think you need the space in char** v. I hope this helps :)

@Riley Thanks! That helped.

You shouldn't need the space in stoi either.

Vim 9 bytes
jD@"a <esc>r^

Try it online!
Note that <esc> is a single byte, namely 0x1B, but since that byte is unprintable, I added a flag and used <esc> instead. This version uses the unprintable.
Explanation:
j               " Move down one line
 D              " Delete everything on this line, and save it in the unnamed register
  @"            " 'n' times
    a <esc>     " Append a 'space'
           r^   " Replace this last space with caret

Underload, 23 bytes
(S(
)S()(( )S^)!!^(^)S)

Assumes S is a string on the stack. N should be given in unary. It should be a sequence of : in between the ) and ! on the second line. For example:
(S(
)S()(( )S^)::::!!^(^)S)

The :::: represents N=4.

Hmm, is that really the tersest way to subtract 1 in Underload? I recognise the general shape, but it's disappointing if there isn't a shorter way.

@ais523 Switching to unary input for n works, because : is easily undone using !.

Perl 5 -n, 20 bytes
say<>;say$"x--$_,'^'

Try it online!
Unlike a previous answer of the same byte count, this does not require the input to be in unary.

Momema, 50 bytes
1+*-8-1s00*-9-9*0s=+1*0-9 10c01+*1-1-9 32c=*1-9 94

Try it online!
Explanation
1   +*-8-1  #  mem[1] = mem[-8] + (-1)   #  a = getnum() - 1
s   0       #  do {                      #  do {
0   *-9     #    mem[0] = mem[-9]        #    b = getchar()
-9  *0      #    mem[-9] = mem[0]        #    putchar(b)
s   =+1*0   #  } while (mem[0] + 1)      #  } while (b != -1)
-9  10      #  mem[-9] = 10              #  putchar('\n')
c   0       #  do {                      #  do {
1   +*1-1   #    mem[1] = mem[1] + (-1)  #    a = a - 1
-9  32      #    mem[-9] = 32            #    putchar(32)
c   =*1     #  } while (mem[1])          #  } while (b != 0)
-9  94      #  mem[-9] = 94              #  putchar(94)

Memory addresses -8 and -9 are memory-mapped for numeric and character IO respectively.

Keg, 9 bytes
᠀
¿; ℠*\^

Try it online!

Rust, 32 bytes
|n,s|print!("{}
{:>2$}",s,"^",n)

Try it online

Brain-Flak -A, 116 bytes
([{}]()<{({}<>)<>}(((((()()()()()){}()){}()){}()){})>){((){}<((((()()()()){}){}){})>)}{}((()()()()()){}){<>({}<>)}{}

Try it online!

J, 9 bytes
,:'^'{.~-

Try it online!
        -   negate the number
  '^'{.~    take that many characters from the string "^"
,:          append 2 items

Zsh -F, 20 bytes
printf %s\\n%*c $@ ^

Try it online!
Method stolen from the C answer.

Jelly, 7 bytes
ṄṛṬị⁾^

Try it online!
Same length, but different to, Erik's existing answer
How it works
ṄṛṬị⁾^  - Main link. Takes S on the left and N on the right
Ṅ       - Print S with a newline
 ṛ      - Discard it and yield N
  Ṭ     - Yield a list with a 1 at the Nth index and 0s otherwise
   ị⁾^  - Index into "^ "

Vyxal o, 6 5 bytes
,‹\^꘍

Try it Online!

You can omit the trailing , with the o flag.

PHP 4.1, 35 31 bytes
This one was really simple, but still fun!
<?="$S
",str_pad('^',$P,' ',0);

You can pass the values over POST, GET, SESSIONS, ...
The key S must contain the string, while the key P must contain the character number where you want the ^.

Old answer (35 bytes):
<?="$S
",str_repeat(' ',--$P),'^';

rs, 35 bytes
(\d+), "(.*?)"/\2\n( )^^(\1)^
 \^/^

Unfortunately, the online demo has a bug that I need to fix with newlines, so I can't put a demo link.
EDIT: I fixed the bug in the demo page. So...
Live demo!
This is pretty simple:

Line 1 places the text, a newline, and a series of spaces repeated one more times than we want.
Line 2 gets rid of the extra space.

Lua, 58 53 bytes
a=" "function p(n,s)print(s,"\n"..a:rep(n-1).."^")end

Thanks to manatwork this just got shorter by 5 bytes. Looks like I need to refresh my Lua skills.
First version:
function p(n,s)print(s.."\n"..string.rep(" ",n-1).."^")end

That static method call is horribly long. function p(n,s)x=" ";print(s.."\n"..x:rep(n-1).."^")end

Actually you can remove one more character. As “Trailing new lines, spaces etc are allowed in the output”, replace the first .. with ,. This way a trailing tab will appear in the first line, but is allowed.

Javascript, 50 bytes
Code
function f(n,s){return s+'\n'+s.substr(0,n-1)+'^'}
Output
console.log(f(2, "hello"));
hello
h^

This approach takes advantage of the fact that you do not specify an empty string preceding the caret, only a caret pointing to the index in the input string and anything following that. If you happen to have a caret in your input string and an error there then it might get a little bit confusing :)
For example
console.log(f(3, "he^lo"));
he^lo
he^

or
console.log(f(3, "he^"));
he^
he^

Batch, 56 Bytes
@set/p=
@for /l %%a in (2,1,%1)do @cd|set/p=.<BS>
@echo ^^

This code contains two points of interest. First, it takes input from both StdIn and command line arguments. The string is read from StdIn while the index of the caret is taken as a parameter. Second, Batch doesn't play nice when it come to outputting a single space character (U+0020) so a bit of a work around is required: cd|set/p=.<BS> In this line <BS> stands in for the backspace character (U+0008) and the last character is a space. This is accounted for in the byte count.

SAS, 22
macro a put &s/@&n'^'%

Usage:
%let s="Lorem ipsum dolor sit amet";
%let n=2;
data;a;run;

Output:
Lorem ipsum dolor sit amet
 ^

If running in 'batch' mode, the run is not required so the code in needed to produce the function and run it (just not setting the inputs) would be 30 bytes
macro a put &s/@&n'^'% data;a;

So, it may be cheating... this style macro(function) definition in SAS does not have parameters, so the inputs are defined separately, in Usage as two %let statements.  Parsing from STDIN would substantially lengthen the solution and only works when running SAS in 'batch' mode, which is not necessarily commonplace.

Turtlèd, 17 bytes
r!-[*.-l_]' d?:'^

explanation
r!-               move right, take input into string variable, decrement string pointer
   [*    ]        while current char is not *
     .-           write pointed char from string, decrement pointer
       l_         move left, write * if the pointer is on the last char of string
          ' d     write space, move down
             ?:'^ Take input into register, move forward by the amount in register, write ^

Pyth, 8 bytes
z+*dtQ\^

Takes inputs separated by a newline (i.e. 2\nLorem ipsum).
Try it online!
Explanation:
z           The second input, implicitly printed with trailing newline
  *d__      The space character, __ times
    tQ        where __ is the first input -1
 +    \^    Append a literal carat character and printed

Jelly, 8 7 bytes
Ṅ⁶ṁ”^⁹¦

Try it online!
That dollardolor makes me laugh!!
Thanks to @Dennis for -1.

Vim, 7 keystrokes (buffer input/output, excluding input keystrokes)
o<Esc> + input number + i <Esc>r^
Explanation

o<Esc> creates a new line
#i <Esc> creates # spaces
r^ replaces the last space by ^

Note: This answers does not write the output to stdout (:w !tee, + 6 keystrokes) - so maybe it will be considered invalid.

SmileBASIC, 26 bytes
INPUT N,S$?S$?" "*(N-1);"^

1-indexed arrow adds 4 bytes...

Note that you only want N-1 spaces before the caret.

C++14, 45 bytes
As unnamed lambda modifying its input, assuming s is similar to std::string (has operator+=):
[](int n,auto&s){for(s+=10;--n;s+=32);s+=94;}

Usage:
#include<string>
#include<iostream>

auto f =
[](int n,auto&s){for(s+=10;--n;s+=32);s+=94;}
;

int main() {
 std::string s = "abcdefghijk";
 f(2,s);
 std::cout << s << std::endl;
}

Gol><> (Golfish), 14 bytes
`^IMR` aTiEHot

Try it here.
Explanation
`^             # push caret
  I            # read input as number
   M           # subtract 1
    R`         # pop N, and Repeatedly push a space, N times
       a       # push 10 (ASCII newline)
        T      # set teleport pad
         i     # input character
          EH   # if EOF, output stack and halt
            o  # otherwise, output the character just read
             t # teleport back to pad

Why is this non-competing?

I think it used features which were added to the language after this question was asked.

In that case the annotation is no longer necessary and I've removed it. The reason I asked is that "non-competing" has been historically misused to mean "this answer doesn't actually meet the challenge requirements and should be deleted".

tcl, 47
gets stdin s
puts $s\n[format %[gets stdin]s ^]

demo

V, 6 bytes
ïÀá r^

Try it online!

Braingolf, 25 bytes
VV"^ "R3-M#
&@v[v.Rv]v<&@

Try it online!

Ruby 2.7, 24 bytes
x=->{_1+'
'+" "*~-_2+?^}

PowerShell Core, 29 27 bytes
$args[1]
'^'|% *ft $args[0]

Try it online!
-2 bytes thanks to Mazzy!

? Try it online!

Japt -R, 5 bytes
-1 byte if we can take the string input as a singleton array.
·p^ùV

Try it

05AB1E, 6 bytes
,'^ú¦,

Try it online!
,       # output with trailing newline...
        # implicit input
     ,  # output with trailing newline...
 '^     # "^"...
   ú    # with...
        # implicit input...
    ¦   # minus 1...
   ú    # spaces in front

Haskell, 38 bytes
n!s=s++'\n':g n
g 1="^"
g n=' ':g(n-1)

Try it online!

Red, 35 bytes
func[n s][prin[s lf pad/left"^^"n]]

Try it online!

Stax, 5 bytes
P'^)p

Run and debug it

APL (Dyalog Classic), 14 bytes
{↑⍺((-⍵)↑'^')}

Try it online!
A port of @FrownyFrog J answer

Thunno 2 N, 6 bytes
⁻ṣ'^+,

Attempt This Online!
Explanation
⁻ṣ'^+,  # Implicit input
⁻ṣ      # First input decremented spaces
  '^+   # With a "^" appended
     ,  # Paired with the second input
        # Implicit output joined by newlines

Java (JDK), 32 bytes
Speaking of which, the Java answer of this problem needed a little upgrade :)
a->b->b+"\n"+" ".repeat(a-1)+"^"

Try it online!

Go, 79 bytes
import."strings"
func f(s string,n int)string{return s+`
`+Repeat(" ",n-1)+"^"}

Attempt This Online!


text:
Find the Shortest Swype Path
Introduction
Lately, I've been getting used to typing with Swype.
I've noticed certain words can be produced by drawing a straight line from your starting letter to your ending letter, or by skipping letters that repeat.
For example, I can type the word balloon by Swyping across the following letters:
b > a > l > o > n.
Challenge
Let us define the Shortest Swype Path, or SSP, as the minimum number of distinguishable line segments needed to type a string.  A line segment is a continuous straight line between any two, or more, letters.  Any change in direction starts a new line segment - though some words may be Swyped by drawing only a single straight line.
Use this simple QWERTY keyboard layout:
q w e r t y u i o p
a s d f g h j k l
  z x c v b n m

In the above example, the word balloon will have an SSP of 4 as detailed in the sequence below:
1) Start at `b` (line segments = 0)
2) slide to `a` (line segments = 1)
3) slide to `l` (line segments = 2)
4) slide to `o` (line segments = 3)
5) slide to `n` (line segments = 4)

The string qwerty has SSP = 1 since no change of direction is required when Swyping this word.
Input
A single word string containing any a-z via STDIN, function argument, or command line.
Output
Print via STDOUT, return, or your languages closest alternative, the number n representing the string's SSP.
One trailing newline optional in outut.  Standard loopholes disallowed.  Shortest submission in bytes wins.
Notes

A change in direction starts a new line segment.
Letters that repeat are only counted once (e.g.: bookkeeper should be treated as bokeper).
Normally, Swpye corrects missed letters by looking at neighboring letters and filling in its best guess.  For this challenge, assume there is no natural language augmentations, predictive text or error correction.
Uppercase A-Z inputs are treated like their lowercase counterparts.
Ignore any numbers 0-9 in the input.
Diagonal paths are allowed - that is, a straight line that covers letters o, k, n, for example, count as 1 segment.  This rule applies to any diagonal slope (e.g.: letters c, h, i are in line).

Examples
Input          Output
---------------------
a                0
aa               0
aaaaaa           0
aaaaaabc         2
in               1
int              2
java             3
qwerty           1
chicago          5
balloon          4
BALLOON          4
typewriter       5
bookkeeper       6
stackexchange    11
2hello7          3
2HELLO7          3

h is on the line from c to i, but there are no letters between c and o?

If the submissions have to support uppercase letters as well, I suggest including some in the test cases.

@Sparr Correct.

@Dennis Good call - added test cases.

I do enjoy typing with Swype, but I don't know about programming for the lines...

CJam, 78 76 73 68 62 bytes
relA,s-:_2ew{:-},{{i"x8LÑejPG ÀÏi"225b28b=A+Ab}/.-:ma}%e`,

Note that the code contains unprintable characters.
Borrowing @isaacg's clever idea of using RLE to count the paths saved 6 bytes.
Try it online in the CJam interpreter. If the link doesn't work, copy the code from this paste.
How it works
rel      e# Read a token from STDIN and cast it to lowercase.
A,s-     e# Remove all digits.
:_       e# Duplicate each element of the argument (string/array).
2ew      e# Push all overlapping slices of length 2.
{:-},    e# Filter out slices where both elements are equal.
{        e# For each slice:
  {      e#   For each character of the slice:
    i    e#     Push its code point.

    "x8LÑejPG ÀÏi"225b28b

         e#     Convert the string from base 225 to base 28, pushing the array
         e#     [15 7 16 17 18 27 26 8 9 0 3 11 4 6 24 1 22 5 21 10 25 23 12 2 13 14].
         e#     These are the positions on the QWERTY keyboard, starting from the
         e#     upper left corner and going right.

    =    e#     Select the element that corresponds to the code point.

         e#     Arrays wrap around in CJam. Since 'a' has code point 97, the array has
         e#     length 26 and 97 % 26 == 19, 'a' corresponds to the 20th element.

    A+Ab e#     Add 10 and convert to base 10. Example: 8 -> [1 8]
  }/     e#
  .-     e#     Vectorized subtraction. [a b] [c d] -> [a-c b-d]
  :ma    e#     atan2. Pushes the angle of the direction. [y x] -> arctan(y/x)
}%       e#
e`       e# Apply run-length encoding.
,        e# Count the runs.

Very clever.  Thank you for the explanation.

Pyth, 53 50 49 bytes
lrPMfT-VJm.jF.D@jC"XÖ;¿ìÇ×;¤ð$  _"28CdT@GrzZtJ8

Keyboard compression format thanks to @Dennis.
This answer contains some unprintable characters. See the links below for the correct code.
Demonstration. Test Harness.
Explanation:
lrPMfT-VJm.jF.D@jC"..."28CdT@GrzZtJ8
                              rzZ      Convert input to lowercase.
                            @G         Take the intersection with G.
                                       This removes the numbers.
         m                             Map over the characters
                 C"..."                Treat the string as a base 256 number.
                j      28              Convert this number to base 28, giving:
                                       [15, 7, 16, 17, 18, 27, 26,  ... ]
                                       which is the character positions
                                       from top left, rotated by 97 places.
               @         Cd            Index this list by ord(character)
             .D            T           divmod by 10, giving the x-y position.
          .jF                          Convert this to a complex number.
        J                              Save the result to J.
      -VJ                        tJ    Vectorize - over J and J[1:]. This gives
                                       pairwise diffeences between J's elements.
    fT                                 Filter the differences on being truthy.
                                       This removes letter pairs with no movement.
  PM                                   Map the remaining complex numbers to their
                                       phases, which indicates their directions.
 r                                 8   Run-length encode the result.
l                                      Print out the number of separate RLE groups.

Over 20% shorter! Looking forward to see your explanation.

source: Stack Exchange

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

sort: votes


text:
Code Bots 3: Parallel Programming Antipatterns
Welcome back! I'm excited to present the 3rd CodeBots challenge.  This one has been a long time in the making.  This challenge will be split up in 3 sections: the short version, the long version, and additional details.
The Short Version
Each competitor will write a 24-command program.  These bots will move around the world and copy their code into other bots, while trying to prevent other bots to do the same.  One of the possible commands is the no-op Flag.  If a bot has more of your Flag than any other bot's Flag, you get a point.  You win by having the most points.
All of the above was true for the past two challenges.  This time around, bots will be able to run multiple lines of code at the same time.
The Long Version
The API
Every bot will have exactly 24 lines, where each line is in the following format:
$label command parameters //comments

Labels and comments are optional, and each command has a different number of parameters.  Everything is case-insensitive.
Parameters
Parameters are typed, and can be in the following formats:

A value from 0 to 23.
A variable: A, B, C, D
A value using addition: A+3 or 2+C
A line of code, which is designated using the # sign (#4 would represent the 5th line, while #C+2 would represent the line calculated by C+2).
You can use a $label instead of designating a line of code.
Your opponent's variable or line of code, designated by *.  Your opponent is the bot in the square that you are facing.  (*B represents your opponent's B value, while *#9 represents your opponent's 10th line).  If there is nobody in that square, the command is not executed.

Commands
Move V
Moves the bot North+(V*90 degrees clockwise).  Movement does not change direction.
Turn V
Turns the bot V*90 degrees clockwise.
Copy V W
Copies whatever is in V into W.  If V is a line number, then W has to be a line number.  If V is a variable or value, then W must be a variable.
Flag
Does nothing.
Start V
Starts a new thread attached to the variable V.  Immediately, and on each future turn, the thread will execute the command on line V.
If V is already attached to a thread, then this command is a no-op.  If V is an opponent's variable, then the opponent will start a thread attached to that variable.
Stop V
Stops the thread attached to the variable V at the end of this turn.
Lock V
Prevent the line or variable V from being used in any way except by the thread that called Lock.  A subsequent call to Lock by the same thread unlocks V.  Locks cannot be called on opponent's variables or lines.
If Cond V W
This will test Cond.  If the condition is true, then it will move the thread pointer to the line number V, otherwise to the line number W.  That line will then be immediately executed.
Conditionals can be X=Y, X<Y, !X, or ?X:

X=Y tests whether two lines are of the same type and from the same bot, or you test whether two values equal the same amount.
X<Y tests whether the value of X is less than Y.
!X tests whether the variable or line X is locked (returns true if locked)
?X tests whether a given variable has a thread attached to it

Additional Details
Multi-threaded interactions
Actions of the same type are executed at the same time.  Actions are executed in the following order:

Lock.  If several threads attempt to lock a variable, they will all fail.  If a thread is unlocking a variable while another is attempting to lock it, the variable will remain unlocked.

Start.  If several threads attempt to start a thread on a variable, it will count as a single start.

Copy.  If two threads both copy to the same variable, the variable will end up as a random value.  If they both copy to the same line, neither will work.  If a thread copies to the same variable another thread is copying from, then the latter thread will copy a random value.  If two threads are both copying from the same variable, they will both work fine.

If.  All conditionals will be tested simultaneously, and then the thread variables will be updated after.  Executing an If can cause an action with a higher priority to be added.  Actions with higher priority will be executed before moving on past the If, while actions with a lower priority will execute after the If.

Move.  Multiple moves on the same bot will move the bot the sum of all of the moves.  If multiple bots would end up in the same spot, they will be returned to their starting spot.

Turn.  Multiple turns on the same bot will sum.

Stop.  Multiple stop commands on the same variable will count as a single stop.

Other details
Your initial thread starts attached to the D variable
Recursing with an If (having an If statement pointed to itself) will cause your bot to do nothing
If a thread is stopped after locking, those locks will be unlocked
Actions to use a locked variable or line will do nothing.
If a bot is shorter than 24 lines, remaining lines will be filled with Flag
Performing a write on a variable that is also attached to a starting thread will actually have the thread start its execution on the new value as the thread starts the following turn.
Bots are placed in a toroidal world in the following pattern:
B...B...B...
..B...B...B.
B...B...B...

I have added several sample bots that are commented as a language reference.
The controller is located here.  I've worked a long time on it, but it probably still has bugs.  When the spec and the controller contradict, the spec is correct.
Scoreboard
1. 771  LockedScannerBot
2. 297  CopyAndSelfFlag
3. 289  DoubleTapBot
4. 197  ThreadCutterBot
5. 191  TripleThread
6. 180  ThickShelled
7. 155  Attacker
8. 99   RandomMover
9. 90   BananaBot
10. 56  LockedStationaryDoubleTap

Wow, at least, DoubleTap seems much better than samples !

What should happen if I try to read a locked variable from another thread? Say I do LOCK A then in another thread there's a MOVE A. Does A evaluate to 0 or a random value or does the move fail or...?

Ditto on what happens when a thread reaches a line locked by another thread. Is it a noop? Does it get skipped?

Should "Copy $label A" work? It interprets as "Copy #11 A" which isn't valid and crashes the interpreter, instead of "Copy 11 A" as I'd hope for.

possible bug... I seem to be able to read my own flag lines to copy from them, even when they are locked by another thread.

Both reading the variable (as in Move A), and executing the line is a no-op.

@sparr concerning your $label, I'll have to see what I can do, but right now, I'm doing a super dumb find/replace.

What happens if you use * and no bot is in front of you? for example If ?*A, Copy 1 *A

@MegaTom it is a no-op.

Locked Scanner Bot
Scans the enemy as fast as possible and replaces the lines with flags.
    Lock D
    Copy $a A
    Start A
    Copy $b B
    Start B

$d  Lock $d0
    Lock $d1
$d0 Copy $flag *#C+1
$d1 If 1=1 $d0 $d0

$a  Lock A
    Lock $a0
    Lock $a1
    Lock $a2
$a0 Copy $flag *#C
$a1 Copy C+2 C
$a2 If !*#C $a1 $a0

$b  Lock B
    Lock $b0
    Lock $b1
    Lock $b2
$b0 Move C
$b1 Turn 1
$b2 If 1=1 $b0 $b0

$flag Flag

I'm curious about the conditional in your A thread. !*#C checks if your target's line #C (your C) is locked, right? How is that helpful?

@Sparr The A thread doesn't waste time replacing a line of the enemies code with a flag if it's locked.

Thanks. I misread the spec originally regarding the speed of If statements.

DoubleTapBot
This bot has 3 threads :
One for moving (A),
The two others for flagging (B and D).
B flag 1/2 turn, D flag 1/3 turn. So some turn, he will double flag the opponent :).
I assume that C will return to 0 if it exceed 23.
It shoudl be pretty safe if it have some turn to prepare itself (8 turn), as he will always keep at least 2 threads (A & B) running normally.
I can't try it at the moment, so I'll do the test when I'll be back Home :)
Lock D          //Thread D locks itself
Copy 6 A        //Thread A will start line 6
Start A
Copy 13 B       //Thread B will start line 13
Start B
Copy 20 D       //Moving Thread D to an other part of the program
Lock A          //Thread A locks itself and the line it will be using
Lock #10
Lock #11
Lock #12
Move C          //Move in a pseudo random direction
Turn 1      //always turn to the right
If 1=1 #10 #10  //return to Move C
Lock B          //Thread B locks itself and the line it will be using
Lock #13
Lock #14
Copy #18 *#C    //Copy a flag to the Cth line of the opponent
If 1=1 #16 #16  //jump back to the copy
Flag
Flag
Copy C+1 C      //Increment C
Copy #19 *#C+1  //Copy a flag to the Cth+1 line of the opponent
If 1=1 #20 #20  //jump back to the increment
Flag

Lock number is not a valid command.  I put # signs before each of the numbers.  Also, the command is "Rotate", not "Turn"

@NathanMerrill How, that's a typo, forget the #, thanks for pointing it out. And for turn, modify your post so, you wrote Turn V
Turns the bot V*90 degrees clockwise. :)

Oh, I did. Turn is actually correct, then, I'll go back and update the code

You're locking 11,12,13 when you mean to be locking 10,11,12?

Wow, thanks for pointing that out !

Locked Stationary Double Tap
Inspired by @Katenkyo's DoubleTapBot, this one gives up a couple of flags and any hope of movement in return for completely locking down its own threads so it can't ever be reprogrammed. It is, however, still succeptible to having enemy flags written to non-looping code areas.
Lock $flag              // lock the only flag line, super important!
Lock D                  // lock thread D
Copy 10 A
Start A                 // start thread A at $Astart
Copy 17 B
Start B                 // start thread B at $Bstart
Lock $D1                // lock thread D lines
Lock $D2                // thread D should be safe on turn 8
$D1 Turn C              // Spin in place, once every 2 turns
$D2 If 0=0 $D1 $D1      // thread D loop
$Astart Lock A          // thread A starts here, locks itself
Lock $A1                // lock thread A lines
Lock $A2
Lock $A3                // thread A should be safe on turn 7
$A1 Copy $flag *#C      // ATTACK! once every 3 turns
$A2 Copy C+1 C          // increment C, used for attacks and turning
$A3 If 0=0 $A1 $A1      // thread A loop
$Bstart Lock B          // thread B starts here, locks itself
Lock $B1                // lock thread B lines
Lock $B2                // thread B should be safe on turn 8
$B1 Copy $flag *#C+12   // ATTACK! once every 2 turns
$B2 If 0=0 $B1 $B1      // thread B loop
$flag Flag

Haha, Locking the flag is a pretty good Idea, I should have thought of it !  Anyway, I'm glad that my bot gave some inspiration to someone !

@Katenkyo it's a good idea if it works, but I don't think it should work. The rules-as-written suggest that if D locks the flag line then A/B won't be able to copy from it. However, that doesn't seem to be the case. Bug report in the comments to the question.

Attacker Bot
Copies flags into various locations
Copy A+1 A // Increment A
Move A //Move in the Ath direction
Turn A //Rotate A times
Copy #8 *#A //Copy my flag over
Copy 23 D //Loop back to the beginning.  (I use 23 here as threads auto-increment)

Random Mover
Moves in a psuedorandom direction
Copy 5 C
Copy 8 B
Start C
Move A // If you can't catch me, you can't modify me
If 1=1 #3 #3 //Continue to execute the above line
Start B
Copy 4 A
If 1=1 #6 #6 //Continue to execute the above line
Flag
Copy 5 A
If 1=1 #9 #9 //Continue to execute the above line

Thick Shelled
Locks his stuff as much as he can
Copy 5 B //Designating that the B thread will start on line 5
Start B //Starting the B thread
Lock C //Preventing C from being used
Copy A+1 A //The two threads are offset, meaning that the two threads shouldn't access this at the same time
Lock #A
Copy 2 B

Thread Cutter Bot
   Lock D
   Lock $f
   Copy 16 C
$S If ?*D $1 $2
   Move 1
   Copy $S D
$f Flag
$1 Stop *D
$2 If ?*A $3 $4
$3 Stop *A
$4 If ?*B $5 $6
$5 Stop *B
$6 Copy $f *#C
   Copy C+1 C
   If *#C=#C $E $6
   Copy 2 D
$E Start *D

Stop all enemy threads before filling with your code.

Triple Thread
This simple bot runs three threads all with the same code. Each thread attacks 1/3 turns, moves 1/6, turns 1/6, and does bookkeeping 1/3.
Move 0
Start A
Start B
$loop Copy #A+9 *#C
Move C
Copy #A+9 *#C
Turn C
Copy C+1 C
If 0=0 $loop $loop

Banana Bot
Attempts to throw bananas in the enemies wheel before the enemy can do anything. Prone to being squished.
$d     If !*D $d1 $d0
$d0    Copy 24 *D
$d1    If !D $d2 $start
$d2    If !*B $d5 $d3
$d3    Copy 24 *B
$d4    Copy $d D

$start Lock D             //Banana's like to split.
       Copy $a A
       Start A
       Copy $b B
       Start B
       Lock $flag

$d5    Copy $start *C     //It's okay if enemy messes up our start.
       Copy $d d

$a     Lock A
$a1    Move C
       Turn 1
       Copy $a1 A

$b     Lock B
$b0    Copy C+1 C
       If !*#C $b0 $b1    //Banana's are good at slipping.
$b1    Copy $flag *#C
$b2    Copy $b0 B

$flag  Flag

Copy and Self Flag
This bot runs three threads. The D thread moves until it runs into an enemy, then tries to copy a flag into them, then moves a random direction. The A thread copies its own flag over non-essential lines of the bot's code. The B thread is just a counter.
The variable, flag, and lines of code used by each thread are fully locked in the first 15 turns, and the bot overwrites almost all of its startup code with its own flags. I don't think it's possible to convert this bot to another team's banner after turn 15 without a dedicated attack bot doing nothing but writing flags to it.
    Lock D              // Lock D thread
    Copy $AS A
    Start A             // Start A thread at $AS
    Start B             // B is just a counter
    Copy $DL D          // Jump to D thread startup code
$DC Start B             // Don't let B thread get stopped
$D0 If !*#B $D1 $D2
$D1 Copy $DF *#B
$D2 If !*#B+6 $D3 $DM
$D3 Copy $DF *#B
$DM Move B              // Move some direction after attacking
$DA Move 0              // Move north ...
    If ?*D $DC $DA      // until we hit a live target
$DF Flag                // Flag to copy
$DL Lock #B+3           // Lock the D thread's lines
    If B<12 $DL $DA     // jump to `Move 0` when D thread is safe
$AS Lock A
$AL Lock #B+20
    If B<4 $AL $AD
    Copy 23 B           // reset B so A doesn't overwrite its own code
$AF Flag
    Flag
$AD Copy $AF #B+1       // Copy a safe flag over every unused line of code
    If B<18 $AD $AF

Move 0 is move north, not forward.

@MegaTom aha, thanks. I missed that.

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


text:
Probabilities - how high can you go?
I previously asked a question for how to compute a probability quickly and accurately.  However, evidently it was too easy as a closed form solution was given!  Here is a more difficult version.
This task is about writing code to compute a probability exactly and quickly. The output should be a precise probability written as a fraction in its most reduced form. That is it should never output 4/8 but rather 1/2.
For some positive integer n, consider a uniformly random string of 1s and -1s of length n and call it A. Now concatenate to A a copy of itself. That is A[1] = A[n+1] if indexing from 1, A[2] = A[n+2] and so on.  A now has length 2n. Now also consider a second random string of length n whose first n values are -1, 0, or 1 with probability 1/4,1/2, 1/4 each and call it B.
Now consider the inner product of B with A[1+j,...,n+j] for different j =0,1,2,....
For example, consider n=3. Possible values for A and B could be A = [-1,1,1,-1,...] and B=[0,1,-1]. In this case the first two inner products are 0 and 2.
Task
For each j, starting with j=1, your code should output the probability that all the first j+1 inner products are zero for every n=j,...,50.
Copying the table produced by Martin Büttner for j=1 we have the following sample results.
n   P(n)
1   1/2
2   3/8
3   7/32
4   89/512
5   269/2048
6   903/8192
7   3035/32768
8   169801/2097152

Score
Your score is the largest j your code completes  in 1 minute on my computer.  To clarify a little, each j gets one minute. Note that the dynamic programming code in the previous linked question will do this easily for j=1.
Tie breaker
If two entries get the same j score then the winning entry will be the one that gets to the highest n in one minute on my machine for that j. If the two best entries are equal on this criterion too then the winner will be the answer submitted first.
Languages and libraries
You can use any freely available language and libraries you like. I must be able to run your code so please include a full explanation for how to run/compile your code in linux if at all possible.
My Machine The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor.  This also means I need to be able to run your code.
Winning entries

j=2 in Python by Mitch Schwartz.
j=2 in Python by feersum. Currently the fastest entry.

If the question is unclear in any way, please let me know so I can fix it quickly.

You are by far my favorite question asker. Then again, I do have a thing for computing values exactly and quickly.

@primo Thank you! Does this mean we can expect an answer in RPython? :)

Could you put the difference between this question and the other one?

@kirbyfan64sos The other one is essentially the same question for  j=1 only.

Ok, so, the program calculates the first 50 probabilities above j? Kind of like for n in range(j, 50+j):?

@kirbyfan64sos Actually just up to 50. So from j to 50. They don't make much sense below j.

I can't wait until someone asks casually a question whose solution would mean solution to to P=NP, and someone else casually solves it (in less than 100 bytes.)

I still don't think I understand the question. So it's j=1, n=1...50, j=2, n=2...50, etc?

@qwr Yes exactly.  I am often in chat too if that could help.

Python 2, j=2
I tried to find a sort of 'closed form' for j=2. Perhaps I could make a MathJax image of it, although it would be really ugly with all the index fiddling. I wrote this unoptimized code only to test the formula. It takes about 1 second to complete. The results match with Mitch Schwartz's code.
ch = lambda n, k: n>=k>=0 and fac[n]/fac[k]/fac[n-k]
W = lambda l, d: ch(2*l, l+d)
P = lambda n, p: n==0 or ch(n-1, p-1)
ir = lambda a,b: xrange(a,b+1)

N = 50
fac = [1]
for i in ir(1,4*N): fac += [i * fac[-1]]

for n in ir(2, N):
    s = 0
    for i in ir(0,n+1):
     for j in ir(0,min(i,n+1-i)):
      for k in ir(0,n+i%2-i-j):
       t=(2-(k==0))*W(n+i%2-i-j,k)*W(i-(j+i%2),k)*W(j,k)**2*P(i,j+i%2)*P(n+1-i,j+1-i%2)
       s+=t
    denp = 3 * n - 1
    while denp and not s&1: denp -= 1; s>>=1
    print n, '%d/%d'%(s,1<<denp)

Consider a sequence where the ith member is e if A[i] == A[i+1] or n if A[i] != A[i+1]. i in the program is the number of ns. If i is even, the sequence must begin in and end with e. If i is odd, the sequence must begin and end with n. Sequences are further classified by the number of runs of consecutive es or ns. There are j + 1 of one and j of the other.
When the random walk idea is extended to 3 dimensions, there is an unfortunate problem that there are 4 possible directions to walk in (one for each of ee,en,ne, or nn) which means they are not linearly dependent. So the k index sums over the number of steps taken in one of the directions (1, 1, 1). Then there will be an exact number of steps which must taken in the other 3 directions to cancel it.
P(n,p) gives the number of ordered partitions of n objects into p parts.
W(l,d) gives the number of ways for a random walk of l steps to travel a distance of exactly d. As before there is 1 chance to move left, 1 chance to move right and 2 to stay put.

Thank you!  An image of the formula would be really great.

Thank you for the explanation. You make it look simple!  I just saw your comment that you could make a solution for j=3. That would be amazing!

Python, j=2
The dynamic programming approach for j = 1 in my answer to the previous question does not need many modifications to work for higher j, but gets slow quickly. Table for reference:
n   p(n)

2   3/8
3   11/64
4   71/512
5   323/4096
6   501/8192
7   2927/65536
8   76519/2097152
9   490655/16777216
10  207313/8388608

And the code:
from time import*
from fractions import*
from collections import*

def main():
    N_MAX=50

    T=time()

    n=2
    Y=defaultdict(lambda:0)
    numer=0

    for a1 in [1]:
        for b1 in (1,0):
            for a2 in (1,-1):
                for b2 in (1,0,0,-1):
                    if not a1*b1+a2*b2 and not a2*b1+a1*b2:
                        numer+=1
                    Y[(a1,a2,b1,b2,a1*b1+a2*b2,a2*b1,0)]+=1

    thresh=N_MAX-1

    while time() <= T+60:
        print('%d %s'%(n,Fraction(numer,8**n/4)))

        if thresh<2:
            print('reached N_MAX with %.2f seconds remaining'%(T+60-time()))
            return

        n+=1
        X=Y
        Y=defaultdict(lambda:0)
        numer=0

        for a1,a2,b1,b2,s,t,u in X:
            if not ( abs(s)<thresh and abs(t)<thresh+1 and abs(u)<thresh+2 ):
                continue

            c=X[(a1,a2,b1,b2,s,t,u)]

            # 1,1

            if not s+1 and not t+b2+a1 and not u+b1+a1*b2+a2: numer+=c
            Y[(a1,a2,b2,1,s+1,t+b2,u+b1)]+=c

            # -1,1

            if not s-1 and not t-b2+a1 and not u-b1+a1*b2+a2: numer+=c
            Y[(a1,a2,b2,1,s-1,t-b2,u-b1)]+=c

            # 1,-1

            if not s-1 and not t+b2-a1 and not u+b1+a1*b2-a2: numer+=c
            Y[(a1,a2,b2,-1,s-1,t+b2,u+b1)]+=c

            # -1,-1

            if not s+1 and not t-b2-a1 and not u-b1+a1*b2-a2: numer+=c
            Y[(a1,a2,b2,-1,s+1,t-b2,u-b1)]+=c

            # 1,0

            c+=c

            if not s and not t+b2 and not u+b1+a1*b2: numer+=c
            Y[(a1,a2,b2,0,s,t+b2,u+b1)]+=c

            # -1,0

            if not s and not t-b2 and not u-b1+a1*b2: numer+=c
            Y[(a1,a2,b2,0,s,t-b2,u-b1)]+=c

        thresh-=1

main()

Here we are keeping track of the first two elements of A, the last two elements of B (where b2 is the last element), and the inner products of (A[:n], B), (A[1:n], B[:-1]), and (A[2:n], B[:-2]).

....reached N_MAX with 21.20 seconds remaining


text:
Schrödinger's Laser
Fed up with experimenting on tiny domestic animals, Nobel prize-winning Erwin Schrödinger has decided to find the nearest laser and shoot it at things instead. Because... science!
Description
You will be given two points that the laser passes through and the size of a laser beam, and you must determine where the laser beam must have gone, could have gone, and could not have gone.
The laser beam can be horizontal, vertical, or diagonal. For a size 1 laser beam, they look like this respectively:
       #  #
       #   #
#####  #    #
       #     #
       #      #

The diagonal laser beam can also be flipped. Size 2 laser beams look like this:
       ###  ##
#####  ###  ###
#####  ###   ###
#####  ###    ###
       ###     ##

In general, to get a laser beam of size (n), simply take the laser beam of size (n-1) and add a laser beam of size (1) on both sides. As a final example, here are all possible laser beams of size 3, shown on the same "board":
###.....#####.....##
####....#####....###
#####...#####...####
.#####..#####..#####
..#####.#####.#####.
...###############..
....#############...
.....###########....
####################
####################
####################
####################
####################
.....###########....
....#############...
...###############..
..#####.#####.#####.
.#####..#####..#####
#####...#####...####
####....#####....###

This "board" will always have dimensions of 20x20 (in characters).
Input
Your program will be given five integers as input. They are, in order, x1, y1, x2, y2, and the size of the laser beam. They must be taken exactly in that order. If you wish, you may take the ordered (x, y) pairs as an array, tuple, list, or other built-in data type that stores two values.
Both of the two points given as input will be within the board, and they are guaranteed to be distinct (i.e. the two points will never be the same). The size of the laser beam is bound to 1 ≤ size < 20. There will always be at least one possible laser beam that passes through both of the points.
Output
Your program must output a 20x20 grid of the following characters:

# if every possible laser beam that passes through the two points also passes through this point.
. if there is no laser beam that passes through the two points and this point.
? if some, but not all, of the possible laser beams pass through this point.
X if this is one of the two original input points (this overrides the #).

Test cases
7, 7, 11, 3, 1
..............#.....
.............#......
............#.......
...........X........
..........#.........
.........#..........
........#...........
.......X............
......#.............
.....#..............
....#...............
...#................
..#.................
.#..................
#...................
....................
....................
....................
....................
....................

18, 18, 1, 1, 2
#??.................
?X??................
??#??...............
.??#??..............
..??#??.............
...??#??............
....??#??...........
.....??#??..........
......??#??.........
.......??#??........
........??#??.......
.........??#??......
..........??#??.....
...........??#??....
............??#??...
.............??#??..
..............??#??.
...............??#??
................??X?
.................??#

10, 10, 11, 10, 3
?????..????????..???
??????.????????.????
????????????????????
????????????????????
.???????????????????
..??????????????????
????????????????????
????????????????????
????????????????????
????????????????????
??????????XX????????
????????????????????
????????????????????
????????????????????
????????????????????
..??????????????????
.???????????????????
????????????????????
????????????????????
??????.????????.????

3, 3, 8, 10, 4
??????????..........
??????????..........
??????????..........
???X??????..........
???##?????..........
???###????..........
????###????.........
.????###????........
..????###????.......
..?????##?????......
..??????X??????.....
..??????????????....
..???????????????...
..????????????????..
..?????????????????.
..??????????????????
..??????????????????
..????????.?????????
..????????..????????
..????????...???????

The test cases were generated with the following Ruby script, located inside a Stack Snippet to conserve vertical space.

/*

#!/usr/bin/ruby

$w = $h = 20

class Point
    attr_reader :x, :y
    def initialize x, y
        @x = x
        @y = y
    end
    def inspect
        "(#{@x}, #{@y})"
    end
    def == p
        @x == p.x && @y == p.y
    end
    alias eql? ==
    def hash
        @x * $h + @y
    end
    def valid?
        @x >= 0 && @y >= 0 && @x < $w && @y < $h
    end
end

module Angle
    HORIZONTAL = Point.new(1, 0)
    VERTICAL = Point.new(0, 1)
    DIAG1 = Point.new(1, 1)
    DIAG2 = Point.new(1, -1)
end

def line_points point, angle, size
    points = [point]

    while points[-1].valid?
        points.push Point.new(points[-1].x + angle.x, points[-1].y + angle.y)
    end
    points.pop
    while points[0].valid?
        points.unshift Point.new(points[0].x - angle.x, points[0].y - angle.y)
    end
    points.shift

    if size == 1
        points
    elsif size > 1
        a2 = case angle
            when Angle::HORIZONTAL then Angle::VERTICAL
            when Angle::VERTICAL then Angle::HORIZONTAL
            else Angle::VERTICAL  # HORIZONTAL also works
        end
        (size-1).times do |n|
            np1 = Point.new(point.x + a2.x*(n+1), point.y + a2.y*(n+1))
            np2 = Point.new(point.x - a2.x*(n+1), point.y - a2.y*(n+1))
            points.concat line_points np1, angle, 1 if np1.valid?
            points.concat line_points np2, angle, 1 if np2.valid?
        end
        points
    else
        throw 'something is very wrong'
    end
end

def generate_grid x1, y1, x2, y2, size
    p1 = Point.new(x1, y1)
    p2 = Point.new(x2, y2)
    lasers = []
    points = [Point.new((p1.x + p2.x) / 2, (p1.y + p2.y) / 2)]  # midpoint
    while points.length > 0
        point = points.pop
        new_lasers = Angle.constants
            .map{|angle| line_points point, Angle.const_get(angle), size }
            .select {|laser| laser.include?(p1) && laser.include?(p2) } -
            lasers
        if new_lasers.length > 0
            lasers.concat new_lasers
            points.push Point.new(point.x+1, point.y) if point.x+1 < $w
            points.push Point.new(point.x, point.y+1) if point.y+1 < $h
            points.push Point.new(point.x-1, point.y) if point.x-1 > 0
            points.push Point.new(point.x, point.y-1) if point.y-1 > 0
        end
    end
    grid = Array.new($h) { ?. * $w }
    lasers.each do |laser|
        laser.each do |point|
            grid[point.y][point.x] = ??
        end
    end
    lasers.reduce(:&).each do |point|
        grid[point.y][point.x] = ?#
    end
    grid[p1.y][p1.x] = 'X'
    grid[p2.y][p2.x] = 'X'
    grid
end

testcases = [
    [7, 7, 11, 3, 1],
    [18, 18, 1, 1, 2],
    [10, 10, 11, 10, 3],
    [3, 3, 8, 10, 4]
]

testcases.each do |test|
    puts test * ', '
    puts
    puts generate_grid(*test).map{|line| '    ' + line }
    puts
end

*/

Rules

Your program must be able to solve each of the test cases in under 30 seconds (on a reasonable machine). This is more of a sanity check, as my test Ruby program solved all of the test cases near-instantaneously.
This is code-golf, so the shortest solution wins.

to solve each of the test cases in under 30 seconds (on a reasonable machine) /////// This bugs me since a while: why cant we calculate CPU rounds? Because I dont want to optimize a software for my computer but for as many computers as possible. So when I know that a specific action takes for example 100M CPU rounds than i can calculate this to any fast/slow computer as i want and can adjust the program behaviour if needed. (Yes analysis tools would require cpu capacity too but it's not supposed to be 100% precise)

The terminology used here tripped me up initially. I believe laser normally refers to a device that produces laser beams. What you're representing here are really the beams, right? This is not supposed to be a representation of the actual laser, which would be the device generating the beams?

The last test case looks wrong. A size 4 laser should be 9 pixels wide. The vertical track should be at least that wide, but in fact is narrower.

@steveverrill Size 4 is 7 pixels wide. The width in pixels is 2 * size - 1. Size 1 is 1 pixel, size 2 is 3 pixels, size 3 is 5 pixels (see example above), size 4 is 7 pixels.

I don't see how Schrodinger is related to this challenge.

@JonasDralle Again, the time limit is mostly just a sanity check, and almost every submission is expected to complete in far less time than that.

@RetoKoradi Yes, that's right (sorry for the late response). I'll edit my question to clarify.

@steveverrill A size 4 laser is 7 pixels wide, as described in Reto Koradi's comment. (A size 1 laser is 1 pixel wide, not 3.)

@ace The laser is both in and not in the places represented by ?s, and you can't tell until you shoot it. :P

C, 291 280 277 265 bytes
x,y,A,C,B,D,a,c,b,d,w,s,t;T(i){return abs(i)<2*w-1;}U(j,k){s+=T(j-k)*T(j)*T(k);t*=T(j-k)*j*k<1;}main(){for(scanf("%i%i%i%i%i",&a,&b,&c,&d,&w);y<20;y+=!x)s=0,t=1,U(A=a-x,C=c-x),U(B=b-y,D=d-y),U(A-B,C-D),U(A+B,C+D),putchar((x=++x%21)?".?#x"[!!s+t+(!A*!B+!C*!D)]:10);}

Can be compiled/run using:
gcc laser.c -o laser && echo "10 10 11 10 3" | ./laser
Below, the same code with whitespace and explanatory comments:
// Integers...
x,y,A,C,B,D,a,c,b,d,w,s,t;

// Is true if i is in range (of something)
T(i){return abs(i)<2*w-1;}

// Tests if lasers (horizontal, vertical, diagonal, etc) can/must exist at this point
// T(j-k) == 0 iff the laser of this direction can exist
// s += 1 iff this laser direction can pass through this point
// t *= 1 iff this laser direction must pass through this point
U(j,k){
    s+=T(j-k)*T(j)*T(k);
    t*=T(j-k)*j*k<1;
}

main(){
    // Read input; p0=(a,b), p1=(c,d)
    for(scanf("%i%i%i%i%i",&a,&b,&c,&d,&w); y<20; y+=!x)

        // A, B, C and D represent delta-x and delta-y for each points
        // e.g.: if we're processing (2,3), and p0=(4,5), A=4-2, B=5-3
        // s != 0 iff (x,y) can have some laser through it
        // t == 1 iff all lasers pass through (x,y)
        // (!A*!B+!C*!D) == 1 iff (x,y) is either p0 or p1
        s=0,t=1,U(A=a-x,C=c-x),U(B=b-y,D=d-y),U(A-B,C-D),U(A+B,C+D),
        putchar((x=++x%21)?".?#x"[!!s+t+(!A*!B+!C*!D)]:10);
}

U(int j,int k) --> U(j,k); '\n' --> 10.

k<=0 --> k<1

Good points. I'd upvote if I could!

C, 302 bytes
b[400],x,y,s,t,w,d,e,g,k;f(u,v){d=u*x+v*y;e=u*s+v*t;if(e<d)k=e,e=d,d=k;for(k=0;k<400&d+w>e;++k)g=k%20*u+k/20*v,b[k]|=g>e-w&g<d+w|(g<d|g>e)*2;}main(){scanf("%d%d%d%d%d",&x,&y,&s,&t,&w);w=2*w-1;f(1,0);f(0,1);f(1,1);f(1,-1);b[y*20+x]=4;b[t*20+s]=4;for(k=0;k<400;)putchar(".#.?X"[b[k]]),++k%20?0:puts("");}

Input is taken from stdin, reading the 5 numbers in the defined order.
Before final size reduction step:
#include <stdio.h>
#include <stdlib.h>

int b[400], x, y, s, t, w, d, e, g, k;

void f(int u, int v) {
  d = u * x + v * y;
  e = u * s + v * t;
  if (e < d) k = e, e = d, d = k;
  if (d + w > e) {
    for (k = 0; k < 400; ++k) {
      g = u * (k % 20) + v * (k / 20);
      if (g > e - w && g < d + w) b[k] |= 1;
      if (g < d || g > e) b[k] |= 2;
    }
  }
}

int main() {
  scanf("%d%d%d%d%d", &x, &y, &s, &t, &w);
  w = 2 * w - 1;
  f(1, 0); f(0, 1); f(1, 1); f(1, -1);
  b[y * 20 + x] = 4;
  b[t * 20 + s] = 4;
  for (k = 0; k < 400; ) {
     putchar(".#.?X"[b[k]]);
     ++k % 20 ? 0 : puts("");
  }
}

Some explanation of key steps:

Array b holds the state/result. Bit 0 will be set for all pixels that can be reached by a beam. Bit 1 will be set for all pixels that are not covered by all beams.
Function f is called for all 4 directions (vertical, horizontal, both diagonals). Its arguments specify the normal vector of the direction.
In function f:

The distance of both input points relative to the direction is calculated (d and e)  as the dot product of the point with the normal vector passed in.
The distances are swapped if necessary so that d is always less than or equal to e.
If the difference between d and e is larger than the width of the beam, no beams are possible in this direction.
Otherwise, loop over all pixels. Set bit 0 if the pixel is reachable by any beam, and bit 1 if it is not covered by all beams.

Mark the two input points with value 4. Since we used bits 0 and 1 to track the state, which results in values 0 to 3, this is the smallest unused value.
Loop over the pixels in b, and convert the values in the range 0 to 4 to their corresponding character while printing them out.

you can likely save a little by putting the last line of code into the incrementer in that for loop


text:
Compute 30000 Digits of Pi (π), as Fast as Possible
Compute 30000 digits of the mathematical constant π, with the fastest code.
Implement in any computer programming language that I can run in my 64 bit Linux machine. You should provide your compiler optimization options if any. I am ready to install a new compiler or language runtime to run your code, given that I am not spending any money.
The code that finishes calculation and prints the output in the shortest time wins! I will measure the running time with the time command.
note 1: The program should be single threaded.
note 2: With 3.14, the number of digits is 3; with 3.1415, 5, and so on.
note 3: Hard coding π is not allowed.
note 4: Now you can use any number form in your code, not only integer.
note 5: Your output, which should be in decimal digits, need not contain the .. Just print out the numbers.
note 6: Your last digit should not be rounded up. If the next digit after the last is 5 or more, you should round up your last digit still leave the last digit as is.
Since this question was marked as duplicate, to this question. I should explain that this is a 'fastest-code' question not 'code-golf' and thus not a dupliate. The 'code-golf' answers are not well suited as an answer to this question; they are not the 'fastest'.

@trichoplax After thinking about a while with your comment, I decided to change my mind. Yes, since this is computing the 'digits', rounding up seems incorrect. I changed note 6.

Even before that edit, your question seemed clearly defined, so I'm not sure why there was a downvote. +1

This isn't an exact duplicate of the quadratic convergence on pi question, but it's close enough that IMO it's a dupe.

Are you going to redirect the output to /dev/null for measuring the time? I have a feeling that output might take much longer than the actual calculation even then, but it would be even worse if it's actually printed to a terminal.

@PeterTaylor Why is this marked as a duplicate? This question is not 'code-golf'.

@RetoKoradi Do you think 30000 digits is too less for a fast program?

http://meta.codegolf.stackexchange.com/q/777/194

@PeterTaylor Yes so the 'code-golf' answers are not competitive answers to this question.

"I think for the new challenge to qualify as a duplicate, those old answers also have to be competitive." Code-golf answers ARE competitive for this question, since the linked question ALSO required fast run-time (quadratic convergence). Thus each answer in that question will ALSO be fast, and therefore competitive.

I'm not familiar with the problem, so I don't have a precise idea of what the runtime will be. But considering the links to algorithms with quadratic convergence, it could be very short. And increasing the number of digits might not help the ratio between output and calculation. We'll see the results, I guess.

Although this is a duplicate, I had a python solution that ran in 0.7 s and a C++ rewrite (that's not working for some reason now) that was about 25% faster

Why was this marked as a duplicate? It's actually a very different goal. The other question was to produce the shortest code; this question is to produce the fastest code. I think it is a mistake to mark this as a duplicate — especially since the question is clearly marked as fastest-code.

Also, I have a solution that runs in about 2.3 seconds that I'd like to post.

@ToddLehman Comment with a link to the code and we can at least look at it.

@xiver77 Python 2 with gmpy2 (Chudnovsky alg): http://codepad.org/Yh0fWAKZ. Runtime for 30000 digits is negligible.

I have a C++ program that does it in zero time (it takes a long time to compile though...)  Are you including the time to compile the program?

Python 2 (Spigot Algorithm)
This is just Jeremy Gibbon's algorithm implemented in python. Definitely will be faster once someone else implements this in another language. Other methods might be faster too since I started working on this when the rules stated that I could only use integers. I originally tried doing this without string conversion and joining, but it was actually slower..
def p():
 q,r,t,j=1,180,60,2
 while True:
    u,y=3*(3*j+1)*(3*j+2),(q*(27*j-12)+5*r)//(5*t);yield y;q,r,t,j=10*q*j*(2*j-1),10*u*(q*(5*j-2)+r-y*t),t*u,j+1
p=p()
print''.join(str(p.next())for x in[1]*30000)

Completes on my work machine in about 53 seconds.

Thanks for this. I was reading that PDF after searching for algorithms (without seeing your link to it), and I was having a hard time reading the Haskell syntax. I'm glad I can see it now in a language I can understand.

Also, since this isn't code-golf, don't feel like you need to cram the internal of the while onto one line. And, you can use / instead of // since this is Python 2, though you can leave it for readability.

@mbomb007 Yeah, I realized I didn't need to golf it, it just sort of happened, haha.

Here it is golfed more (just for fun): http://ideone.com/lOhcxB . Run it with a number < 30000 if you want to see output (I used 300).


text:
ASCII Triangle Ripple
Ok, my first golf question. Please be gentle :) I know there's way too many ascii puzzles :P but here we go.
The task is simple, use your favorite programming language to print a triangle ripple. The input should be the size of the ripple.
Each triangle is evenly spaced out. Basically, you keep adding the triangles until there is not enough space for the smallest triangle.
You are allowed white spaces anywhere you want as long as the ripples are the same as the example with the correct size.
Example
q)g 1
__
\/
q)g 2
____
\  /
 \/
q)g 3
______
\    /
 \  /
  \/
q)g 4
________
\  __  /
 \ \/ /
  \  /
   \/
q)g 5
__________
\  ____  /
 \ \  / /
  \ \/ /
   \  /
    \/
q)g 6
____________
\  ______  /
 \ \    / /
  \ \  / /
   \ \/ /
    \  /
     \/
q)g 7
______________
\  ________  /
 \ \  __  / /
  \ \ \/ / /
   \ \  / /
    \ \/ /
     \  /
      \/
q)g 8
________________
\  __________  /
 \ \  ____  / /
  \ \ \  / / /
   \ \ \/ / /
    \ \  / /
     \ \/ /
      \  /
       \/

As usual, shortest code wins :)

While not an exact duplicate of Draw Concentric ASCII Hexagons, I'm not sure it adds much over the other.

@Geobits IMO its different enough - the input spec is quite different, the method of figuring out how many shapes to draw is different, and triangles != hexagons ;-)

@WooiKent I'm now doubting if I understood the question correctly.  What is a ripple?  Is it one concentric set of triangles, or something else?

nice question, but it is underspecified. (1) Reading the text literally, when the input is 1,2 or 3, we should always output three triangles. (2) I would take it as a given that each set of triangles should be concentric, and (3) it appears they should also have their bottom corners on the same line. (4) Does the horizontal separation have to be exactly one space as shown, or are other separations allowed? (5) Is unnnecesary whitespace allowed to the (a,b,c,d) left, right, above, below?

I think it's rather clear, although not explicit. You always draw one triangle of the given size, with nested triangles of size n-3, n-6, n-9, etc.

apologies if the question is not clear, it is one concentric set of triangles. Each triangles is evenly spaced. You basically keep adding triangles until you cant add one.

Pyth, 31 bytes
VhQ+J<t+++*Nd*N"\ "d*Q\_Q_XJ"\/

Demonstration.
Explanation:
VhQ+J<t+++*Nd*N"\ "d*Q\_Q_XJ"\/
                                   Implicit: Q = eval(input()), d = ' '
VhQ                                for N in range(Q + 1):
                                   Concatenate:
          *Nd                      N spaces
         +   *N"\ "                N of the string "\ "
        +          d               another space
       +            *Q\_           Q of the string "_"
                                   If N = 2 and Q = 7, the string so far is:
                                   "  \ \  _______" and we want
                                   " \ \  _" as the left half.
      t                            Remove the first character.
     <                  Q          Take the first Q characters remaining.
                                   This is the left half of the triangle ripple.
    J                              Store it in J.
                          XJ"\/    Translate \ to / in J.
                         _         Reverse it.
   +                               Concatenate the left and right halves and print.

GNU sed -nr, 210
A start:
s/1/__/g
p
s#_(.*)_#\\\1/#
s#\\__#\\  #
s#__/#  /#
ta
:a
p
s#(.*) _{6}(_*) # \1\\  \2  /#;ta
s#(.*)  (  )# \1\2#;
s#(.*) _(_*)_ # \1\\\2/#
y/_/ /
Tc
:b
p
:c
s#(.*)((\\)  ( *)(/)|()()()\\/)# \1\3\4\5#;tb

Input is a positive unary integer via STDIN, as per this meta-question.
Output:
$ for i in 1 11 111 1111 11111 111111 1111111; do sed -rnf triripple.sed <<< $i; done
__
\/

____
\  /
 \/

______
\    /
 \  /
  \/

________
\  __  /
 \ \/ /
  \  /
   \/

__________
\  ____  /
 \ \  / /
  \ \/ /
   \  /
    \/

____________
\  ______  /
 \ \    / /
  \ \  / /
   \ \/ /
    \  /
     \/

______________
\  ________  /
 \ \  __  / /
  \ \ \/ / /
   \ \  / /
    \ \/ /
     \  /
      \/

$

C, 165 bytes
n,x,y,b,c;main(c,v)char**v;{for(n=atoi(v[1]);y<=n;++y){for(x=-n;x<n;++x){b=2*n-abs(2*x+1);c=b-2*y+2;b-=6*y;putchar(b>0?95:b<-4&c>0&c%4==1?"/\\"[x<0]:32);}puts("");}}

Before the golfing steps that destroy readability:
#include <stdio.h>
#include <stdlib.h>

int main(int c, char** v) {
    int n = atoi(v[1]);
    for (int y = 0; y <= n; ++y) {
        for (int x = -n; x < n; ++x) {
            int b = 2 * n - abs(2 * x + 1);
            int c = b - 2 * y + 2;
            b -= 6 * y;
            putchar(b > 0 ? 95 :
                    b < -4 && c > 0 && c % 4 == 1 ? "/\\"[x<0] : 32);
        }
        puts("");
    }
}

This loops over all characters in the rectangle containing the figure, and evaluates the line equations that separate the inside of the triangle from the outside, as well as the ones that separate the different parts of the triangle.

Nice job with math. You should try this one: http://codegolf.stackexchange.com/q/51396/21348

156: n,x,y,b,c;main(c,v)char**v;{for(n=atoi(v[1]);y<=n;++y)for(x=-n;x<=n;putchar(x++-n?b>6*y?95:b<6*y-4&c>0&c%4==1?"/\\"[x<1]:32:10))c=(b=2*n-abs(2*x+1))-2*y+2;}

Retina, 182 bytes
1
_
^
#$_
((`#([^#]*?)( ?)_(_*)_( ?)([^#]*?)$
$0# $1\$3/$5
+)`\\( ?)_(_*)_( ?)/(?=[^#]*$)
\ $1$2$3 /
#( *(\\ )*\\ *)  ( *(/ )*/)$
$0# $1$3
)`#( *(\\ )*)\\/(( /)*)$
$0# $1$3
#
#
^#
<empty line>

Takes input as unary.
Each line should go to its own file and # should be changed to newline in the files. This is impractical but you can run the code as is as one file with the -s flag, keeping the # markers. You can change the #'s to newlines in the output for readability if you wish. E.g.:
> echo -n 1111|retina -s triangle|tr # '\n'
________
\  __  /
 \ \/ /
  \  /
   \/

The code isn't too well golfed (yet).

C — 206 bytes
i,j,m,k,a,b;main(i,v)char**v;{m=atoi(v[1])*2;while(k<m*(m/2+1)){i=k/m;j=k%m;a=i*3,b=(i+j)%2;putchar("_\\/ "[j>=a&&j<m-a?0:j>i-2&&b&&j<i*3-1&&j<m/2?1:j<=m-i&&!b&&j>m-a&&j>=m/2?2:3]);if(j==m-1)puts("");k++;};}
 x,m,i,j,a,b;
int main(x,v)char**v;{
    m=atoi(v[1])*2;
    for(i=0;i<m/2+1;i++){
        for(j=0;j<m;j++){
            a=i*3,b=(i+j)%2;
            j>=a&&j<m-a?a=0:j>=i-1&&b&&j<i*3-1&&j<m/2?a=1:j<=m-i&&!b&&j>m-a&&j>=m/2?a=2:(a=3);putchar("_\\/ \n"[a]);
        }
        puts("");
    }
}

Example output
Pauls-iMac:ppcg pvons$ for i in $(seq 1 7); do ./a.out $i; done
__
\/
____
\  /
 \/
______
\    /
 \  /
  \/
________
\  __  /
 \ \/ /
  \  /
   \/
__________
\  ____  /
 \ \  / /
  \ \/ /
   \  /
    \/
____________
\  ______  /
 \ \    / /
  \ \  / /
   \ \/ /
    \  /
     \/
______________
\  ________  /
 \ \  __  / /
  \ \ \/ / /
   \ \  / /
    \ \/ /
     \  /
      \/

You can trim this down quite a bit. Taking advantage of old style C, you can declare variables without a type if they are int. Also, if you declare them at the global scope, they are automatically initialized to 0. Instead of having a bunch of putchar() calls in different branches, you can use a single call and replace the if statements with ternary operators. Of course it becomes hard to read that way, but it's completely in the spirit of this site to write ugly code if it's shorter. :)

Thanks @RetoKoradi, I reduced it from 279 to 214 by implementing your suggestions :) I think I'd need to improve my algorithm to get further improvements.

Yes, once you get beyond the mechanics, the key is to find rules that simplify the logic as much as possible. If you look at my solution, which is fundamentally very similar, I found that the logic simplified quite a bit by placing the origin of the horizontal coordinate in the center of the triangle. That way, I could take advantage of the symmetry. And others probably found even better approaches. It's really interesting how much can be done on a problem that looks so deceptively simple.

JavaScript (ES6) 165 180 204
Run snippet in Firefox to test. If returning the string is not enough, using alert for output is 2 chars more.

// 165 - return the string
F=n=>
  (i=>{
    for(r='__'[R='repeat'](m=n);i<n;)
      r+=`\n`+' '[R](i)
       +('\\ '[R](t=-~(m>3?i:~-n/3))+' ').slice(0,n-i)
       +'__'[R](m>3?m-=3:0)
       +(' '+' /'[R](t)).slice(i++-n)
  })(0)||r

// 167 - output the string
A=n=>{
  for(i=0,r='__'[R='repeat'](m=n);i<n;)
    r+=`\n`+' '[R](i)
     +('\\ '[R](t=-~(m>3?i:~-n/3))+' ').slice(0,n-i)
     +'__'[R](m>3?m-=3:0)
     +(' '+' /'[R](t)).slice(i++-n);
  alert(r)
}

// TEST
out=x=>O.innerHTML += x+'\n'

for(k=1;k<13;k++)out(k+'\n'+F(k))


text:
Copy Memory Only Using Store And Subtraction
A peer of mine approached me with this challenge and I wasn't able to come up with an elegant solution. After discussing my approach, we began to wonder what the people at Code Golf would come up with.
Given

A processor that implements only two instructions:

STO <register>, <address> (store from this register to this address)
SUB <register>, <address> (subtract the value at this address from this  register)

It also only contains 2, 32-bit registers: A and B
As well as 2, 32-bit RAM address: 0x00 and 0x01
The values of A and B are unknown

Challenge
Write a program to copy RAM address 0x00 into 0x01 optimised to use the fewest number of instructions possible.

Welcome to PCG! Note that this isn't a very good challenge. It's simple enough to likely only have one good solution. Try using the Sandbox for Proposed Challenges first next time to get feedback about proposed challenges. Thanks.

@mbomb007 Thank you, I'm new and figured there was a better way to do this. I'm sorry for the poor question and I greatly appreciate the help. Thank you!

Assuming registers are signed and/or wrapping
8 instructions:
STO A 0x01
SUB A 0x01
SUB A 0x00
STO A 0x00
SUB A 0x00
SUB A 0x00
STO A 0x00
STO A 0x01

A 7-instruction version provided by lrn:
STO A 0x01
SUB A 0x01
SUB A 0x00
STO A 0x01
SUB A 0x01
SUB A 0x01
STO A 0x01

That and the next instruction serve to zero register A. Then we do a what amounts to [00]=-[00], then some more stuff to restore [00] to its original value while simultaneously setting A to that value, then we write that value to [01]. The requirement was that [01] and [00] both end up having the value that [00] initially had.

Oops, I read the challenge as being to swap the memory locations.

@feersum: I don't think you could do that with this command set without adding a third address.

All without using register B. Nice! This is probably the optimal solution.

A 3rd address or maybe an XOR instruction. I don't see a way for there to be an answer any simpler than this. It was definitely better than mine, so I marked it as the answer. Congratulations!

@Brett Can you post yours, please? I'm interested.

Why store A to 0x00 in the second to last step? If you use 0x01 as temporary in step 4 and forward, you don't need to store back into 0x00. That is: STO A 0x01; SUB A 0x01; SUB A 0x00; STO A 0x01; SUB A 0x01; SUB A 0x01; STO A 0x01 should copy 0x00 to 0x01 and keep 0x00 unchanged in one instruction less.