title: Pointers, pointers, pointers!

text:
# Question
Title: 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 **N**th 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 `return`ed
* 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!

# Answer
# 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);}

```
> 39 votes

# Answer
# Brainf\*ck - 133 bytes

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

```

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

```
Hello world!!!
 ^

```
> 38 votes

# Answer
# 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);
}

```
> 25 votes

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

```
> 21 votes

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

```
> 17 votes

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

```
> 17 votes

# Answer
# Bash, 27

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

```

### Output

```
$ ./carrot.sh 2 "Lorem ipsum, dollar sit amet."
Lorem ipsum, dollar sit amet.
 ^$

```
> 12 votes

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

```
> 12 votes

# Answer
# Python, 29

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

```

Concatenates the string, a newline, `n-1` spaces, and a `^`.
> 11 votes

# Answer
# 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)}^`}

```
> 9 votes

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

```
> 7 votes

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

```
> 7 votes

# Answer
# 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.
> 6 votes

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

```
> 5 votes

# 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!
> 4 votes

# 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);}

```
> 4 votes

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

```
> 4 votes

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

```
> 4 votes

# Answer
# 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`.
> 3 votes

# Answer
# 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!
> 3 votes

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

```
> 3 votes

# Answer
# Forth (gforth), <sup>~~32~~</sup> 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
> 3 votes

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

```
> 2 votes

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

```
> 2 votes

# Answer
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("^");}

```
> 2 votes

# Answer
# 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!
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# Swift, 41

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

```
{$1+reduce(0..<$0,"\n",{$0.0+" "})+"^"}

```
> 2 votes

# Answer
# 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!
> 2 votes

# Answer
# Python 3, 29 bytes 31

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

```

Try it online!

A Plain Comprehensible snippet, used function lambda function and concatenation
> 2 votes

# Answer
# Perl 5 `-p`, 16 bytes

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

```

Try it online!

---

# Perl 5 `-p`, 16 bytes

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

```

Try it online!
> 2 votes

# Answer
# Integral, ~~7~~ 6 Bytes

```
▼8gv^►

```

Try it!

*-1 thanks to @petStorm*
> 2 votes

# Answer
# 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!
> 2 votes

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

```
> 2 votes

# Answer
# Perl 5, 31

```
sub{"$_[0]
"." "x($_[1]-1)."^"}

```
> 1 votes

# Answer
## F#, 31 characters

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

```
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# GolfScript 11

```
n@~(' '*'^'

```

Test here.
> 1 votes

# 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.
> 1 votes

# Answer
# Perl, 45

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

```
<>=~/(.*), "(.*)"/;print"$2
"." "x($1-1)."^";

```
> 1 votes

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

```
> 1 votes

# Answer
# C, ~~60~~ 49

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

```

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

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

```
> 1 votes

# Answer
# 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'

```
> 1 votes

# Answer
# J, 19

Including parentheses!

The verb:

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

```

Use:

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

```
> 1 votes

# Answer
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.
> 1 votes

# Answer
## 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.
> 1 votes

# Answer
## Common Lisp, ~~40~~ 35

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

```

-5 bytes thanks to *PrzemysławP*.
> 1 votes

# Answer
# Haskell, 30 bytes

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

```
> 1 votes

# Answer
# 05AB1E, 7 bytes

```
'^I<ú‚»

```

Try it online!

**Explantion**

```
'^       # push caret
  I<ú    # prepend with input-1 spaces
     ‚   # pair with second input
      »  # join by newline

```
> 1 votes

# Answer
# 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 votes

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

```
> 1 votes

# Answer
## 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.
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# Keg, 9 bytes

```
᠀
¿; ℠*\^

```

Try it online!
> 1 votes

# Answer
# Rust, 32 bytes

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

```

Try it online
> 1 votes

# Answer
# Brain-Flak -A, 116 bytes

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

```

Try it online!
> 1 votes

# Answer
# , 9 bytes

```
,:'^'{.~-

```

Try it online!

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

```
> 1 votes

# Answer
# Zsh `-F`, 20 bytes

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

```

Try it online!

Method stolen from the C answer.
> 1 votes

# Answer
# Jelly, 7 bytes

```
ṄṛṬị⁾^

```

Try it online!

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 "^ "

```
> 1 votes

# Answer
# Vyxal `o`, ~~6~~ 5 bytes

```
,‹\^꘍

```

Try it Online!
> 1 votes

# Answer
# 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),'^';

```
> 0 votes

# Answer
# 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.
> 0 votes

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

```
> 0 votes

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

```
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
# 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.
> 0 votes

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

```
> 0 votes

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

```
> 0 votes

# Answer
# Jelly, ~~8~~ 7 bytes

```
Ṅ⁶ṁ”^⁹¦

```

Try it online!

That ~~`dollar`~~`dolor` makes me laugh!!

Thanks to @Dennis for -1.
> 0 votes

# Answer
# 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 `#` spaces
* `r^` 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.
> 0 votes

# Answer
# SmileBASIC, 26 bytes

```
INPUT N,S$?S$?" "*(N-1);"^

```

1-indexed arrow adds 4 bytes...
> 0 votes

# Answer
# 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;
}

```
> 0 votes

# Answer
# Gol\>\<\> (Golfish), 14 bytes

```
`^IMR` aTiEHot

```

Try it here.

**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

```
> 0 votes

# Answer
# tcl, 47

```
gets stdin s
puts $s\n[format %[gets stdin]s ^]

```

demo
> 0 votes

# Answer
# , 6 bytes

```
ïÀá r^

```

Try it online!
> 0 votes

# Answer
# Braingolf, 25 bytes

```
VV"^ "R3-M#
&@v[v.Rv]v<&@

```

Try it online!
> 0 votes

# Answer
# Ruby 2.7, 24 bytes

```
x=->{_1+'
'+" "*~-_2+?^}

```
> 0 votes

# Answer
# PowerShell Core, ~~29~~ 27 bytes

```
$args[1]
'^'|% *ft $args[0]

```

Try it online!

-2 bytes thanks to Mazzy!
> 0 votes

# Answer
# Japt `-R`, 5 bytes

-1 byte if we can take the string input as a singleton array.

```
·p^ùV

```

Try it
> 0 votes

# Answer
# 05AB1E, 6 bytes

```
,'^ú¦,

```

Try it online!

```
,       # output with trailing newline...
        # implicit input
     ,  # output with trailing newline...
 '^     # "^"...
   ú    # with...
        # implicit input...
    ¦   # minus 1...
   ú    # spaces in front

```
> 0 votes

# Answer
# Haskell, 38 bytes

```
n!s=s++'\n':g n
g 1="^"
g n=' ':g(n-1)

```

Try it online!
> 0 votes

# Answer
# Red, 35 bytes

```
func[n s][prin[s lf pad/left"^^"n]]

```

