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\$ Commented 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
    Commented 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
    Commented 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
    Commented 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.
    Commented Jun 10, 2015 at 14:50

89 Answers 89

39
\$\begingroup\$

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);}
\$\endgroup\$
4
  • 21
    \$\begingroup\$ C can always compete, it just can't always win. ;) \$\endgroup\$
    – Alex A.
    Commented Jun 10, 2015 at 14:47
  • 4
    \$\begingroup\$ @AlexA. <shrug> looks like its winning to me ;-) \$\endgroup\$ Commented Jun 10, 2015 at 15:05
  • 4
    \$\begingroup\$ Save 1 char : f(a,c){printf("%s\n%*c",a,c,94);} \$\endgroup\$
    – Michael M.
    Commented Jun 10, 2015 at 15:17
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Jun 12, 2015 at 14:50
38
\$\begingroup\$

Brainf*ck - 133 bytes

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

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

Hello world!!!
 ^
\$\endgroup\$
4
  • \$\begingroup\$ Welcome to Programming Puzzles and Code Golf! This is a great first post, nice job! :D \$\endgroup\$
    – Alex A.
    Commented Jun 10, 2015 at 14:46
  • \$\begingroup\$ The problem is, no-one knows if this is even valid code, let alone solves the problem :) \$\endgroup\$
    – Simon
    Commented Jun 11, 2015 at 21:46
  • \$\begingroup\$ 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 [->.<] \$\endgroup\$ Commented Jun 11, 2015 at 22:47
  • \$\begingroup\$ @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. \$\endgroup\$ Commented Jun 11, 2015 at 22:54
25
\$\begingroup\$

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);
}
\$\endgroup\$
4
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Ruslan
    Commented Jun 13, 2015 at 20:55
  • \$\begingroup\$ @Ruslan Thanks! Fixed. That was a remnant from a previous version. \$\endgroup\$
    – anatolyg
    Commented Jun 14, 2015 at 7:35
  • 1
    \$\begingroup\$ Why is naked in there? And why is it the first thing I saw? \$\endgroup\$ Commented Mar 28, 2017 at 21:21
  • \$\begingroup\$ It's Microsoft that decided to put the naked in front: msdn.microsoft.com/en-us/library/h5w10wxs.aspx \$\endgroup\$
    – anatolyg
    Commented Mar 29, 2017 at 10:47
21
\$\begingroup\$

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
\$\endgroup\$
3
  • \$\begingroup\$ I think this is the shortest one so far. Well done. \$\endgroup\$
    – Matt Y
    Commented Jun 11, 2015 at 4:51
  • \$\begingroup\$ 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). \$\endgroup\$
    – Jim
    Commented Jun 7, 2017 at 8:32
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Commented Jun 7, 2017 at 13:33
17
\$\begingroup\$

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
    ^
\$\endgroup\$
1
  • \$\begingroup\$ Very creative use of a language not really designed for golfing ;) +1 \$\endgroup\$
    – Matt Y
    Commented Jun 11, 2015 at 4:52
17
\$\begingroup\$

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

Bash, 27

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

Output

$ ./carrot.sh 2 "Lorem ipsum, dollar sit amet."
Lorem ipsum, dollar sit amet.
 ^$ 
\$\endgroup\$
3
  • \$\begingroup\$ Carrot? Also, what's the dollar at the end? \$\endgroup\$
    – Scimonster
    Commented Jun 10, 2015 at 10:43
  • 10
    \$\begingroup\$ The Dollar seems to be the shell's prompt. \$\endgroup\$
    – M.Herzkamp
    Commented Jun 10, 2015 at 11:06
  • 3
    \$\begingroup\$ @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. \$\endgroup\$ Commented Jun 10, 2015 at 15:04
12
\$\begingroup\$

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.
 ^
$
\$\endgroup\$
2
  • 1
    \$\begingroup\$ 2y/1/ /;2s/ $/^/ \$\endgroup\$
    – manatwork
    Commented Jun 10, 2015 at 16:19
  • \$\begingroup\$ @manatwork Good call! \$\endgroup\$ Commented Jun 10, 2015 at 16:24
