58
\$\begingroup\$

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

89 Answers 89

2
\$\begingroup\$

Integral, 7 6 Bytes

▼8gv^►

Try it!

-1 thanks to @petStorm

\$\endgroup\$
1
  • \$\begingroup\$ Save a byte (▼8gv^► (6 bytes)) by using the v instruction. \$\endgroup\$
    – user96495
    Aug 8, 2020 at 10:18
2
\$\begingroup\$

Python 3, 29 bytes 31

lambda N,S:S+'\n'+' '*~-N+'^'

Try it online!

A Plain Comprehensible snippet, used function lambda function and concatenation

\$\endgroup\$
4
  • \$\begingroup\$ (N-1) can be ~-N. You can also use f-strings for 28 bytes \$\endgroup\$
    – Jo King
    Aug 8, 2020 at 8:36
  • \$\begingroup\$ @JoKing Thank you for your opinion \$\endgroup\$
    – Eesa
    Aug 8, 2020 at 9:49
  • 1
    \$\begingroup\$ 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). \$\endgroup\$ Aug 8, 2020 at 11:19
  • \$\begingroup\$ @JoKing Sorry, my mistake. Thank you once again. \$\endgroup\$
    – Eesa
    Aug 8, 2020 at 16:43
2
\$\begingroup\$

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

enter image description here

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

enter image description here

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!

\$\endgroup\$
2
+100
\$\begingroup\$

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
\$\endgroup\$
4
  • \$\begingroup\$ I think you need to output the original line as well. \$\endgroup\$
    – Razetime
    Dec 20, 2020 at 12:01
  • \$\begingroup\$ oh true that, let me fix it \$\endgroup\$ Dec 20, 2020 at 12:03
  • \$\begingroup\$ alright, should work now \$\endgroup\$ Dec 20, 2020 at 12:08
  • \$\begingroup\$ {↑⍺('^',⍨⍵⍴'')} or ↑⊣,⍥⊂'^',⍨''⍴⍨⊢ with the latter being ↑⊣⍮'^',⍨''⍴⍨⊢ in Extended. \$\endgroup\$
    – Adám
    Feb 18, 2021 at 6:47
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

GolfScript 11

n@~(' '*'^'

Test here.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ Nice save Scimonster O_O \$\endgroup\$
    – Nebula
    Jun 10, 2015 at 15:10
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ Jun 10, 2015 at 19:53
1
\$\begingroup\$

Perl 5, 31

sub{"$_[0]
"." "x($_[1]-1)."^"}
\$\endgroup\$
2
  • \$\begingroup\$ 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) \$\endgroup\$
    – Mr. Llama
    Jun 10, 2015 at 16:10
  • \$\begingroup\$ @Mr.Llama thanks, those are good. \$\endgroup\$
    – hobbs
    Jun 10, 2015 at 16:12
1
\$\begingroup\$

Perl, 45

This is a pretty horribly golfed answer, but it's my first attempt at code golf.

<>=~/(.*), "(.*)"/;print"$2
"." "x($1-1)."^";
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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)."^". \$\endgroup\$
    – Dennis
    Jun 11, 2015 at 5:57
1
\$\begingroup\$

F#, 31 characters

let p n s=s+"\n"+"^".PadLeft(n)
\$\endgroup\$
1
\$\begingroup\$

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

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'
\$\endgroup\$
2
  • \$\begingroup\$ The ternary operator seems pointless here as you only have instruction for the “then” branch: $i++&y/1/ /&s/ $/^/. \$\endgroup\$
    – manatwork
    Jun 12, 2015 at 15:17
  • \$\begingroup\$ @manatwork good call! updated answer \$\endgroup\$
    – hmatt1
    Jun 12, 2015 at 15:19
1
\$\begingroup\$

C, 60 49

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

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

\$\endgroup\$
0
1
\$\begingroup\$

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.
 ^
\$\endgroup\$
1
\$\begingroup\$

J, 19

Including parentheses!

The verb:

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

Use:

9 (],:'^',~' '#~<:@[) 'Invalid Java!'
Invalid Java!
        ^
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Haskell, 30 bytes

s!n=s++'\n':([1..n]>>" ")++"^"
\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
3
  • \$\begingroup\$ 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 :) \$\endgroup\$
    – Riley
    Feb 2, 2017 at 14:52
  • \$\begingroup\$ @Riley Thanks! That helped. \$\endgroup\$
    – Admicos
    Feb 2, 2017 at 15:00
  • \$\begingroup\$ You shouldn't need the space in stoi either. \$\endgroup\$
    – Riley
    Feb 2, 2017 at 15:04
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Common Lisp, 40 35

(format t"~A
~VT^"(read)(1-(read)))

-5 bytes thanks to PrzemysławP.

\$\endgroup\$
2
  • \$\begingroup\$ (format t"~A<enter>~VT^"(read)(1-(read))) saves 5 bytes \$\endgroup\$
    – user65167
    May 13, 2017 at 17:57
  • \$\begingroup\$ @PrzemysławP Thanks, I edited the answer; I was pretty busy, sorry for the delay \$\endgroup\$
    – coredump
    Jun 7, 2017 at 8:19
1
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$
    – user62131
    Jun 7, 2017 at 9:49
  • \$\begingroup\$ @ais523 Switching to unary input for n works, because : is easily undone using !. \$\endgroup\$ Jun 11, 2017 at 23:31
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Keg, 9 bytes

᠀
¿; ℠*\^

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Rust, 32 bytes

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

Try it online

\$\endgroup\$
1
\$\begingroup\$

Brain-Flak -A, 116 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

05AB1E, 7 bytes

'^I<ú‚»

Try it online!

Explantion

'^       # push caret
  I<ú    # prepend with input-1 spaces
     ‚   # pair with second input
      »  # join by newline
\$\endgroup\$
1
  • 2
    \$\begingroup\$ 6 bytes by taking the inputs in reversed order. \$\endgroup\$ Aug 7, 2020 at 8:38
1
\$\begingroup\$

J, 9 bytes

,:'^'{.~-

Try it online!

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

Zsh -F, 20 bytes

printf %s\\n%*c $@ ^

Try it online!

Method stolen from the C answer.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.