Try it online!
> 0 votes

# Answer
# Stax, 5 bytes

```
P'^)p

```

Run and debug it
> 0 votes

# Answer
# APL (Dyalog Classic), 14 bytes

```
{↑⍺((-⍵)↑'^')}

```

Try it online!

A port of @FrownyFrog J answer
> 0 votes

# Answer
# Thunno 2 `N`, 6 bytes

```
⁻ṣ'^+,

```

Attempt This Online!

#### Explanation

```
⁻ṣ'^+,  # Implicit input
⁻ṣ      # First input decremented spaces
  '^+   # With a "^" appended
     ,  # Paired with the second input
        # Implicit output joined by newlines

```
> 0 votes

# Answer
# Java (JDK), 32 bytes

Speaking of which, the Java answer of this problem needed a little upgrade :)

```
a->b->b+"\n"+" ".repeat(a-1)+"^"

```

Try it online!
> 0 votes

# Answer
# Go, 79 bytes

```
import."strings"
func f(s string,n int)string{return s+`
`+Repeat(" ",n-1)+"^"}

```

Attempt This Online!
> 0 votes

---
Tags: code-golf
---


title: Generate ;# code

text:
# Question
Title: Generate ;# code
Related to: Make a ;# interpreter

In the above linked challenge the task was to create an interpreter for the esoteric language `;#`.

## The `;#` language

The language has exactly two commands: `;` and `#` (all other characters are ignored by the interpreter):

`;`: Increment the accumulator

`#`: Modulo the accumulator by 127, print the corresponding ASCII character and reset the accumulator to 0.

## Challenge

Because I am lazy but still want to test some more testcases, I need a program or function which converts plain text to `;#` code.

## Input

The input is a string, taken either as argument or through stdin. It will only contain printable ASCII characters and newlines.

## Output

The output is the generated `;#` program by returning, or printing to stdout. As long as the program is valid, it may contain excess characters other than `#` and `;` as all other characters are ignored.

## Examples

```
Input: Hello, World!
Output: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#

Input: ABC
Output: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#

Input: ;#
Output: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#

```

## Leaderboard

