title: ASCII Triangles

text:
# Question
Title: ASCII Triangles
Your task is to write a program or a function that prints an ASCII triangle. They look like this:

```
|\
| \
|  \
----

```

Your program will take a single numeric input `n`, with the constraints `0 <= n <= 1000`. The above triangle had a value of `n=3`.

The ASCII triangle will have `n` backslashes (`\`) and vertical bars (`|`), `n+1` lines and dashes (`-`), and each line will have an amount of spaces equal to the line number (0-based, ie first line is line 0) besides the ultimate line.

## Examples:

Input:

```
4

```

Output:

```
|\
| \
|  \
|   \
-----

```

Input:

```
0

```

Output:

```

```

In this test case, the output must be empty. No whitespace.

Input:

```
1

```

Output:

```
|\
--

```

Input & output must be **exactly** how I specified.

This is , so aim for the shortest code possible!

# Answer
> 4 votes
# Jelly, 14 bytes

```
’⁶x⁾|\jṄµ€Ṫ”-ṁ

```

Try it online!

### How it works.

```
’⁶x⁾|\jṄµ€Ṫ”-ṁ  Main link. Argument: n

        µ       Combine the links to the left into a chain.
         €      Map the chain over [1, ..., n]; for each k:
’                 Decrement; yield k-1.
 ⁶x               Repeat the space character k-1 times, yielding a string.
   ⁾\j            Join the character array ['|', '\'], separating by those spaces.
      Ṅ           Print the result, followed by a linefeed.
         Ṫ      Tail; extract the last line.
                This will yield 0 if the array is empty.
          ⁾-ṁ   Mold the character '-' like that line (or 0), yielding a string
                of an equal amount of hyphen-minus characters.

```

# Answer
> 11 votes
# C, 58 bytes

```
i;f(n){for(i=2*n;~i--;printf(i<n?"-":"|%*c\n",2*n-i,92));}

```

--

Thanks to @Steadybox who's comments on this answer helped me shave a few bytes in my above solution

# Answer
> 8 votes
## Javascript (ES6), ~~97~~ ~~85~~ ~~81~~ ~~75~~ 74 bytes

```
n=>(g=(n,s)=>n?g(--n,`|${" ".repeat(n)}\\
`+s):s)(n,"")+"-".repeat(n&&n+1)

```

Turns out I wasn't using nearly enough recursion

```
f=n=>(g=(n,s)=>n?g(--n,`|${" ".repeat(n)}\\
`+s):s)(n,"")+"-".repeat(n&&n+1)

console.log(f(0))
console.log(f(1))
console.log(f(2))
console.log(f(3))
console.log(f(4))
```

# Answer
> 6 votes
# 05AB1E, ~~16~~ ~~15~~ 16 bytes

Saved a byte thanks to *Adnan*

```
FðN×…|ÿ\}Dg'-×»?

```

Try it online!

**Explanation**

```
F       }         # for N in range [0 ... input-1]
 ðN×              # push <space> repeated N times
    …|ÿ\          # to the middle of the string "|\"
         Dg       # get length of last string pushed
           '-×    # repeat "-" that many times
              »   # join strings by newline
               ?  # print without newline

```

# Answer
> 5 votes
# , ~~18~~ ~~17~~ 16 bytes

*1 byte saved thanks to @nmjcman101 for using another way of outputting nothing if the input is `0`*

```
é\é|ÀñÙá ñÒ-xÀ«D

```

Try it online!

Hexdump:

```
00000000: e95c e97c c0f1 d9e1 20f1 d22d 78c0 ab44  .\.|.... ..-x..D

```

### Explanation (outdated)

We first have a loop to check if the argument is `0`. If so, the code below executes (`|\` is written). Otherwise, nothing is written and the buffer is empty.

```
Àñ     ñ            " Argument times do:
  é\é|              " Write |\
      h             " Exit loop by creating a breaking error

```

Now that we got the top of the triangle, we need to create its body.

```
Àñ   ñ              " Argument times do:
  Ù                 " Duplicate line, the cursor comes down
   à<SPACE>         " Append a space

```

Now we got one extra line at the bottom of the buffer. This has to be replaced with `-`s.

```
Ó-                  " Replace every character with a -
   x                " Delete the extra '-'

```

---

This answer would be shorter if we could whatever we want for input `0`

# , ~~14~~ 13 bytes

```
é\é|ÀñÙá ñÒ-x

```

Try it online!

# Answer
> 4 votes
# C#, 93 bytes

```
n=>{var s=n>0?new string('-',n+1):"";while(n-->0)s="|"+new string(' ',n)+"\\\n"+s;return s;};

```

Anonymous function which returns the ASCII triangle as a string.

Full program with ungolfed, commented function and test cases:

```
using System;

class ASCIITriangles
{
    static void Main()
    {
      Func<int, string> f =
      n =>
      {
          // creates the triangle's bottom, made of dashes
          // or an empty string if n == 0
          var s = n > 0 ? new string('-', n + 1) : "";

          // a bottom to top process
          while ( n-- > 0)
          // that creates each precedent line
            s = "|" + new string(' ', n) + "\\\n" + s;

          // and returns the resulting ASCII art
          return s;
      };

      // test cases:
      Console.WriteLine(f(4));
      Console.WriteLine(f(0));
      Console.WriteLine(f(1));
    }
}

```

# Answer
> 3 votes
# PowerShell, ~~51~~ 67 bytes

```
param($n)if($n){1..$n|%{"|"+" "*--$_+"\"};write-host -n ('-'*++$n)}

```

Try it online!

*(Byte increase to account for no trailing newline)*

Takes input `$n` and verifies it is non-zero. Then loops to construct the triangle, and finishes with a line of `-`. Implicit `Write-Output` happens at program completion.

# Answer
> 3 votes
# CJam, ~~24~~ ~~22~~ 21 bytes

*Saved 1 byte thanks to Martin Ender*

```
ri_{S*'|\'\N}%\_g+'-*

```

Try it online!

**Explanation**

```
ri                     e# Take an integer from input
  _                    e# Duplicate it
   {                   e# Map the following to the range from 0 to input-1
    S*                 e#   Put that many spaces
      '|               e#   Put a pipe
        \              e#   Swap the spaces and the pipe
         '\            e#   Put a backslash
           N           e#   Put a newline
            }%         e# (end of map block)
              \        e# Swap the top two stack elements (bring input to the top)
               _g+     e# Add the input's signum to itself. Effectively this increments any
                       e#  non-zero number and leaves zero as zero.
                  '-*  e# Put that many dashes

```

# Answer
> 3 votes
# Python 2, 69 bytes

```
lambda x:'\n'.join(['|'+' '*n+'\\'for n in range(x)]+['-'*-~x*(x>0)])

```

Try it online!

# Answer
> 3 votes
# bash + printf, 68 bytes

```
for((;i<$1;))
{
a=$a-
printf "|%$[i++]s\\\\\n"
}
[ $a ] && echo $a-

```

Use "bash *program\_name* *number*" to run. Sample run:

```
bash-4.1$ bash triangle 0
bash-4.1$ bash triangle 1
|\
--
bash-4.1$ bash triangle 2
|\
| \
---
bash-4.1$ bash triangle 3
|\
| \
|  \
----

```

# Answer
> 2 votes
# SmileBASIC, 51 bytes

```
INPUT N
FOR I=0TO N-1?"|";" "*I;"\
NEXT?"-"*(N+!!N)

```

# Answer
> 2 votes
## C ~~101~~ ~~93~~ 75 bytes

```
f(n){i;for(i=0;i++<n;)printf("|%*c\n",i,92);for(;n--+1;)printf("-");}

```

Ungolfed version

```
void f(int n)
{
  int i;

  for(i=0;i++<n;)
    printf("|%*c\n",i,92);

  for(;n--+1;)
    printf("-");

}

```

@Steadybox Thanks for pointing out, makes a lot of sense.

# Answer
> 2 votes
# Common Lisp, ~~89~~ 86 bytes

Creates an anonymous function that takes the n input and prints the triangle to `*standard-output*` (stdout, by default).

## Golfed

```
(lambda(n)(when(< 0 n)(dotimes(i n)(format t"|~v@t\\~%"i))(format t"~v,,,'-<~>"(1+ n))))

```

## Ungolfed

```
(lambda (n)
  (when (< 0 n)
    (dotimes (i n)
      (format t "|~v@t\\~%" i))
    (format t "~v,,,'-<~>" (1+ n))))

```

I'm sure I could make this shorter somehow.

# Answer
> 2 votes
# Retina, 39 bytes

```
.*
$*
*\`(?<=(.*)).
|$.1$* \¶
1
-
-$
--

```

**Try it online**

Convert decimal input to unary. Replace each `1` with `|<N-1 spaces>\¶`, print, and undo replace. Replace each `1` with a hyphen, and the last hyphen with 2 hyphens. Tadaa!

# Answer
> 2 votes
# Python 3, 60 bytes

```
f=lambda n,k=0:k<n and'|'+' '*k+'\\\n'+f(n,k+1)or'-'[:n]*-~n

```

Try it online!

Two more solutions with the same byte count.

```
f=lambda n,k=0:n and'|'+' '*k+'\\\n'+f(n-1,k+1)or-~k*'-'[:k]
f=lambda n,s='|':-~n*'-'[:n]if s[n:]else s+'\\\n'+f(n,s+' ')

```

# Answer
> 2 votes
# dc, 98 bytes

```
256?dse1+d[q]st1=t^124*23562+dsaP2sk[[lkd256r^32*la+dsaPd1+skle>y]srle1<r]dsyx[45Ple1-dse0!>q]dsqx

```

Try it online!

### Explanation

This takes due advantage of dc's `P` command, which utilizes conversion to base `256` on most systems. Therefore, for any input `n`, the program first raises `256` to the `n + 1`th power, multiplies the result by `124` (ASCII character `|`), and then adds `256*92+10=23562` to the product (where `92` is equivalent to the character `\` and `10` is the decimal value of the new-line (`\n`)). This results in a decimal number that when converted to base `256` with `P` results in the output `|\\n` where `\n` is the literal new-line character. A duplicate of this decimal number is also stored on top of register `a`.

Then, a "macro-loop" is invoked, as long as `n > 1`, in which a counter is incremented until `n`, beginning from `2`, and, as the 3rd through `n`th base `256` digits are unset, `256` is raised to each of those increments, a result which is then multiplied by `32` (the ASCII single space character). Then the value on top of register `a` is incremented by the resulting product, thus, on each iteration, setting each one of the unset base `256` digits in the between the `|` and the `\` characters to a single space.

Finally, after all `n-1` lines have been output, another "macro-loop" is invoked in which all the `n+1` dashes are output through the feeding of `45` to `P` on each iteration.

*Note:* The `[q]st1=t` segment makes sure that nothing is output for the input `0` by checking if the incremented input is equal to one, and if it is, simply executes the macro `[q]` which exits the program.

# Answer
> 2 votes
# Charcoal, 15 bytes

```
Ｎβ¿β«↓β→⁺¹β↖↖β»

```

Try it online!

## Breakdown

```
Ｎβ¿β«↓β→⁺¹β↖↖β»
Ｎβ               assign input to variable β
   ¿β«         »  if β != 0:
      ↓β           draw vertical line β bars long
        →⁺¹β       draw horizontal line β+1 dashes long
            ↖      move cursor up one line and left one character
             ↖β    draw diagonal line β slashes long

```

# Answer
> 2 votes
# Japt, 20 bytes

Saved 2 bytes thanks to @ETHproductions

```
o@'|+SpX +'\Ãp-pUÄ)·

```

Try it online!

### Explanation

```
o@'|+SpX +'\Ãp-pUÄ)·
o                       // Creates a range from 0 to input
 @                      // Iterate through the array
  '|+                   // "|" +
     SpX +              // S (" ") repeated X (index) times +
          '\Ã            // "\" }
             p-pU       // "-" repeated U (input) +1 times
                 Ä)·    // Join with newlines

```

# Answer
> 2 votes
# J, 20 bytes

*-13 bytes thanks to bob*

```
*#' \|-'{~3,~2,.=@i.

