# 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. – FryAmTheEggman Jun 10 '15 at 1:08
• 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 Jun 10 '15 at 2:04
• 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 ;) – Geobits Jun 10 '15 at 3:06
• @SohamChowdhury I'll just pretend that was intentional ;) Do you want me to fix it? – Matt Y Jun 10 '15 at 9:36
• 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! – Alex A. Jun 10 '15 at 14:50

# 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 – Jo King Aug 8 '20 at 8:36
• @JoKing Thank you for your opinion – Eesa Aug 8 '20 at 9:49
• 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). – the default. Aug 8 '20 at 11:19
• @JoKing Sorry, my mistake. Thank you once again. – Eesa Aug 8 '20 at 16:43

# 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. – Razetime Dec 20 '20 at 12:01
• oh true that, let me fix it – Kamila Szewczyk Dec 20 '20 at 12:03
• alright, should work now – Kamila Szewczyk Dec 20 '20 at 12:08
• {↑⍺('^',⍨⍵⍴'')} or ↑⊣,⍥⊂'^',⍨''⍴⍨⊢ with the latter being ↑⊣⍮'^',⍨''⍴⍨⊢ in Extended. – Adám Feb 18 at 6:47

# 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:

"." "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 Jun 10 '15 at 16:10 • @Mr.Llama thanks, those are good. – hobbs Jun 10 '15 at 16:12 # 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)."^". – Dennis Jun 11 '15 at 5:57

## F#, 31 characters

let p n s=s+"\n"+"^".PadLeft(n)


### Ruby, 1723 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? – manatwork Jun 10 '15 at 18:28 • The rules say: "Output is printed out to the console or returned". I am returning the output. – boxmein Jun 10 '15 at 18:32 • The accent was not on the action but on the subject: your proc neither receives nor returns the source code. – manatwork Jun 10 '15 at 18:35 • Oh, sorry! Edited the code. – boxmein Jun 10 '15 at 18:51 • You can save 1 char by replacing ?\n with $/. – Tony Ellis Jun 11 '15 at 8:39

# 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 Jun 12 '15 at 15:17
• @manatwork good call! updated answer – hmatt1 Jun 12 '15 at 15:19

# 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.
^


# J, 19

Including parentheses!

The verb:

(],:'^',~' '#~<:@[)


Use:

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


This is my first code golf, but here I go.

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. # Haskell, 30 bytes s!n=s++'\n':([1..n]>>" ")++"^"  # 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! • 1. 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 Feb 2 '17 at 14:52 • @Riley Thanks! That helped. – Admicos Feb 2 '17 at 15:00 • You shouldn't need the space in stoi either. – Riley Feb 2 '17 at 15:04 ## 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 – user65167 May 13 '17 at 17:57 • @PrzemysławP Thanks, I edited the answer; I was pretty busy, sorry for the delay – coredump Jun 7 '17 at 8:19 ## 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. – user62131 Jun 7 '17 at 9:49 • @ais523 Switching to unary input for n works, because : is easily undone using !. – Esolanging Fruit Jun 11 '17 at 23:31 # 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! # Perl 5-p, 16 bytes $_.=$"x<>;s;$;^


Try it online!

# Perl 5-p, 16 bytes

$\=$"x(<>-1)."^"


Try it online!

# Rust, 32 bytes

|n,s|print!("{}
{:>2$}",s,"^",n)  Try it online # 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!

# Brain-Flak -A, 116 bytes

([{}]()<{({}<>)<>}(((((()()()()()){}()){}()){}()){})>){((){}<((((()()()()){}){}){})>)}{}((()()()()()){}){<>({}<>)}{}


Try it online!

# 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. – Kevin Cruijssen Aug 7 '20 at 8:38

# J, 9 bytes

,:'^'{.~-


Try it online!

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


# 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 – manatwork Jun 10 '15 at 17:24
• 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. – manatwork Jun 10 '15 at 18:37