```
var QUESTION_ID=122139,OVERRIDE_USER=73772;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 54 votes
# ;#+, 61 bytes

*Outgolfed by Conor O'Brien*

```
;;;;;;;(~;;;;;~-;-)~>:~;;;;(~;;;;;;~-;-)~>~-*((;~<#~):<#-:-*)

```

Try it online!

Note that the input has a trailing null byte.

# Answer
> 36 votes
# ;#+, 40 bytes

```
;;;;;~+++++++>~;~++++:>*(-(;~<#~):<#-*:)

```

Try it online! Input is terminated with a null byte.

## Explanation

The code is split into two parts: generation and iteration.

## Generation

```
;;;;;~+++++++>~;~++++:>

```

This puts the constants `;` and `#` into memory as such:

```
;;;;;~+++++++>~;~++++:>
;;;;;                     set A to 5
     ~                    swap A and B
      +++++++             add B to A 7 times
                          (A, B) = (5*7, 5) = (35, 5)
             >            write to cell 0
              ~           swap A and B
               ;          increment A
                ~         swap A and B
                          (A, B) = (35, 6)
                 ++++     add B to A 4 times
                          (A, B) = (59, 6)
                     :    increment cell pointer
                      >   write to cell 1

```

## Iteration

```
*(-(;~<#~):<#-*:)
*                    read a character into A
 (            * )    while input is not a null byte:
  -                  flip Δ
   (     )           while A != 0
    ;                decrement
     ~               swap A and B
      <              read ";" into A
       #             output it
        ~            swap A and B
           :         decrement cell pointer
            <        read "#" into A
             #       output it
              -      flip Δ
               *     take another character from input
                :    increment cell pointer

```

# Answer
> 13 votes
# Jelly, ~~10~~ ~~8~~ 7 bytes

```
O”;ẋp”#

```

Try it online!

```
O”;ẋp”#  Main Link
O        Map over `ord` which gets the codepoint of every character
 ”;ẋ     Repeat ';' the required number of times
     ”#  '#'
    p    Cartesian Product; this puts a '#' at the end of each element in the array

Implicit Output shows as a single string

```

-2 bytes thanks to @Emigna
-1 byte thanks to @Dennis

# Answer
> 13 votes
# brainfuck, ~~59~~ ~~54~~ 33 bytes

-21 bytes with KSab's bfbrute tool.

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

```

Try it online!

# Answer
> 11 votes
# GS2, 6 bytes

```
■•;2•#

```

Try it online!

### Reversible hexdump (xxd)

```
0000000: ff 07 3b 32 07 23                                ■•;2•#

```

### How it works

```
■       Map the rest of the program over  all code points C of the input.
 •;         Push ';'.
   2        Multiply; repeat ';' C times.
    •#      Push '#'.

```

# Answer
> 10 votes
# Taxi, 779 bytes

```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 1 r 1 l 4 r 1 l.[c]Switch to plan "e" if no one is waiting.Pickup a passenger going to Charboil Grill.Go to Charboil Grill:n 1 l 3 l 3 l.Pickup a passenger going to The Underground.Go to Writer's Depot:w 1 r.[p]; is waiting at Writer's Depot.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.Go to The Underground:n 1 r 1 l.Switch to plan "n" if no one is waiting.Pickup a passenger going to The Underground.Go to Zoom Zoom:n 3 l 2 r.Go to Writer's Depot:w.Switch to plan "p".[n]# is waiting at Writer's Depot.Go to Writer's Depot:n 3 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.Go to Chop Suey:n 1 r 1 l 4 r 1 l.Switch to plan "c".[e]

```

Try it online!

Ungolfed:

```
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to Chop Suey.
Go to Chop Suey: north 1st right 1st left 4th right 1st left.
[c]
Switch to plan "e" if no one is waiting.
Pickup a passenger going to Charboil Grill.
Go to Charboil Grill: north 1st left 3rd left 3rd left.
Pickup a passenger going to The Underground.
Go to Writer's Depot: west 1st right.
[p]
; is waiting at Writer's Depot.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.
Go to The Underground: north 1st right 1st left.
Switch to plan "n" if no one is waiting.
Pickup a passenger going to The Underground.
Go to Zoom Zoom: north 3rd left 2nd right.
Go to Writer's Depot: west.
Switch to plan "p".
[n]
# is waiting at Writer's Depot.
Go to Writer's Depot: north 3rd left 2nd left.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.
Go to Chop Suey: north 1st right 1st left 4th right 1st left.
Switch to plan "c".
[e]

```

Explanation:

```
Pick up stdin and split it into characters.
Covert each character to ASCII.
Print ";" as you count down from that ASCII to zero.
Print "#".
Pickup the next character and repeat until done.

```

# Answer
> 10 votes
# Brainfuck, 43 bytes

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

```

Null byte terminates the program.

## Explanation

```
+[+[<]>->++]          59 (semicolon) location 5
--[>--<+++++++]>-       35 (hash) location 7
<,[                     input location 6
    [   while input byte not 0
        <.>     print semicolon
        -       decrement input byte
    ]
    >.< print hash
,]  loop while input not null

```

# Answer
> 9 votes
# 05AB1E, 8 bytes

```
Ç';×'#«J

```

Try it online!

**Explanation**

```
Ç          # convert each input char to its ascii value
 ';×       # repeat ";" those many times
    '#«    # append a "#" to each run of semi-colons
       J   # join to string

```

# Answer
> 8 votes
# Python 3, 39 bytes

```
[print(";"*ord(s)+"#")for s in input()]

```

Try it online!

# Answer
> 5 votes
## \>\<\>, 22 bytes

```
i:0(?;\"#"o
o1-:?!\";"

```

Try it online, or at the fish playground

Input is STDIN, output is STDOUT. In \>\<\>, characters and ASCII codes are the same thing, so all we need to do is read a character, print `";"` and decrement the character until it's 0, then print `"#"` and loop until there's no more input left.

# Answer
> 5 votes
# F#, 79 bytes

```
let c i=System.String.Join("#",Seq.map(fun c->String.replicate(int c)";")i)+"#"

```

Try it online!

# Expanded

```
// string -> string
let convert input =
    System.String.Join(
        "#",      // join the following char seq with "#"
        input     // replicate ";" n times where n = ASCII value of char c
        |> Seq.map (fun c-> String.replicate (int c) ";")
    ) + "#" // and add the last "#" to the output

```

convert takes the input string and outputs a ;# program

## Usage

```
convert "Hello, World!" |> printfn "%s"
convert "ABC" |> printfn "%s"
convert ";#" |> printfn "%s"

```

# Answer
> 5 votes
# Python 2 - 36 bytes

```
for i in input():print';'*ord(i)+'#'

```

**Try it online!**

# Answer
> 5 votes
# PowerShell, ~~29~~ ~~27~~ 25 bytes

```
$args|% t*y|%{';'*$_+'#'}

```

Pretty straightforward. Takes input as command-line argument. Output is a valid ;# program that prints the requested text.

# Answer
> 4 votes
# JavaScript, ~~55~~ ~~54~~ ~~51~~ ~~50~~ 48 bytes

```
s=>1+[...s].map(c=>";".repeat(Buffer(c)[0])+"#")

```

Try it online

* 1 byte saved thanks to Neil.

---

## Alternatives

If we can take input as an array of individual characters then 5 bytes can be saved.

```
a=>1+a.map(c=>";".repeat(Buffer(c)[0])+"#")

```

If we can also output as an array then 2 more bytes can be saved.

```
a=>a.map(c=>";".repeat(Buffer(c)[0])+"#")

```

# Answer
> 4 votes
# brainfuck, 47 bytes

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

```

Try it online!

See also: ovs's answer, which takes a similar approach, but with a different method of generating constants and a different cell layout.

---

## Explanation:

This challenge lines up with the brainfuck spec pretty well, which means the solution is essentially trivial. Brainfuck takes input as ASCII values, which is exactly what ;# need to output as.

The schematic for transpiling is simple: Generate the ASCII value for `;` and `#`, print `;` equal to the ASCII value of the input character, print `#`, repeat for every input.

```
+++++++[-             7
         >++++++++       * 8 = 56
         >+++++<<        * 5 = 35 (#)
       ]>+++<                  56 + 3 = 59 (;)
,[                    Input into first cell
  [>.<-]              Print ;'s equal to ASCII input
  >>.<<,              Print one #
 ]                    End on EOF

```

# Answer
> 4 votes
## Mathematica, 49 bytes

```
StringRepeat[";",#]<>"#"&/@ToCharacterCode@#<>""&

```

## Explanation

Converts the input string to a list of character codes, then `Map`s the function `StringRepeat[";",#]<>"#"&` over the list, then `StringJoin`s the result with the empty string.

# Answer
> 3 votes
# Befunge-98 (FBBI), ~~23~~ ~~17~~ 10 bytes

-5 bytes thanks to Jo King.

```
"#@~k:*k,;

```

Try it online!

# Answer
> 3 votes
# Aceto, 19 bytes

Since there's an interpreter in Aceto, I thought there outta be an Aceto answer to this challenge as well. It fits neatly in a 2rd order Hilbert curve:

```
\n;*
'o'p
`!#'
,dpO

```

First of all, we read a single character (`,`) and duplicate and negate it to test whether it is a newline (`d!`, when reading a newline, an empty character is normally pushed on the stack). I then use what I think is a pretty clever trick to handle the newline case compactly:

``'\n`

If the value on the stack is `True` (we read a newline), that code means: *do* (```) put a character literal on the stack (`'`), which is a newline: `\n`.

If the value on the stack is `False` (we didn't read a newline), that code means: *don't* (```) read a character literal (`'`). That means the next character is executed as a command. Fortunately, a backslash escapes the next command (it makes it so that it doesn't get executed), so `n` doesn't print a newline (which is what `n` usually does).

The rest of the code is straightforward; we convert the character on the stack to the integer of its unicode codepoint (`o`), we push a literal semicolon (`';`), multiply the number with the string (`*`, like in Python), `p`rint the result, push a literal (`'`) `#`, `p`rint it too, and go back to the `O`rigin.

Run with `-F` if you want to see immediate results (because buffering), but it works without, too.

# Answer
> 3 votes
# Perl, 24 bytes

```
s/./";"x(ord$&)."#"/ges

```

Run with `perl -pe`.

Alternative solution:

```
say";"x ord,"#"for/./gs

```

Run with `perl -nE`.

# Answer
> 3 votes
# Fourier, 19 bytes

```
$(I(`;`&j)`#`0~j&i)

```

**Try it on FourIDE!**

To run, you must enclose the input string in quotation marks.

***Explanation pseudocode***

```
While i != Input length
    temp = pop first char of Input
    While j != Char code of temp
        Print ";"
        Increment j
    End While
    Print "#"
    j = 0
    Increment i
End While

```

# Answer
> 3 votes
# Solace, 11 bytes

Yay, new languages.

```
';@jx{'#}Ep

```

### Explanation

```
';           Push the code point of ';' (59).
  @j         Push the entire input as a list of code points.
    x        For each code point in the input, repeat 59 that many times.
     {  }E   For each resulting list of 59s:
      '#      Push the code point of '#' (35).
          p  Flatten and print as unicode characters.

```

# Answer
> 3 votes
# R, ~~59~~ 56 bytes

```
for(x in utf8ToInt(scan(,'')))cat(rep(';',x),'#',sep="")

```

Try it online!

# Answer
> 2 votes
# Actually, 11 bytes

```
O⌠';*'#o⌡MΣ

```

Try it online!

Explanation:

```
O⌠';*'#o⌡MΣ
O            convert string to list of ASCII ordinals
 ⌠';*'#o⌡M   for each ordinal:
  ';*          repeat ";" that many times
     '#o       append "#"
          Σ  concatenate

```

# Answer
> 2 votes
# APL (Dyalog), 18 bytes

```
'#',¨⍨';'⍴¨⍨⎕UCS

```

Try it online!

`⎕UCS` Convert to Unicode code points

`';'⍴¨⍨` use each code point to reshape ( = *Rho**R*; *R*eshape) a semicolon

`#',¨⍨` append a hash to each string

# Answer
> 2 votes
# Ruby, ~~28~~ 25 bytes

24 bytes, plus the `-n` command line switch to repeatedly operate on `stdin`.

```
$_.bytes{|b|$><<?;*b+?#}

```

3 bytes saved (and output corrected on newlines!) thanks to manatwork.

# Answer
> 2 votes
# PHP, 54 Bytes

```
for(;$o=ord($argn[$i++]);)echo str_repeat(";",$o)."#";

```

Try it online!

# Answer
> 2 votes
## Alice, 12 bytes

```
'#I.h%&';d&O

```

Try it online!

### Explanation

```
'#    Push 35, the code point of '#'.
I     Read a code point C from STDIN. Pushes -1 at EOF.
.h%   Compute C%(C+1). For C == -1, this terminates the program due to division
      by zero. For C > -1, this just gives back C, so it does nothing.
&';   Pop C and push that many 59s (the code point of ';').
d     Push the stack depth, which is C+1.
&O    Print that many code points from the top of the stack.
      The IP wraps around to the beginning and another iteration of this
      loop processes the next character.

```

# Answer
> 2 votes
# PHP, 48 bytes

```
for(;$c?:~$c=~ord($argn[$i++]);)echo";#"[!++$c];

```

# Answer
> 2 votes
# jq, 30 characters

(26 characters code + 4 characters command line options)

```
explode|map(";"*.+"#")|add

```

Sample run:

```
bash-4.4$ jq -Rr 'explode|map(";"*.+"#")|add' <<< 'Hello, World!' | jq -Rrj '[scan(".*?#")|gsub("[^;]";"")|length%127]|implode'
Hello, World!

```

On-line test

# Answer
> 2 votes
# Pyth, 10 bytes

```
sm_+\#*\;C

```

Try it!

# Answer
> 2 votes
# Röda, 24 bytes

```
{chars|[";"*ord(_),"#"]}

```

Try it online!

# Answer
> 2 votes
# Minecraft Functions (18w11a, 1.13 snapshots), 861 bytes

Uses four functions

a

```
scoreboard objectives add a dummy
scoreboard objectives add b dummy
scoreboard objectives add c dummy
scoreboard objectives add d dummy
scoreboard objectives add e dummy
scoreboard players set x a 0
scoreboard players set x b 0
scoreboard players set x c 1000
scoreboard players set x d 0
scoreboard players set x e 1
function b
function c

```

b

```
scoreboard players operation x b = x i
scoreboard players operation x b %= x c
scoreboard players operation x a *= x c
scoreboard players operation x a += x b
scoreboard players operation x i /= x c
execute if score x i > x d run function b

```

c

```
scoreboard players operation x i = x a
scoreboard players operation x i %= x c
function d
tellraw @s "#"
scoreboard players operation x a /= x c
execute if score x a > x d run function c

```

d

```
tellraw @s ";"
scoreboard players operation x i -= x e
execute if score x i > x d run function d

```

"Takes input" from a scoreboard objective named `i`, create it with `/scoreboard objectives add i dummy` and then set it using `/scoreboard players set x i 5`. Then call the function using `/function a`

Limitations:

Minecraft does not really support strings, or input, or much of anything really, so due to language limitations, input is passed to the `i` scoreboard, as ascii values, so "ABC" would be `65066067`.

However, due to *another* limitation, scoreboard objectives can only store numbers with 10 or less digits, so all strings must be passed in chunks of three letters. For example, "Hello, World!" must be converted to `'072101108', '108111044', '032087111', '114108100', '033'` and the function must be called for each of these numbers. Hope that counts as a valid input method.

This python function will convert the strings, it does not change the string in any way, other than getting the ascii representation,

```
def convert(string):
    line = ''.join('{:0>3}'.format(ord(c)) for c in string)
    print([line[i:i+9] for i in range(0, len(line), 9)])

```

Minecraft may not have been the best choice of language.

# Answer
> 2 votes
# Brachylog, 15 bytes

```
ạ{;";"j₍,"#"}ᵐc

```

Try it online!

```
ạ                   % Convert the string into its ascii codes
 {          }ᵐ      % map this over each resulting code:
  ;";"j₍            %   repeat ";" that many times
        ,"#"        %   tack on a "#" at the end of that
              c     % at the end of the map, concatenate the results of the map

```

# Answer
> 2 votes
# Brain-Flak, 94 bytes

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

```

Try it online!

# Answer
> 2 votes
# , 48 bytes

```
cat(strrep(';',utf8ToInt(scan(,''))),'',sep='#')

```

Try it online!

Outputs 'pure' ;# code with no other characters.

---

# , 43 bytes

```
paste(strrep(';',utf8ToInt(scan(,''))),'#')

```

Try it online!

Outputs 'dirty' ;# code with various other characters (\[,\],0-9, ,") that are all ignored.

# Answer
> 2 votes
# Rockstar, ~~216~~ ~~201~~ ~~191~~ 175 bytes

This started out a lot shorter until I remembered that we had to handle line breaks in the input - each line in Rockstar is a separate input - and *then* discovered, in what I can only assume to be a bug, that the space character passes equality tests with the empty string `\t`, `\n` & `0`.

```
listen to S
O's""
while S
X's0
while S at X
Y's31
C's-1
until C is S at X
build Y up
cast Y into C

let O be+";"*Y+"#"
build X up

listen to S
if S
let O be+";"*10+"#"

say O

```

Try it here (Code will need to be pasted in)

This 151 byte version includes a newline after each `#`, which, although being valid in ;# as they're simply ignored, would fail when passed back to my Rockstar interpreter.

```
listen to S
while S
X's0
while S at X
Y's31
C's-1
until C is S at X
build Y up
cast Y into C

say ";"*Y+"#"
build X up

listen to S
if S
say ";"*10+"#"

```

# Answer
> 2 votes
# A0A0, 103 057 102 945 bytes

https://gist.github.com/stefvanschie/a32e23f45553fc19b79b9cb7159c7e04

(I think putting that many characters into a codebox here is a bit too much.)

Yes, I'm serious. A0A0 has loops, but this solution would require nested loops (a loop for reading a character and within that a loop for printing the right amount of semicolons). I'm not even certain if nested loops are possible at all. I have a solution that can display the correct code for a single character, since that doesn't require any nested loops in only 143 bytes. If anyone knows how to do this, please let me know. The code for a single character is also on the gist.

The reason this is still possible is by using a dirty work-around: write code for every single character, then jump to that spot for the right character. Since there are only a finite amount of printable ASCII characters and you can't go above character 126 because of the modulo 127, this is possible. This is where the byte count comes from. I generated almost 600 lines of code that does exactly that.

The important part is at the top

```
A0A0
A0C3G1G1G1G1A0
A0I1D8M5V0G0A0
A0A1G-3G-3G-3G-3A0
G-3

```

Most of this serves as an infinite loop, but the code in between `A0` on the third line is actual important code.

```
I1D8M5V0G0
I1         ; reads a character and stores it on the next operand as its ascii value
  D8       ; subtracts 8 from the operand
    M5     ; multiply the operand by 5
      V0   ; the operand, value is put on the next instruction
        G0 ; set by the operand, jumps this amount of lines down

```

On every correct line you can find a loop with the right amount of prints for each semicolon `P59` and hash tag `P35`, as well as another jump to jump back to this input loop.

Rev: Improved positioning of the character prints

# Answer
> 1 votes
## CJam, ~~12~~ 10 bytes

```
q{i';*'#}%

```

Explanation:

```
q           e# Read input
 {          e# For each character in the input:
  i         e#  Get code point
   ';*      e#  Repeat ';' that many times
      '#    e#  Add a '#'
        }%  e# End for
e# Implicit output

```

# Answer
> 1 votes
# Japt, ~~10~~ 9 bytes

```
c@'#i';pX

```

Try it

---

## Explanation

```
     :Implicit input of string U
c@   :Map over the codepoints of characters in the string
'#   :"#"
i    :Prepend
';   :";"
p    :repeated
X    :The current codepoint times

```

# Answer
> 1 votes
# PowerShell, 36 Bytes

```
-join([char[]]"$args"|%{';'*$_;'#'})

```

just prints `;`s and then a `#`

# Answer
> 1 votes
# Wolfram Mathematica, 69 bytes

```
FromCharacterCode[Flatten[{Table[59,{,#}],38}&/@ToCharacterCode[x]]]

```

`Table[59,{,#}]` is a short replacement for `ConstantArray[]`.

# Answer
> 1 votes
# C, ~~61~~ 57 bytes

```
c;f(){for(;~(c=getchar());puts("#"))while(c--)puts(";");}

```

Hope you don't mind a newline after every character :P However, this is allowed, as it doesn't affect the program, since all bytes aside from `;#` are ignored.

# Answer
> 1 votes
# shortC, 27 bytes

```
c;AO;~(c=G);J"#"))Wc--)J";"

```

# Answer
> 1 votes
# Cubix, 19 bytes

*-5 bytes thanks to @MickyT!*

```
i.#';UoU^!.$U@?(';o

```

on a cube:

```
    i .
    # '
; U o U ^ ! . $
U @ ? ( ' ; o .
    . .
    . .

```

this version is much cleverer than the prior one (my version) with moving the instruction pointer around, using `U` (left-hand u-turn) and the way the adjacencies on the cube to loop and produce the correct output. Explanation to follow.

### Old Version, 24 bytes:

```
..@.;i?...>;'(/!.;o;W'.#

```

Try it online! and Watch it online! (the latter might be really slow)

Since this question had a relatively simple I/O scheme, I figured this would be a good fit for a Cubix solution. I still spent a few days trying to solve it, though. The breakthrough was when I tried using `!`, which skips the next instruction if the top of the stack is truthy (not zero, I think), enabling something like a `while` loop.

Cubified:

```
    . .
    @ .
; i ? . . . > ;
' ( / ! . ; o ;
    W '
    . #

```

The instruction pointer starts at the top left corner of the leftmost face, pointing east. Here's the code:

Outer loop:

```
; - pop the top item off the stack. does nothing at the beginning since the stack is empty.
i - read in the ascii character as an integer. Reads -1 at end of input.
? - turns right if the top of the stack is positive, and left if negative.
@ - if negative (end of input), ends the program
/ - mirrors the direction pointer (swapping S<->W and N<->E), entering the inner loop

```

Inner loop:

```
( - decrements the top of the stack (the ascii value of the input)
' - pushes the next char
; - the semicolon
o - outputs as a char
; - pops the top of the stack
! - ignores the next instruction if the top of the stack is not zero

```

then when the appropriate number of `;` have been printed,

```
/ - the IP is moving W, so it now switches S
W - move the IP left
' - push the next char
# - pushes this char
o - prints #
> - points the IP east
; - pop the top of the stack

```

and then returns to the top of the outer loop.

# Answer
> 1 votes
# Ly, 18 bytes

```
&ir[[";"o1-]"#"op]

```

Try it online!

# Answer
> 1 votes
# Braingolf, 11 bytes

```
&([#;]##)&@

```

Try it online!

Ooh, moderately golfy

# Answer
> 1 votes
# Befunge-93, ~~31~~ ~~28~~ 26 bytes

Edit: -2 bytes thanks to James Holderness

```
#;"~1+:!#@_>1#\-#,: #\_$$,

```

Try it Online

### How it works

```
#;"          Adds # and ; to the stack
   ~1+:!#@_  Gets the input and dupes it. Ends if the input is eof
           >1#\-#,: #\_ Prints a semi-colon until the input byte reaches 0
                       $$, Prints the ending hash and loops back round

```

# Answer
> 1 votes
# Pushy, 12 bytes

```
@$:59'.;35'.

```

**Try it online!**

This prints each character of the `;#` code on a newline. To condense the code, simply prepend `N` to the program to remove the printing delimiter.

# Answer
> 1 votes
# Kotlin, 49 bytes

```
{it.map{('a'-97..it).map{print(';')}
print('#')}}

```

## Beautified

```
        {
            it.map {
                ('a'-97..it).map { print(';') }
                print('#')
            }
        }

```

## Test

```
import java.io.ByteArrayOutputStream
import java.io.PrintStream

/**
 * @author James Tapsell
 */
var o: (String) -> Unit =
{it.map{('a'-97..it).map{print(';')}
print('#')}}

data class Test(val input: String, val output: String)

val tests = listOf(
        Test("Hello, World!", ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#"),
        Test("ABC", ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#"),
        Test(";#", ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#")
)

fun main(args: Array<String>) {
    tests.forEach {
        val out = ByteArrayOutputStream()
        System.setOut(PrintStream(out))
        o(it.input)
        val text = String(out.toByteArray())
        if (text != it.output) {
            throw AssertionError()
        }
    }
}

```

## TIO

TryItOnline

# Answer
> 1 votes
# Canvas, 5 bytes

```
ｃ;×#］

```

Try it here!

Explanation:

```
{    ] map over the characters of the input
 c     convert the character to its unicode codepoint
  ;×   repeat ";" that many times
    #  push "#"

```

# Answer
> 1 votes
# Add++, 18 bytes

```
L^,€O59C€*"#"€Ω+BF

```

Try it online!

# Answer
> 1 votes
# Stax, <sup>~~7~~</sup> 6 bytes

```
ç`5≡Tf

```

Run and debug it

# Answer
> 1 votes
# Vyxal `Ks`, ~~8~~ ~~7~~ 6 bytes

*~~-1~~ -2 thanks to Aaron Miller*

```
\;*\#+

```

Try it Online!

```
\;*\#+    # Full program
          # Vectorized: Replace each...
          # (K flag) ordinal character in (implicit) input...
\;        # with the character `;`...
  *       # repeated that many times, and...
   \#+    # add the character `#`
          # (s flag) Concatenate results and output

```

# Answer
> 1 votes
# Excel, 56 bytes

```
=CONCAT(REPT(";",CODE(MID(A1,SEQUENCE(LEN(A1)),1)))&"#")

```

Could be 8 bytes shorter to output an array of cells ending with #.

## VBA (immediate window), 73 bytes

```
d="":for i=1to len([a1]):d=d &string(asc(mid([a1],i,1)),";") &"#":next:?d

```

# Answer
> 0 votes
# C (72 bytes)

```
main(c){while((c=getchar())!=-1){while(c--)putchar(';');putchar('#');}}

```

# Answer
> 0 votes
# Gema, 28 charcters

```
?=@repeat{@char-int{?};\;}\#

```

Sample run:

```
bash-4.4$ gema '?=@repeat{@char-int{?};\;}\#' <<< 'Hello, World!' | gema '\A=@set{a;0};\;=@incr{a};\#=@int-char{@mod{$a;127}}@set{a;0};?='
Hello, World!

```

# Answer
> 0 votes
## QBIC, 36 bytes

```
[_l;||[asc(_sA,a,1|)|Z=Z+@;`]Z=Z+@#`

```

Explanation

```
[_l;||        FOR a = 1 to LEN(A$) # A$ is read from the vmd line
[asc(...)     FOR b = 1 to the ASCII value of
   _sA,a,1|     The next char of A$
Z=Z+@;`       Add the increment instruction to Z$
]         NEXT increment instruction
Z=Z+@#`       When all incrementers are added, issue a print-command
              NEXT for the outer FOR loop is added inplicitly at EOF
              Z$ is printed implicitly at EOF

```

# Answer
> 0 votes
# Go, 91 bytes

```
import(."fmt";."strings")
func f(s string){for _,c:=range s{Print(Repeat(";",int(c))+"#")}}

```

Try it online!

## Explanation

```
import( . "fmt"                     // fmt import to print stuff out
        . "strings"                 // strings import for string manipulation
)                                   // the dots import into the global namespace

func transpile(str string) {        // function that takes a string argument
    for _, char := range str {      // iterate over the runes (characters) in str
        Print(                      // print x without newline where x is...
              Repeat(";",           // ...";" repeated y times where y is...
                     int(char)) +   // ...the ASCII integer of the rune and...
              "#")                  // ..."#" to end it
    }
}

```

# Answer
> 0 votes
# Bean, 48 bytes

```
00000000: 53d0 80c3 cf53 d080 a078 2080 7b23 8100  SÐ.ÃÏSÐ. x .{#..
00000010: 0020 8088 40a0 5f4c d3d0 80a3 8101 2080  . ..@ _LÓÐ.£.. .
00000020: b553 5080 a05f 2080 ad8b 2381 020a 3b23  µSP. _ ...#...;#

```

Try it online!

### Equivalent JavaScript (ES6):

```
[..._.join("\n")].map((c)=>";".repeat(c.charCodeAt())+"#");

```

### Explanation

Taking multiline standard input as an array of string lines in `_`, it first joins them with `\n` and spreads the resulting string into an array of characters, which is then mapped like in @Shaggy's answer.

The difference is, it outputs the raw array of `;#` strings that represent each character, but because the language specification will ignore all of the following characters: `[]' ,` this is valid behavior.

# Answer
> 0 votes
# C# 54 + 18 = 72 Bytes

```
using System.Linq;
s=>string.Join("",s.Select(c=>new string(';',c)+"#"));

```

### Ungolfed full program and explanation

```
using System.Linq;

class P
{
    static void Main()
    {
        System.Func<string, string> f =
            s => string.Join("",       //4. Join the results separated by an empty string and implicitly return
                s.Select(c =>          //1. For each character in the input
                    new string(';', c) //2. Implicitly convert the character to an int with the ASCII-Code and create a new string with that many ;
                    + "#"));           //3. Add a #

        System.Console.WriteLine(f(";#"));
        System.Console.WriteLine(f("ABC"));
        System.Console.WriteLine(f("Hello World!"));
    }
}

```

# Answer
> 0 votes
# Husk, ~~13~~ 10 bytes

```
ṁȯ`:'#R';c

```

Try it online!

### Ungolfed/Explained

```
ṁȯ          -- map function and concatenate result
         c  --   ASCII order of element times
      R';   --   repeat ';' and
  `:'#      --   append '#'

```

# Answer
> 0 votes
# Haskell, ~~50~~ 32 bytes

This is a direct port of my Husk answer:

```
((\n->(';'<$['\1'..n])++"#")=<<)

```

Try it online!

Thanks @Laikoni for saving me 18 bytes!

# Answer
> 0 votes
# Python 3, 51 bytes

```
[print(''.join((';'*ord(i)+'#')for i in input()))]

```

Try it online!

# Answer
> 0 votes
# q/kdb+, 24 bytes

**Solution:**

```
{,["#"sv(7h$x)#'";"]"#"}

```

**Explanation:**

`q` is interpreted right-to left. We cast the input to it's ASCII values, thus `"Hello, World!"` becomes `72 101 108 108 111 44 32 87 111 114 108 100 33`. We then take this many of the `;` character, which gives us a list of lists. These lists are joined together with `#`, then we a `#` on the end to terminate the string.

```
{,["#"sv(7h$x)#'";"]"#"} / the solution
{                      } / lambda function
 ,[                ]"#"  / concatenate with "#"
              #'         / apply each-left take (#) each-right
                ";"      / the right (the character ;)
        (7h$x)           / the left (input cast to ASCII values)
   "#"sv                 / join these lists back together with "#"

```

**Bonus:**

Could save 1 byte moving the cast outside the function, but that's a bit underhand:

```
{,["#"sv x#'";"]"#"}7h$

```

Taking inspiration from the APL solution and the above yields a 22 byte solution:

```
{raze(x#'";"),'"#"}7h$

```

which becomes 20 bytes in `k`

```
{,/(x#'";"),'"#"}7h$

```

# Answer
> 0 votes
# Charcoal, 8 bytes

```
ＦＳ⁺×;℅ι#

```

Try it online!

### Explanation (for those too lazy to click the link)

```
Ｆ         For
 Ｓ        each character in next input as string
   ⁺    #  Append "#"
    × ℅ι   Multiply (repeat) by the character code of i (loop variable)
     ;     ";"

```

# Answer
> 0 votes
# Common Lisp, 71 bytes

```
(lambda(s)(map'list(lambda(x)(format t"~v,,,v<~>#"(char-code x)#\;))s))

```

Try it online!

# Answer
> 0 votes
# SNOBOL4 (CSNOBOL4), 90 bytes

```
	N =INPUT
T	N LEN(1) . L REM . N :F(END)
	&ALPHABET L @X
	OUTPUT =DUPL(';',X) '#' :(T)
END

```

Try it online!

```
	N =INPUT			;* read input
T	N LEN(1) . L REM . N :F(END)	;* set L to the first character, N to the REMainder, and
					;* if there is no match (N is empty), goto END
	&ALPHABET L @X			;* @ssign X with the value of the match of L inside &ALPHABET (all ASCII chars)
	OUTPUT =DUPL(';',X) '#' :(T)	;* set OUTPUT to ';' duplicated X times concatenated with '#', and a newline
					;* then goto T
END

```

# Answer
> 0 votes
# Gol\>\<\>, 11 bytes

```
iEHr{R`;`#r

```

Try it online!

### How it works

```
iEHr{R`;`#r

i            Input n as char
 EH          If EOF, print stack contents as chars (from top) and exit

             Stack content                     [x y z... n]
   r{        Reverse the whole stack except n  [...z y x n]
     R`;     Pop n and push that many ';'s     [...z y x ;...;]
        `#   Push '#'                          [...z y x ;...; #]
          r  Reverse stack                     [# ;...; x y z...]
             Repeat indefinitely

```

The `r...r` structure makes the invariant that the stack content is the desired string reversed.

# Answer
> 0 votes
# J, 23 Bytes

Nothing special.

```
,([:,&'#'#&';')"0 u:inv

```

### Explanation:

```
,([:,&'#'#&';')"0 u:inv
                  u:inv   | Convert string to code points
 (            )"0         | For each item:
  [:,&'#'#&';'            | Repeat ';' n times and append #
,                         | Ravel the resulting character array

```

Note that the result contains lots of whitespace, since arrays have to be rectangular.

# Answer
> 0 votes
# Java 10, 63 bytes

```
c->{var s="";for(var d:c){for(;d-->0;)s+=";";s+="#";}return s;}

```

Try it online here.

Ungolfed version:

```
c -> { // lambda taking a char[] as argument and returning a String
    var s = ""; // the output String
    for(var d : c) { // iterate over all the input chars
        for(; d-- > 0 ;) // as many times as the ASCII value of the current char
            s += ";";    // append ";" to the program to compute the character
        s += "#"; // append "#" to output the character
    }
    return s; // return the finished program
}

```

# Answer
> 0 votes
# Ahead, 13 bytes

```
~W$:ki@j";#"~

```

Try it online!

# Answer
> 0 votes
# Noether, 21 bytes

```
I~sL(";"si/B*P"#"P!i)

```

Try it online!

**Explanation:**

```
I~s                   - Get input and store in the variable s
   L(               ) - Loop until the top of stack equals the length of s
     ";"              - Push the string ";"
        si/           - Return the character of string s at position i
           B          - Return the ASCII code of the character
            *P        - Multiply ";" by the ASCII code and print
              "#"P    - Push the string "#" and print
                  !i  - Increment i

```

# Answer
> 0 votes
# Pascal (FPC), 94 bytes

```
var c:char;i:word;begin repeat read(c);for i:=1to ord(c)do write(';');write('#')until eof end.

```

Try it online!

Assumes non-empty input.

# Answer
> 0 votes
# VBA (Excel) 82 Bytes

I really think this challenge should've been scored in the length of your program after it is converted into ;#. I would score 6769 characters (including newlines)

```
Function d(e)
  For i=1To Len(e)
    d=d &String(Asc(Mid(e,i,1)),";") &"#"
  Next
End Function

```

*Note: the leading spaces aren't needed, just make it more read-able, not that I should be worried about that... just look at the output from this thing!!!*

**Un-golfed With Comments:**

```
Function toSemiHash(translate)
    'For 1 to the length of the string
    For i = 1 To Len(translate)
        'Append a semicolon the char-code number of times along with a hash
        fromSemiHash = fromSemiHash & String(Asc(Mid(translate, i, 1)), ";") & "#"
    Next
End Function

```

# Answer
> 0 votes
# PHP, 75 Bytes

This shorter then the parser I wrote for it.

**Generator**

```
function g($s){foreach(str_split($s)as$a)echo str_repeat(';',ord($a)).'#';}

```

You can test it like this:

```
$strings = [
    'Hello, World!',
    ';#',
    '!'
];

foreach($strings as $s){
    g($s); echo "\n\n";
}

function g($s){foreach(str_split($s)as$a){echo str_repeat(';',ord($a)).'#';}}

```

**Parser (second attempt)**

The one from my first attempt should work fine as well. This one is shorter, so well just use it to verify that the generator works correctly.

```
function f($s){foreach(split('#',$s)as$a)echo!$a?'':chr(substr_count($a,';')%127);}

```

You can test both like this:

```
//turn of warning message or set in PHP.ini
error_reporting(0);
$s = "Hello, World!";

function g($s){foreach(str_split($s)as$a)echo str_repeat(';',ord($a)).'#';}
function f($s){foreach(split('#',$s)as$a)echo!$a?'':chr(substr_count($a,';')%127);}

//output buffer the generator
ob_start();
    g($s);
$s=ob_get_clean();
f($s);

```

Output

```
 Hello, World!

```

Test both of them

A few things to note:

* Because neither one return information, we can capture the output by using output buffering.
    + We could also put it a file, use `$argv[1]` for input, remove the function calls, add the shebang `#!/bin/env php` and run it from the terminal. Which would cut it down to around something like `65`. Then we could just pipe that into the other script. So :-P
* Because the parser is old, we have to use PHP \< 7 for it. Don't worry our dev team is currently working hard on a patch to make it compatible with PHP7,(just change split to explode). They should have it done sometime in the spring after they quite code golfing and get back to work!

**Lastly**

My first attempt at a parser was recursive, so I thought it only fitting I make a generator that is also recursive. Unfortunately as with the first one, it's longer `89 bytes`.

```
 function g($s,$i,$r){echo''==($a=$s[$i])?$r:g($s,++$i,$r.=str_repeat(';',ord($a)).'#');}

```

You can test it with the same code above:

```
error_reporting(0);
$s = "Hello, World!";

//function g($s){foreach(str_split($s)as$a)echo str_repeat(';',ord($a)).'#';}
function f($s){foreach(split('#',$s)as$a)echo!$a?'':chr(substr_count($a,';')%127);}

//recursive
function h($s,$i,$r){echo''==($a=$s[$i])?$r:h($s,++$i,$r.=str_repeat(';',ord($a)).'#');}

//output buffer the generator
ob_start();
   // g($s);
   h($s,0,'');
$s=ob_get_clean();
f($s);

```

Recursive Generator

Things that didn't make the cut

```
  //parser 98 bytes, strtok + do while
  function p($s){$f=strtok;$a=$f($s,'#');do{echo chr(substr_count($a,';')%127);}while($a=$f('#'));}

```

# Answer
> 0 votes
# brainfuck, 48 bytes

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

```

Try it online!

### How it works

```
+++++++[>+++++>++++++++<<-]>>+++>       'write ; and # onto the tape
,[                                      'read input as ascii values and loop
    [-<.>]                              'decrement input 1 and write ; then repeat until 0
    <<.>>                               'write #
,]                                      'read input as ascii values and loop

```

# Answer
> 0 votes
# , 23 bytes

```
[:,[:('#',~#&';')"+3&u:

```

Try it online!

```
[:,(35,~#&59)"+&.(3&u:)

```

Try it online!

Posting since the existing J answer is incorrect.

### How it works

```
[:,[:('#',~#&';')"+3&u:
                   3&u:  Convert to ASCII value
     (          )"+      Apply to each number...
           #&';'           Convert to that many ';'s
      '#',~                and add '#' to the right
   [:                    Treat the above as monadic fork
  ,                      Ravel; flatten the multidimensional array
[:                       Treat the above as monadic fork

[:,(35,~#&59)"+&.(3&u:)
              f&.g       Apply g, f, then inverse of g...
                 (3&u:)    g: convert to ASCII value
   (        )"+            f: apply to each number...
        #&59                 convert to that many 59's (charcode of ';')
    35,~                     and add 35 to the right (charcode of '#')
[:,                      Ravel the result

```

Both use the `"+` trick to avoid numeric literal problem.

# Answer
> 0 votes
# Whitespace, 82 bytes

```
[N
S S N
_Create_Label_OUTER_LOOP][S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve][N
S S S N
_Create_Label_INNER_LOOP][S N
S _Duplicate][N
T   S T N
_If_0_Jump_to_Label_HASTAG][S S S T N
_Push_1][T  S S T   _Subtract][S S S T  T   T   S T T   N
_Push_59_;][T   N
S S _Print_as_character][N
S N
S N
_Jump_to_Label_INNER_LOOP][N
S S T   N
_Create_Label_HASHTAG][S S S T  S S S T T   N
_Push_35_#][T   N
S S _Print_as_character][N
S N
N
_Jump_to_Label_OUTER_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Start OUTER_LOOP:
  Integer c = read character from STDIN
  Start INNER_LOOP:
    If(c == 0):
      Jump to function HASHTAG
    c = c - 1
    Print ";" to STDOUT
    Go to next iteration of INNER_LOOP

function HASHTAG:
  Print "#" to STDOUT
  Go to next iteration of OUTER_LOOP

```

Note: All characters read from STDIN in Whitespace are automatically stored in the heap as their code-point values.

# Answer
> 0 votes
# Backhand, 27 bytes

```
}o" i# :" }]@_!}|{:" [; o".

```

Try it online!

I'm sure a shorter solution exists, given this has 6 no-ops. This prints a null byte to begin with

### Explanation:

```
}o       Print a null byte
    i  :  }]  ! |{     Get a character of input and check if it is EOF
                   "  ; o"   If it is not, print a ;
               }| :  [       Decrement the counter and check again
                   Once the counter hits zero exit the loop
            @_    If the value was -1 (EOF) exit
           ]  !   Otherwise execute some garbage
 o" i#  "         Print a # and get the next character of input

```

# Answer
> 0 votes
## W `j` `d`, 7 bytes

The input format is `[['a','b',..]]`

```
◘Pp½h#û

```

## Explanation

Uncompressed:

```
C';*'#+M

```

<pre><code>       M % For every item in the input:
C        % Convert to a character
 ';*     % Repeat ; ASCII codepoint times
    '#+  % Append a #

Flag:j   % Join without newline
```
</code></pre>

# Answer
> 0 votes
# GolfScript, 10 bytes

```
{";"*"#"}%

```

Try it online!

# Answer
> 0 votes
# Burlesque, 13 bytes

```
m{'#j**';j.*}

```

Try it online!

```
m{      # For each char in string (implicit concat)
  '#    # Push #
  j**   # Find ord(char)
  ';j.* # That many ;
 }

```

# Answer
> 0 votes
# Raku, 44 bytes

```
say $*IN.slurp.ords.map(';'x*).join('#'),'#'

```

Try it online!

# Answer
> 0 votes
# AWK, ~~52~~ 49 + 8 = 57 bytes

`-lordchr` command-line parameter to import the ORDCHR extension.

```
BEGIN{RS=".|"}{for(;i++<ord(RT);)s=s";"}i=$0=s"#"

```

Try it online!

This code roams the input one character at a time, and prints as many `;` as needed, and a `#` between characters. To print everything in one line, just put `ORS=""` inside the brackets of the `BEGIN` pattern.

# Answer
> 0 votes
# Lua, 57 bytes

```
(...):gsub('.',load'print((";"):rep((...):byte()).."#")')

```

Try it online!

Essentially grabs the byte value of each character and repeats `;` that many times, followed by a `#` and a newline.

# Answer
> 0 votes
# Thunno 2 `J`, 7 bytes

```
C';×'#+

```

Attempt This Online!

#### Explanation

```
C';×'#+  # Implicit input
C        # Cast to ordinals
 ';×     # Repeat ";" that many times
    '#+  # Append "#" to each
         # Implicit output, joined

```

# Answer
> -1 votes
## C, 51 bytes

```
c;main(){for(;c||~(c=getchar());puts("#;"+!!--c));}

```

Outputs lots of extra newlines, and an extra `;` at the end, but neither of those affect the output of the `;#` program, so it should be fine.

Using puts was suggested by ais523 in a comment: Make a ;# transpiler.

`~(x)` is a shorter way to write `(x)!=-1`.

`"#;"+!!--c` is a pointer arithmetic equivalent of `--c?";":"#;"`.

---
Tags: code-golf, code-generation
---