```

Try it online!

## original: 33 bytes

```
(#&'| \'@(1,1,~])"0 i.),('-'#~>:)

```

### ungolfed

```
(#&'| \' @ (1,1,~])"0 i.) , ('-'#~>:)

```

Try it online!

# Answer
> 2 votes
# Commodore BASIC (C64/128, TheC64 & Mini, VIC-20, PET, C16/+4) - 46 BASIC Bytes

```
0inputn:ifnthenfori=1ton:?"{shift+B}{left}"spc(i)"{shift+M}":next:fori=.ton:print"-";:next

```

There is a sanity check for zero, but any other positive integer will work.

Note, a C64 has 25 rows and 40 columns text (some PETs and the C128 in VDC mode has 80 columns, the VIC-20 is 22 columns by 23 rows) so the output will be skewed if you exceed the screen limit in either direction.

I've added a screenshot so that you may see the PETSCII characters that I can't make happen in this listing.

# Answer
> 1 votes
## QBIC, 41 bytes

```
:~a>0|[a|?@|`+space$(b-1)+@\`][a+1|Z=Z+@-

```

Explanation

```
:~a>0|  Gets a, and checks if a > 0
        If it isn't the program quits without printing anything
[a|     For b=1; b <= a; b++
?@|`+   Print "|"
space$  and a number of spaces
(b-1)   euqal to our current 1-based line - 1
+@\`    and a "\"
]       NEXT
[a+1|   FOR c=1; c <= a+1; c++
Z=Z+@-  Add a dash to Z$
        Z$ gets printed implicitly at the end of the program, if it holds anything
        The last string literal, IF and second FOR loop are closed implicitly.

```

# Answer
> 1 votes
## Pyke, ~~18~~ 17 bytes

```
I Fd*\|R\\s)Qh\-*

```

Try it here!

# Answer
> 1 votes
# MATL, 19 bytes

```
?'\|- '2GXyYc!3Yc!)

```

Try it online!

```
?         % Implicit input. If non-zero
  '\|- '  %   Push this string
  2       %   Push 2
  G       %   Push input
  Xy      %   Identity matrix of that size
  Yc      %   Prepend a column of 2's to that matrix
  !       %   Transpose
  3       %   Push 3
  Yc      %   Postpend a column of 3's to the matrix
  !       %   Transpose
  )       %   Index into string
          % Implicit end. Implicit display

```

# Answer
> 1 votes
# Python2, 73 bytes

```
n=input()
w=0
exec'print"|"+" "*w+"\\\\"+("\\n"+"-"*-~n)*(w>n-2);w+=1;'*n

```

A full program. I also tried string interpolation for the last line, but it turned out be a couple bytes longer :/

```
exec'print"|%s\\\\%s"%(" "*w,("\\n"+"-"*-~n)*(w>n-2));w+=1;'*n

```

Another solution at 73 bytes:

```
n=j=input()
exec'print"|"+" "*(n-j)+"\\\\"+("\\n"+"-"*-~n)*(j<2);j-=1;'*n

```

# Test cases

```
0:

1:
|\
--

2:
|\
| \
---

3:
|\
| \
|  \
----

6:
|\
| \
|  \
|   \
|    \
|     \
-------

```

# Answer
> 1 votes
# Pyth, ~~23~~ 18 bytes

```
VQ++\|*dN\\)IQ*\-h

```

Test suite available online.
Thanks to Ven for golfing off 5 bytes.

## Explanation

```
VQ++\|*dN\\)IQ*\-h
 Q           Q    Q  [Q is implicitly appended, initializes to eval(input)]
       d             [d initializes to ' ' (space)]
VQ         )         For N in range(0, eval(input)):
      *dN             Repeat space N times
   +\|                Prepend |
  +      \\           Append \
                      Implicitly print on new line
            IQ       If (input): [0 is falsy, all other valid inputs are truthy]
                 hQ   Increment input by 1
              *\-     Repeat - that many times
                      Implicitly print on new line

```

# Answer
> 1 votes
## R, 101 bytes

```
for(i in 1:(n=scan())){stopifnot(n>0);cat("|",rep(" ",i-1),"\\\n",sep="")};cat("-",rep("-",n),sep="")

```

This code complies with the `n=0` test-case if you only consider `STDOUT` !
Indeed, the `stopifnot(n>0)` part stops the script execution, displays nothing to `STDOUT` but writes `Error: n > 0 is not TRUE` to `SDTERR`.

**Ungolfed :**

```
for(i in 1:(n=scan()))
    {
    stopifnot(n>0)
    cat("|", rep(" ", i-1), "\\\n", sep = "")
    }

cat("-", rep("-", n), sep = "")

```

# Answer
> 1 votes
# Befunge-98, 68 bytes

```
&:!#@_000pv<
:kg00 ',|'<|`g00:p00+1g00,a,\'$,kg00
00:k+1g00-'<@,k+1g

```

# Answer
> 1 votes
# Python 2, 62 bytes

```
n=input();s='\\'
exec"print'|'+s;s=' '+s;"*n
if n:print'-'*-~n

```

Try it online!

Prints line by line, each time adding another space before the backslash. If a function that doesn't print would be allowed, that would likely be shorter.

# Answer
> 1 votes
## JavaScript (ES6), 71 bytes

```
f=
n=>console.log(' '.repeat(n).replace(/./g,'|$`\\\n')+'-'.repeat(n+!!n))
```

```
<form onsubmit=f(+i.value);return!true><input id=i type=number><input type=submit value=Go!>
```

Outputs to the console. Save 6 bytes if printing to the SpiderMonkey JavaScript shell is acceptable. Save 13 bytes if returning the output is acceptable.

# Answer
> 1 votes
# Haskell, ~~82~~ 65 bytes

```
g 0=""
g n=((take n$iterate(' ':)"\\\n")>>=('|':))++([0..n]>>"-")

```

Try it online! Usage:

```
Prelude> g 4
"|\\\n| \\\n|  \\\n|   \\\n-----"

```

Or more nicely:

```
Prelude> putStr $ g 4
|\
| \
|  \
|   \
-----

```

# Answer
> 1 votes
# Python 2, 67 bytes

Another function in Python 2, using `rjust`.

```
lambda n:('|'.join(map('\\\n'.rjust,range(n+2)))+'-'*-~n)[4:]*(n>0)

```

Try it online!

# Answer
> 1 votes
# Perl, 63 bytes

```
$n=shift;print'|',$"x--$_,"\\\n"for 1..$n;print'-'x++$n,$/if$n

```

Ungolfed:

```
$ perl -MO=Deparse triangle.pl
$n = shift @ARGV;
print '|', $" x --$_, "\\\n" foreach (1 .. $n);
print '-' x ++$n, $/ if $n;

```

`$"` is the list separator, which defaults to " ". `$/` is the output record separator, which defaults to "\n". `$_` is the implicit loop variable.

# Answer
> 1 votes
# bash + Unix utilities, 71 bytes

```
(($1))&&(echo '|\';(($1-1))&&$0 $[$1-1]|sed 's/|/| /;s/-/--/'||echo --)

```

Test program:

```
for n in 0 1 2 3 4 5; do echo $n; ./triangle $n; echo; done

```

Test output:

```
0

1
|\
--

2
|\
| \
---

3
|\
| \
|  \
----

4
|\
| \
|  \
|   \
-----

5
|\
| \
|  \
|   \
|    \
------

```

# Answer
> 1 votes
# brainf\**k, 256 bytes

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

```

Try it online!

## How it works

```
# Read input and convert to number (https://esolangs.org/wiki/Brainfuck_algorithms#Input_a_decimal_number)
[-]>[-]+[[-]>[-],[+[-----------[>[-]++++++[<------>-]<--<<[->>++++++++++<<]>>[-<<+>>]<+>]]]<]<

# We need the characters {LF} (10); {space} (32); {minus} (45); \(92) | (120)

P1 > ++++++++++
   [
p0  <
P1  >
P2  >  +
P3  >  +++
P4  >  ++++
P5  >  +++++++++
P6  >  ++++++++++++
P5  <
P4  <
P3  <
P2  <
P1  < -
   ]
P0 <           # Contains n
P1 >           # is zero
P2 >           # is {LF}
P3 > ++        # is {space}
P4 > +++++     # is {minus}
P5 > ++        # is \
P6 > ++++      # is |
p5 <
p4 <
p3 <
p2 <
p1 <
p0 <
   [           # Loop through n
P1 >[-]+       # p1 will be 1 if input was not 0; used to output the additional {minus}
p2 >
p3 >
p4 >
p5 >
p6 > .
## output p7 spaces; copy p7 to p8
p7 >
   [
p8 > +
p7 <
p6 <
p5 <
p4 <
p3 < .  # output {space}
p4 >
p5 >
p6 >
p7 > -
   ]
## copy p8 back to p7
p8 >
   [
   -
p7 < +
p8 >
   ]
p7 <
p6 <
p5 < . # output \
p6 >
p7 > + # increase number of spaces
p6 <
p5 <
p4 <
p3 <
p2 < . # output {LF}
p1 <
p0 < -
   ]
p1 >
p2 >
p3 >
p4 >
p5 >
p6 >
## output p7 minuses
p7 >
   [
p6 <
p5 <
p4 < .
p5 >
p6 >
p7 > -
   ]
p6 <
p5 <
p4 <
p3 <
p2 <
## output additional minus
p1 <
  [
p2 >
p3 >
p4 > .
p3 <
p2 <
p1 < -
  ]

```

This is my first contribution and I'm not sure whether it is allowed to re-use code from others. My code above uses the code published in the Wiki to read the input characters and convert them into a number. Hope that's okay.

# Answer
> 1 votes
# Python 3, ~~72~~ 71 bytes

```
x=int(input())
for i in range(x):print('|'+' '*i+'\\')
print('-'*(x+1))

```

Try it online!

# Python 2, 62 bytes

```
x=input()
for i in range(x):print'|'+' '*i+'\\'
print'-'*(x+1)

```

Try it online!

# Answer
> 1 votes
# C, ~~115~~ 112 bytes

```
i,n,w;f(){if(n){for(i=n;i--;){w=n-i;printf("|");for(;0<--w;)printf(" ");puts("\\");}for(i=n;~i--;)printf("-");}}

```

Try it online!

# x86-32 machine code, 87 bytes

```
bd00 8089 ecbb 0400 83fb 0074 fe89 d989
d829 c850 b40e b07c cd10 5851 89c1 4183
f901 7502 7408 50b4 0eb0 20cd 1058 90e2
ee50 b40e b05c cd10 5850 b40e b00a cd10
b00d cd10 5859 e2c7 89d9 4150 b40e b02d
cd10 58e2 f6eb fe

```

**To boot, pad it to 510 bytes with zeros and add `55aa` at the end!**
**This means "add `times 510 - ($-$$) db 0` and `db 0xaa55` to the ungolfed assembly code".**

Ungolfed (compilable, compile using `nasm -fbin -o triangles triangles.asm`):

<pre><code>[org 0x7c00]
[bits 16]

    mov bp, 8000h ; set up stack
    mov sp, bp

    mov bx, 4 ; N

    ; cx = i, bx = n, ax = w
    cmp bx, 0 ; if n == 0, don't print anything
    je $
    mov cx, bx ; i = n
    l1: ; first for
        mov ax, bx
        sub ax, cx ; w = n - i
        push ax
        mov ah, 0eh
        mov al, '|'
        int 10h ; print |
        pop ax
        push cx
        mov cx, ax
        inc cx
        l2: ; second for (prints whitespaces)
            cmp cx, 1 ; if (i != 1) print " "; - there was a bug with first \ printing far right from the triangle
            jne l2_1
            je l2_2
            l2_1:
                push ax
                mov ah, 0eh
                mov al, ' '
                int 10h
                pop ax
            l2_2:
                nop
        loop l2 ; while i < 0 l2(); i--;
        push ax
        mov ah, 0eh
        mov al, '\'
        int 10h ; print backslash
        pop ax
        push ax
        mov ah, 0eh
        mov al, 0ah
        int 10h
        mov al, 0dh
        int 10h ; print newline
        pop ax
        pop cx
    loop l1 ; while i < 0 l1(); i--;
    mov cx, bx ; i = n
    inc cx ; i++
    l3: ; third for (prints dashes)
        push ax
        mov ah, 0eh
        mov al, '-'
        int 10h
        pop ax
    loop l3 ; while i < 0 l3(); i--;

    jmp $ ; hang forever
```
</code></pre>

# Answer
> 1 votes
# APL (Dyalog Unicode), <sup>~~41~~</sup> 33 bytes

```
{×⍵:↑({'\',⍨⍵↑'|'}¨⍳⍵),⊂'-'⍴⍨⍵+1}

```

Try it online!

-7 bytes from Adám.

-1 byte using signum function.

### Explanation

```
{×⍵:↑({'\',⍨⍵↑'|'}¨⍳⍵),⊂'-'⍴⍨⍵+1} ⍝ ⍵=n
 ×⍵:                              ⍝ If sign(n)
                        '-'⍴⍨⍵+1  ⍝ Repeat '-' n+1 times
                       ⊂          ⍝ Enclose it to a single string
                      ,           ⍝ Join with
                 }¨⍳⍵             ⍝ for each x in range 1..n
            ⍵↑'|'                 ⍝ Inner fn: take x characters from '|' appending spaces
      '\',⍨                       ⍝ Reverse join with '\'

```

Try it online!

# Answer
> 1 votes
# Pip `-n`, 21 bytes

```
IaO['|.sX,a.'\'-Xa+1]

```

Try it online!

### Explanation

```
IaO['|.sX,a.'\'-Xa+1]
                       s is space; a is 1st command-line arg (implicit)
Ia                     If a is nonzero:
  O                     Output this expression without a trailing newline:
   [                ]    A list containing these two items:
       sX,a               A list of increasing runs of spaces
    '|.                    with a pipe character concatenated to the front of each run
           .'\             and a slash concatenated to the back
              '-Xa+1      A string of a+1 hyphens

```

For example: with an input of 3, the list will be `[["|\"; "| \"; "| \"]; "----"]`. The -n flag separates all items of a list with newlines when it is printed, so we get

```
|\
| \
|  \
----

```

The if statement means the program does nothing if the input `a` is 0, as required.

# Answer
> 1 votes
# Vyxal `Ṁosr`, 12 bytes

```
⟑I‛|\j…;tƛ\-

```

Try it Online!

Flags FTW

```
⟑I‛|\j…;tƛ\-
⟑             # Over each in [0, n) (not [1, n] thanks to Ṁ flag)
 I            # Push n spaces
  ‛|\j        # Join ['|', '\'] by that (r flag makes the arguments reversed)
      …       # Print it with a trailing newline (without popping)
       ;      # Close loop
        t     # Get the last element
         ƛ\-  # Replace each with a hyphen
              # o flag - force implicit output
              # s flag - join this list of hyphens to a single string

```

# Answer
> 0 votes
## Javascript 101(Full Program), 94(Function Output), 79(Return) bytes

Full Program

Will not run in Chrome (as process doesn't exist apparently)
Will not run in TIO (as prompt apparently isn't allowed)

```
x=prompt();s='';for(i=0;i<x;i++)s+='|'+' '.repeat(i)+`\\
`;process.stdout.write(s+'-'.repeat(x&&x+1))

```

Function with EXACT print

```
x=>{s='';for(i=0;i<x;)s+='|'+' '.repeat(i++)+`\\
`;process.stdout.write(s+'-'.repeat(x&&x+1))}

```

Try it Online

Function with return string

```
x=>{s='';for(i=0;i<x;)s+='|'+' '.repeat(i++)+`\\
`;return s+'-'.repeat(x&&x+1)}

```

Try it Online

Repeating characters in Javascript is dumb and so is suppressing newlines on output

# Answer
> 0 votes
# Python 2, 82 bytes

```
def f(i,c=0):
 if c<i:print'|'+' '*c+'\\';f(i,c+1)
 print'-'*((c+1,c)[c<1]);exit()

```

Try it online!

Longer that the other Python answers but a recursive function just to be different.

It feels wasteful using two `print` statements but I can't find a shorter way round it. Also the `exit()` wastes 7 to stop it printing decreasing number of `-` under the triangle.

# Answer
> 0 votes
# Javascript (ES6), 84 bytes

Creates an anonymous function that presents the result on an alert box. No output is present if 0.

```
i=>{for(X=i,a='';i--;)a='|'+(' '.repeat(i))+'\\\n'+a;X&&alert(a+('-'.repeat(++X)))}

```

---

If printing is really required (137 bytes):

```
i=>for(X=i,d=document.body;i--;)d.innerHTML='|'+(' '.repeat(i))+'\\<br>'+d.innerHTML;X&&window.print(d.innerHTML+=('-'.repeat(++X)))

```

Changes the HTML code and prints the page into a paper sheet. The page stays white if 0.

# Answer
> 0 votes
# Clojure, 104 bytes

```
(fn[h](let[r #(apply str(repeat % %2))](doseq[n(range h)](println(str\|(r n\ )\\)))(print(r(inc h)\-))))

```

At least I should have lots of room to golf from here!

Loops over the range from `0` to `h-1`, printing a `\|`, then `h`-many spaces, then a `\\`. Finally, at the end, it prints `h+1` many dashes.

```
(defn triangle [hypot-n]
  (let [r #(apply str (repeat % %2))] ; Create a shortcut string repeat function, since I need it twice.
    (doseq [line-n (range hypot-n)] ; Loop over the range 0 to hypot...
      (println (str \| (r line-n \ ) \\))) ; Printing a bar, then line-n many spaces, then a slash
    (print (r (inc hypot-n) \-)))) ; Then print the trailing dashes

```

# Answer
> 0 votes
## Batch, 110 bytes

```
@set s=
@for /l %%i in (1,1,%1)do @call:c
@if %1 gtr 0 echo -%s: =-%
@exit/b
:c
@echo ^|%s%\
@set s= %s%

```

Special-casing 0 is no hardship as `%s: =-%` would fail anyway.

# Answer
> 0 votes
# JavaScript, 66 bytes

```
f=(x,i=0)=>i<x?`|${" ".repeat(i)}\\\n`+f(x,i+1):"-".repeat(x&&i+1)

```

# Answer
> 0 votes
# Mathematica, 57 bytes

```
Array[{"|"," "~Table~#,"\\
"}&,#,0]<>Table["-",#+Sign@#]&

```

Unnamed function taking a nonnegative integer as input and returning a string-with-newlines. It deals with the special case of input `0` by noting that the number of dashes is equal to the input plus the sign of the input.

# Answer
> 0 votes
# Underload, ~~58~~ 39 bytes

```
:()~(|)~(~!((-):S~^S)~:S( )*(\
)S)~^^!^

```

Assumes the input is a Church numeral on the stack.

## Explanation

```
          stack (assume input N = 2):
            (:*)
:         keep a copy of the input on the bottom
            (:*)(:*)
()~       insert the finalization snippet
            (:*)()(:*)
(|)~      insert the accumulator
            (:*)()(|)(:*)
(...)~^^  run (...) N times:

    ~!(...)~  set finalization snippet
                (:*)((-):S~^S)(|)
    :S        output copy of accumulator
                (:*)((-):S~^S)(|)           output = |
    ( )*      append space to accumulator
                (:*)((-):S~^S)(| )          output = |
    (\;)S     output backslash and newline
               (:*)((-):S~^S)(| )          output = |\;

    ~!(...)~  set finalization snippet
                (:*)((-):S~^S)(| )
    :S        output copy of accumulator
                (:*)((-):S~^S)(| )          output = |\;|
    ( )*      append space to accumulator
                (:*)((-):S~^S)(|  )         output = |\;|
    (\;)S     output backslash and newline
                (:*)((-):S~^S)(|  )         output = |\;| \;

!         delete accumulator
            (:*)((-):S~^S)                  output = |\;| \;
^         execute finalization snippet:
            (:*)                            output = |\;| \;

    (-)       push hyphen
                (:*)(-)                     output = |\;| \;
    :S        output hyphen
                (:*)(-)                     output = |\;| \;-
    ~^        repeat N times
                (--)                        output = |\;| \;-
    S         print
                                            output = |\;| \;---

```

# Answer
> 0 votes
# 8th, ~~94~~ 89 bytes

**Code**

```
: f 0; dup ( "|" . ( " " . ) swap times "\\" . cr ) 0 rot n:1- loop n:1+ "-" swap s:* . ;

```

**Explanation**

The word `f` requires an integer input

```
: f \ n --
   0;                      \ Exit if input equals to 0
   dup                     \ Duplicate input on the stack
   ( "|" .                 \ Print a piece of the vertical side
   ( " " . ) swap times    \ Print space between sides
   "\\" . cr )             \ Print a piece of the slanted side
   0 rot n:1- loop         \ Repeat the above operation for the size required
   n:1+ "-" swap s:* .     \ Print the bottom side
;

```

**Usage**

```
ok> 4 f
|\
| \
|  \
|   \
-----

```

# Answer
> 0 votes
## Ruby, 48 bytes

```
->n{puts ?-*(n.times{|x|puts ?|+' '*x+?\\}+(n<=>0))}

```

# Answer
> 0 votes
# Jelly, 19 bytes

```
Ḷ×⁶j@€⁾|\;‘×”-$$YxṠ

```

Try it online!

Explanation:

```
Ḷ×⁶j@€⁾|\;‘×”-$$YxṠ Link 0. Arguments: z.
Ḷ                   Range from 0 to z - 1. [arg-z]
  ⁶                 Space (' ').
 ×                  Product of x and y. [multi-char-string-warning]
      ⁾|\           Two char string ("|\").
   j                Join x on y.
    @               Reverse arguments.
     €              Convert this link to a map on the left argument.
          ‘         Increment z. [arg-z]
            ”-      Character ('-').
           ×        Product of x and y. [multi-char-string-warning]
              $     Merge last two links to a monadic link.
               $    Merge last two links to a monadic link.
         ;          Concatenate x and y.
                Y   Join z on newlines ('\n').
                  Ṡ Sign of z. [arg-z]
                 x  Repeat x y times.
```

# Answer
> 0 votes
# Python 3, 75 bytes

```
def x(n):
 if n:
  for i in range(n):print('|'+' '*i+'\\')
  print('-'*-~n)

```

Try it online!

Here's my Python 3 answer, and it's pretty long. I wonder how I can shorten it...

Thanks to Eric The Outgolfer for helping in the comments...

# Answer
> 0 votes
# PHP, 75 bytes

(70 bytes if I used extended ascii)

```
for($p=str_pad;+$i<$argv[1];)echo$p("|",++$i),"\\
";echo$p("",$i+!!$i,"-");

```

takes input from command line argument. Run with `-nr`.

# Answer
> 0 votes
**Swift 3 96 bytes**

```
var a=5,b="";for c in 0..<a{var d="|";for _ in 0..<c{d+=" "};print(d+"\\");b+="-"};print(b+"-")

```

# Answer
> 0 votes
**VBA Excel, ~~68~~ 65 bytes**

Using Immediate Window and \[a1\] as input

```
for x=0to[a1]-1:?"|"string(x,32)"\":next:if x then?string(x+1,45)

```

# Answer
> 0 votes
# Python 3, 61 bytes

```
n=5
q="".join(map(lambda x:"|%s\\\n"%(x*" "),range(n)))+"-"*n

```

Try it online!

# Answer
> 0 votes
# Perl 5, 50 +2 (-ap) = 52 bytes

```
$_&&='|\\';say,s/\\/ $&/ while$F[0]--;s/./-/g;chop

```

Try it online!

# Answer
> 0 votes
# *Acc!!*, 179 bytes

```
N
Count d while _%60-10 {
(_/60*10+_%60-48)*60+N
}
_/60
Count r while _-r {
Write 124
Count s while r-s {
Write 32
}
Write 92
Write 10
}
Count h while _+3*_/(3*_-1)-h {
Write 45
}

```

Try it online!

## Explanation

Load a number into the accumulator, print that many rows of `| ... \`, and print that many (plus 1) hyphens. Unless the number is 0, in which case print 0 hyphens. No trailing newline in any case.

Most of the code is quite straightforward (handy loop variable mnemonics: `d`igit, `r`ow, `s`pace, and `h`yphen). The two interesting parts are inputting a multi-digit number and handling the 0 case.

### Inputting a number

```
N
Count d while _%60-10 {
(_/60*10+_%60-48)*60+N
}
_/60

```

We divide the accumulator into two sections: `_%60` stores the ASCII code of the character we just read, and `_/60` stores the number we're constructing. We loop until `_%60` is `10`--that is, when we encounter a newline. Inside the loop, `_%60` is the ASCII code of the new least-significant digit. `_%60-48` is the digit itself. `_/60` is the previous value of the number, so we multiply that by 10 and add the new digit to get the new value of the number: `_/60*10+_%60-48`. Multiply that quantity by `60` and add the next input character `N`, and we're ready to loop. After the loop finishes, we set the accumulator to `_/60`, the stored number itself.

### Handling the 0 case

```
Count h while _+3*_/(3*_-1)-h {

```

My original loop condition was `_+1-h`: loop (accumulator + 1) times. But if the accumulator is 0, we want to loop 0 times, not 1. So instead of adding 1, we add `3*_/(3*_-1)`. When `_` is 0, this quantity is 0. When `_` is greater than 0, this quantity is 1 (since `3*_` is less than twice `3*_-1`).

# Answer
> 0 votes
# Java 8, 109 bytes

```
n->{String r="|\\\n";int i=0;for(;++i<n;r+=r.format("|%"+i+"s\\%n",""));for(;i-->=0;r+="-");return n<1?"":r;}

```

Can most likely be golfed some more.

**Explanation:**

Try it here.

```
n->{                 // Method with integer parameter and String return-type
  String r="|\\\n";  //  Result-string, starting at "|\" + new-line
  int i=0;           //  Index-integer, starting at 0
  for(;++i<n;        //  Loop (1) from 1 to `n` (exclusive)
    r+=              //   Append to the result-String:
       r.format("|   //    A literal "|"
        %"+i+"s      //    + `i` amount of spaces
        \\           //    + a literal "\"
        %n","")      //    + a new-line
  );                 //  End of loop (1)
  for(;i-->=0;       //  Loop (2) from `n` down to 0 (inclusive)
    r+="-"           //   Append that many literal "-" to the result-String
  );                 //  End of loop (2)
  return n<1?        //  If the input was 0:
    ""               //   Return an empty String
   :                 //  Else:
    r;               //   Return the result-String
}                    // End of method

```

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

```
	N =INPUT
T	OUTPUT =LT(X,N) '|' DUPL(' ',X) '\'	:F(E)
	X =X + 1	:(T)
E	OUTPUT =DUPL('-',X + 1)
END

```

Try it online!

# Answer
> 0 votes
# Japt `-R`, 14 bytes

```
°Æ'\i|úXÄÃpUç-

```

Try it

```
°Æ'\i|úXÄÃpUç-     :Implicit input of integer U
°                  :Postfix increment U
 Æ                 :Map each X in the range [0,U)
  '\               :  Literal "\"
    i              :  Prepend
     |ú            :    "|" right padded with spaces to length
       XÄ          :   X+1
         Ã         :End map
          p        :Push
           Uç-     :  "-" repeated U (now incremented) times
                   :Implicit output, joined with newlines

```

# Answer
> 0 votes
# JavaScript (Babel Node), 65 bytes

```
f=(n,s=`\\
`,l)=>n?'|'+s+f(n-1,' '+s,l||'-'.repeat(n&&n+1)):l||''

```

Try it online!

# Answer
> 0 votes
# Haxe 4 (161 bytes)

```
class T{static function main()trace((x->x==0?"":[for(i in 0...x+1)i==x?[for(i in 0...x+2)""].join("-"):"|"+[for(i in -1...i)""].join(" ")+"\\"].join("\n"))(3));}

```

Try Online (slightly bigger there since playground requires class to be called "Test")

### Test

Save as *T.hx*, compile and run interpreted mode `haxe --run T`

## How it works

```
class T {
    static function main()
        trace(
            (x ->
                x == 0
                        ? ""
                        : [for (i in 0...x + 1)
                                i == x
                                        ? [for (i in 0...x + 2) ""].join("-")
                                        : "|" + [for (i in -1...i) ""].join(" ") + "\\"
                ].join("\n")
            )(3)
        );
}

```
* A class and entrypoint (static function called `main`) are required in Haxe.
* `(3)` is the input
* The snippet compiles to of all Haxe compiler targets (C++, JavaScript, PHP, Python, Lua, JVM, Java, etc)

# Answer
> 0 votes
# 05AB1E, 15 bytes

```
F'|NúR'\J,}ƒ'-?

```

Try it online!

# Answer
> 0 votes
# Zsh, 60 bytes

```
for ((;i<$1;))printf "|%$[i++]s\\\\\n"&&a=$a-
(($1))&&<<<$a-

```

Try it Online. Credit to the bash solution.

# Answer
> 0 votes
# \>\<\>, 86 bytes

```
:?!;01.
!0:@>"|"o>:?va"\"oo~:&$1+:&(?!v
   "-"v>-^ ;8>1-:?!;53!.|     >
 o"-"o<^1o*4<^

```

Try it online! \- Animated

Good luck figuring this out

---
Tags: code-golf, ascii-art
---


# Question
Title: Implement an encoder for RFC 1924 IPv6 Addresses
### Introduction

Everyone should know IPv6 by now. IPv6 has very long, cumbersome addresses. In 1996 some very intelligent people created a scheme to encode them much better in RFC 1924. For reasons I cannot understand, this hasn't been widely adopted. To help adoption, it is your task to implement a converter in the language of your choice. Because storage is very expensive, especially in source code repositories, you obviously have to use as little of it as possible.

### Challenge

Write an encoder for the address format specified in RFC1924. The input is a IPv6 address in the boring standard format.

Stolen from Wikipedia this is:

---

> An IPv6 address is represented as eight groups of four hexadecimal digits, each group representing 16 bits (two octets). The groups are separated by colons (:). An example of an IPv6 address is:

```
2001:0db8:85a3:0000:0000:8a2e:0370:7334

```

> The hexadecimal digits are case-insensitive, but IETF recommendations suggest the use of lower case letters. The full representation of eight 4-digit groups may be simplified by several techniques, eliminating parts of the representation.

> **Leading zeroes**

> Leading zeroes in a group may be omitted. Thus, the example address may be written as:

```
2001:db8:85a3:0:0:8a2e:370:7334

```

> **Groups of zeroes**

> One or more consecutive groups of zero value may be replaced with a single empty group using two consecutive colons (::). Thus, the example address can be further simplified:

```
2001:db8:85a3::8a2e:370:7334

```

> The localhost (loopback) address, 0:0:0:0:0:0:0:1, and the IPv6 unspecified address, 0:0:0:0:0:0:0:0, are reduced to ::1 and ::, respectively. This two-colon replacement may only be applied once in an address, because multiple occurrences would create an ambiguous representation.

---

You **must** handle omitted zeroes in the representation correctly!

The output is a IPv6 address in the superior RFC1924 format.

As in the RFC this is:

---

> The new standard way of writing IPv6 addresses is to treat them as a 128 bit integer, encode that in base 85 notation, then encode that using 85 ASCII characters. The character set to encode the 85 base85 digits, is defined to be, in ascending order:

```
         '0'..'9', 'A'..'Z', 'a'..'z', '!', '#', '$', '%', '&', '(',
         ')', '*', '+', '-', ';', '<', '=', '>', '?', '@', '^', '_',
         '`', '{', '|', '}', and '~'.

```

> The conversion process is a simple one of division, taking the remainders at each step, and dividing the quotient again, then reading up the page, as is done for any other base conversion.

---

You can use the suggested conversion algorithm in the RFC or any other you can think of. It just has to result in the correct output!

### Example Input and Output

Here is the one from the RFC:

Input:

> 1080:0:0:0:8:800:200C:417A or 1080::8:800:200C:417A

Output:

> 4)+k&C#VzJ4br\>0wv%Yp

Your program can take input and return the output in any standard way. So it is ok to read from stdin and output to stdout or you can implement your code as a function that takes the input as argument and returns the output.

### Winning criteria

As always standard loopholes are disallowed

This is so shortest correct code in bytes wins!

This is my first challenge, so please do notify me about any problems/ambiguities in the description.

# Answer
# Pyth, ~~93~~ 91 bytes

```
Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")$from ipaddress import*;z=int(ip_address(z))$sm@Kdjz85

```

Second submission in Pyth!

Can't try online because `$` is unsafe.

When tested against the example, produces the expected result:

```
$ pyth -c 'Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")$from ipaddress import *$$z=int(ip_address(z))$sm@Kdjz85'
1080::8:800:200C:417A
4)+k&C#VzJ4br>0wv%Yp

```

Edits:

* Saved two bytes by replacing `$$` with `;` and removing space before `*`

## Explanation

First part creates the mapping string and assigns it to `K`:

```
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~

```

This is done as follows:

```
Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")
K                                       implicitly assign to K
 s[                                 )   the string joined from the following list
     UT                                 range [0..9]
   jk                                   joined with the empty string: 0123456789
       rG1                              capitalized version of the string G (whole alphabet)
          G                             G itself
           "!#$%&()*+-;<=>?@^_`{|}~"    all other symbols (shorter to declare than generate)

```

Then, the second part is two pieces of normal python amounting to 47 bytes, to convert the input ipv6 address to a number (because `z` is accessed later in the code, it is first implicitly assigned to any input value before running the Python code)

```
*from ipaddress import *$$z=int(ip_address(z))$

```

Then, the last part converts the resulting number to base 85 as a list and maps every value to the mapping string `K`:

```
sm@Kdjz85
     jz85  convert z to base 85
 m         map over the converted number with lambda d:
  @Kd      K[d]
s          join as a string and implicitly print

```

# Pure Pyth, 100 bytes

```
Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")IgJx=zcz\:kZ=z-z]k=z.n++<zJ]*-8lz]\0>zJ)=zimid16z65536sm@Kdjz85

```

You can try it here

In order to support leading/middle/trailing `::`, I must insert a list of missing zeroes in the correct position in the ip once converted to a list of hex numbers, which takes up more space than the inline Python version. There's room for improvement but I doubt it can beat the other version!

# 63 bytes version

Doesn't support the `::` notation to skip zeroes:

```
Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")=zimid16cz\:65536sm@Kdjz85

```

You can try it here

The different part here is converting the ipv6 to a number using base conversions:

```
=zimid16cz\:65536
         z          read string from input and assign it to z
        c \:        split it at columns
   m                map over the split list with lambda d:
    id16            convert d from base 16 to 10
  i         65536   convert list of ints from base 65536 to 10
=z                  assign result back to z

```
> 2 votes

# Answer
# Pip, 108 bytes

```
YaR"::""*:"YyR"*"":0"X7-(":"Ny)Yy^":"Fiy{W#i<4iPU0bPBi}((J,t).AZ.z."!#$%&()*+-;<=>?@^_`{|}~")@((Jb)FB16TD85)

```

Remains fairly competitive without an IP address class/library

Try It Online!
> 2 votes

# Answer
# GCC C (functions) on x86, 240 bytes

This uses a couple of GCC specials:

```
#define U unsigned __int128
#define b(n) y[n&1]=__builtin_bswap64(y[n]);
g(U x){x?g(x/85),x%=85,putchar(x>9?x<36?x+55:x<62?x+61:"!#$%&()*+-;<=>?@^_`{|}~"[x-62]:x+48):0;}
f(char *a){long long y[3];inet_pton(10,a,&y[1]);b(2);b(1);g(*(U *)y);}

```

### Explanation

* `f()` is the entry point. It takes a single `char *`
* `inet_ntop()` converts full or compressed string representation of input address to the elements 1 and 2 of a 64-bit integer array
* Output from `inet_ntop()` is in network order (big endian), but the integer is needed in host order (little endian on x86) in order to perform arithmetic required for base conversion. Unfortunately gcc does not provide a `__builtin_bswap128()`. Instead the element 2 of the 64-bit integer array is `bswap64()`ed to the element 0 and the element 1 is `bswap64()`ed to itself. Elements 0 and 1 of the array now contain the address correctly in a host order 128-bit integer.
* Standard successive div/mod by 85 is used to present the integer in base 85. Because the first div/mod yields the last base 85 digit (and so on), the function `g()` performs this conversion recursively. The digits are effectively pushed to the stack and then output in the correct order.
* Conversion of digit value to ASCII character is a little messy. This is probably golfable.

### Test driver

Mildly ungolfed for readability.

Compile with `make ipv6enc` or `gcc ipv6enc.c -o ipv6enc`:

```
#define U unsigned __int128
#define b(n) y[n&1]=__builtin_bswap64(y[n]);
g(U x){
  if(x){
    g(x/85);
    x%=85;
    putchar(x>9?x<36?x+55:x<62?x+61:"!#$%&()*+-;<=>?@^_`{|}~"[x-62]:x+48):0;
  }
}
f(char *a){
  long long y[3];
  inet_pton(10,a,&y[1]);
  b(2);
  b(1);
  g(*(U *)y);
}

int main (int argc, char **argv) {

    f("1080::8:800:200C:417A");

    return 0;
}

```

---

### To do - Big endian version, 165 bytes

Find a big-endian platform where I can use the gcc 128-bit integers, so I can get rid of all the byte swapping stuff. The code should look like this, but right now this is untested on a big-endian platform:

```
#define U unsigned __int128
g(U x){x?g(x/85),x%=85,putchar(x>9?x<36?x+55:x<62?x+61:"!#$%&()*+-;<=>?@^_`{|}~"[x-62]:x+48):0;}
f(char *a){U y;inet_pton(10,a,&y);g(y);}

```
> 1 votes

# Answer
# Ruby `-ripaddr`, 109 bytes

```
->s{IPAddr.new(s).to_i.digits(85).reverse.map{([*0..9,*?A..?Z,*?a..?z]*""+"!#$%&()*+-;<=>?@^_`{|}~")[_1]}*""}

```

Attempt This Online!
> 1 votes

---
Tags: code-golf, string, internet, encoding
---


title: Hell0 W0rld! scored by ASCII values

text:
# Question
Title: Hell0 W0rld! scored by ASCII values
Write a program that outputs `Hell0 W0rld!`. It must match this output exactly, including capitalization, zeroes instead of o's, exactly one space, etc. Trailing new lines are allowed.

Lowest score wins. Scoring is based on the sum of the values of each character in the language's code page - otherwise Unicode values should be used. New lines are treated as spaces.

Here are a few example scores:

```
abc //Score: 294

print(Hell0 W0rld!) //Score: 1597

//Score: 1454
multi
line
code

```

You can check your ASCII score by inputting your code here. You can view individual ASCII values here.

# Answer
# Lenguage, score 0

Well, this is quite boring and obvious, but it seems to achieve the perfect score (assuming I understand the challenge correctly). To fix this loophole, you should probably add the program's length to the sum of the code points; I'm pretty sure that won't break the relative order of the current answers.

The program is

```
2282524454641945458940768311481012240407465625061984267694778013056442426959468031225640633070772676474431950201473533908

```

null bytes. Fortunately, 0 multiplied by the number above is still 0.

I believe this decompresses (alternatively, it *compresses*) to the automatically generated (with the help of a random web page that claims "Original Java program not from me") brainfuck program:

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

```

It almost certainly could be golfed (but I haven't tried), but that is unnecessary.
> 41 votes

# Answer
# 05AB1E, score ~~513~~ 252

<sup>-261 points thanks to @Dorian</sup>

Posting this separately from my other answer, as this one is arguably less cheating. I've been waiting for somebody else to do this for a while, but nobody did. I tried multiple languages. Pyth has extremely short code for this (`Cl"..."`, if I remember correctly), but it turned out it can't input null bytes, and most other golfing languages I found have painfully large char codes for quotes (and I couldn't write this piece of code in the rest).

```
"ǝǝǝǝǝǝǝǝǝǝǝǝ...ǝǝǝǝǝ"gтB

```

Where there are 174047470094320053473995 `ǝ` characters, that conveniently happen to have a value of 0 in the code page.

Explanation:

```
"ǝǝǝǝǝǝǝǝǝǝǝǝ...ǝǝǝǝǝ"        push the long string
                      g       pop and get its length
                       тB     push 100 and convert to that base

```

You definitely shouldn't try the full version online, but you can try online the version with the length finding part skipped.
> 16 votes

# Answer
# , 41 characters, code point sum 81

```
3200245300300120052223120310300244053**7**403
```

Try it online!

Unlike with many of my 7 programs, there's nothing particularly clever going on here; this basically just prints a string in the simplest possible way (which in 7 involves encoding the string into a piece of source code, evaluating it, analysing the resulting stack element to figure out what source code is most likely to have created it, and then giving the resulting source code directly to the output routines).

The reason this scores so well is that 7 has a code page consisting of only 8 characters, and the code that's used to represent string literals tends to use only `0`, `1`, `2`, `3`, `4`, `5` (as those commands have much easier-to-analyse effects on the stack than **`6`** and **`7`** do, so it's more likely that the original source will be accurately reproduced by the **`6`** command). This means that none of the code points in the bulk of the program will go above 5 (the assignment of code points to characters in 7 is the obvious one), leading to an *average* code point value of around 2½ (for this program, happenstance means it's more like 2). Thus, although there are a lot of characters in the program, the sum of the codepoints continues to stay low. (Unlike the Lenguage answer, the code point sum + character count is also very low, so this answer isn't even really cheating.)
> 12 votes

# Answer
# COW, Score: 117799

```
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MoO MoO
MoO MoO MoO MoO MoO Moo Moo OOO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MOo MOo MOo
MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo Moo MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MOo MOo MOo MOo MOo
MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo
MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo
MOo MOo MOo MOo Moo MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MOo MOo MOo
MOo MOo MOo Moo MOo MOo MOo MOo MOo MOo MOo MOo Moo OOO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO
MoO MoO Moo

```

Try it online!

My cow could not understand that the lower score in this challenge is better, so they scored very high! I kept telling them: "Please score lower, it is better", but they kept responding: "MoO"!
> 10 votes

# Answer
# HTML, Score: 959

```
Hell0
W0rld!
```

If newlines (`\r` and `\n`) would have been count as their ASCII code (`10` and `13`) the score would be **937** or **940** because in HTML, new lines in "inline" elements are rendered as space.
> 8 votes

# Answer
# Keg, sum = ~~966~~ ~~868~~ ~~853~~ 843

```
� +HOO��� +�UOG�(�+"

```

Try it online!

-15 score from cutting out the `0` (with a bit of help from the awful old Python script).

-10 score from A\__'s idea to use `"` and implicit print over the costlier `,`.

Based on a comment by Night2, as well as Jo King's old 32-byte quine.

```
� +HOO��� +�UOG�(�+"        Push the shifted codepoints beginning-first.
� +     � +                 ('H' and 'W' are pushed as sums,
                             because '+' is cheaper than '\'.)
                  +         Add
                 �          29
                   "        then rotate the stack
                (           once for every item on the stack.

```

If newlines weren't treated as spaces for scoring, this would be 832:

```

 +GNN���TNF�� +(�+"

```

Try it online!
> 7 votes

# Answer
# MineFriff, Score: 3725

```
Cff3,a*a,9*c,a*b4,6*8,8*a7,ff2,8*6,9*c,:a*a1,9*8,`
>l?#;o~

```

Try it online!

This ain't winning any competitions any time soon I tell you (I dread seeing what Scratch's score would be...). I'll post an image of what this looks like in-game soon, but first I have to actually re-install the python-in-minecraft mod and actually get it all working first.

See y'all soon! (I hope...)

## Actual In-Game Progess Report

### 10 mins in

* I managed to *finally* get Forge opened on my mac. That really shouldn't have taken 10 minutes but it did
* Minecraft 1.8 (unmodded) still hasn't launched/finished downloading.
* Still downloading the actual mod
* All star seems like a nice song to listen to while doing this

### 14 mins in

* Minecraft 1.8 finally opened
* Mod finally downloaded
* All star finished playing
* Moving on to actually using forge

### 17 mins in

* Forge successfully has installed and I'm loading in the mod now
* Jake Paul is *apparently* number one. Send help please.

### 20 mins in

* Help received. No longer listening to cringey songs
* I think I've properly installed the mod. No clue if it works because minecraft doesn't want to load.

### 23 mins in

* And I downloaded the wrong version of the mod. Oops. Nothing broken, just wasted, oh, I don't know, **6 minutes**. Sigh.

### 27 mins in

* I still can't read the documentation. Apparently, I needed to drag *all* the folders from the extracted zip into the mods folder
* Starting to think about downloading the minefriff world

### 30 mins in

* **MOD IS FINALLY INSTALLED**
* Thank goodness. Robbie Rotten is now number one. No help needed this time.
* Time to see if everything still works.

### 34 mins in

* About to test if actual interpreter works in-game. Wish me luck!

### 36 mins in

* Nup. Game crashed. :(

### Tomorrow

* I'll be trying 1.10 instead of 1.8

### Next day, 1 min in

* Minecraft 1.10 has somehow deleted itself from my list of available installations. Now I have to manually find it somewhere and then somehow get Forge to make a 1.10 profile. Problem is, I won't be able to work on it for another 4 hours. See y'all then!
> 6 votes

# Answer
# PHP, Score: 959

"Classic" answer. PHP outputs by default.

```
Hell0 W0rld!

```

Try it online!
> 5 votes

# Answer
# Bash, score: 1360

```
echo    Hell0   W0rld!

```

Try it online!
> 5 votes

# Answer
# Keg, Score: 1051

```
Hell0 W0rld\!

```

Try it online!
> 4 votes

# Answer
# Zsh, Score 1207

```
<<<"Hell0 W0rld!"

```

Try it online, with a self-scorer!

Using `<<<Hell0\ W0rld!` is shorter, but more expensive: `\` = `92`, but 2⨯`"` = `68`.
> 4 votes

# Answer
# Forth (gforth), Score: 1105

```
." Hell0 W0rld!"

```

Try it online!

Prints the given string to stdout.
> 4 votes

# Answer
# bit\**, Score: 2519

```
#72/#101/#108/#108/#48/#32/#87/#48/#114/#108/#100/#33/

```

Try it online!
> 4 votes

# Answer
# Japt, Score: 863

```
")FMM8SME"c+#

```

Test it
> 4 votes

# Answer
# C (gcc), Score: 2021

Thanks to GammaFunction

```
A(){puts("Hell0 W0rld!");}

```

Also, just for fun, here is a C program that had a score of 1 using overflow. It's a base64 encoded rar file https://pastebin.com/SJMcRnLj

Try it online!
> 3 votes

# Answer
# Jelly, Score:1213

Just the string. Nothing interesting.

```
“Hell0 W0rld!

```

## Score: 1744

Simply a compression.

```
“ØƲṡhḍḊF®Ḍ?»

```

Try it online!

Code page summator
> 3 votes

# Answer
# Turing Machine Code, Score: ~~7105~~ ~~6279~~ 5175

```
0   _   !   l   !
!   _   d   l   "
"   _   l   l   #
#   _   r   l   $
$   _   0   l   %
%   _   W   l   &
&   _   _   l   '
'   _   0   l   (
(   _   l   l   )
)   _   l   l   +
+   _   e   l   ,
,   _   H   l   -

```

*Implemented suggestions by Naruyoko*
*Shaved off another 1100+ using tabs instead of spaces*

Try it online!

# Turing Machine But Way Worse, Score: ~~69695~~ 55343

```
0   0   0   1   1   0   0
0   1   1   1   2   0   0
0   2   0   1   3   0   0
0   3   0   1   4   0   0
0   4   1   1   5   0   0
0   5   0   1   6   0   0
0   6   0   1   7   0   0
0   7   0   1   8   1   0
0   8   0   1   9   0   0
0   9   1   1   10  0   0
0   10  1   1   11  0   0
0   11  0   1   12  0   0
0   12  0   1   13  0   0
0   13  1   1   14  0   0
0   14  0   1   15  0   0
0   15  1   1   16  1   0
0   16  0   1   17  0   0
0   17  1   1   18  0   0
0   18  1   1   19  0   0
0   19  0   1   20  0   0
0   20  1   1   21  0   0
0   21  1   1   22  0   0
0   22  0   1   23  0   0
0   23  0   1   24  1   0
0   24  0   1   25  0   0
0   25  1   1   26  0   0
0   26  1   1   27  0   0
0   27  0   1   28  0   0
0   28  1   1   29  0   0
0   29  1   1   30  0   0
0   30  0   1   31  0   0
0   31  0   1   32  1   0
0   32  0   1   33  0   0
0   33  0   1   34  0   0
0   34  1   1   35  0   0
0   35  1   1   36  0   0
0   36  0   1   37  0   0
0   37  0   1   38  0   0
0   38  0   1   39  0   0
0   39  0   1   40  1   0
0   40  0   1   41  0   0
0   41  0   1   42  0   0
0   42  1   1   43  0   0
0   43  0   1   44  0   0
0   44  1   1   45  0   0
0   45  1   1   46  0   0
0   46  0   1   47  0   0
0   47  0   1   48  1   0
0   48  0   1   49  0   0
0   49  0   1   50  0   0
0   50  1   1   51  0   0
0   51  0   1   52  0   0
0   52  0   1   53  0   0
0   53  0   1   54  0   0
0   54  0   1   55  0   0
0   55  0   1   56  1   0
0   56  0   1   57  0   0
0   57  1   1   58  0   0
0   58  0   1   59  0   0
0   59  1   1   60  0   0
0   60  0   1   61  0   0
0   61  1   1   62  0   0
0   62  1   1   63  0   0
0   63  1   1   64  1   0
0   64  0   1   65  0   0
0   65  0   1   66  0   0
0   66  1   1   67  0   0
0   67  1   1   68  0   0
0   68  0   1   69  0   0
0   69  0   1   70  0   0
0   70  0   1   71  0   0
0   71  0   1   72  1   0
0   72  0   1   73  0   0
0   73  1   1   74  0   0
0   74  1   1   75  0   0
0   75  1   1   76  0   0
0   76  0   1   77  0   0
0   77  0   1   78  0   0
0   78  1   1   79  0   0
0   79  0   1   80  1   0
0   80  0   1   81  0   0
0   81  1   1   82  0   0
0   82  1   1   83  0   0
0   83  0   1   84  0   0
0   84  1   1   85  0   0
0   85  1   1   86  0   0
0   86  0   1   87  0   0
0   87  0   1   88  1   0
0   88  0   1   89  0   0
0   89  1   1   90  0   0
0   90  1   1   91  0   0
0   91  0   1   92  0   0
0   92  0   1   93  0   0
0   93  1   1   94  0   0
0   94  0   1   95  0   0
0   95  0   1   96  1   0
0   96  0   1   97  0   0
0   97  0   1   98  0   0
0   98  1   1   99  0   0
0   99  0   1   100 0   0
0   100 0   1   101 0   0
0   101 0   1   102 0   0
0   102 0   1   103 0   0
0   103 1   1   104 1   1

```

*Tabs instead of spaces, saving over 14,000*

Try it online!
> 3 votes

# Answer
# Charcoal, score 722

```
⍘Ｌ”y；；；(...231699726063762276300861 in total...)；；；”γ

```

Port of @someone's 05AB1E answer. Explanation: If you convert 231699726063762276300861 to base 95 using the printable ASCII character set then you get the desired output. Only printable ASCII characters are automatically turned into string literals, so our null bytes have to be quoted with `”y”`. Using Charcoal's code page, the special characters have the byte values 148 + 204 + 9 + 121 + 0 + ... + 0 + 9 + 231 = 722.

As proof of concept, you can see it just for the letters `He`: Try it online!
> 3 votes

# Answer
# Malbolge, Score: 6087

Just because I can.

```
('<;_#!7[}4{2VxTv-QsqNo'K+k)"Fgf|Bcc>=O<;(Kq7XXm3TjSng-x+)((`%d#"E~Y|{{>g,;;ut

```
> 3 votes

# Answer
# x86-64 machine code (Linux executable w/ system calls), score 1508

274 bytes: 18 code bytes, 12 data bytes, and 244 zero-padding bytes to make a rel32 = `00 01 00 00` instead of some larger number in the lowest byte.

The natural character-set of x86 machine code is 1 binary byte. No argument can be made for word, unlike with a RISC with fixed-length instructions.

Hexdump of the `.text` section of the executable (actually from assembling the same thing into a flat binary for `hexdump -C`). I'm not counting the metadata bytes of the whole executable emitted by the linker.

```
00000000  8d 35 00 01 00 00 5f 04  0c 92 04 01 0f 05 04 30  |.5...._........0|
00000010  0f 05 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000020  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
*
00000100  00 00 00 00 00 00 48 65  6c 6c 30 20 57 30 72 6c  |......Hell0 W0rl|
00000110  64 21                                             |d!|
00000112

```

Disassembly (`objdump -d -Mintel`).

```
0000000000400080 <_start>:            # Entry point
  400080:       8d 35 00 01 00 00       lea    esi,[rip+0x100]        # 400186 <msg>

0000000000400086 <_start.lea_ref>:
  400086:       5f                      pop    rdi      # fd = argc = 1
  400087:       04 0c                   add    al,0xc
  400089:       92                      xchg   edx,eax
  40008a:       04 01                   add    al,0x1
  40008c:       0f 05                   syscall         # write(argc=edi, msg=rsi, msglen=rdx) leaves RAX=msglen
  40008e:       04 30                   add    al,0x30
  400090:       0f 05                   syscall         # exit(edi=1)
        ... (a bunch of 00 bytes)

0000000000400186 <msg>:
         48 65  6c 6c 30 20 57 30 72 6c 64 21    db "Hell0 W0rld!"

```

Note that Linux static executables start with all registers = 0 (except RSP which points to `argc` on the stack).

`add al, imm8` has opcode `04`, and is the lowest opcode that takes an immediate. Using that to turn a `0` into a number we want, and `xchg`-with-eax for another zero, is the best way I've found to construct small numbers under these scoring rules. `push imm8`/`pop` is somewhat worse, and `mov reg,imm8` has a high opcode.

**The opcode map at http://ref.x86asm.net/coder64.html was very useful for this.**

---

**Built with `nasm -felf64 hell0.asm && ld -o hell0 hell0.o` from this source:** (Including a mess of commented out possibilities, many with their instruction bytes to remind me why I didn't use them.)

If `MSGXOR` is `%define`d to a non-zero value, link with `ld -N` (aka `--omagic`) to make `.text` read+write. In that case, the `%if` includes a loop that XORs every byte of the string. `0x60` and `0x64` are both equal. Subtraction with `0x30` doesn't save enough, and subtraction with larger values wraps around for too many bytes creating larger bytes.

```
BITS 64                     ; for flat binary.
%define MSGXOR 0x60

default rel
_start:
    lea    esi,[rel msg]  ; small positive offset.  Truncating the address to 32-bit is ok in a non-PIE
;    mov esi, msg         ; better than   rsi, msg  or strict qword
 .lea_ref:

;    add    al, 1        ; nr_write.  04  add al, imm8 is the lowest-opcode immediate instruction
    ;cmovnz edi, eax     ; 0f 45 f8    RDI is the highest-numbered register, and mode=11 is killer in ModRM
;    xchg   edi, eax          ; 9x
;    mov    edi, [rsp]        ; 8b 3c 24
    pop    rdi                ; 5f      fd = argc=1

;    lea    edx, [rax+msglen]     ; 8d 50 0d
    add    al, msglen
    xchg   edx, eax                ; len = msglen

%if 0
    lea    edi, [rax]   ; 8d 38
    add    edi, eax
    mov    esi, eax
%endif
;    push  "Hell"  ; 68 48 65 6c 6c  ; then would need to deal with 64-bit addresses

;    add cl, msglen    ; 80 c1 0c
;    mov cl, msglen    ; b1 0d

%if MSGXOR != 0
    add al, msglen-2      ; last byte is a '!' which grows when XORed with 0x60
.loop:
    xor byte [rsi+rax], MSGXOR
    sub eax, strict dword 1      ; longer immediate makes the backwards jcc farther from FF
        ;sub al, 1; 2c 01
    jnc  .loop                   ; }while(rax>=0); jnc has a lower opcode than jge or jns

;    lea ecx, [.loop]     ; at the top: 8d 0d 00 00 00 00       ; loop back with an indirect jump so the loop exit can jump forwards?
;        push  rcx    ; 51
;        ret          ; c3
;       jmp  rcx    ; ff e1   nope, doesn't look good.  Just have to eat the nearly-FF rel8

;    loop .loop   ; e2 f2
.break:
;;; AL = -1     after the loop
   add    eax, strict dword 2
%else
   add    al, 1                  ; RAX = 1 = _NR_write
%endif
; %else EAX = 0 still

;    add    al, 1 + !!MSGXOR      ; RAX = 1 = _NR_write
;    mov    al, 1
    syscall                      ; write(argc, msg, msglen) returns RAX=msglen

;    xor    al, 60 ^ msglen
    add    al, 60-msglen       ; or sub to wrap to 231 _NR_exit_group?
;    or     al, 60
;    mov    al, 60     ; exit.
;    mov    eax, 60
    syscall

 padbytes equ 0x100 - ($ - .lea_ref)
 times padbytes   db 0

; in the same section as the code so we can control the rel32 to have one non-zero byte of 01
X equ MSGXOR
;msg: db "Hell0 W0rld!"
msg: db 'H'^X, 'e'^X, 'l'^X, 'l'^X, '0'^X, ' '^X, 'W'^X, '0'^X, 'r'^X, 'l'^X, 'd'^X, '!'  ; last byte not XORed
msglen equ $-msg
;ml: db msglen

;msg: db 0x28, 0x5, 0xc, 0xc, 0x50, 0x40, 0x37, 0x50, 0x12, 0xc, 0x4, 0x41   ; with ^0x60

```

Score counted with `hexdump | awk` with a custom format to dump bytes in decimal, and awk to add them up.

```
nasm hell0.asm -o hell0.bin &&
 <hell0.bin hexdump -e '32/1 "%d " "\n"' |
 awk '{for(i=1; i<=NF; i++)tot+= $i;} END{printf "score = %#x = %d\n", tot, tot}'

```

**With MSGXOR = 0x60, score = 1668, the loop does *not* pay for itself with this short message**, especially with `0` digits instead of `o` lower-case ASCII. `cmp al,imm8` is `3C`, but `cmp/jcc` and counting *up* towards `mslen-1` instead of materializing `msglen` and `msglen-2` separately might help. But it wouldn't help enough; **we're 160 score away from break-even.**

```
# with MSGXOR = 0x60
0000000000400080 <_start>:
  400080:       8d 35 00 01 00 00       lea    esi,[rip+0x100]        # 400186 <msg>

0000000000400086 <_start.lea_ref>:
  400086:       5f                      pop    rdi
  400087:       04 0c                   add    al,0xc
  400089:       92                      xchg   edx,eax
  40008a:       04 0a                   add    al,0xa

000000000040008c <_start.loop>:
  40008c:       80 34 06 60             xor    BYTE PTR [rsi+rax*1],0x60
  400090:       2d 01 00 00 00          sub    eax,0x1
  400095:       73 f5                   jae    40008c <_start.loop>

0000000000400097 <_start.break>:
  400097:       05 02 00 00 00          add    eax,0x2
  40009c:       0f 05                   syscall
  40009e:       04 30                   add    al,0x30
  4000a0:       0f 05                   syscall
        ...

0000000000400186 <msg>:
  400186:       28 05 0c 0c 50 40      # not really instructions, deleted disassembly
  40018c:       37
  40018d:       50
  40018e:       12 0c 04
  400191:       21                      .byte 0x21

```

I can't find a way to jump backwards that isn't horrible. Register-indirect jump sucks, and short displacements need a `0xF?` byte. Padding with any non-zero byte to change the displacement costs at least as much as it reduces the `rel8` displacement, and `00 00` is `add [rax], al`. Hmm, Possibly with a 256-byte-aligned address in RAX, we could pad with `00 00` without modifying memory? But `xchg` with EAX is a `9?` byte and getting an address into RAX is costly.

But if we have a pointer in RAX, we can't use `add al, 1` or `sub al, 1` to loop. In 32-bit code we'd have `4?` `inc`/`dec`, but not RIP-relative addressing. x86-64 `inc`/`dec` are terrible, using the `ff /0` modrm encoding.

(**I considered using a linker script to set the absolute virtual address to something even lower**, but LEA's opcode is lower than `mov r32, imm32`. Hrm, for EAX there is `05` `add eax, imm32` with an absolute address. So looping another reg with inc or dec might be viable. Or looping EAX with a pointer-compare, especially if I can make the absolute data address something like `00 00 01 00` just outside the low 64k where Linux disallows memory-mapping by default. But then I'd feel like I had to count the linker script or its resulting metadata. Or if I'm messing around with the metadata (ELF headers) in the executable, maybe have to count the whole thing instead of just the .text section.)

32-bit code needs `int 0x80` for system calls, not `0f 05` syscall.
> 3 votes

# Answer
# , Score: 1452

```
echo'Hell0 W0rld!'

```

Try it online!
> 2 votes

# Answer
# evil, Score: 12853

Hard-code the characters

```
zaeeeaeeewzaeeaeeaeawzuueeueueawzuueeueueawzaeeeaeewzaeeeeewzaeeeeeuewzaeeeaeewzuueeueeaaawzuueeueueawzaeeaeeaewzaeeeeeaw

```

Try it online!
> 2 votes

# Answer
# Labyrinth, Score:2151

```
72.101.108.108.48.32.87.48.114.108.100.33.@

```

## Explanation

```
72                                          Push ord code of 'H'
  .                                         Output
   101.108.108.48.32.87.48.114.108.100.33.  And so on
                                          @ And exit.

```

Try it online!
> 2 votes

# Answer
## MSM, Score: 1465

```
!dlr0W 0lleH...........

```

It is great that `!` is not an MSM instruction. Half of the program pushes onto stack, half of it concatenates them.
> 2 votes

# Answer
# brainfuck, score: 5822

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

```

Try it online!
> 2 votes

# Answer
# Befunge, Score: 1385

```
"!dlr0W 0lleH">:#,_@

```

This is my first legitimate code golf so it's probably not the best. Still not sure how the scoring system works. Is lower or higher better?
> 2 votes

# Answer
# 80186 machine code (MS-DOS .COM format), score: 1799 (2061 bytes)

Nothing particularly special about this except that I used literal values on the stack to save score over `MOV` statements. To be able to use the same value for the function number and string location, I used just a little bit of padding.

```
68 00 09 58 50 5A CD 21 C3
(2039 zeroes) 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
48 65 6C 6C 30 20 57 30 72 6C 64 21 24

```

## TASM (ideal mode) source

```
IDEAL
P186

MODEL TINY
CODESEG
ORG 100H

MAIN:
    PUSH 0900H
    POP  AX
    PUSH AX
    POP  DX
    INT  21H
    RET

PADDING DB 7F7H DUP (0)
HELLO   DB "Hell0 W0rld!$"

END MAIN
ENDS

```
> 2 votes

# Answer
# HTML, score: 936

```
Hell0 W0rld!
```

HTML treats any whitespace as a space.
> 2 votes

# Answer
# Python 2, Score:1584

Prints the string...

```
print"Hell0 W0rld!"

```

Try it online!
> 1 votes

# Answer
# Ruby, Score:1245

```
$><<"Hell0 W0rld!"

```

Try it online!
> 1 votes

# Answer
# shortC, Score:1166

ShortC version of this.

```
AJ"Hell0 W0rld!"

```

Try it online!
> 1 votes

# Answer
## Scratch 3, score: ~~2908~~ 2012

In ScratchBlocks Syntax.

```
define
say[Hell0 W0rld!

```

Defines an anonymous function. When called, it returns `Hell0 W0rld!`.

http://scratchblocks.github.io/#?style=scratch3&script=define%0Asay%5BHell0%20W0rld!%5D
> 1 votes

# Answer
# ink, Score: 959

```
Hell0 W0rld!

```

Try it online!
> 1 votes

# Answer
# str, Score: 1081

```
`(ELL7RLD`32+o;

```

There are a lot of unprintable characters that don't show up above, see the TIO link for the full code.

Adds 32 to each character to get a lower score (the naive solution has a score of 1321)

Try it online!
> 1 votes

# Answer
# Runic Enchantments, Score: 1091

```
"Hell0 W0rld!"@

```

Try it online!

I honestly can't find a way to do this cheaper. The costs of string manipulation are just not worth the savings that can be gained. Eg. subtrating 30 from each character the output string saves `360` but costs `289` to undo plus another `165` in control logic (`454` total). Encoding the operational part of the program *inside* the string saves `32` (one fewer `"`) but costs `187`.
> 1 votes

# Answer
# Jelly, Score 998

```
“¡¡¡...(22405534226214299955809248283 more ¡'s)...¡¡¡‘Lb⁹Ọ

```

\\$254 + 0 + 0 + \cdots + 0 +252 + 76 + 98 + 137 + 181 = 998\\$

Proof of concept A
\\$35 \times 256 + 33=8993\\$ `¡`'s prints `#!`

Proof of concept B
\\$22405534226214299955809248289\\$ `¡`'s *would* print `Hell0 W0rld!`
(just a few too many characters for TIO)

### How?

```
“¡¡¡...¡¡¡‘Lb⁹Ọ - Main Link: no arguments
“¡¡¡...¡¡¡‘     - list of code-page indices = [0,0,0,...,0,0,0]
           L    - length = 22405534226214299955809248289
             ⁹  - literal 256
            b   - to base = [72,101,108,108,48,32,87,48,114,108,100,33]
              Ọ - to characters = "Hell0 W0rld!"

```

---

Base decompression using Jelly's code-page as digits would also score 998:

```
“¡¡¡...(22716232902740826769901577500 more ¡'s)...¡¡¡‘LṃØJ

```

\\$254+0+0+⋯+0+252+76+219+18+179=998\\$
> 1 votes

# Answer
# Assembly (nasm, x64, Linux), score: 9942 (114 bytes)

```
extern puts
global main
section .data
a: db "Hell0 W0rld!",0
section .text
main:
mov rdi,a
call puts wrt ..plt
ret

```

Try it online!

Simple assembler code which does the job (taken from original NASM's 64-bit hello-world, with unnecessary things being cut and some labels renamed to minimise the score). Probably can be golfed further.
> 1 votes

# Answer
# ///, Score 959

```
Hell0 W0rld!

```

Try it online!
> 1 votes

# Answer
# International Phonetic Esoteric Language, Score: 1192 (WIP language) (OLD)

```
<Hell0 W0rld!>o

```

No TIO interpreter yet, but is runnable by cloning the repository above, and calling `python3 main.py "code here"`.

```
<Hell0 W0rld!>o

<Hell0 W0rld!>  ;push string "Hell0 W0rld!"
              o ;pop, print

```
> 1 votes

# Answer
# , Score: 1420

Boring answer coming through. One thing to note, using " instead of ' saved 10 score points.

```
cat("Hell0 W0rld!")

```

Try it online!
> 1 votes

# Answer
# Whitespace, score: 2438 (118 bytes)

```
[S S T  T   S S S T S S N
_Push_-68_!][S S T  T   N
_Push_-1_d][S S S T T   T   N
_Push_7_l][S S S T  T   S T N
_Push_13_r][S S T   T   T   S T S T N
_Push_-53_0][S S T  T   T   T   S N
_Push_-14_W][S S T  T   S S S T S T N
_Push_-69_space][S T    S S T   S N
_Copy_0-based_2nd_-53_0][S S S S T  T   T   N
_Push_7_l][S N
S _Duplicate_top_7_l][S S S N
_Push_0_e][S S T    T   T   T   S T N
_Push_-29_H][N
S S N
_Create_Label_LOOP][S S S T T   S S T   S T N
_Push_constant_101][T   S S S _Add_top_two][T   N
S S _Print_as_character][N
S N
N
_Jump_to_Label_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).

Uses this Whitespace tip of mine to print the output. The optimal constant is generated by this Java program. In addition, I use one duplicate for the `ll` and one copy for the `0` to save bytes/score.
> 1 votes

# Answer
# JavaScript, Score: 1644

```
alert("Hell0 W0rld!")

```

You can't really do much with JavaScript.
> 1 votes

# Answer
## Rust, score: 2788

```
fn    main(){print!("Hell0 W0rld!")}

```

I was able to save some score by using a tab, but it's hard to make a short answer in Rust.
> 1 votes

# Answer
### x86 machine code - 72 bytes, score : 9253

I'm using `write()` syscall for printing a string.

```
     1                                  global _start
     2                                  section .data
     3 00000000 48656C6C                msg db  "Hell"
     4
     5                                  section .text
     6                                  _start:
     7
     8 00000000 8D0D[00000000]              lea ecx, [rel msg]
     9 00000006 43                          inc ebx
    10 00000007 80C204                      add dl, 4
    11 0000000A B004                        mov al, 4
    12 0000000C CD80                        int 0x80
    13 0000000E 80EA03                      sub dl, 3
    14 00000011 C60100                      mov byte [ecx + 0 - 0], 0
    15 00000014 800130                      add byte [ecx + 0 - 0], "0"
    16 00000017 B004                        mov al, 4
    17 00000019 CD80                        int 0x80
    18 0000001B C60120                      mov byte [ecx + 0 - 0], 0x20
    19 0000001E B004                        mov al, 4
    20 00000020 CD80                        int 0x80
    21 00000022 42                          inc edx
    22 00000023 66C7015730                  mov word [ecx+ 1 - 1], "W0"
    23 00000028 B004                        mov al, 4
    24 0000002A CD80                        int 0x80
    25 0000002C 80C203                      add dl, 3
    26 0000002F C701726C6421                mov dword [ecx + 3 - 3], "rld!"
    27 00000035 B004                        mov al, 4
    28 00000037 CD80                        int 0x80
    29 00000039 99                          cdq
    30 0000003A 42                          inc edx
    31 0000003B C6010A                      mov byte [ecx + 0 - 0], 0x0a
    32 0000003E B004                        mov al, 4
    33 00000040 CD80                        int 0x80
    34
    35 00000042 31DB                        xor ebx, ebx
    36 00000044 B001                        mov al, 1
    37 00000046 CD80                        int 0x80
    38
    39
    40 00000048 48                      .size: db $ - _start

```

Output : `Hell0 W0rld!`
> 1 votes

# Answer
# 80186, score 1727

```
A:  org  $0100
    mov  sp, $0200
    popa
    int  $21
    ret

    db $200-$ dup 0
    dw $0000  ; DI
    dw $0000  ; SI
    dw $0000  ; BP
    dw $0000  ; Ignored
    dw $0000  ; BX
    dw $0300  ; DX
    dw $0000  ; CX
    dw $0900  ; AX
    dw $0000  ; IP for RET

    db $300-$ dup 0
    db "Hell0 W0rld!$"
B:

```

Try it online!
> 1 votes

# Answer
# PowerShell, 13 bytes, 1027 score

```
"Hell0 W0rld"

```

Try it online!
> 1 votes

# Answer
## Pascal, 884 ≥ 3387 (ASCII) ≥ 6645 (EBCDIC)

The programming language Pascal is independent from any “code page”. The Pascal ISO standards call this circumstance “implementation-defined”. The theoretical minimum score should be about 900. If you tailored your source code to ASCII, you’ll capitalize keywords and identifiers and use tabs as token separators (the blanks outside the `string` are meant to be tabs):

```
PROGRAM A(OUTPUT);BEGIN WRITE('Hell0 W0rld!')END.

```

If you tailored your source code to EBCDIC, you’ll keep keywords and identifiers lower-case and also use tabs:

```
program a(output);begin write('Hell0 W0rld!')end.

```

In yet another character encoding other letters may be particularly “expensive” and you might trade longer code for “cheaper” letters.
> 1 votes

# Answer
# Io, score: 1584

Thanks to its lightweight syntax, we can get rid of the parentheses.

```
"Hell0 W0rld!"print

```

Try it online!
> 0 votes

# Answer
# VBScript, 1523 score

```
MSGBOX "Hell0 W0rld!"

```
> 0 votes

# Answer
# Windows Batch, 1278 score

```
ECHO Hell0 W0rld

```
> 0 votes

# Answer
# Noether, Score: 1107

```
"Hell0 W0rld!"P

```

Try it online!
> 0 votes

# Answer
# Bits, score: 3973

```
1001000000101001100001100111110000001111110101111111100000010010001100000100011101

```

If you're interested, this is 82 bits = 10.25 bytes.

### Explanation

```
1001000    // H
000101     // e
001100     // l
001100     // l
1111100000 // 0
011111     //
1010111    // W
1111100000 // 0
010010     // r
001100     // l
000100     // d
011101     // !
           // [Implicit join and output]

```
> 0 votes

---
Tags: code-challenge, hello-world
---


title: Counting Stripey Bracelets

text:
# Question
Title: Counting Stripey Bracelets
A bracelet consists of a number, \\$\mathit{N}\\$, of beads connected in a loop. Each bead may be any of \\$\mathit{C}\\$ colours. Bracelets are invariant under rotation (shifting beads around the loop) and reflection (turning the bracelet over).

Here are all \\$11\\$ bracelets with exactly two beads of each of three different colours. Source (Tilman Piesk).

A bracelet has \\$\mathit{S}\\$ stripes if merging all adjacent beads of identical colour until no longer possible would result in a bracelet with \\$\mathit{S}\\$ beads. In the above picture, the bracelet in the first column has \\$3\\$ stripes, while those in the second, third, fourth and fifth columns have \\$4\\$, \\$6\\$, \\$5\\$, and \\$6\\$ stripes, respectively.

Equivalently a bracelet has \\$\mathit{S}\\$ stripes if precisely \\$\mathit{d}\\$ neighbouring pairs of beads have different colours, where

$$\mathit{d} = \begin{cases} 0, & \text{if $\mathit{S}=1$} \\ S, & \text{if $\mathit{S}\>1$} \end{cases}$$

Note: The above picture does not show all stripey bracelets with six beads as it only shows those with *exactly* two of each of three *different* colours - there are \\$92\\$ distinct bracelets with six beads when choosing from three colours which may be partitioned into sets of stripey bracelets with \\$3\\$, \\$15\\$, \\$10\\$, \\$36\\$, \\$15\\$, and \\$13\\$ members with \\$1\\$ to \\$6\\$ stripes, respectively.

### Challenge

Given \\$\mathit{N}\\$, \\$\mathit{C}\\$, and \\$\mathit{S}\\$ output the number, \\$|\mathit{B}\_{\mathit{N},\mathit{C},\mathit{S}}|\\$, of different \\$\mathit{N}\\$-bead bracelets with \\$\mathit{S}\\$ stripes whose beads may be any of \\$\mathit{C}\\$ colours.

All three of the inputs are positive integers. You may assume that \\$\mathit{S} \le \mathit{N}\\$.

This is , so try to make the shortest code possible in your programming language of choice when measured in bytes.

### Examples

###### N = 4 beads, C = 3 colours, S = 4 stripes

\\$|\mathit{B}\_{4,3,4}| = 6\\$

```
-R--G--R--G-
-R--G--R--Y-
-R--G--Y--G-
-R--Y--R--Y-
-R--Y--G--Y-
-G--Y--G--Y-

```

###### N = 5 beads, C = 2 colours, S = 4 stripes

\\$|\mathit{B}\_{5,2,4}| = 2\\$:

```
-R--R--G--R--G-
-R--G--R--G--G-

```

###### N = 5 beads, C = 4 colours, S = 1 stripe

\\$|\mathit{B}\_{5,4,1}| = 4\\$:

```
-R--R--R--R-
-G--G--G--G-
-Y--Y--Y--Y-
-B--B--B--B-

```

###### N = 6 beads, C = 3 colours, S = 4 stripes

\\$|\mathit{B}\_{6,3,4}| = 36\\$:

```
-R--G--G--R--Y--Y-  ⇦ top of column 2 in the image
-R--R--Y--G--G--Y-  ⇦ middle of column 2 in the image
-R--R--G--Y--Y--G-  ⇦ bottom of column 2 in the image
-R--R--R--G--R--G-    (... the rest don't have exactly two of each colour)
-R--R--R--G--R--Y-
-R--R--R--G--Y--G-
-R--R--R--Y--R--Y-
-R--R--R--Y--G--Y-
-R--R--G--R--R--G-
-R--R--G--R--R--Y-
-R--R--G--R--G--G-
-R--R--G--R--Y--Y-
-R--R--G--G--R--Y-
-R--R--G--G--Y--G-
-R--R--Y--R--R--Y-
-R--R--Y--R--Y--Y-
-R--R--Y--G--Y--Y-
-R--G--R--G--G--G-
-R--G--R--Y--Y--Y-
-R--G--G--R--G--G-
-R--G--G--G--R--Y-
-R--G--G--G--Y--G-
-R--G--G--Y--G--G-
-R--G--G--Y--Y--G-
-R--G--Y--Y--Y--G-
-R--Y--R--Y--Y--Y-
-R--Y--G--G--G--Y-
-R--Y--G--G--Y--Y-
-R--Y--G--Y--Y--Y-
-R--Y--Y--R--Y--Y-
-R--Y--Y--G--Y--Y-
-G--G--G--Y--G--Y-
-G--G--Y--G--G--Y-
-G--G--Y--G--Y--Y-
-G--Y--G--Y--Y--Y-
-G--Y--Y--G--Y--Y-

```

###### N = 6 beads, C = 3 colours, S = 6 stripes

\\$|\mathit{B}\_{6,3,6}| = 13\\$:

```
-R--G--Y--R--Y--G-  ⇦ top of column 3 in the image
-R--G--Y--G--R--Y-  ⇦ middle of column 3 in the image
-R--G--R--Y--G--Y-  ⇦ bottom of column 3 in the image
-R--G--Y--R--G--Y-  ⇦ only of column 5 in the image
-R--G--R--G--R--G-    (... the rest don't have exactly two of each colour)
-R--G--R--G--R--Y-
-R--G--R--G--Y--G-
-R--G--R--Y--R--Y-
-R--G--Y--G--Y--G-
-R--Y--R--Y--R--Y-
-R--Y--R--Y--G--Y-
-R--Y--G--Y--G--Y-
-G--Y--G--Y--G--Y-

```

### Test cases

```
N, C, S, #
1, 1, 1, 1
1, 3, 1, 3
2, 1, 1, 1
2, 1, 2, 0
2, 2, 1, 2
3, 2, 3, 0
3, 5, 2, 20
4, 2, 4, 1
4, 3, 4, 6  * see above
5, 2, 4, 2  * see above
5, 3, 4, 15
5, 4, 1, 4  * see above
5, 8, 1, 8
5, 8, 2, 112
5, 8, 3, 336
5, 8, 4, 1400
5, 8, 5, 1680
6, 3, 1, 3
6, 3, 2, 15
6, 3, 3, 10
6, 3, 4, 36  * see above
6, 3, 5, 15
6, 3, 6, 13  * see above
6, 4, 3, 40
6, 5, 1, 5
6, 5, 2, 50
6, 5, 3, 100
6, 5, 4, 410
6, 5, 5, 510
6, 5, 6, 430

```

---

Brownie points for matching or beating \\$18\\$ bytes in Jelly

# Answer
# K (ngn/k), ~~44~~ 42 bytes

A function taking three curried arguments, call as `f[N][C][S]`.

```
(+/=)@+/~-1=':+?{a@*<a,:|'a:(#x)':x,x}'+!#

```

Try it online!
> 5 votes

# Answer
# 05AB1E, ~~23~~ 21 (20) bytes

```
LIãεā._Dí«Σ}н}ÙʒγgQ}g

```

Inputs in the order \\$C,N,S\\$.

Try it online or verify halve of the test cases (the test cases with larger \\$N\\$ time out).

**Explanation:**

Step 1: Get a list of all possible bracelets of size \\$N\\$ using up to \\$C\\$ amount of colors:

```
L           # Push a list in the range [1, first (implicit) input C]
 Iã         # Take the cartesian product with the second input N

```

Try just step 1 online.

Step 2: Only keep unique bracelets by removing rotations and reflections:

```
ε           # Map over each inner list:
 ā._        #   Get a list of all its rotations:
 ā          #    Push a list in the range [1,length] (without popping)
  ._        #    Rotate the original list each value amount of times towards the left
    D       #   Duplicate this list of rotations
     í      #   Reverse each inner list
      «     #   Merge the two lists together
       Σ}   #   Sort the list of lists - † should have been just {
         н  #  Only keep the first one
}Ù          # After the outer map: uniquify the list of lists

```

Try just the first 2 steps online.

Step 3: Only keep bracelets with \\$S\\$ amount of stripes:

```
ʒ           # Filter the lists by:
 γ          #  Split it into groups of equal adjacent items
  g         #  Pop and push the length
   Q        #  Check if it's equal to the third (implicit) input S
}           # Close the filter

```

Try just the first 3 steps online.

Step 4: Output the amount of valid stripey bracelets remaining:

```
g           # Pop and push the length
            # (which is output implicitly as result)

```

† - The `Σ}` (sort-by builtin without implementation) should have been `{` (sort builtin) for -1 byte, but due to some weird bug it doesn't work in this case.. :/ It does change the order somewhat, but definitely not to the expected lexicographical order..
Here an example output for the expected vs actual sorted rotations+reflections of a sample bracelet.
> 4 votes

# Answer
# Python 3, ~~148~~ 147 bytes

```
lambda N,C,S:sum(t==t[j::k]+t[:j:k]for*t,j,k in product(*map(range,[C]*N+[N]),[1,-1])if(len([*groupby(t*2)])//2or 1)==S)/N/2
from itertools import*

```

Try it online!

-1 Thanks to Jonathan Allan

Ungolfed:

```
from itertools import product
def f(N,C,S):
    z = 0
    for t in product(range(C),repeat=N):
        if sum(t[i] != t[i-1] for i in range(N)) == S*(S>1):
            for i in range(N):
                u = t[i:]+t[:i]
                z += t == u
                z += t[::-1] == u
    return z // (2*N)

```

Uses Burnside's lemma.
> 4 votes

# Answer
# Jelly, 15 bytes

```
ṗµṙJ;U$Ṃ)QŒgẈċ⁵

```

Try it online!

Port of @Kevin Cruijssen's 05AB1E answer, so upvote that!

## Explanation

```
ṗµṙJ;U$Ṃ)QŒgẈċ⁵ - Dyadic link taking C, N and S as the third command-line argument
ṗ               - C cartesian-power N (C implicitly converted to range [1..C])
 µ      )       - Over each X:
   J            -  Get list [1, len(X)]
  ṙ             -  For each Y in that, rotate X left by Y
      $         -  Last two links as a monad:
     U          -   Reverse each
    ;           -   Concatenate
       Ṃ        -  Minimum
         Q      - After map, uniquify
          Œg    - Split into groups of adjacent equal elements (vectorizes)
            Ẉ   - Length of each
             ċ⁵ - Count occurences of the third input (S)

```
> 3 votes

# Answer
# Vyxal, 18 bytes

```
ɾ↔ƛż¨VǓ:RJg;UvĠvLO

```

Try it Online!

Same as my Jelly answer, so ports 05AB1E.
> 3 votes

# Answer
# Python, 153 bytes

```
lambda n,c,s:len({a for x in product(*[range(c)]*n)if s==len([*groupby(a:=min(x[k::r]+x[:k:r]for k in range(n)for r in[-1,1]))])})
from itertools import*

```

Attempt This Online!

-6 thanks to Jonathan Allan
> 3 votes

# Answer
# Pyth, 54 bytes

```
LhSsm,.<_bd.<bdlbV.CUEEV.pNI!/YyHIqQ|ltr8+HhH1 aYyH;lY

```

Try it online!

Takes three inputs in order of `S`, `C`, `N`
> 2 votes

# Answer
# Python3, 299 bytes:

```
R=range
def f(N,c,S):
 q,p,K=[(N,S,[])],[],0
 while q:
  n,s,r=q.pop(0)
  if(t:=[r[k:]+r[:k]for k in R(N)]+[r[::-1]])!=n+s==0<(r[0]-r[-1]or S==1)>0==any(j in p for j in t):p+=t;v=r;K+=S==sum(v!=(v:=x)for x in r)
  elif n:q+=[(n+~j,s-1,r+[i]*-~j)for i in{*R(c)}-{([-1]+r)[-1]}for j in R(n)]
 return K

```

Try it online!

Completes all the test cases in \<20 seconds.
> 2 votes

# Answer
# JavaScript (ES7), 158 bytes

```
(n,c,s)=>(F=k=>k--&&([...p=[...Array(n)].map((_,i)=>q=k/c**i%c|0)].some(v=>F[p=[p.pop(t+=q!=v),...p]]|F[[...p].reverse(q=v)],t=0)|t+!t-s?0:F[p]=1)+F(k))(c**n)

```

Try it online!

### Commented

```
(n, c, s) =>            // outer function taking the parameters
( F = k =>              // inner recursive function taking a counter k
  k-- && (              // stop when k = 0 / decrement it
    [... p =            // build an array p[]
      [...Array(n)]     // of n elements,
      .map((_, i) =>    // filled with:
        q =             //   values from 0 to c - 1
        k / c ** i % c  //   with the last one saved in q
        | 0             //
      )                 // end of map()
    ].some(v =>         // for each value v in a copy of this array:
      F[                //   test whether we've already generated
        p = [           //     a rotation of the same pattern
          p.pop(        //     we use pop() to compute the rotations
            t += q != v //     and, at the same time, we keep track of
          ),            //     the number of stripes in t by counting
          ...p          //     runs of equal beads
        ]               //
      ] |               //
      F[                //   test whether we've already generated
        [...p].reverse( //     a reflection of the same pattern
          q = v         //     save the last bead in q
        )               //
      ],                //
      t = 0             //   start with t = 0
    ) |                 // end of some(); if it was truthy or the
    t + !t - s ?        // number of stripes is not the expected one:
      0                 //   leave the final result unchanged
    :                   // else:
      F[p] = 1          //   increment the final result and mark the
                        //   pattern as generated
  ) + F(k)              // add the result of a recursive call
)(c ** n)               // initial call to F

```
> 1 votes

# Answer
# Charcoal, ~~63~~ 56 bytes

```
ＮθＮηＮζＩＬΦＥＸηθＥθ﹪÷ιＸηλη∧⁼∧⊖ζζＬΦι⁻λ§ι⊕μ⁼ι⌊Ｅθ⌊Ｅ⟦ι⮌ι⟧Ｅθ§ν⁺λπ

```

Try it online! Link is to verbose version of code. Explanation:

```
ＮθＮηＮζ

```

Input `N`, `C` and `S`.

```
ＩＬ

```

Output the number of ...

```
ΦＥＸηθＥθ﹪÷ιＸηλη

```

... all of the rotations and reflections of all of the bracelets of `N` beads with `C` colours, filtered where...

```
∧⁼∧⊖ζζＬΦι⁻λ§ι⊕μ

```

... they have `S` stripes, and ...

```
⁼ι⌊Ｅθ⌊Ｅ⟦ι⮌ι⟧Ｅθ§ν⁺λπ

```

... the bracelet is in its canonical form, which is the minimum of its rotations and reflections, i.e. limiting the output to unique bracelets.
> 1 votes

---
Tags: code-golf, math, combinatorics
---