| Bytes | Lang | Time | Link |
|---|---|---|---|
| 044 | Tcl | 170202T232957Z | sergiol |
| 044 | Swift 6 | 250301T220755Z | macOSist |
| 079 | Go | 230608T155342Z | The Thon |
| 032 | Java JDK | 230608T153754Z | Fhuvi |
| 006 | Thunno 2 N | 230608T135442Z | The Thon |
| 005 | Vyxal o | 221011T042251Z | DialFros |
| 007 | Jelly | 210323T011134Z | caird co |
| 020 | Zsh F | 210218T081422Z | pxeger |
| 014 | APL Dyalog Classic | 210218T075545Z | Galen Iv |
| 005 | Stax | 210218T073559Z | Razetime |
| 035 | Red | 210218T072941Z | Galen Iv |
| 023 | APL Dyalog Unicode | 201220T112107Z | Kamila S |
| 014 | Gol><> Golfish | 170202T231458Z | Nick Mat |
| 038 | Haskell | 201117T202548Z | binaryca |
| 006 | 05AB1E | 201117T195202Z | Makonede |
| 005 | Japt R | 201111T213257Z | Shaggy |
| 027 | PowerShell Core | 201109T220638Z | Julian |
| 006 | V | 170209T224415Z | DJMcMayh |
| 009 | J | 201109T084235Z | FrownyFr |
| 007 | 05AB1E | 170202T133831Z | Emigna |
| 025 | Braingolf | 170607T082823Z | Mayube |
| 007 | Jelly | 160920T133921Z | Erik the |
| 017 | Turtlèd | 160920T040847Z | Destruct |
| 116 | BrainFlak A | 201109T010317Z | Wheat Wi |
| 374 | Hexagony | 201109T002618Z | Undersla |
| 031 | Forth gforth | 201108T124658Z | Razetime |
| 024 | Ruby 2.7 | 200809T181759Z | Sapphire |
| 032 | Rust | 200808T192316Z | TehPers |
| 029 | Python 3 | 200808T060902Z | Eesa |
| 006 | Integral | 200808T074129Z | lyxal |
| 016 | Perl 5 p | 200808T072856Z | Dom Hast |
| 009 | Keg | 200808T073034Z | lyxal |
| 050 | Momema | 200808T072654Z | Esolangi |
| 020 | Perl 5 n | 200808T040416Z | Xcali |
| 053 | MAWP v1.02 | 200807T070624Z | Razetime |
| 023 | Underload | 170210T061447Z | Esolangi |
| 008 | Pyth | 150610T012003Z | FryAmThe |
| 4035 | Common Lisp | 160920T140047Z | coredump |
| 009 | Vim | 170209T224213Z | DJMcMayh |
| 026 | SmileBASIC | 170202T031700Z | 12Me21 |
| 121 | C++ with the standard library | 170202T143701Z | Admicos |
| 045 | C++14 | 170202T132257Z | Karl Nap |
| nan | Vim | 161001T195752Z | Christia |
| 030 | Haskell | 160920T153606Z | BlackCap |
| 013 | Straw | 160920T095826Z | TuxCraft |
| 008 | Pyth | 160920T042852Z | Steven H |
| nan | This is my first code golf | 150620T080544Z | user4169 |
| 050 | Javascript | 150610T171113Z | user4149 |
| 022 | SAS | 150617T141544Z | Fried Eg |
| 056 | Batch | 150617T135830Z | ankh-mor |
| 024 | IA32 machine code | 150610T091420Z | anatolyg |
| 041 | Swift | 150614T061037Z | Xplorld |
| 019 | J | 150613T164323Z | Alex Shr |
| 042 | Scala | 150612T141555Z | user2336 |
| 6049 | C | 150611T233602Z | takra |
| 035 | SAS | 150610T231938Z | Joe |
| 020 | Perl | 150612T150453Z | hmatt1 |
| 057 | Pascal | 150612T143439Z | manatwor |
| 036 | Python3 | 150610T091738Z | Spikatri |
| nan | 150610T122153Z | pallavt | |
| 133 | Brainf*ck | 150610T082859Z | sudo rm |
| nan | Ruby | 150610T182250Z | boxmein |
| 046 | R | 150610T203807Z | MickyT |
| 031 | F# | 150610T050132Z | Hand-E-F |
| 3531 | PHP 4.1 | 150610T143125Z | Ismael M |
| 053 | Lua | 150610T170827Z | ECS |
| 009 | CJam | 150610T012436Z | Dennis |
| 033 | C | 150610T095203Z | edc65 |
| 045 | Perl | 150610T172029Z | fvla |
| 029 | Python | 150610T045323Z | feersum |
| 016 | sed | 150610T051605Z | Digital |
| 031 | Perl 5 | 150610T025754Z | hobbs |
| 021 | K | 150610T153623Z | kirbyfan |
| 035 | rs | 150610T151934Z | kirbyfan |
| 052 | JavaScript | 150610T150555Z | Nebula |
| 025 | Matlab | 150610T144202Z | Oebele |
| 042 | PHP CLI | 150610T100814Z | HamZa |
| 055 | C# | 150610T100042Z | edc65 |
| 011 | GolfScript | 150610T094310Z | Cristian |
| 047 | C | 150610T063517Z | Spikatri |
| 034 | SpecBAS | 150610T072347Z | Brian |
| 027 | Python | 150610T070521Z | grc |
| 027 | Julia | 150610T050244Z | Alex A. |
| 019 | dc | 150610T025936Z | Digital |
| 032 | JavaScript ES6 | 150610T025824Z | adroitwh |
| 041 | Matlab/Octave | 150610T031530Z | FryAmThe |
| 090 | TSQL | 150610T023547Z | MickyT |
| 010 | TIBASIC | 150610T014523Z | user3932 |
| 027 | Bash | 150610T011544Z | Digital |
| 029 | Python | 150610T011106Z | xnor |
Swift 6, 44 bytes
{$0+"\n\({String.init}()(" ",$1-1))^"}
Go, 79 bytes
import."strings"
func f(s string,n int)string{return s+`
`+Repeat(" ",n-1)+"^"}
Java (JDK), 32 bytes
Speaking of which, the Java answer of this problem needed a little upgrade :)
a->b->b+"\n"+" ".repeat(a-1)+"^"
Thunno 2 N, 6 bytes
⁻ṣ'^+,
Explanation
⁻ṣ'^+, # Implicit input
⁻ṣ # First input decremented spaces
'^+ # With a "^" appended
, # Paired with the second input
# Implicit output joined by newlines
Jelly, 7 bytes
ṄṛṬị⁾^
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 "^ "
APL (Dyalog Unicode), 23 bytes
⊣,(⎕UCS 10),'^',⍨' '⍴⍨⊢
Explanation:
⊣,(⎕UCS 10),'^',⍨' '⍴⍨⊢
⊣,(⎕UCS 10) ⍝ original line + linefeed
'^',⍨' '⍴⍨⊢ ⍝ generate the pointer
Explaining the generator by example:
('^',⍨' '⍴⍨⊢)
{'^',⍨' '⍴⍨⍵}
{(' '⍴⍨⍵),'^'}
{(⍵⍴' '),'^'}
(⍵⍴' ') ⍝ generate ⍵ spaces
'^' ⍝ append the pointer
Gol><> (Golfish), 14 bytes
`^IMR` aTiEHot
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
05AB1E, 6 bytes
,'^ú¦,
, # output with trailing newline...
# implicit input
, # output with trailing newline...
'^ # "^"...
ú # with...
# implicit input...
¦ # minus 1...
ú # spaces in front
J, 9 bytes
,:'^'{.~-
- negate the number
'^'{.~ take that many characters from the string "^"
,: append 2 items
05AB1E, 7 bytes
'^I<ú‚»
Explantion
'^ # push caret
I<ú # prepend with input-1 spaces
‚ # pair with second input
» # join by newline
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 ^
Brain-Flak -A, 116 bytes
([{}]()<{({}<>)<>}(((((()()()()()){}()){}()){}()){})>){((){}<((((()()()()){}){}){})>)}{}((()()()()()){}){<>({}<>)}{}
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!
Forth (gforth), 32 31 bytes
: b type cr 1- spaces 94 emit ;
Input is given as <number> s" <string>" b.
Note the required space after s".
-1 byte from Bubbler.
Shorter than MAWP lol
Ruby 2.7, 24 bytes
x=->{_1+'
'+" "*~-_2+?^}
Python 3, 29 bytes 31
lambda N,S:S+'\n'+' '*~-N+'^'
A Plain Comprehensible snippet, used function lambda function and concatenation
Momema, 50 bytes
1+*-8-1s00*-9-9*0s=+1*0-9 10c01+*1-1-9 32c=*1-9 94
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.
Perl 5 -n, 20 bytes
say<>;say$"x--$_,'^'
Unlike a previous answer of the same byte count, this does not require the input to be in unary.
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.
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.
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
Common Lisp, 40 35
(format t"~A
~VT^"(read)(1-(read)))
-5 bytes thanks to PrzemysławP.
Vim 9 bytes
jD@"a <esc>r^
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
SmileBASIC, 26 bytes
INPUT N,S$?S$?" "*(N-1);"^
1-indexed arrow adds 4 bytes...
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!
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;
}
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#spacesr^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.
Haskell, 30 bytes
s!n=s++'\n':([1..n]>>" ")++"^"
Straw, 13 bytes
<#<>
> ,}*>^>
^ is the only non-alphanumeric character (with \) to not be assigned to a command, so no need for a string literal to push it.
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
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.
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^
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.
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.
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);
}
Swift, 41
It is disappointing that Swift does not have operator * on Array or String.
{$1+reduce(0..<$0,"\n",{$0.0+" "})+"^"}
J, 19
Including parentheses!
The verb:
(],:'^',~' '#~<:@[)
Use:
9 (],:'^',~' '#~<:@[) 'Invalid Java!'
Invalid Java!
^
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.
^
C, 60 49
f(n,s){puts(s);while(n-=1)putch(' ');putch('^');}
First post, so I guess it's not that good.
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;
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'
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.
Python3, 38 36 bytes
def f(s,i):return s+'\n'+' '*~-i+'^'
# OR
def f(s,i):print(s+'\n'+' '*~-i+'^')
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("^");}
Brainf*ck - 133 bytes
+++++>>+>>+++>>+++++++++<<<<<<[[->++++++++++<]>>]<++++<<++<<<<--<,>[->+<<->]>>>,<<[->>-<<]<<[->>>>++++++++++<<<<]>>+[,.]>.>[->.<]>>>.
Expects input as [0-9]{2}.* e.g. "02Hello world!!!" would produce
Hello world!!! ^
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
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
^
>
F#, 31 characters
let p n s=s+"\n"+"^".PadLeft(n)
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),'^';
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
CJam, 9 bytes
q~N@(S*'^
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.
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);}
Perl, 45
This is a pretty horribly golfed answer, but it's my first attempt at code golf.
<>=~/(.*), "(.*)"/;print"$2
"." "x($1-1)."^";
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
^
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.
^
$
Perl 5, 31
sub{"$_[0]
"." "x($_[1]-1)."^"}
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
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...
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.
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.
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!
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."
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);}
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
}
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.
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
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.
^
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.
^$
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)}^`}
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.
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
^
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.
Bash, 27
printf %s\\n%$[$1-1]s^ "$2"
Output
$ ./carrot.sh 2 "Lorem ipsum, dollar sit amet."
Lorem ipsum, dollar sit amet.
^$
Python, 29
lambda n,s:s+'\n'+' '*~-n+'^'
Concatenates the string, a newline, n-1 spaces, and a ^.