11
\$\begingroup\$

Python, 29

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

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

\$\endgroup\$
2
  • 2
    \$\begingroup\$ If only rjust wasn't so long... \$\endgroup\$
    – Sp3000
    Commented Jun 10, 2015 at 3:20
  • 12
    \$\begingroup\$ Ah, the tadpole operator. \$\endgroup\$
    – user20574
    Commented Jun 10, 2015 at 11:46
9
\$\begingroup\$

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)}^`}
\$\endgroup\$
9
  • \$\begingroup\$ 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(" ")+" ^". \$\endgroup\$
    – Dennis
    Commented Jun 10, 2015 at 4:00
  • 1
    \$\begingroup\$ 33 bytes: (replace \n with an actual newline) p=(a,b)=>b+`\n${' '.repeat(a-1)}^` \$\endgroup\$
    – nderscore
    Commented Jun 10, 2015 at 4:20
  • \$\begingroup\$ @dennis The indexing works perfectly for me: i.sstatic.net/Tdejc.png \$\endgroup\$
    – adroitwhiz
    Commented Jun 10, 2015 at 4:21
  • \$\begingroup\$ @Dennis Array(1).join(' ') results in an empty string :) \$\endgroup\$
    – nderscore
    Commented Jun 10, 2015 at 4:21
  • \$\begingroup\$ @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.sstatic.net/Tdejc.png \$\endgroup\$
    – adroitwhiz
    Commented Jun 10, 2015 at 4:27
7
\$\begingroup\$

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

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

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.

\$\endgroup\$
4
  • \$\begingroup\$ You'd be better off taking input from Input for the number and Ans for the string. \$\endgroup\$
    – lirtosiast
    Commented Jun 10, 2015 at 1:59
  • \$\begingroup\$ The first one also doesn't work if the program name, assignment, and string combined are longer than 16 chars. \$\endgroup\$
    – lirtosiast
    Commented Jun 10, 2015 at 4:06
  • \$\begingroup\$ @ThomasKwa 26, actually, since I have a color calculator :P It technically does work, if you count overwriting part of the input as 'working'. \$\endgroup\$
    – user39326
    Commented Jun 11, 2015 at 5:02
  • \$\begingroup\$ 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. \$\endgroup\$
    – lirtosiast
    Commented Jun 12, 2015 at 14:39
5
\$\begingroup\$

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

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!

\$\endgroup\$
2
  • \$\begingroup\$ 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>. \$\endgroup\$
    – anatolyg
    Commented Jun 10, 2015 at 8:57
  • \$\begingroup\$ @anatolyg , Thanks! I did not think that omitting the types would work, but to my surprise, it did. \$\endgroup\$
    – Spikatrix
    Commented Jun 10, 2015 at 9:09
4
\$\begingroup\$

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);}
\$\endgroup\$
4
\$\begingroup\$

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

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;
\$\endgroup\$
8
  • \$\begingroup\$ Good to see SO's resident SAS expert here on PPCG. :) \$\endgroup\$
    – Alex A.
    Commented Jun 11, 2015 at 23:11
  • \$\begingroup\$ I'm fairly sure some of the old timers who know DM scripting could best this score... And my cmdmac skills suck. \$\endgroup\$
    – Joe
    Commented Jun 11, 2015 at 23:12
  • \$\begingroup\$ 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. \$\endgroup\$
    – Alex A.
    Commented Jun 11, 2015 at 23:15
  • \$\begingroup\$ Yeah, my SAS ingrained reflexes don't let me use that intuitively I guess :). Thanks. \$\endgroup\$
    – Joe
    Commented Jun 11, 2015 at 23:17
  • \$\begingroup\$ 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. \$\endgroup\$
    – Alex A.
    Commented Jun 11, 2015 at 23:28
3
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$
    – Oebele
    Commented Jun 10, 2015 at 14:43
  • \$\begingroup\$ @Oebele it prints a warning, but the returned string is unaffected. \$\endgroup\$ Commented Jun 10, 2015 at 16:55
3
\$\begingroup\$

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
                            ^
>
\$\endgroup\$
6
  • \$\begingroup\$ function(n,x)cat(x,"\n",rep(" ",n-1),"^",sep="") is 48 characters \$\endgroup\$
    – Flounderer
    Commented Jun 10, 2015 at 22:37
  • \$\begingroup\$ @Flounderer Thanks for that ... my original idea was similar to that, but I didn't do it as nicely \$\endgroup\$
    – MickyT
    Commented Jun 10, 2015 at 22:45
  • \$\begingroup\$ If I am allowed two initial spaces, this works: function(n,x)cat(" ",x,"\n",rep("",n),"^") and saves a few characters \$\endgroup\$
    – Flounderer
    Commented Jun 10, 2015 at 23:09
  • \$\begingroup\$ @Flounderer I suspect not. strwrap also has some possibilities but it would probably end up longer. \$\endgroup\$
    – MickyT
    Commented Jun 10, 2015 at 23:23
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Flounderer
    Commented Jun 11, 2015 at 2:14
3
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\begingroup\$ (i-1) -> ~-i \$\endgroup\$
    – Dennis
    Commented Jun 12, 2015 at 5:20
  • \$\begingroup\$ I'm weak with bit operations and math.... Thanks anyway! :-D \$\endgroup\$
    – Spikatrix
    Commented Jun 12, 2015 at 5:29
3
+50
\$\begingroup\$

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 1 - has a shortcut 1-. \$\endgroup\$
    – Bubbler
    Commented Nov 8, 2020 at 12:51
2
\$\begingroup\$

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

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."
\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Jun 10, 2015 at 14:56
  • \$\begingroup\$ 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! \$\endgroup\$ Commented Jun 10, 2015 at 19:59
2
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Jun 10, 2015 at 16:55
2
\$\begingroup\$

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("^");}
\$\endgroup\$
5
  • \$\begingroup\$ Can you store System.out somwhere? \$\endgroup\$ Commented Jun 10, 2015 at 14:37
  • 2
    \$\begingroup\$ No need for public. And change IntStream.range(1,i).forEach(j->System.out.print(" ")); to for(;--i>0;)System.out.print(" "); \$\endgroup\$
    – Spikatrix
    Commented Jun 10, 2015 at 15:04
  • \$\begingroup\$ @CoolGuy aha! sometimes simple is better \$\endgroup\$
    – pallavt
    Commented Jun 11, 2015 at 5:00
  • \$\begingroup\$ Can you move the s+="\n" inside the for() initialization to use the semicolon there? \$\endgroup\$
    – lirtosiast
    Commented Jun 11, 2015 at 23:31
  • \$\begingroup\$ @ThomasKwa 1 byte less \$\endgroup\$
    – pallavt
    Commented Jun 12, 2015 at 5:03
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Swift, 41

It is disappointing that Swift does not have operator * on Array or String.

{$1+reduce(0..<$0,"\n",{$0.0+" "})+"^"}
\$\endgroup\$
1
  • \$\begingroup\$ For Swift 2.0: {$1+(0..<$0).reduce("\n"){$0.0+" "}+"^"} \$\endgroup\$
    – Kametrixom
    Commented Jul 22, 2015 at 16:22
2
\$\begingroup\$

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!

\$\endgroup\$
3
  • \$\begingroup\$ Spaces no longer compute as NaN! :) \$\endgroup\$
    – Dion
    Commented Aug 7, 2020 at 7:52
  • \$\begingroup\$ Yay! I fixed the code to take in multi digit numbers \$\endgroup\$
    – Razetime
    Commented Aug 7, 2020 at 8:18
  • \$\begingroup\$ 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 \$\endgroup\$
    – Dion
    Commented Aug 7, 2020 at 8:21
2
\$\begingroup\$

Perl 5 -p, 16 bytes

$_.=$"x<>;s; $;^

Try it online!


Perl 5 -p, 16 bytes

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

Try it online!

\$\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.