title: ASCII Meme Arrow Generator

text:
# Question
Title: ASCII Meme Arrow Generator
# Specifications

Given a number `n`, output an ASCII "meme arrow" (greater-than symbol, `>`) of size `n`.

`n` will always be a positive integer, greater than 0.

## Examples

`n = 2`

```
\
 \
 /
/

```

`n = 5`

```
\
 \
  \
   \
    \
    /
   /
  /
 /
/

```

# Sample code

Here is a sample program, written in Crystal, that returns the correct results. Run it as `./arrow 10`.

`arrow.cr`:

```
def f(i)
        i.times { |j|
                j.times { print ' ' }
                puts "\\"
        }
        i.times { |j|
                (i-j-1).times { print ' ' }
                puts '/'
        }
end

f(ARGV[0].to_i)

```

# Rules

* This is . The shortest answer wins. However, I will not select an answer, because the shortest answer may change over time.
* Standard loopholes are not allowed.

# Answer
> 12 votes
# Canvas, 2 bytes

```
＼═

```

Try it here!

# Answer
> 10 votes
# C (gcc), 56 bytes

```
f(n,i){for(i=-n;n;printf("%*c\n",i?++i+n:n--,i?92:47));}

```

Try it online!

```
f(n,i){for(i=-n;i;printf("%*c\n",  ++i+n    ,  92   ));     //first print descending '\'s
       for(    ;n;printf("%*c\n",        n--,     47));}    // then print returning  '/'s

```

# Answer
> 7 votes
# Python 2, 54 bytes

```
f=lambda n,p='':n*'?'and p+'\\\n'+f(n-1,p+' ')+p+'/\n'

```

Try it online!

Outputs with a trailing newline.

# Answer
> 5 votes
# C# (Visual C# Interactive Compiler), 66 bytes

```
n=>new int[n*2].Select((a,b)=>"".PadLeft(b<n?b:n*2+~b)+"\\/"[b/n])

```

Saved a byte thanks to @someone.

Try it online!

# Answer
> 5 votes
# Perl 5 `-p`, 36 bytes

```
$\=($q=$"x$_)."\\
$\$q/
"while$_--}{

```

Try it online!

# Answer
> 5 votes
# 05AB1E, 6 bytes

```
'\3.Λ∊

```

Try it online!

**Explanation**

```
   .Λ    # draw
'\       # the string "\"
         # of length input
  3      # in the south-eastern direction
     ∊   # then vertically mirror it

```

# Answer
> 4 votes
# Ruby, ~~111~~ ~~99~~ ~~77~~ ~~73~~ ~~68~~ ~~64~~ ~~57~~ 56 bytes

-12 bytes thanks to Benjamin Urquhart, -43 thanks to manatwork and -2 bytes thanks to Value Ink.

```
->i{s=[];puts (0...i).map{|j|s=(p=' '*j)+?/,*s;p+?\\},s}

```

Try it online!

Explanation:

```
f=->i{                      # instead of a function, use a lambda
  s=[]                      # needs a helper variable *now*, for scope
  puts(                     # puts takes arbitrary num of args; \n after each
    (0...i).map{|j|         # not from 0 to i but from 0 to i-1 (*three* dots)
      s=(
        p=' '*j             # p will remain in scope inside of .map,
      )
      +?/                   # character literal instead of string
      ,*s                   # essentially appending to the array

      p+?\\                 # p is what's returned by .map, not s!

    },                      # up until here, 1st arg to display
    s                       # NOW, as the *2nd* arg, s is displayed
  )
}

```

# Alternative (but longer) Solutions

A friend read this answer and then tried to come up with a couple more approaches. Putting them here, too, so that they're not lost to the vast interwebs.

## inject and unshift, 72 bytes

```
->n{puts (0...n).inject([]){|s,i|i=' '*(n-1-i);s.unshift i+?\\;s<<i+?/}}

```

Try it online!

## downto, inject and unshift, 80 bytes

```
->n{puts n.downto(1).map{|i|' '*(i-1)}.inject([]){|s,i|s<<i+?/;s.unshift i+?\\}}

```

Try it online!

## intriguing, two non-nested loops, 127 bytes

```
->n{
r=->s,c{s[0..-(c+1)],s[-c..-1]=s[c..-1],s[0..c-1];s};
n.times{|i|puts r[' '*n+?\\,n-i]}
n.times{|i|puts r[' '*n+?/,i+1]}
}

```

Try it online!

# Answer
> 4 votes
# PowerShell, ~~44~~ 41 bytes

```
filter f{if($_){'\'
--$_|f|%{" $_"}
'/'}}

```

Try it online!

# Answer
> 4 votes
# MarioLANG, 719 677 bytes

```
+
+
+
+
+
+         ((((+)+++++)))<
+>======================"
+)++++++)+++++++++++((-[!)
========================#=-
) ![-    <+;)+++)---)++++)<
)=#======"=================
) >)+)+((!
+ "======#
         <))))).(((((((<
 ========">============"
>)+)+((-[!+))        -[!((((((((.)).))))+(-[!)
"========#=============#====================#<
!)                                          <
#==========================================="
                  >(((((.)))>
                  "========<"========
 ![-)).))).(((((((![-    ))+![-((+)+)<((![<
 #================#=========#========"==#="===
 >                                   !  >-!
 "===================================#  "=#

```

Try it online!

This was harder than expected...

# Answer
> 4 votes
# C64Mini/C64 BASIC (and other CBM BASIC variants), 52 tokenized BASIC bytes used

```
 0INPUTN:N=N-1:FORI=0TON:PRINTTAB(I)"\":NEXT:FORI=NTO0STEP-1:PRINTTAB(I)"/":NEXT

```

Here is the non-obfuscated version for exaplantion:

```
 0 INPUT N
 1 LET N=N-1
 2 FOR I=0 TO N
 3  PRINT TAB(I);"\"
 4 NEXT I
 5 FOR I=N TO 0 STEP -1
 6  PRINT TAB(I);"/"
 7 NEXT I

```

What ever number is entered into `N` in line zero is reduced by one as the `TAB` command is zero-indexed; The `FOR/NEXT` loops in lines two through to four and five through to seven then output the upper and lower part if the `meme` arrow respectively (represented by a shifted `M` and shifted `N` in graphics mode source)

# Answer
> 4 votes
# brainfuck, 125 bytes

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

```

Try it online!

```
++++++++++[->+>+++++++++>+++<<<]>>++>++>    ; Initialize with " \"
,                                           ; Get input
[->                                         ; loop and decrement n
    [->+<<<.>>]                             ; output number of spaces, copy n
    <<<.                                    ; output \
    <.                                      ; output newline
    >>>>
    >[-<+>]<+                               ; copy copy of n back to original place
<]
<<[--<<+>>]<<+>>                            ; change "\" to "/"
>>>
[                                           ; second loop for bottom half
 -                                          ; decrement n
 [-<+<.>>]                                  ; output n spaces
 <<<<<.>.                                   ; output \ and newline
 >>>[->+<]>                                 ; copy n back
]

```

# Answer
> 3 votes
# Charcoal, 5 bytes

```
↘Ｎ‖Ｍ↓

```

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

```
↘Ｎ

```

Input a number and print a diagonal line of `\`s of that length.

```
‖Ｍ↓

```

Reflect the line vertically.

# Answer
> 3 votes
# T-SQL code, 80 bytes

```
DECLARE @ INT=3

,@z INT=0
x:PRINT
space(@-abs(@-@z-.5))+char(92-@z/@*45)SET
@z+=1IF @z<@*2GOTO x

```

**Try it online**

# T-SQL query, 96 bytes

In order to make this work online i had to make some minor alterations. Spaces in the beginning of a row doesn't display in the online snippet. So I am using ascii 160 instead. When running in management studio, it is possible to change the settings to show result as text, which would result in the correct spaces in this posted script.

```
DECLARE @ INT=3
SELECT space(@-abs(@-number-.5))+char(92-number/@*45)FROM
spt_values WHERE number<@*2and'p'=type

```

**Try it online**

# Answer
> 3 votes
# MAWP, 69 bytes

```
%@!0//[!1A]%[1A[1A84W;]%99W25WM1M;25W;]%[!1A]~[1A[1A84W;]%67W5M;25W;]

