Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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!
share|improve this question
10  
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 2 days ago
3  
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 2 days ago
2  
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 2 days ago
5  
+1 for "dollar" –  Soham Chowdhury 2 days ago
5  
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. 2 days ago

42 Answers 42

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);}
share|improve this answer
7  
C can always compete, it just can't always win. ;) –  Alex A. 2 days ago
1  
@AlexA. <shrug> looks like its winning to me ;-) –  Digital Trauma 2 days ago
3  
Save 1 char : f(a,c){printf("%s\n%*c",a,c,94);} –  Mig 2 days ago
    
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. –  Reto Koradi 9 hours ago

Brainf*ck - 133 bytes

+++++>>+>>+++>>+++++++++<<<<<<[[->++++++++++<]>>]<++++<<++<<<<--<,>[->+<<->]>>>,<<[->>-<<]<<[->>>>++++++++++<<<<]>>+[,.]>.>[->.<]>>>.

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

Hello world!!!
 ^
share|improve this answer
1  
+1 for using brainfuck. Well done. –  fridgefish 2 days ago
    
Welcome to Programming Puzzles and Code Golf! This is a great first post, nice job! :D –  Alex A. 2 days ago
    
The problem is, no-one knows if this is even valid code, let alone solves the problem :) –  Simon yesterday
    
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 yesterday
    
@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. –  Joseph Malle yesterday

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 = '^', al = 0

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);
}
share|improve this answer
4  
+1 for machine code. –  fridgefish 2 days ago

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
share|improve this answer

Pyth, 8

zp\^*tQd

Try it online here

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
share|improve this answer
    
I think this is the shortest one so far. Well done. –  fridgefish yesterday

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
    ^
share|improve this answer
    
Very creative use of a language not really designed for golfing ;) +1 –  fridgefish yesterday

Python, 29

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

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

share|improve this answer
1  
If only rjust wasn't so long... –  Sp3000 2 days ago
4  
Ah, the tadpole operator. –  immibis 2 days ago

Bash, 27

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

Output

$ ./carrot.sh 2 "Lorem ipsum, dollar sit amet."
Lorem ipsum, dollar sit amet.
 ^$ 
share|improve this answer
    
Carrot? Also, what's the dollar at the end? –  Scimonster 2 days ago
5  
The Dollar seems to be the shell's prompt. –  M.Herzkamp 2 days ago
    
@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. –  Digital Trauma 2 days ago

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)}^`}
share|improve this answer
    
1. 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(" ")+" ^". –  Dennis 2 days ago
    
33 bytes: (replace \n with an actual newline) p=(a,b)=>b+`\n${' '.repeat(a-1)}^` –  nderscore 2 days ago
    
@dennis The indexing works perfectly for me: i.stack.imgur.com/Tdejc.png –  darkness3560 2 days ago
    
@Dennis Array(1).join(' ') results in an empty string :) –  nderscore 2 days ago
    
@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: i.stack.imgur.com/Tdejc.png –  darkness3560 2 days ago

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.
 ^
$
share|improve this answer
1  
2y/1/ /;2s/ $/^/ –  manatwork 2 days ago
    
@manatwork Good call! –  Digital Trauma 2 days ago

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
    ^
share|improve this answer

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.
share|improve this answer

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;
share|improve this answer
    
Good to see SO's resident SAS expert here on PPCG. :) –  Alex A. yesterday
    
I'm fairly sure some of the old timers who know DM scripting could best this score... And my cmdmac skills suck. –  Joe yesterday
    
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. –  Alex A. yesterday
    
Yeah, my SAS ingrained reflexes don't let me use that intuitively I guess :). Thanks. –  Joe yesterday
    
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. –  Alex A. yesterday

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.

share|improve this answer
    
You'd be better off taking input from Input for the number and Ans for the string. –  Thomas Kwa 2 days ago
    
The first one also doesn't work if the program name, assignment, and string combined are longer than 16 chars. –  Thomas Kwa 2 days ago
    
@ThomasKwa 26, actually, since I have a color calculator :P It technically does work, if you count overwriting part of the input as 'working'. –  M. I. Wright yesterday
    
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. –  Thomas Kwa 10 hours ago

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.

share|improve this answer
    
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 2 days ago
    
@Oebele it prints a warning, but the returned string is unaffected. –  FryAmTheEggman 2 days ago

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.
 ^$
share|improve this answer

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!

share|improve this answer
    
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 2 days ago
    
@anatolyg , Thanks! I did not think that omitting the types would work, but to my surprise, it did. –  Cool Guy 2 days ago

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
share|improve this answer

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.
 ^
share|improve this answer

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);}
share|improve this answer

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."
share|improve this answer
    
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. –  Ismael Miguel 2 days ago
    
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! –  Ismael Miguel 2 days ago

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!

share|improve this answer
    
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. –  FryAmTheEggman 2 days ago

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
                            ^
>
share|improve this answer
    
function(n,x)cat(x,"\n",rep(" ",n-1),"^",sep="") is 48 characters –  Flounderer 2 days ago
    
@Flounderer Thanks for that ... my original idea was similar to that, but I didn't do it as nicely –  MickyT 2 days ago
    
If I am allowed two initial spaces, this works: function(n,x)cat(" ",x,"\n",rep("",n),"^") and saves a few characters –  Flounderer 2 days ago
    
@Flounderer I suspect not. strwrap also has some possibilities but it would probably end up longer. –  MickyT 2 days ago
1  
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 yesterday

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!

share|improve this answer
    
(i-1) -> ~-i –  Dennis 19 hours ago
    
I'm weak with bit operations and math.... Thanks anyway! :-D –  Cool Guy 19 hours ago

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.

share|improve this answer

GolfScript 11

n@~(' '*'^'

Test here.

share|improve this answer

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.

share|improve this answer
    
Nice save Scimonster O_O –  liam_ 2 days ago
    
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 –  Ismael Miguel 2 days ago

Perl 5, 31

sub{"$_[0]
"." "x($_[1]-1)."^"}
share|improve this answer
    
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 2 days ago
    
@Mr.Llama thanks, those are good. –  hobbs 2 days ago

Perl, 45

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

<>=~/(.*), "(.*)"/;print"$2
"." "x($1-1)."^";
share|improve this answer
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 yesterday

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("^");}
share|improve this answer
    
Can you store System.out somwhere? –  Ismael Miguel 2 days ago
    
No need for public. And change IntStream.range(1,i).forEach(j->System.out.print(" ")); to for(;--i>0;)System.out.print(" "); –  Cool Guy 2 days ago
    
@CoolGuy aha! sometimes simple is better –  pallavt yesterday
    
Can you move the s+="\n" inside the for() initialization to use the semicolon there? –  Thomas Kwa yesterday
    
@ThomasKwa 1 byte less –  pallavt 19 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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