```

I am not going to golf this further bcause funny number. Sorry, guys.

Try it!

# Answer
> 2 votes
# APL(NARS), 40 chars, 80 bytes

```
{f←{⍺,⍨⍵⍴' '}⋄⊃('\'f¨k),('/'f¨⌽k←¯1+⍳⍵)}

```

test:

```
  h←{f←{⍺,⍨⍵⍴' '}⋄⊃('\'f¨k),('/'f¨⌽k←¯1+⍳⍵)}
  h 2
\
 \
 /
/
  h 5
\
 \
  \
   \
    \
    /
   /
  /
 /
/

```

# Answer
> 2 votes
# TypeScript's type system, 87 bytes

```
//@ts-nocheck
type F<N,S="">=N extends[{},...infer N]?`
${S}\\${F<N,`${S} `>}
${S}/`:""

```

Try it at the TypeScript playground

Takes input as a unary number represented by a tuple type N. If I instead took the unary number as a string type of spaces, this becomes **71 bytes:**

```
type F<S,O=''>=S extends` ${infer S}`?F<S,`${S}\\
${O&string}${S}/
`>:O

```

Try it at the TS playground

I like the shorter version better because it's tail-recursive and just overall really elegant, but I think the I/O format is a little cheaty.

# Answer
> 2 votes
# Vyxal, 8 bytes

```
ɾ\\↳↲øṀ§

```

Try it Online!

```
   ↳     # Right-pad
 \\      # \
ɾ        # To length each of range(1, n+1)
    ↲    # Left-pad each to length n
     øṀ  # Mirror, flipping slashes
       § # Vertical join, transposing and joining by newlines

```

# Answer
> 1 votes
# C (gcc), ~~67~~ 65 bytes

-2 bytes thanks to ceilingcat

```
f(n,i){for(i=~n;i++<n;)i&&printf("%*c\n",n-abs(i)+1,"/\\"[i<0]);}

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 32 bytes

```
.+
$* ¶$&$*
\G.
¶$`\
r`.\G
$'/¶

```

Try it online! Explanation:

```
.+
$* ¶$&$*

```

Generate two lines of `n` spaces.

```
\G.
¶$`\

```

Turn the top line into a `\` diagonal.

```
r`.\G
$'/¶

```

Turn the bottom line into a `/` diagonal.

# Answer
> 1 votes
# Haskell, ~~52~~ 49 bytes

-3 bytes thanks to Sriotchilism O'Zaic.

```
unlines.g
g 0=[]
g n="\\":map(' ':)(g$n-1)++["/"]

```

Try it online!

# Answer
> 1 votes
# Python 2, ~~85~~ ~~84~~ ~~81~~ ~~80~~ 75 bytes

```
def a(n):l="for i in range(n):print' '*";exec l+"i+'\\\\'\n"+l+"(n+~i)+'/'"

```

Try it online!

# Answer
> 1 votes
# PowerShell, 50 bytes

```
param($n)0..--$n|%{' '*$_+'\'}
$n..0|%{' '*$_+'/'}

```

Try it online!

Will look into making it so it only goes through the range once. Not bad for the no brain method though.

# Answer
> 1 votes
# Twig, 115 bytes

Builds the string backwards, "returning" it in the end.

Uses a macro to generate all the results.

```
{%macro a(N,s="")%}{%for i in N..1%}{%set s=('%'~i~'s
'~s~'%'~i~'s
')|format('\\','/')%}{%endfor%}{{s}}{%endmacro%}

```

This macro has to be in a file, and imported like this:

```
{% import 'macro.twig' as a %}

{{ a.a(<value>) }}

```

You can try it on https://twigfiddle.com/5hzlpz (click on "Show raw result").

# Answer
> 1 votes
# MATL, ~~14~~ ~~13~~ 12 bytes

```
Xy92*t45-Pvc

```

*1 Byte saved thanks to @LuisMendo*

**Explanation**

```
        % Implicitly grab the input as an integer
Xy      % Create an identity matrix this size
92*     % Multiply by 92 (ASCII for '\')
t       % Duplicate the matrix
45-     % Subtract 45 from every element yielding 47 (ASCII for '/') on the diagonal
        % and -45 everywhere else
P       % Vertically flip this matrix
v       % Vertically concatenate the two matrices
c       % Convert to characters (negative numbers are replaced with a space)
        % Implicitly display the result

```

Try it out at MATL Online

# Answer
> 1 votes
# Pyth, 19 bytes

```
VQ+*dN\\)V_Q+*dhN\/

```

Try it online!

TIL multiplying a string by a negative value multiplies it by its absolute value.

# Answer
> 1 votes
# Python 3, ~~90~~ 83 bytes

```
lambda n:'\n'.join([' '*i+'\\'for i in range(n)]+[' '*(n+~i)+'/'for i in range(n)])

```

Try it online!

-7 bytes thanks to @squid

# Answer
> 1 votes
# Rockstar, 133 bytes

Try it online here!

```
F takes N,S
If N is 0
Give back N

Say S+"\"
Let T be S+" "
Let M be N-1
F taking M,T
Say S+"/"

Listen to X
F taking X,""

```

Since Rockstar is not famous for string operations, it takes relatively lots of code to do it (recursively was even longer).

The size of the arrow is taken as input.

# Answer
> 1 votes
# PHP, ~~79~~ ~~63~~ 61 bytes

```
function f($x,$s=''){if($x)echo"$s\\
",f($x-1,"$s "),"$s/
";}

```

Try it online!

Recursive in PHP.

### *-12 bytes* by @manatwork

# Answer
> 1 votes
# \\/\\/\>, 74 bytes

```
jp100o
-84*}!o:?!x1
@+:q:p=?x:o~$:0(pa"\/"q?$~}}:
x2-:p$1-y$:0(?
.{suh?!;2

```

**Explanation:** (lines rotated based on start point)

```
jp100o                        //setup
:?!x1-84*}!                   //add leading spaces, loop and decrement until 0
~$:0(pa"\/"q?$~}}:@+:q:p=?x:o //add correct slash, go back to loop or switch sides
$:0(?x2-:p$1-y                //flip direction state or continue to print
{suh?!;2.                     //remove extra data and print stack

```

# Answer
> 1 votes
# Python 3, 55 bytes

```
f=lambda n,i="":n and i+"\\\n"+f(n-1,i+" ")+i+"/\n"or""

```

Try it online!

# Answer
> 1 votes
# Erlang (escript), 69 bytes

Port of xnor's Python answer.

```
r(0,_)->"";r(I,X)->X++"\\\n"++r(I-1,X++" ")++X++"/\n".
r(I)->r(I,"").

```

Try it online!

# Answer
> 1 votes
# Python 3, ~~91~~ 86 bytes

```
n=range(int(input()))
for i in n:print(' '*i+'\\')
for i in n:print(' '*(n[-1]-i)+'/')

```

Try it online!

Edit 1: saved 5 bytes by making n a range instead of integer

# Answer
> 1 votes
# Vyxal `j`, 95 bitsv2, 11.875 bytes

```
ƛI\\JøṀ;½fyRṘJ

```

Try it Online!

Bitstring:

```
00001000000011101111110001100110011110111010010010110001001000111000011010000100001110000011111

```

Beats all non-canvas users

# Answer
> 1 votes
# YASEPL, 58 bytes

```
=i=a'(`1=b;space,i~>"\"!+}7,a`2!-=b;space,i~>divide!}7,0,2

```

and just for fun...

# ibe, 118 bytes

```
adadadadadadaddsRafWmreafYmpeafUmtiakqskTagTmwakwafTmwslWssTmQmwaaYafQmwssQmRmqakeskTakrafTmwslWssTmQmraaUagQmwsaQmqme

```

(this is an esolang i made a while ago that i dont plan on releasing)

# Answer
> 0 votes
# Python 2, 63 bytes

```
f=lambda n,s='':n and f(n-1,~-n*' '+'\\\n'+s+~-n*' '+'/\n')or s

```

Try it online!

# Answer
> 0 votes
# Stax, 10 bytes

```
Ç₧¥╗M'gQ9⌂

```

Run and debug it

# Answer
> 0 votes
# JavaScript (Node.js), 42 bytes (If trailing new line is allowed)

```
n=>(F=s=>n--?s+`\\
`+F(s+" ")+s+`/
`:"")``

```

Try it online!

# JavaScript (Node.js), ~~48~~ 46 bytes

```
n=>(F=s=>s+`\\
${--n?F(s+" ")+`
`:""}${s}/`)``

```

Try it online!

# Answer
> 0 votes
# SimpleTemplate, 100 bytes

This was quite a fun challenge, but some bugs in the language made it hard to optimize.

```
{@set_ argv.0}{@while_}{@callstr_repeat intoS" ",_}{@setO S,"\\\n",O,S,"/\n"}{@incby-1_}{@/}{@echoO}

```

Basically, cycles throught the values backwards, working the string from the middle out.

---

**How the answer should be**

Due to the bugs, the code wasn't being interpreted properly.

This is how the code would be, if the compiler didn't had any bug (86 bytes):

```
{@forfrom argv.0to0step-1}{@callrepeat intoS" ",_}{@setO S,"\\
",O,S,"/
"}{@/}{@echoO}

```

Oh, well, at least the solution works :x

# Answer
> 0 votes
# Swift 5/Xcode 10.2.1, 91 bytes

```
(0..<n*2).map{String(repeating:" ",count:$0<n ?$0:n*2-$0-1)+($0<n ?"\\":"/")+"\n"}.joined()

```

Try it online!

# Answer
> 0 votes
# Java 8, 80 bytes

```
n->{for(int i=0;i<2*n;)System.out.printf("%"+(i++<n?i:n-~n-i)+"c\n",i>n?47:92);}

```

Try it online.

**Explanation:**

```
n->{                    // Method with integer parameter and no return-type
  for(int i=0;i<2*n;)   //  Loop `i` in the range [0, 2 * input `n`):
    System.out.printf(  //   Print with format:
      "%"+(i++<n?       //    If `i` is smaller than input `n`:
                        //    (and increase `i` by 1 right after this check with `i++`)
            i           //     Use `i` leading spaces
           :            //    Else:
            n-~n-i)     //     Use `2 * n - i + 1` leading spaces
      +"c\n",i>n?       //    If `i` is larger than input `n`:
              47        //     Append a trailing '/' and newline
             :          //    Else:
              92);}     //     Append a trailing '\' and newline

```

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

```
"\\/"¬c@õ!ùX zY

```

Try it

```
õ!ù'\ cUÆ'/ ùU´

```

Try it

# Answer
> 0 votes
# Pyth, 23 bytes

```
V2VQ
+*?N--QH1H\ ?N\/\\

```

Try it online!

Note that the program must not have a terminating newline! If saving it on linux, you can remove the last byte in a file using `head -c -1 <file>`.

I think this is the first time I have used for loops in pyth? Anyways, this is a rather direct port of the example source code in the question (though the 2 loops are combined, and the innermost loop is converted into string multiplication, and the remaining 2 prints are joined into one).

# Answer
> 0 votes
# Batch File, 117 + 9 bytes

Executed using `cmd/v/q/c`.

```
for /l %%i in (1,1,%1)do (for /l %%j in (2,1,%%i)do set %%i= !%%i!)&echo !%%i!\
for /l %%i in (%1,-1,1)do echo !%%i!/

```

# Answer
> 0 votes
# Pyth, 18 bytes

```
js.e+R?k\/\\b_B*L;

```

Try it online!

# Answer
> 0 votes
# Python 3.8 (pre-release), 80 bytes

```
lambda n:'\n'.join([' '*i+'\\'for i in(r:=range(n))]+[' '*(n+~i)+'/'for i in r])

```

Try it online!

Same approach as the one I suggested to @Artemis Fowl, but takes advantage of the walrus operator.

# Answer
> 0 votes
# Pepe, 91 bytes

```
rErEeEeEEEeeREeEREErereeereeERrEeeEeeeeeRrEeeeReereRerEEEererEeeEeEEEErEEEEREErereeereeERee

```

Try it online!

# Answer
> 0 votes
# Perl 5, 59 bytes

```
$_--;say$"x$_."\\"for(0..$_);say$"x$_."/"for(reverse 0..$_)

```

Example execution:

```
perl -nE '$_--;say$"x$_."\\"for(0..$_);say$"x$_."/"for(reverse 0..$_)'

```

Waits for an integer to be provided on `STDIN` when executed. Once provided, it will display the arrow.

# Answer
> 0 votes
# Rockstar, 85 bytes

```
listen to N
X's0
while N-X
say " "*X+"\"
let X be+1

while X
let X be-1
say " "*X+"/"

```

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

# Answer
> 0 votes
# Husk, 23 bytes

```
+mo`:'\R' ŀ¹mo`:'/R' ↔ŀ

```

Try it online!

There is probably a way to halve the size of this program.

# Answer
> 0 votes
# Forth (gforth), 72 bytes

```
: f dup 0 ?do i spaces 92 emit cr loop 1- for i spaces 47 emit cr next ;

```

Try it online!

there's probably a better way to do this.

# Answer
> 0 votes
# Zsh, 46 bytes

```
/ \\()for a;<<<${(l:a:)0};\\ {1..$1};/ {$1..1}

```

Try it online!

It really ought to be possible to get shorter than this...

# Answer
> 0 votes
# , 19 bytes

```
' \/'{~(,2*|.)@=@i.

```

Try it online!

# Answer
> 0 votes
# JavaScript (Node.js), 59 bytes

```
n=>eval("for(o='';s=''.padEnd(n--);)o=s+`\\\\\n${o+s}/\n`")

```

Attempt This Online!

I had a different idea, it didn't turn out as golfy as the obvious method but I still felt like posting it.

The program constructs the string with a for loop, counting down from `n`, and continuously sets a string `o` to: n spaces, backtick, newline, `o`, n spaces, forward slash, newline.

# Answer
> 0 votes
# Go, 133 bytes

```
import."strings"
func f(n int)(o string){for i:=0;i<n;i++{o+=Repeat(` `,i)+"\\\n"}
for i:=n;i>0;i--{o+=Repeat(` `,i-1)+"/\n"}
return}

```

Attempt This Online!

# Go 1.22+, 131 bytes

```
import."strings"
func f(n int)(o string){for i:=range n{o+=Repeat(` `,i)+"\\\n"}
for i:=range n{o+=Repeat(` `,n-i-1)+"/\n"}
return}

```

You cannot Attempt This Online!

Run it on the Go Playground!

# Answer
> 0 votes
# Perl 5 \+ `-p`, 20 bytes

Uses non-printable characters (backspace `0x08` and form feed `0x0c`) to position the characters in the terminal.

```
$_='\.'x$_."./.."x$_
```

Try it online!

## Explanation

Stores in `$_` a repetition of the literal string `\<FF>` `$_` (implicit input) times, concatenated with `<BS>/<FF><BS>` repeated `$_` times.

`$_` is then output implicitly by `-p`.

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


title: Count the number of sides on a polygon

text:
# Question
Title: Count the number of sides on a polygon
# Count the number of sides on a polygon

The polygon-side-counting robot has decided to travel the world without telling anyone before, but it is crucial that the process of polygon counting is not stopped for too long. So you have following task: Given a black and white image of a polygon, your program/functoin should return the number of sides.

The program will be fed to an old punch card computer, and as punchcards are very expensive nowadays, you better try to make your program as short as possible.

The edges are at least 10 pixels long, and the angles formed by two adjecent edges is at least 10° but no more than 170° (or again greater than 190°). The polygon is completely contained within the image, and the polygon as well as it's complement is connected (there are no isolated islands) so this input would **not** be valid:

# Scoring

This is codegolf, that means the shortest submission in bytes wins, your submission has to find the correct number of edges for every test case. (And the submission should work for other cases as well, optimization for just those test cases is not allowed.)

If you want to submit a solution that does not find the correct number each time, you can submit that too, but it will be ranked behind all the submissions that perform better.

Please include the total number in your submission title. (The total error the sum of the absolute differences between the real number of sides and the each output).

# Test cases

### n=10

### n=36

### n = 7

### n=5

### This is not a test case, just out of curiosity: How many edges do you get for this input?

# Answer
> 13 votes
# Python 2 + PIL, no error, ~~313~~ 307 bytes

```
from Image import*
I=open(sys.argv[1])
w,h=I.size;D=I.getdata()
B={i%w+i/w*1j for i in range(w*h)if D[i]!=D[0]}
n=d=1;o=v=q=p=max(B,key=abs)
while p-w:
 p+=d*1j;e=2*({p}<B)+({p+d}<B)
 if e!=2:e%=2;d*=1j-e*2j;p-=d/1j**e
 if abs(p-q)>5:
    t=(q-v)*(p-q).conjugate();q=p;w=o
    if.98*abs(t)>t.real:n+=1;v=p
print n

```

Takes an image file name on the command line, and prints the result to STDOUT.

Gives the correct result for all tests, and *n* = 28 for the circle.

## Explanation

The algorithm works by walking along the perimeter of the polygon, and counting the number of encountered vertices (detected as changes in direction). We start at the pixel farthest away from the origin, `o`, which is guaranteed to be a vertex, and therefore, to be adjacent to an edge (i.e., a boundary between a foreground pixel and a background pixel). We keep track of our position, `p`, the most recent vertex, `v`, and the most recent "checkpoint", `q`, all of which are initially equal to `o`. We also keep track of the direction of the edge, `d`, relative to the current pixel; `d` initially points east, which is a safe direction, since we know there's an edge to the east of `o`, or else it wouldn't be farthest from the origin. We move along the edge, in a direction perpendicular to `d`, such that `d` points to our left, i.e., in a clockwise direction. Whenever we "fall off the edge", i.e., in any situation where `p` is outside the polygon, or where the pixel to our left (i.e., in the direction of `d`) is inside the polygon, we adjust `p` and `d` accordingly before resuming.

Every time the distance between `p` and the last checkpoint, `q`, gets bigger than 5, we try to determine whether we passed over a vertex between `q` and `p`: We compare the angle between `vq` (i.e., the vector from `v` to `q`), which is the general direction of the side of the polygon we were walking along when we reached the last checkpoint, and `qp`, the displacement between the last checkpoint and the current position. If the angle is greater than about 10°, we conclude that we're walking along a different side of the polygon, increase the vertex count, and set `v`, the current vertex, to `p`. At each checkpoint, regardless of whether we detected a vertex or not, we update `q`, the last checkpoint, to `p`. We continue in this fashion until we arrive back at `o`, the starting point, and return the number of vertices found (note that the vertex count is initially 1, since the starting point, `o`, is itself a vertex.)

The images below show the detected vertices. Note that taking `p`, the current position at each checkpoint, as the position of the new vertex is not optimal, since the real vertex is probably somewhere between the last checkpoint, `q`, and `p`, along the perimeter. As you can see, all the vertices other than the first one (generally, the bottom-right vertex) are a little off. Fixing this would cost more bytes, but this seems to be working well enough as it is. That being said, it's a little hard not to overfit with only four test cases.

# Answer
> 0 votes
# Wolfram Language (Mathematica), 32 bytes

```
Length[ImageCorners[#,3,.01,4]]&

```

Try it online! (Testcases are base64 encoded after running it through optipng)

---
Tags: code-golf, image-processing
---


title: Number to Binary

text:
# Question
Title: Number to Binary
It seems we've managed to go all this time without a plain vanilla Number-To-Binary challenge! Whilst this will inevitably be only one element in many languages, it should put a few esolangs through their paces.

I truly looked for this challenge to no avail. If it already exists, comment as such and I'll delete this post-haste.

# Input

A single non-negative integer.

# Output

The same number as represented in Base 2.

# Test Cases

* `4 -> 100`
* `10 -> 1010`
* `1234 -> 10011010010`

# Victory Condition

, so fewest bytes wins!

# Notes

# Answer
> 7 votes
# Thunno, \\$ 1\log\_{256}(96)\approx \\$ 0.82 bytes

```
b

```

Attempt This Online!

# Answer
> 15 votes
# Piet \+ ascii-piet, 29 bytes (6×9=54 codels)

```
tkvuumf_iliqqdltT QqKln?_sf ?

```

Try Piet online!

B2C2 is `I` (no-op). The printing loop is now:

```
O d 1 % D I

```

which nicely forms a color loop.

---

# Piet \+ ascii-piet, 33 bytes (5×9=45 codels)

```
tkvuumf_iliqqdltT _?tser?_iqtf? ?

```

Try Piet online!

The bit-extracting logic is the same as Parcly Taxel's. The printing logic is new.

Loop 1: push bits of the input (`A1 -> A8 -> B8 -> B1 -> A1`)

```
D           No-op
I           Take input (n); no-op afterwards
d 2 %       [...bits n n%2]
2 1 r 2 /   [...bits n%2 n/2]
d ! D       Turn right if the new n is 0

```

Now there is a leading zero, which is handled nicely by `A2->B2` (`>`). Since the number below is 0 or 1, and `0>0 == 0` and `1>0 == 1`, the net effect is to simply remove the extra zero.

Loop 2: print bits until the stack is empty (`D2 -> E2 -> E1 -> D2 -> D5 -> E4 -> E1`)

```
d 1 > !    If the top exists, push 1; otherwise push 0
D          Turn right if it is 1; halt otherwise (white trap)
O          Output as number

```

# Answer
> 11 votes
# Python, 13 bytes

```
"{:b}".format

```

Attempt This Online!

# Answer
> 11 votes
# Piet \+ ascii-piet, ~~50~~ ~~44~~ 42 bytes (~~2×25=50~~ ~~2×22=44~~ 2×21=42 codels)

```
tabru?qd?t?itknmdjem_  a?liqdltailckt?iq ?

```

Try Piet online!

### Pointer Path

# Answer
> 10 votes
# Piet \+ ascii-piet, 73 bytes (7×12=84 codels)

```
um    R metabrujjL    ?  ll?dD    j  d ?T    l rr tN   ttbj nfI        nn

```

Try Piet online!

# Answer
> 9 votes
# Brain-Flak, 132 bytes

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

```

Outputs the individual numbers in a list with newlines as separators, and does not output anything for 0.

Explanation:

```
{                                                                   #  loop while top of left stack is not 0
(({})<><(()())>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})<>    #  leave the result of modulo 2 on right stack
({}<(()())>)({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>)    #  integer division by 2 on left stack
}                                                                   #  end loop
<>                                                                  #  switch to right stack
                                                                    #  implicit output of active (right) stack

```

Try it online!

I'm not the best at this language so I may have left a lot of room for further golfing, please let me know if you found a better way to do it.

# Answer
> 8 votes
# Pure Bash (no external utilities), 37

```
b()(((a=$1/2))&&b $a
echo -n $[$1%2])

```

Try it online!

This is a recursive function `b()` that takes its argument and divides by 2. If the result is non-zero, then `b()` is recursively called with the result. After the recursive call, the remainder when the argument is divided by 2 is the current binary digit. This is a pretty standard base conversion by repeated division by 2, with remainders becoming digits in base 2. Making it a recursive function has a couple of advantages here:

* Recursive function boilerplate is marginally shorter than while loop boilerplate for the same algorithm
* The repeated division yields digits (remainders) in reverse order to how they should be presented. By outputting the digit at each level after the recursive call, we effectively use the call stack to store the yielded digits and replay them back in the correct order

Ungolfed and perhaps a bit more readable:

```
function b() {
    a=$(( $1 / 2 ))
    if (( $a != 0 )); then
        b $a
    fi
    echo -n $(( $1 % 2 ))
}

```

# Answer
> 6 votes
# JavaScript, 16 bytes

```
x=>x.toString(2)

```

Try it online!

# Answer
> 6 votes
## bc \- 14 bytes

```
obase=2;read()

```

Run bc by typing `bc` into a terminal and pressing `Enter`. Type this code in, press `Enter`, type in the number to convert, and finally press `Enter` one more time. Press `Ctrl` \+ `C` to exit `bc`.

`read()` reads user input (in base 10 by default), and then `obase=2` sets it to output in binary. Given that we don't tell it to do any math operations (other than base-conversion), it just outputs the input, but in binary due to the `obase=2`.

Example:

```
$ bc
bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
obase=2;read()    <-- Press Enter
1234              <-- Press Enter again
10011010010       <-- Press Ctrl + C to exit
^C
(interrupt) Exiting bc.

```

I've tested this on Arch Linux, but any system with `bc` installed should work.

# Answer
> 6 votes
# K (ngn/k), 2 bytes

```
2\

```

Try it online!

# Answer
> 6 votes
# 05AB1E, 1 byte

```
b

```

Try it online!

# Answer
> 6 votes
# C (GCC), 21 bytes

```
f(n){printf("%b",n);}

```

Attempt This Online!

Will be pretty shocked if there is any way to do it shorter in C (unless I missed a weird print function).

# Answer
> 6 votes
# Befunge-93 (PyFunge), 28 bytes

```
2&v
2/>:0`!#^_:2%\
 ._@#-2:<

```

Try it online!

## Explanation:

`2&v` and `>` below: Push 2 (used as an "end of string" character of sorts), push user input (henceforth X), then go down and enter the main loop.

### Main Loop

`:0\`!`: Check if X is greater than 0. Invert the answer. (Specifically: duplicate X, push 0, swap, greater than, invert)

`#^_`: If top of stack is 1 (i.e. X \<= 0), go up to print loop, else continue right. (Bridge, (up), horizontal if)

`:2%`: Get X%2. (Duplicate X, push 2, modulo)

`\`: Store below X on stack. (Swap)

`2/`: Divide X by 2. Loop restarts with this as X. (push 2, integer divide)

### Print Loop

`<`: Go left. (going right here would add a `!` but it would not increase bytes as we have a spare whitespace on the left)

`-2:`: Check if top of stack = 2 (end of string). (RTL; duplicate, push 2, subtract)

`_@#`: Terminate program if top of stack = 0 (i.e. next item is 2). (RTL; bridge, (terminate), horizontal if)

`.`: Print top of stack as integer.

Note: I originally had a `$` to pop the leading 0 above the `^` in the main loop, but as per comments, leading 0s are allowed. Changing the `^` to a `v` would be equivalent, unless I were to add back in the `$` at the cost of 6 vs 10 bytes.

# Answer
> 6 votes
# Prolog (SWI), 26 bytes

```
:-read(X),format("~2r",X).

```

Try it online!

With builtin.

# Prolog (SWI), ~~42~~ ~~36~~ 35 bytes

*-6 bytes thanks to @Steffan*

*-1 byte thanks to @false*

```
N+X:-N<1,X=0;N//2+B,X is N/\1+10*B.

```

Try it online!

Without builtin.

---

Man, I haven't golfed in Prolog in a while; I forgot how wonky it is to code in it lol. Please tell me if there are any more golfs!

# Answer
> 6 votes
# Haskell, 31 bytes

```
f 0=0
f n=n`mod`2+10*f(n`div`2)

```

Try it online!

I'm unsure why `f$n`div`2` doesn't work as opposed to `f(n`div`2)`... I hope someone can explain this to me and help golf this code.

# Answer
> 6 votes
# Quipu, 78 bytes

```
2&1@0&2&0&3&
//**[][][][]
1&2&2&++1&/\
>>>>%%  --
\/1&1&  0&
    []  >>
    **

```

Attempt This Online!

### Explanation

Programs in Quipu consist of several "threads," vertical strips of code that are executed one at a time and also store values. Quipu is missing a lot of features that would have been useful for this challenge: lists, string concatenation, exponentiation... Lacking better methods, we generate the output as a base-10 number whose digits are either 0 or 1.

The first time thread 0 is executed, it loads the input number; subsequently, it divides its value by 2:

```
    # Previous value of this thread (implicit; initially 0)
2&  # Push 2
//  # Divide
1&  # Push 1
>>  # Go to that thread if the above result is greater than 0
\/  # Otherwise, read input number

```

Thread 1 generates successive powers of 10, starting at 1:

```
    # Previous value of this thread
1@  # Push 10
**  # Multiply
2&  # Push 2
>>  # Go to that thread if the above result is greater than 0
1&  # Otherwise, push 1

```

Thread 2 takes the current value mod 2 and multiplies by the appropriate power of 10:

```
0&  # Push 0
[]  # Load that thread's value
2&  # Push 2
%%  # Mod
1&  # Push 1
[]  # Load that thread's value
**  # Multiply

```

Thread 3 keeps a running sum of the values generated by thread 2. This will be our output number.

```
    # Previous value of this thread
2&  # Push 2
[]  # Load that thread's value
++  # Add

```

Thread 4 tests if the value in thread 0 is still greater than 1; if so, jump back to thread 0:

```
0&  # Push 0
[]  # Load that thread's value
1&  # Push 1
--  # Subtract
0&  # Push 0
>>  # Go to that thread if the above result is greater than 0

```

Once thread 0's value has reached 1 (or 0), execution continues with thread 5, which simply outputs the final result:

```
3&  # Push 3
[]  # Load that thread's value
/\  # Print

```

# Answer
> 6 votes
# Minecraft Data Pack via Lectern, 355 bytes

```
@function a:b
data modify storage  b set value []
scoreboard players set  i 2
function a:c
@function a:c
scoreboard players operation a i = i i
data modify storage  b prepend value 0
execute store result storage  b[0] int 1 run scoreboard players operation a i %=  i
scoreboard players operation i i /=  i
execute if score i i matches 1.. run function a:c

```

The function is `a:b`.

Takes input in the fake player `i` and the objective `i` (Which can be set using `/scoreboard objectives add i dummy`, `/scoreboard players set i i <input number>`).

Outputs a list via data storage `: b` (Which can be read by `/data get storage : b`).

I'm not sure this I/O format is valid, but this would be the standard way to do that if you were writing a library, although with the objective created by the data pack (and, of course, with more meaningful names).

# Answer
> 5 votes
# Python, 17 bytes

```
lambda n:f"{n:b}"

```

Attempt This Online!

# Answer
> 5 votes
# Vyxal, 1 byte

```
b

```

Try it Online!

# Answer
> 4 votes
# Python 2, ~~62~~ 54 bytes

```
i,o=input(),""
while i:i,j=divmod(i,2);o=`j`+o
print o

```

Try it online!

Just as a way of doing it without any builtins.

# Answer
> 3 votes
# Whitespace, 70 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input_n][N
S S N
_Create_Label_BINARY_LOOP][S N
S _Duplicate_n][N
T   S S N
_If_0_Jump_to_Label_PRINT_LOOP][S N
S _Duplicate_n][S S S T S N
_Push_2][T  S T T   _Modulo][S N
T   _Swap_top_two][S S S T  S N
_Push_2][T  S T S _Integer_divide][N
S N
N
_Jump_to_Label_BINARY_LOOP][N
S S S N
_Create_Label_PRINT_LOOP][T N
S T _Print_as_integer][N
S N
S N
_Jump_to_Label_PRINT_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).

Outputs with one additional leading `0`. This can be removed at the cost of 8 additional bytes:
Try it online.

**Explanation in pseudo-code:**

```
Integer n = STDIN as integer
Start BINARY_LOOP:
  If n==0:
    Jump to PRINT_LOOP
  Push n modulo-2 to the stack
  n = n integer-divided by 2
  Go to the next iteration of BINARY_LOOP

PRINT_LOOP:
  Print current top of the stack as integer to STDOUT
  Go to the next iteration of PRINT_LOOP

```

Stops the program with an error when it tries to print while the stack is empty.

# Answer
> 3 votes
# MATL, 1 byte

```
B

```

Try it at MATL Online

# Answer
> 3 votes
# Julia 0.7, 3 bytes

```
bin

```

Try it online!

# Julia 1.x, 9 bytes

```
bitstring

```

Attempt This Online!

Prints with leading zeroes.

# Answer
> 3 votes
# Swift, ~~55~~ ~~49~~ 20 bytes

##### -6 bytes thanks to @RydwolfPrograms

##### -29 bytes thanks to @Jacob

```
{String($0,radix:2)}

```

Try it online!

# Answer
> 3 votes
# , 2 bytes

```
#:

```

Attempt This Online!

`#:` returns the binary expansion of a given number y as a boolean list.

# Answer
> 3 votes
# Scratch, ~~70~~ 68 bytes

Puts a list of binary digits onto the `a` global variable, which is automatically displayed when the program finishes execution.

Saved 2 bytes by using `([floor v]of((n)/(2` instead of `((n)-(((n)mod(2))/(2`

Scratchblocks syntax:

```
define a(n
if<(n)>(0)>then
a([floor v]of((n)/(2
add((n)mod(2))to[a v

```

Try it on Scratch

# Answer
> 3 votes
# Desmos, 50 bytes

```
f(n)=mod(floor(n/2^{[floor(log_2(n+0^n))...0]}),2)

```

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 3 votes
# Haskell, 62 bytes

```
import Data.Sequence
d 0=Nothing
d n=Just$divMod n 2
unfoldl d

```

Attempt This Online!

A different approach than Aiden Chow's answer; this one uses `unfoldl` from `Data.Sequence`, which is elegant but unfortunately much less golfy.

### Explanation

`unfold` is conceptually the opposite of `fold`. `fold` takes a function that combines two values into one and a sequence of values, and returns a single value; `unfold` takes a function that splits one value into two and a single value, and returns a sequence of values. Specifically, the type of `unfoldl` looks like this:

```
unfoldl :: (b -> Maybe (b, a)) -> b -> Seq a

```

It takes a function and a single value of type `b` and returns a sequence of values of type `a`. The function must take a value of type `b` and return either a tuple containing one `b` and one `a` or `Nothing`. `unfoldl` applies the function repeatedly to the initial value, taking the first element of the tuple as the new value and saving off the second tuple elements as the sequence. It stops when it gets `Nothing` instead of a tuple.

In our case, both types are `Int`. We want the first element of the tuple to be the input int-divided by 2, and the second element to be the input mod 2. Conveniently, Haskell has a `divMod` function that returns exactly the tuple we want. Thus, our binary converter is just

```
unfoldl d

```

where `d` is a function that stops when it hits `0`:

```
d 0 = Nothing

```

and otherwise returns the result of `divMod` wrapped in a `Maybe`:

```
d n = Just (divMod n 2)

```

# Answer
> 3 votes
# , 9 bytes

```
intToBits

```

Attempt This Online!

Outputs as little-endian with trailing zeros.

---

# , 18 bytes

```
\(n)n%/%2^(n:0)%%2

```

Attempt This Online!

Outputs as big-endian (standard convention) with possibly a lot of leading zeros.

# Answer
> 3 votes
# Brain-Flak, 40 bytes

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

```

Try it online!

The other Brain-flak answer looked very long.

# Explanation

The first thing we can notice is that the following snippet:

```
(()[{}])

```

does something very nice. It's equivalent to `1-x`, which when constrained to the inputs of `0` and `1` will give us an increment and mod 2 operation. So we can calculate the mod 2 of a number by just repeating this snippet that many times starting with `0`.

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

```

This is nice and it can be modified to give us the full `divmod`. Each cycle we add the value of the accumulator we are building. Since it is `1` half the time and `0` the other half this gives us half the value. The one issue is it rounds up instead of down, so instead of adding `n` each step we add `1-n`. That is we add 1 when the accumulator is 0 and 0 when the accumulator is 1.

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

```

Now we add a bit of code to add a new accumulator each step and we can just repeat this divmod process until the div is zero.

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

```

# Answer
> 2 votes
# Java 8, 18 bytes

```
n->n.toString(n,2)

```

Try it online.

**Explanation:**

```
n->               // Method with Integer parameter and String return-type
  n.toString(n,2) //  Convert and return the given Integer as base-2 String

```

# Answer
> 2 votes
# Charcoal, 3 bytes

```
⍘Ｎ²

```

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

```
 Ｎ  Input as a number
⍘   Convert to base as a string
  ² Literal integer `2`
    Implicitly print

```

16 bytes without base conversion builtins:

```
Ｐ0ＮθＷθ«←§01θ≧÷²θ

```

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

```
Ｐ0

```

Output `0` by default (not strictly necessary according to the question definition but the builtin version does this).

```
Ｎθ

```

Input the integer.

```
Ｗθ«

```

Repeat until it is zero.

```
←§01θ

```

Output the least significant bit of the integer, moving right-to-left. (`←Ｉ﹪θ²` would also work for the same byte count.)

```
≧÷²θ

```

Integer divide the integer by 2.

# Answer
> 2 votes
# Retina 0.8.2, 23 bytes

```
.+
$*
+`(1+)\1
$+0
01
1

```

Try it online! Link includes test cases. Code is taken from the Retina 0.8.2 unary arithmetic tutorial for decimal to unary and unary to binary, except that for decimal to unary, the input is assumed to be decimal, so `.` is used instead of `\d`, and for unary to binary, `${1}` is golfed to `$+`.

# Answer
> 2 votes
# C# (.NET Core), 24 bytes

```
x=>Convert.ToString(x,2)

```

Try it online!

# Answer
> 2 votes
# Ruby `-n`, 8 bytes

```
p"%b"%$_

```

Attempt This Online!

# Answer
> 2 votes
# dc, 4 bytes

```
2o?p

```

Try it online!

# Answer
> 2 votes
## Scala, 16 bytes

```
_.toBinaryString

```

Try it Online! I took some inspiration from the Java solution's boilerplate to hide the type inference elsewhere.

# Answer
> 2 votes
# Pip, 3 bytes

```
TBa

```

Try It Online!

Builtin that converts to binary (TB). `a` is the input integer

# Answer
> 2 votes
# JavaScript (Node.js), 22 bytes

```
f=n=>n?f(n/2|0)+n%2:""

```

Try it online!

Not quite as short as the builtin but wanted to get a short solution doing it more manually. This solution recursively divides `n` by 2 and prepends the remainder.

Explanation:

```
f = n =>          // define f with arg n
  n               // is n nonzero?
   ?              // yes ->
     f(           //   recurse with
       n / 2 |0   //     divide by 2 and floor result
     ) + n % 2    //   append remainder (0 or 1)
   : ""           // no -> empty string is prepended to coerce everything

```

Figured this out from reading wikiHow to convert decimal to binary lol

# Answer
> 2 votes
# PHP, 6 bytes

```
decbin

```

Try it online!

No PHP answer yet? Surprisingly competitive this time!!!

# Answer
> 2 votes
# Alice, 25 bytes

```
/O \v$.:2[!<
@Mq/>.2%'0+^

```

Try it online!

This explanation below are still valid, I just reorganised the flow to save two bytes

```
/ M \w.2%'0+![2:.$K/ q O @   Full program (includes a new line)
/ M \                        Reads the argument
     w          .$K          Main loop
      .2%                    Gets the modulus by two of the number
         '0+![               Store the modulus + the char code of 0 to the tape
              2:             Divide the number by 2
                   / q O @   Join the tape, output and exit

```

# Answer
> 2 votes
## Befunge-93, 27 Bytes

```
v
2:._@#<-
&
<_!#: ^#/2\%2:

```

Try it online!

Alternately the following works as long as 0/0 results in a non-zero value pushed onto the stack (this is an option of PyFunge and the default behavior of this compiler online

```
v
2:._@#<-
&
<_  :/^#2\%2:

```

This results in only needing 26 bytes

This is my first post and so if anyone has comments of how I can improve this post feel free to let me know

# Answer
> 2 votes
# Swift, ~~35~~ 28 bytes

```
let b={String($0+0,radix:2)}

```

# Answer
> 2 votes
# Perl 5, 13 bytes

```
printf"%b",<>

```

Try it online!

# Answer
> 2 votes
# Labyrinth, 29 bytes

```
?
~:"" 2%!@
 _ ( _ "
 2/);(""

```

Try it online!

Handling zero input is nontrivial since loops in Labyrinth require a nonzero value at entry. To remedy this, the code uses bitwise NOT of the input value and repeatedly divides it by 2, which is floor division and therefore equivalent to arithmetic right shift. The loop is exited when the top reaches -1, and it runs at least once to ensure that the second loop is also entered with a nonzero value. As a result, the input of 0 outputs `0`.

```
Entry   ?~
?       Take input  [n]
~       Bitwise NOT [~n]

Loop 1  :_2/)(  [~n ~n/2 .. ~n/2^i] -> [~n .. ~n/2^(i+1)]
:_2/    Copy and divide by 2
)       Test if the top is -1; exit if so
(       Revert the value to continue the loop

Path    ;  [~n ~n/2 .. ~n/2^i 0] -> [~n ~n/2 .. ~n/2^i]
;       Drop the unnecessary zero

Loop 2  (_2%!  [~n ~n/2 .. ~n/2^i] -> [~n .. ~n/2^(i-1)]
(       Invert the parity of the top
        (decrement is chosen to ensure the top is nonzero)
_2%!    Mod 2 and print
        Exit the loop if there is nothing more to print

End     @
@       Halt

```

# Answer
> 1 votes
# Python 3, 19 bytes

```
lambda n:bin(n)[2:]

```

# Answer
> 1 votes
# MathGolf, 1 byte

```
à

```

Try it online.

**Explanation:**

```
à  # Convert the (implicit) input-integer to a binary-string
   # (after which the entire stack is output implicitly as result)

```

Irrelevant note: `â` (convert to a binary-list) isn't an equal-byte alternative, since it (for whatever reason) outputs in reversed order.

# Answer
> 1 votes
# Wolfram Language (Mathematica), 18 bytes

```
#~IntegerString~2&

```

Try it online!

# Answer
> 1 votes
# Brachylog, 1 byte

Try it online!

# Answer
> 1 votes
# Pyt, 1 byte

```
ɓ

```

Try it online!

Built-ins ftw

# Answer
> 1 votes
# Factor, 4 bytes

```
>bin

```

Try it online!

# Answer
> 1 votes
# Arturo, 15 bytes

```
$=>[as.binary&]

```

Try it

# Answer
> 1 votes
# Japt, 1 byte

```
¤

```

Try it

Shortcut for `s2`  which converts a number to a `s`tring in base `2`

# Answer
> 1 votes
# Excel, 11 bytes

```
=BASE(A1,2)

```

Straightforward built-in. Input is in the cell `A1` and can be anything from 0 to 253-1. Formula goes in any other cell in the sheet.

# Answer
> 1 votes
# GeoGebra, 23 bytes

```
a
InputBox(a
ToBase(a,2

```

Try It On GeoGebra!

# Answer
> 1 votes
# APL(Dyalog Extended), ~~9~~ 1 byte SBCS

Try it on APLgolf!

Literally a builtin... What more can I say?

# Answer
> 1 votes
# PARI/GP, 6 bytes

```
binary

```

Attempt This Online!

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 70 bytes

```
	I =INPUT
N	O =REMDR(I,2) O GT(I)	:F(O)
	I =I / 2	:(N)
O	OUTPUT =O
END

```

Try it online!

# Answer
> 1 votes
# Jelly, 1 byte

```
B

```

Try it online!

Lmao my first answer in Jelly. Just a builtin.

# Answer
> 1 votes
# CJam, 2 bytes

```
Yb

```

Try it online!

Link includes test cases

# Explanation

```
 b # Convert to base
Y  # builtin *2*

```

For fun, here's one which pads to 16 bits:

# CJam, 6 bytes

```
YbGTe[

```

Try it online!

# Explanation

```
 b    # Convert to base
Y     # builtin *2*
   e[ # and pad to length
 G    # builtin *16*
      # with
  T   # zeroes

```

# Answer
> 1 votes
# Simply, 17 bytes

The code simply creates an anonymous arrow function that calls the `&tb` function, and returns the result.

```
fn($x)=>&tb($x 2)

```

To use this function, assign it to a variable and call it:

```
$fn = fn($x)=>&tb($x 2)

echo call $fn(5);

```

---

## What does `&tb` do?

The function `&tb` is a built-in alias to `&tobase`.

This is the result of running `echo &doc(&tobase);`:

```
Documentation for tobase:
Converts the integer $number to the $base.
The $base must be between 1 and 36, otherwise, returns null.
E.g.: tobase(10, 10) = "10", tobase(10, 2) = "1010", tobase(10, 1) = "1111111111".

```

---

## Ungolfed

You can rewrite the code like this:

```
Set the variable $fn to an anonymous function with the argument $number.
Begin.
    Return the result of calling the function &tobase with the arguments $number and 2;
End.

```

Or, if you want it to be more code-like:

```
$fn = anonymous function($number) {
    return &tobase($number, 2);
};

```

# Answer
> 1 votes
# Knight (v2), 29 bytes

```
;=a@;=n*2P;W=n/n 2=a+,%n 2aOa

```

Try it online!

Zero outputs nothing, which is allowed in the rules.

# Answer
> 1 votes
# J 2 bytes

```
#:

```

Some test cases:

```
   #:12345

1 1 0 0 0 0 0 0 1 1 1 0 0 1

   #:33

1 0 0 0 0 1

```

# Answer
> 1 votes
# Raku, 8 bytes

```
.base(2)

```

Try it online!

The above version operates on the current topic, as seen in the demo code. To make it a function accepting an argument, just wrap it in curly braces for another two bytes.

# Answer
> 1 votes
# Thunno 2, 1 byte

Attempt This Online!

# Answer
> 1 votes
# Zsh, 13 bytes

```
<<<$[[##2]$1]

```

Try it online!

Vanilla answer... here are a couple more interesting variants

# Answer
> 1 votes
# ForWhile, 25 bytes

`{:[:1&'2/0@1+0$:)@[48+#)}`

Takes argument from the stack and prints to console

online interpreter

# Explanation

```
{                       }  \ anonymous procedure
 :[                        \ repeat n times
   :1&                     \ push the lowest bit of n
      '2/                  \ divide n by 2
         0@1+0$            \ increment memory cell 0
               :)          \ break loop if n is zero
                 @         \ read memory at address 0 (n is still on stack)
                  [48+#)   \ print bits converted to characters

```

# Answer
> 1 votes
# Uiua, 9 bytes SBCS

```
&pf⇌⋯⋕&sc

```

Try it online! Outputs as a list of bits.

## Explanation

```
&pf⇌⋯⋕&sc
      &sc # read line from stdin
     ⋕    # parse string as number
    ⋯     # encode number as bit array, LSB-first
   ⇌      # reverse array
&pf       # print to stdout

```

# Answer
> 0 votes
# Nibbles, 1.5 bytes

```
``@

```

Attempt This Online!

Built-in.

# Answer
> 0 votes
# Risky, 1.5 bytes

```
?}2

```

Try it online!

```
?}2
 }  Convert
?   input
 }  to base
  2 2

```

# Answer
> 0 votes
# Nim, 45 bytes

```
import strformat
func b(n:int):auto= &"{n:b}"

```

Attempt This Online!

# Answer
> 0 votes
# flax, 1 byte

```
B

```

Attempt This Online!

Builtin

# Answer
> 0 votes
## vemf, 1 byte

```
é

```

Represents α as a 64-element list of bits.

# Answer
> 0 votes
# YASEPL, 76 bytes

```
=d'(=y)""`9!m$d%!yſm!d/(}7,0,9=o-!h)""!u®"y"-=k$u`8!m¥u,"y"!hſm!u-}1,o,8>h

```

YASEPL is a (horribly coded and just stupid in general) esolang I made a while ago in Node.JS. it gets input via a prompt and STDIN. heres the output:

# Answer
> 0 votes
# \*\>\<\>, 14 bytes

Input is passed in through the `-i` flag.

```
:2%:n-2,:0)?!;

```

```
:               Duplicate the value on the stack
 2              Push 2 onto the stack
  %             Modulo those two
   :            Duplicate the result
    n           Pop and print that duplicate
     -          Subtract the result from our original number
      2         Push 2
       ,        Divide the two
        :       Duplicate that result
         0      Push 0
          )?!;  If the dividend is greater than 0, loop again

```

Try it online!

---
Tags: code-golf, binary
---


# Question
Title: Hare Krishna Hare Krishna Krishna Krishna Hare Hare
Recently, I've seen Hare Krishna people with their mantra on the emblem and I've found it may be quite interesting to code golf.

# The challenge

Write the Hare Krishna mantra, i.e.:

```
Hare Krishna Hare Krishna
Krishna Krishna Hare Hare
Hare Rama Hare Rama
Rama Rama Hare Hare

```

# Winning criteria

This is , so shortest code in bytes wins!

# Rules

* Casing must be preserved.
* Text should contain new lines.
* Lines may have trailing space(s).
* Trailing newline is allowed.
* Parsing from web or any other external resource disallowed.

# Answer
> 70 votes
# Jelly, 22 bytes

```
“t,ȧṫÞċḅ»Ḳ“¡¥Ɓc’ṃs4K€Y

```

Try it online!

### How it works

```
“t,ȧṫÞċḅ»Ḳ“¡¥Ɓc’ṃs4K€Y  Main link. No arguments.

“t,ȧṫÞċḅ»               Use Jelly's dictionary to yield the string
                        "Hare Rama Krishna". Fortunately, the words Rama, Krishna,
                        and hare (lowercase H) are in the dictionary.
         Ḳ              Split at spaces, yielding ["Hare", "Rama", "Krishna"].
          “¡¥Ɓc’        Base-250 literal; yielding 15973600.
                ṃ       Convert 15973600 to base ["Hare", "Rama", "Krishna"]
                        (ternary), where "Krishna" = 0, "Hare" = 1, and "Rama" = 2.
                 s4     Split the resulting string array into chunks of length 4.
                   K€   Join each of the four chunks by spaces.
                     Y  Join the resulting strings by linefeeds.

```

# Answer
> 67 votes
# 05AB1E, 38 bytes

Can be shortened by 2 bytes if trailing newlines are okay.

```
“«Î‡Ä¦í¥Â“#€¦`«'kì)™ð«•2ÍZì•3BSè#4ô¨»?

```

Try it online!

**Explanation**

```
“«Î‡Ä¦í¥Â“                              # push the string "drama share irish dna"
          #                             # split on spaces
           €¦                           # remove the first character of each word
             `                          # split to stack as separate words
              «'kì                      # concatenate the last 2 and prepend "k"
                  )™                    # wrap in list and title-case
                    ð«                  # append a space to each
                      •2ÍZì•            # push 27073120
                            3B          # convert to base-3: 1212221110100011
                              Sè        # index into the list with each
                                #       # split on spaces
                                 4ô     # split into pieces of 4
                                   ¨    # remove the last
                                    »   # join on spaces and newlines
                                     ?  # print without newline

```

# Answer
> 46 votes
# Python 2, 60 bytes

```
a="Hare"
for x in"Krishna","Rama":print a,x,a,x+'\n',x,x,a,a

```

Try it online!

This seems to beat template-replacement approaches like this attempt.

# Answer
> 41 votes
# Octave, ~~74~~ 59 bytes

```
[{'Hare ','Krishna ','Rama ',10}{'ababdbbaadacacdccaa'-96}]

```

Verify the output here.

**Explanation:**

`{'Hare ','Krishna ','Rama ',10}` creates a cell array with three strings, where the fourth is `10` (ASCII-value for newline).

`{'ababdbbaadacacdccaa'-96}` is a vector that indexes the cell array above. The vector is `[1 2 1 2 4 ...]` since we subtract `96` from the string `ababd...`.

The surrounding square brackets are used to concatenate the results, instead of getting `ans = Hare; and = Krishna; ans = ...`

# Answer
> 20 votes
# Retina, 39 bytes

```

hkhk¶kkhh
h
Hare
*`k
Krishna
k
Rama

```

Try it online!

Mostly plain substitutions, the only "trick" is the modifier `*` which prints the result of the substitution and then reverts the string back to what it was before.

# Answer
> 16 votes
# PHP, 61 Bytes

```
<?=strtr("0101
1100
0202
2200",["Hare ","Krishna ","Rama "]);

```

simply replacement from the digits as key in the array with the values strtr

Try it online!

# Answer
> 13 votes
# JavaScript, ~~75~~ 70 bytes

```
`0101
1100
0202
2200`.replace(/./g,n=>['Hare ','Krishna ','Rama '][n])

```

### Try it online!

```
console.log(`0101
1100
0202
2200`.replace(/./g,n=>['Hare ','Krishna ','Rama '][n]))
```

# Answer
> 12 votes
# C

# ~~154 bytes, 124 bytes,~~ 96 bytes

```
i;main(){char*c="agagvggaavapapvppaaHare \0Krishna \0Rama \0\n";while(i<19)printf(c+c[i++]-78);}

```

Try it online!

28 bytes saved, thanks to Dennis

# Answer
> 11 votes
# , ~~40~~, 36 bytes

```
iHare Krishna
 Rama ç^/ä$Ùdww.$2p

```

Try it online!

Hexdump:

```
00000000: 6948 6172 6520 4b72 6973 686e 6120 0a0e  iHare Krishna ..
00000010: 2052 616d 6120 1be7 5e2f e424 d964 7777   Rama ..^/.$.dww
00000020: 2e24 3270                                .$2p

```

Explanation:

```
iHare Krishna   " Enter 'Hare Krishna' on line 1
<C-n> Rama      " Enter 'Hare Rama' on line 2. This works because <C-n>
                " autocompletes alphabetically, and 'Hare' comes before 'Krishna'
<esc>           " Return to normal mode
ç^/             " On every line:
   ä$           "   Duplicate the text on the line horizontally
     Ù          "   Make a new copy of the line
      dw        "   Delete a word
        w       "   Move forward a word
         .      "   Delete a word again
          $     "   Move to the end of the line
           2p   "   And paste what we've deleted twice

```

The `<C-n>` command is extremely useful for challenges like this. :)

# Answer
> 10 votes
# C#, 109 bytes

```
void a(){Console.Write("{0}{1}{0}{1}\n{1}{1}{0}{0}\n{0}{2}{0}{2}\n{2}{2}{0}{0}","Hare ","Krishna ","Rama ");}

```

Fairly straightforward, `Console.Write` implicitly formats the string, and using `Write` instead of `WriteLine` not only saves 4 bytes, but avoids a trailing newline. Uses Unix-style newlines so might not work so well on windows, extra 6 bytes for windows by changing `\n` to `\r\n`

This method will output directly to the console, if you prefer a method that returns a string:

### C#, 118 bytes

```
string a(){return string.Format("{0}{1}{0}{1}\n{1}{1}{0}{0}\n{0}{2}{0}{2}\n{2}{2}{0}{0}","Hare ","Krishna ","Rama ");}

```

Alternatively if you need a fully stand-alone and compilable program:

### C#, 135 bytes

```
class A{static void main(){System.Console.Write("{0}{1}{0}{1}\n{1}{1}{0}{0}\n{0}{2}{0}{2}\n{2}{2}{0}{0}","Hare ","Krishna ","Rama ");}}

```

This should work as a compiled program provided you set `A` as the entry class.

# Answer
> 9 votes
# Python 2, ~~92~~ ~~88~~ 74 bytes

```
for i in'0101311003020232200':print['Hare','Krishna','Rama','\n'][int(i)],

```

Try it online!

*No*, it's not clever, no, it's not the shortest but hey, I'm new to this and it works.

Another solution (~~84~~ 80 bytes):

```
h='Hare'
k='Krishna'
r='Rama'
n='\n'
print h,k,h,k,n+k,k,h,h,n+h,r,h,r,n+r,r,h,h

```

# Answer
> 8 votes
## C, 85 bytes

```
i;f(){for(i=0;printf("$0$0900$$9$*$*9**$$)"[i++]-36+"Hare \0Rama \0Krishna \0\n"););}

```

I would prefer a secular mantra, but I hope this is one of those peaceful religions.

See it work here.

This compacts a naive implementation by 23 bytes.

# Answer
> 6 votes
# PowerShell, ~~73~~ ~~53~~ 52 Bytes

absolutely demolished by Jeff Freeman \- using an actual newline instead of `\n` saves another byte, and also saved one more on the array format. (from `(1,2)` to `,1,2`)

-1 thanks to TesselatingHeckler, no comma in the array notation.

```
$a="Hare ";"Krishna ","Rama "|%{"$a$_$a$_
$_$_$a$a"}

```

My old answer - Tried a few other replace methods but all ended up being slightly longer somehow.

```
$a,$b,$c="Hare ","Krishna ","Rama ";"$a$b$a$b
$b$b$a$a
$a$c$a$c
$c$c$a$a"

```

there are newlines in the string.

pretty straightforward, uses the fact that powershell will expand variables within doublequotes, and a shorter method of assigning variables to save some bytes.

# Answer
> 6 votes
## Perl, 67 bytes

Inspired by this JavaScript entry.

```
$_='0101
1100
0202
2200
';s/./qw'Hare Krishna Rama'[$&].$"/ge;print

```

## Perl, 67 bytes

```
@_=<Hare Krishna Rama>;print"@_[split//]\n"for<0101 1100 0202 2200>

```

# Answer
> 5 votes
# R, ~~75~~ ~~85~~ 83 bytes

```
cat(x<-c("Hare ","Krishna ","\n")[c(1,2,1:3,2,2,1,1,3)],sub(x[2],"Rama ",x),sep="")

```

It creates a vector with `Hare` , `Krishna` , and the newline, takes the ones needed, and then repeats it replacing `Krishna`  by `Rama` .

Needed to include the space on every word and `sep=""` because otherwise `cat()` would put a space at the beginning of each line.

# Answer
> 5 votes
# Matlab ~~139 136~~  105 bytes (thanks to @2501)

```
fprintf('Hare Krishna Hare Krishna\nKrishna Krishna Hare Hare\nHare Rama Hare Rama\nRama Rama Hare Hare')

```

Try it Online in Octave!

# Answer
> 5 votes
# MySQL, ~~115~~ 100 bytes

(Thanks @manatwork!)

```
SELECT CONCAT(a,b,a,b,d,b,b,a,a,d,a,c,a,c,d,c,c,a,a)FROM(SELECT'Hare 'a,'Krishna 'b,'Rama 'c,'\n'd)t

```

# Answer
> 5 votes
# Husk, 22 bytes

```
ṁSeÖ>m´+Πmw¶¨Hȧeȷ#,R□m

```

Try it online!

I've worked for quite some time on this answer since I wanted to beat the "compressed number" algorithm of the current top answer by exploiting more of the regularities in the text.

In the end I "only" managed to tie its score. I actually have in mind a couple of builtins for Husk that could easily save more bytes, but implementing them before posting this answer would have felt too much like cheating.

## Explanation

Husk automatically prints a matrix of strings by joining them with spaces and newlines. In this case we are actually trying to build the matrix

```
[["Hare","Krishna","Hare","Krishna"],
["Krishna","Krishna","Hare","Hare"],
["Hare","Rama","Hare","Rama"],
["Rama","Rama","Hare","Hare"]]

```

which will implicitly get printed to StdOut as the required text. For simplicity, I will show each step of computation as if it was printed by a full program, joining strings with spaces and newlines.

### We need to work with "Hare" and ("Krishna" and "Rama"): `mw¶¨Hȧeȷ#,R□m`

`¨Hȧeȷ#,R□m` is a compressed string; Husk has a dictionary containing common *n-grams* (sequences of characters) which are encoded with symbols possibly reminding of the original n-gram. For example, the `H` here is a plain "H", while `ȧe` is "are\n". The plaintext string this decodes to is "Hare\nKrishna Rama" (where `\n` is an actual newline).  splits this string on the newline, and `mw` splits each line into words. The output we get up to here is:

```
Hare
Krishna Rama

```

### "Hare" should pair with both of the other words: `Π`

Cartesian product of all the lines. This means that we pair each element of the first line with each element of the second line. Our result is:

```
Hare Krishna
Hare Rama

```

### The first and third lines are just those words repeated twice: `m´+`

Concatenate each of the lines with itself. (`´` makes `+` use a single argument twice, and `m` maps this function to each line). We get:

```
Hare Krishna Hare Krishna
Hare Rama Hare Rama

```

### The other lines are the previous lines sorted in reverse alphabetical order: `ṁSeÖ>`

This is not as weird as it looks. `Ö>` sorts a list in descending order. With `SeÖ>` we create a two-element list with the original argument before and after having been sorted.  maps this function to each line, and concatenates the resulting lists. This is finally:

```
Hare Krishna Hare Krishna
Krishna Krishna Hare Hare
Hare Rama Hare Rama
Rama Rama Hare Hare

```

# Answer
> 4 votes
# Ruby, ~~62~~ 61 bytes

As I worked on this it eventually became almost identical to @xnor's Python answer, except Ruby doesn't have spaces between arguments in its `print` function, forcing me to use joins instead and resulting in a longer answer...

-1 bytes from @manatwork

```
%w"Krishna Rama".map{|i|puts [h=:Hare,i]*2*' ',[i,i,h,h]*' '}

```

Try it online!

# Answer
> 4 votes
# Sed, 72

Score includes +1 for the `-r` flag.

```
s/^/Hari Krishna/
s/.*/& &/
s/(\S+)(.*)\b(.+)/&\n\3\2\1/p
s/K\S+/Rama/g

```

Try it online.

# Answer
> 4 votes
# Bash, ~~93~~ 90 bytes

```
h="Hare " k="Krishna " r="Rama " s="$h$k$h$k\n$k$k$h$h\n$h$r$h$r\n$r$r$h$h"
echo -e "${s}"

```

# Answer
> 3 votes
# Pyth -- ~~45~~ 41 bytes

```
Ms(GHGHbHHGG)K"Hare "gK"Krishna "gK"Rama

```

Try It

# Answer
> 3 votes
# AHK, ~~107~~ 92 bytes

This feels ridiculous but I can't find a shorter means in AHK to do this:

```
h=Hare
k=Krishna
Send %h% %k% %h% %k%`n%k% %k% %h% %h%`n%h% Rama %h% Rama`nRama Rama %h% %h%

```

---

Here's what I tried first that was 107 bytes and tried to be fancy. As Digital Trauma pointed out, though, it would have been shorter to just send the raw text.

```
n=1212422114131343311
a=Hare |Krishna |Rama |`n
StringSplit,s,a,|
Loop,Parse,n
r:=r s%A_LoopField%
Send %r%

```

StringSplit creates a pseudo-array with 1 as the first index. So the first term is referenced with `s1`, the second with `s2`, etc. Otherwise, there's nothing fancy here.

# Answer
> 3 votes
## Batch, 75 bytes

```
@for %%h in (Krishna Rama)do @echo Hare %%h Hare %%h&echo %%h %%h Hare Hare

```

# Answer
> 3 votes
# ksh / bash / sh, 66 bytes

```
h=Hare;for j in Krishna Rama;do echo $h $j $h $j"
"$j $j $h $h;done

```

# Answer
> 3 votes
# C 96 bytes

```
*v[]={"Hare ","Krishna ","Rama ","\n"};
main(){for(long a=0x30ae2305d10;a/=4;printf(v[a&3]));}

```

You only need two bits of information to figure out which word from the prayer is needed next, so instead of using a bunch of memory and encoding it as a string, you can just encode it as a 40 bit integer (i.e. inside a long int).

# Answer
> 3 votes
# APL (Dyalog), 47 bytes

Requires `⎕IO←0` which is default on many systems.

```
↑∊¨↓'Krishna ' 'Hare ' 'Rama '[(4⍴3)⊤8×4 1 5 2]

```

Try it online!

`8×4 1 5 2` multiply; \[32,8,40,16\]

`(4⍴3)⊤` convert to 4-digit base 3; matrix \[\[1,0,1,0\],\[0,0,1,1\],\[1,2,1,2\],\[2,2,1,1\]\]

`[``]` index

split into list of lists

`∊¨` enlist (flatten each)

mix into matrix (padding with spaces)

# Answer
> 3 votes
# Haskell, ~~92~~ 91 bytes

```
g=mapM_ putStr$(!!)["Hare ","Krishna ","Rama ","\n"]<$>(read.(:[]))<$>"0101311003020232200"

```

Edit: removed concat, used mapM\_ for putStr instead

Try it online!

# Answer
> 2 votes
# Retina, 60

Direct port of my sed answer:

```

Hari Krishna
.+
$0 $0
:`(\S+)(.*)\b(.+)
$0¶$3$2$1
K\S+
Rama

```

Try it online.

# Answer
> 2 votes
# Perl, 98 72 bytes

@a=("Hare ","Krishna ","Rama ","\n");foreach(split//,'ababdbbaadacacdccaad'){print $a\[ord($\_)-97\]}

98 now reduced to 72, following @hobbs reworking, nice.

```
print+("Hare ","Krishna ","Rama ",$/)[$_]for'01013110030202322003'=~/./g

```

# Answer
> 2 votes
# Perl, ~~76~~ 74 bytes

```
$_=121202211;$_.=0 .y/2/3/r;print$_?(0,Hare,Krishna,Rama)[$_].$":$/for/./g

```

# Answer
> 2 votes
# Java 7, ~~104~~ 103 bytes

```
String c(){return"xyxy\nyyxx\nxRama xRama\nRama Rama xx".replace("x","Hare ").replace("y","Krishna ");}

```

**Explanation:**

```
String c(){                                      // Method without parameters and String return-type
  return"xyxy\nyyxx\nxRama xRama\nRama Rama xx"  //  Return this String
    .replace("x","Hare ")                        //  after we've replaced all "x" with "Hare "
    .replace("y","Krishna ");                    //  and all "y" with "Krishna "
}                                                // End of method

```

Try it here.

# Answer
> 2 votes
# Hack 68 bytes

```
<?hh echo strtr("0101
1100
0202
2200",["Hare ","Krishna ","Rama "]);

```

Straight port of the PHP Answer, just wanted to finally get an excuse to use hack in PPCG :D

# Answer
> 2 votes
# Batch, ~~117~~ ~~111~~ 103 89 bytes

```
@set a=Hare
@for %%A in ("Krishna " "Rama ") do @echo %a%%%~A%a%%%~A^

%%~A%%~A%a%%a%

```

Down to 103 now that trailing newlines are allowed. Down to 89 after adapting the Powershell answer.

`^\n\n` is used to insert a newline at the end of the first line and there's a space after `Hare`.

# Answer
> 2 votes
# Brainfuck Substitutor, 277 bytes

```
{--y{-z[<]w++v->u>+<t-[x[-]Hxtuyy-]>-.ax+[ty<]>>-]<-.rx>+[-vwz>-]>.ext>w<y{]>-. x>tt-<]>u]>-.Kxtuyy-]>w.ix+[v-z>{]>.sx+[vv-z>{]>.hx+[v-z>{]>-.nxt>{<yy-]>.!xwwwww.Rxtuy]>y.mx+[v-z>+>{]>.
Hare Krishna Hare Krishna!Krishna Krishna Hare Hare!Hare Rama Hare Rama!Rama Rama Hare Hare

```

Brainfuck Substitutor (or BFS for short) can redefine characters to be replaced with other characters.

This program redefines the characters of the Hare Krishna mantra with brainfuck 'mini' programs that prints the appropiate characters.

As this is run in succinct mode (which doesn't need any command line arguments and is on my default), we can't redefine newlines (at least, in the current version) so I use the character `!` instead - but it still outputs a newline.

This first bit of the program: `{--y{-z[<]w++v->u>+<t-[x[-]` is short replacements for patterns that come up often in the future.

The interpreter breaks them down like this:

```
{ equals --
y equals {- equals ---
z equals [<]
w equals ++
v equals ->
u equals >+<
t equals -[
x equals [-]

```

Similar thing goes for every other character. I used the shortest brainfuck constants on the esolangs wiki page to get my algorithms, and replaced common patterns. There may be other patterns I can replace (my original attempt was 320 bytes), but this is what I have for now.

# Answer
> 2 votes
# Emacs Lisp, 109 bytes

```
(lambda()(apply'concat(mapcar(lambda(x)(nth(- x ?a)'("Hare ""Krishna ""Rama ""\n")))"ababdbbaadacacdccaad")))

```

Can theoretically be reduced to 103 bytes by using `^@`,`^A`,`^B` and `^C` instead of `a`, `b`, `c` and `d` and `x` instead of `(nth(- x ?a))`, but then it could not be pasted due to NULL characters.

# Answer
> 2 votes
# Wolfram Mathematica, 71 ~~75~~ bytes

```
{"Krishna ","Hare ","Rama ","\n"}[[IntegerDigits[73825885093,4]+1]]<>""

```

Every part of result was encoded as an index in a list, and every index was encoded as digit of 4-ary integer.

# Answer
> 2 votes
## Perl 6, ~~61~~ 60

```
my $a="Hare ";"$a$_ $a$_\n$_ $_ $a$a".say for <Krishna Rama>

```

# Answer
> 2 votes
# Haskell 103 95 Bytes

```
main=putStr$concat$concat$[[h,x,h,x,n,x,x,h,h,n]|x<-["Krishna ","Rama "]]where h="Hare ";n="\n"

```

**Old 103 Bytes:**

```
main=putStr$concat[h,k,h,k,n,k,k,h,h,n,h,r,h,r,n,r,r,h,h] where h="Hare ";k="Krishna ";r="Rama ";n="\n"

```

# Answer
> 2 votes
# C++ 158 Bytes

```
#include <iostream>
#define H "Hare "
#define K "Krishna "
#define R "Rama "
#define N "\n"
void m(){std::cout<<(H K H K N K K H H N H R H R N R R H H);}

```

# Answer
> 2 votes
# C# ~~103~~ 99 Bytes

```
()=>{string a="Hare ",b="Krishna ",c="Rama ",d="\n";return a+b+a+b+d+b+b+a+a+d+a+c+a+c+d+c+c+a+a;};

```

Ungolfed full program:

```
class A
{
    static void Main()
    {
        System.Func<string> f =
            () =>
            {
                string a = "Hare ",
                    b = "Krishna ",
                    c = "Rama ",
                    d = "\n";
                return a + b + a + b + d + b + b + a + a + d + a + c + a + c + d + c + c + a + a;
            };
        System.Console.Write(f());
    }
}

```

# Answer
> 2 votes
# Clojure(Script), 70 bytes (69 bytes?)

```
(def a"Hare")(run! #(println a % a %(str"\n"%)% a a)["Krishna""Rama"])

```

This version with 69 bytes will only work at the repl, because `map` is lazy and I don't use the return value for anything. Dunno how the rules work in this case...

```
(def a"Hare")(map #(println a % a %(str"\n"%)% a a)["Krishna""Rama"])

```

# Answer
> 2 votes
# ///, 46 bytes

```
/4/Hare //k/Krishna //X/4k4k
kk44/X
/k/Rama /X

```

Try it online!

There was already one answer in ///, but this one adds a bit of complexity to remove some bytes.

In pseudocode this could translate to:

```
4="Hare "
k="Krishna "
X=4+k+4+k+'\n'+k+k+4+4
print(X+'\n')
replace k with "Rama "
print(X)

```

(I wanted to use `h` as the letter to substitute with "Hare ", but "Krishna" also contains an `h`, so that messed up the substitutions and I had to switch it with `4`)

# Answer
> 2 votes
# Wren, 91 bytes

```
Fn.new{
var n="Hare"
return["Krishna","Rama"].map{|i|[n,i,n,i,"
"+i,i,n,n].join(" ")+"
"}
}

```

Try it online!

## Explanation

```
Fn.new{                                    // New anonymous function
var n="Hare"                               // Define a template constant
return["Krishna","Rama"].map{|i|[n,i,n,i,  /* Map using the rule*/"
"+i,i,n,n].join(" ")+                      /* [n,i,n,i,"\n",i,i,n,n]*/"
"}
}

```

# Answer
> 2 votes
# **CSS: 132 Bytes**

No use of HTML. Not the best, not the worst but the Brainfuck (No. of bytes) and Matlab solutions (Direct output) made me post this. Can some CSS wizards help save some bytes?

```
body:after{content:"Hare Krishna Hare Krishna\AKrishna Krishna Hare Hare\AHare Rama Hare Rama\ARama Rama Hare Hare";white-space:pre}
```

---

CSS with superpowers could not beat it until someone can prove me wrong.

# SASS: 163 Bytes

```
$a:Hare;$b:Krishna;$c:Rama;body:after{content:"#{$a} #{$b} #{$a} #{$b}\A#{$b} #{$b} #{$a} #{$a}\A#{$a} #{$c} #{$a} #{$c}\A#{$c} #{$c} #{$a} #{$a}";white-space:pre}

```

**Run it on:**

# Answer
> 1 votes
# Fourier, 94 bytes

```
|72a97a114a101a32a|H|75a114a-9a115a104a+6a97a32a|K|82a97a109a97a32a|RHKHK10aKKHH10aHRHR10aRRHH

```

**Try it on FourIDE!**

Makes good use of functions: `H` for *Hare*, `K` for *Krishna* and `R` for *Rama*.

Now I can't get the song *My Sweet Lord* out of my head :P

# Answer
> 1 votes
# 05AB1E, 54 bytes

```
•4Ñ••}ò´••9Ä•)©\•2}¾S•3BRv®yè8ÝJ"ahrekisnm"‡})4ôvyðý™,

```

Try it online!

```
•4Ñ•                          # Hare
    •}ò´•                     # Krishnu
         •9Ä•)©\              # Rama
                •2}¾S•3BR     # Sequencing data.
v®yè8ÝJ"ahrekisnm"‡}          # For each sequence part, push the right word.
                    )4ôvyðý™, # Format it correctly.

```

---

05AB1E changed its base-214 encryption to base-255; this is the reason this submission no longer works; however, it was valid at the time.

# Answer
> 1 votes
# SmileBASIC 3, 76 bytes

Straightforward answer with string multiplication. `?` is print.

```
?"Hare Krishna "*2?"Krishna "*2+"Hare "*2?"Hare Rama "*2?"Rama "*2+"Hare "*2

```

# Answer
> 1 votes
# `cat` 97 bytes

```
Hare Krishna Hare Krishna<CR>
Krishna Krishna Hare Hare<CR>
Hare Rama Hare Rama<CR>
Rama Rama Hare Hare<^D>

```

I consider `<^D>` as two characters, whence 97

# Answer
> 1 votes
# Groovy, 82 bytes

```
a=["Hare ","Krishna ","Rama ","\n"]
"0101311003020232200".each{print a[it as int]}

```

An improvement of my previous answer (1 byte longer)

```
h="Hare "
k="Krishna "
r="Rama "
n="\n"
print h+k+h+k+n+k+k+h+h+n+h+r+h+r+n+r+r+h+h

```

# Answer
> 1 votes
# Recursiva, ~~57~~ 53 bytes

```
r2r1r0"0101/n1100/n0202/n2200"'Hare ''Krishna ''Rama

```

Try it online!

# Answer
> 1 votes
# ///, 49 bytes

```
/#/Hare //k/Krishna //j/Rama /#k#k
kk##
#j#j
jj##

```

Try it online!

Although /// is an esoteric language, this one is shorter than most of the other (non-golfing, and a bad implementation of this problem in Retina) languages here. Mostly because /// has too few functionalities, that they can be represented in few bytes.

# Answer
> 1 votes
## Javascript 85 bytes

I know there's a better answer already, but i wanted to give it a try anyway, the method is pretty different as you'll see:

```
a=["Krishna ","Rama "];q="Hare ";b=(z)=>q+a[z]+q+a[z]+`
`+a[z]+a[z]+q+q+`
`;b(0)+b(1)

```

```
a=["Krishna ","Rama "];q="Hare ";b=(z)=>q+a[z]+q+a[z]+`
`+a[z]+a[z]+q+q+`
`;console.log(b(0)+b(1));
```

Please note that i had to put the console.log() in a weird spot, if you just paste the code block into the console it'll print the mantra.

## dumbded down better golfed version 76 bytes:

```
a="Krishna ";b="Rama ";c="Hare ";d=`
`;c+a+c+a+d+a+a+c+c+d+c+b+c+b+d+b+b+c+c

```

```
a="Krishna ";b="Rama ";c="Hare ";d=`
`;console.log(c+a+c+a+d+a+a+c+c+d+c+b+c+b+d+b+b+c+c)
```

# Answer
> 1 votes
# Jq 1.5, ~~59~~ ~~57~~ ~~54~~ 52 bytes

```
def h:"Hare "+.;"Krishna ","Rama "|h*2,.*2+"Hare "*2

```

Try it online!

# Answer
> 1 votes
# , ~~49~~ 41 bytes

```
;"1{&(<;.2'Hare Krishna Rama ')(,-)#:5 12

```

### How it works

```
                                   #:5 12 to binary [(0 1 0 1), (1 1 0 0)]
                               ( -)       negate    [(0-1 0-1),(-1-1 0 0)]
                               (, )       append    [(0 1 0 1),(1 1 0 0),(0-1 0-1),(-1-1 0 0)]
     (<;. 'Hare Krishna Rama ')           split by
         2                                the last character, keep it in
   {&                                     negative argument selects from the end
;"1                                       get rid of the ASCII boxes

```

Try it online!

# Answer
> 1 votes
# SmileBASIC, 58 bytes

We can use the fact that the second half is the same as the first, with "Krishna" replaced by "Rama"

```
P"Krishna
P"Rama
DEF P K?("Hare "+K)*2?K*2;"Hare "*2
END

```

(Note trailing spaces)

Storing "Hare " in a variable is the same length.

# Answer
> 1 votes
# Vyxal, 73 bytes

```
`Hλ½ K≥τ⇧¨ Hλ½ K≥τ⇧¨
K≥τ⇧¨ K≥τ⇧¨ Hλ½ Hλ½
Hλ½ R□• Hλ½ R□•
R□• R□• Hλ½ Hλ½`

```

Try it Online!

# Answer
> 1 votes
# K (ngn/k), 65 bytes

```
{`0:,/("Hare ";"Krishna ";"Rama ";"\n")@"ababdbbaadacacdccaa"-97}

```

Try it online!

This has to be the longest K program I have ever written. Takes `"aba..."-97` from the Octave answer.

# Answer
> 1 votes
# Vyxal 3, 39 bytes

```
"ᶜ₂ᶠ„•;DJ$Ṙd½Jf:•"ᵇcð₇₁„r$•"ᴳ=Ṡ„rJᵛV4Ẇ'

```

Try it Online!

# Answer
> 0 votes
# Tcl, 87 bytes

```
puts "[set h Hare] [set k Krishna] $h $k
$k $k $h $h
$h [set r Rama] $h $r
$r $r $h $h"

```

Try it online!

# Answer
> 0 votes
# Go, 167 bytes

```
func f(){w,i,k:=[]string{"Hare","Krishna","Rama"},[]int{0,1,0,1,1,1,0,0,2,0,2,0,2,2,0,0},0
for _,e:=range i{if k>3{print(`
`)
k=0}
if k>0{print(" ")}
print(w[e])
k++}}

```

Attempt This Online!

Prints to STDERR.

---
Tags: code-golf, string, kolmogorov-complexity
---