title: An Old Irish Blessing

text:
# Question
Title: An Old Irish Blessing
I don't know who coined these words, and I'm not Irish, but I give you an Irish blessing:

```
May the road rise up to meet you
May the wind be always at your back
May the sun shine warm upon your face
The rains fall soft upon your fields
And until we meet again
May God hold you in the hollow of His hand

```

I was planning on posting this a few weeks from now, but it just dawned on me that yesterday was Saint Patrick's Day.

**Rules:**

* Produce the above text exactly.
*(Feel free to break this rule for the sake of cleverness and amusement.)*
* The program must generate the text on its own accord. `cat` is not a valid solution.
* The solution with the fewest characters "wins".

I saw slight variations in wording among versions of the blessing I obtained from the Internet, so I tried to average them out. Please use the version posted above. Also, I dropped the punctuation to make it a bit easier.

May the luck of the Irish enfold you.

# Answer
> 3 votes
# 05AB1E, ~~117~~ 115 bytes

```
'€¿“‡âŽÓ€î€†€€èÊ€‚“„€Ë‡´).ª“€¿€€†â£ƒ€¾€„‰Ã€î““€¿€€ïë€ï‡Š€›€ž‚ƒ““€¿€€‡µã»©ÃˆÉ€žŠÑ““€€¥·sŽ§š¼ˆÉ€ž™æ““€ƒ‡æ€¦‰Ã†î“).ªÀ»

```

Try it online!

Thanks to Kevin Cruijssen for -2 bytes

```
'€¿                 "may"
“‡âŽÓ€î€†€€èÊ€‚“    "god hold you in the hollow of"
„€Ë‡´               "his hand"
)                   push stack into a list
.ª                  sentence-case each
“€¿€€†â£ƒ€¾€„‰Ã€î“  "may the road rise up to meet you"
“€¿€€ïë€ï‡Š€›€ž‚ƒ“  "may the wind be always at your back"
“€¿€€‡µã»©ÃˆÉ€žŠÑ“  "may the sun shine warm upon your face"
“€€¥·sŽ§š¼ˆÉ€ž™æ“   "the rains fall soft upon your fields
“€ƒ‡æ€¦‰Ã†î“        "and until we meet again"
)                   push stack into a list
.ª                  sentence-case each
À                   rotate list left
»                   join by newlines
                    implicitly print

```

# Answer
> 14 votes
## Python, 143 chars

```
#coding:u8
print u'慍⁹桴潲摡爠獩灵琠敭瑥礠畯䴊祡琠敨眠湩敢愠睬祡⁳瑡礠畯⁲慢正䴊祡琠敨猠湵猠楨敮眠牡灵湯礠畯⁲慦散吊敨爠楡獮映污潳瑦甠潰潹牵映敩摬ੳ湁湵楴敷洠敥⁴条楡੮慍⁹潇潨摬礠畯椠桴潨汬睯漠楈⁳慨摮'.encode("u16")[2:]

```

run at codepad.org

# Answer
> 8 votes
## Haskell, 179 characters

```
e="\n "++['='..'z']++e;i r=[e!!div r 64,e!!r]
main=putStr$i.fromEnum=<<"뒦뾁빭몁뷴릩끷뮸몁뺵끹봁벪몹끾봺뀒릾끹뭪끼뮳멁맪끦뱼릾븁릹끾봺뷁맦먰뀒릾끹뭪끸뺳끸뭮볪끼릷벁뺵봳끾봺뷁뫦먪뀙뭪끷릮본끫릱뱁븴뫹끺뵴볁뾴뺷끫뮪뱩븀놳멁뺳빮뱁뼪끲몪빁리릮변뒦뾁댴멁뭴뱩끾봺끮볁빭몁뭴뱱봼끴뫁덮븁뭦볩뀀"

```

This exploits the ancient common bond between the Irish and the Koreans. You all knew that lace and potato farming came via Korea, and that Kimchi was first made in Dublin... right?

---

* Edit: (197 -\> 184) No need to `mod` (why⁈ :-) ); eliminated separate declaration for the Korean text.
* Edit: (184 -\> 179) Used a more compact to represent code book.

# Answer
> 4 votes
## INTERCALL, 3421 bytes

A simple solution. Genered automatically, if anyone is wondering...

```
INTERCALL IS A ANTIGOLFING LANGUAGE
SO THIS HEADER IS HERE TO PREVENT GOLFING IN INTERCALL
THE PROGRAM STARTS HERE:
PUSH LXXVII
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXIV
PRINT
PUSH CXI
PRINT
PUSH XCVII
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH CXIV
PRINT
PUSH CV
PRINT
PUSH CXV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXVII
PRINT
PUSH CXII
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CXI
PRINT
PUSH XXXII
PRINT
PUSH CIX
PRINT
PUSH CI
PRINT
PUSH CI
PRINT
PUSH CXVI
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH X
PRINT
PUSH LXXVII
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXIX
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH XCVIII
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH XCVII
PRINT
PUSH CVIII
PRINT
PUSH CXIX
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH CXV
PRINT
PUSH XXXII
PRINT
PUSH XCVII
PRINT
PUSH CXVI
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH CXIV
PRINT
PUSH XXXII
PRINT
PUSH XCVIII
PRINT
PUSH XCVII
PRINT
PUSH XCIX
PRINT
PUSH CVII
PRINT
PUSH X
PRINT
PUSH LXXVII
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXV
PRINT
PUSH CXVII
PRINT
PUSH CX
PRINT
PUSH XXXII
PRINT
PUSH CXV
PRINT
PUSH CIV
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXIX
PRINT
PUSH XCVII
PRINT
PUSH CXIV
PRINT
PUSH CIX
PRINT
PUSH XXXII
PRINT
PUSH CXVII
PRINT
PUSH CXII
PRINT
PUSH CXI
PRINT
PUSH CX
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH CXIV
PRINT
PUSH XXXII
PRINT
PUSH CII
PRINT
PUSH XCVII
PRINT
PUSH XCIX
PRINT
PUSH CI
PRINT
PUSH X
PRINT
PUSH LXXXIV
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXIV
PRINT
PUSH XCVII
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH CXV
PRINT
PUSH XXXII
PRINT
PUSH CII
PRINT
PUSH XCVII
PRINT
PUSH CVIII
PRINT
PUSH CVIII
PRINT
PUSH XXXII
PRINT
PUSH CXV
PRINT
PUSH CXI
PRINT
PUSH CII
PRINT
PUSH CXVI
PRINT
PUSH XXXII
PRINT
PUSH CXVII
PRINT
PUSH CXII
PRINT
PUSH CXI
PRINT
PUSH CX
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH CXIV
PRINT
PUSH XXXII
PRINT
PUSH CII
PRINT
PUSH CV
PRINT
PUSH CI
PRINT
PUSH CVIII
PRINT
PUSH C
PRINT
PUSH CXV
PRINT
PUSH X
PRINT
PUSH LXV
PRINT
PUSH CX
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH CXVII
PRINT
PUSH CX
PRINT
PUSH CXVI
PRINT
PUSH CV
PRINT
PUSH CVIII
PRINT
PUSH XXXII
PRINT
PUSH CXIX
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CIX
PRINT
PUSH CI
PRINT
PUSH CI
PRINT
PUSH CXVI
PRINT
PUSH XXXII
PRINT
PUSH XCVII
PRINT
PUSH CIII
PRINT
PUSH XCVII
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH X
PRINT
PUSH LXXVII
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH XXXII
PRINT
PUSH LXXI
PRINT
PUSH CXI
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH CIV
PRINT
PUSH CXI
PRINT
PUSH CVIII
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH XXXII
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CIV
PRINT
PUSH CXI
PRINT
PUSH CVIII
PRINT
PUSH CVIII
PRINT
PUSH CXI
PRINT
PUSH CXIX
PRINT
PUSH XXXII
PRINT
PUSH CXI
PRINT
PUSH CII
PRINT
PUSH XXXII
PRINT
PUSH LXXII
PRINT
PUSH CV
PRINT
PUSH CXV
PRINT
PUSH XXXII
PRINT
PUSH CIV
PRINT
PUSH XCVII
PRINT
PUSH CX
PRINT
PUSH C
PRINT
END

```

Wow

# Answer
> 3 votes
## GolfScript (204 chars)

Contains non-printing characters, so copy-paste may not work:

```
:k'May the road rise up to meet you
wind be always ar back¢ sun shin¬armÈon€face
Tåainsll soft¡ields
Aäuntil we meet ag²áGod holdø inñlow of His hand'{k{{k$}*0:k;}{127.2$<{-:k}*;}if}/](+

```

Base64-encoded:

```
OmsnTWF5IHRoZSByb2FkIHJpc2UgdXAgdG8gbWVldCB5b3UKnwh3aW5kIGJlIGFsd2F5cyBhnAVy
IGJhY2uiCXN1biBzaGlurANhcm3IA29upAZmYWNlClTlBGFpbnONA2xsIHNvZnShDGllbGRzCkHk
A3VudGlsIHdlIG1lZXQgYWeyA+EFR29kIGhvbGT4BCBpbvEFjgNsb3cgb2YgSGlzIGhhbmQne2t7
e2skfSowOms7fXsxMjcuMiQ8ey06a30qO31pZn0vXSgr

```

There really is less redundancy than you might expect in the string. I think gzip's savings are 2/3 from Lempel-Ziv and 1/3 from the Huffman encoding; what I'm using is essentially LZ, but I have more overhead than the gzip format.

Note that this is the first solution to take fewer *bytes* than the output.

# Answer
> 2 votes
# PHP, 431 425 bytes

```
<?php $s="May therodisupm\nwnblckfTAgGH";$p=array('01234563','3cd8h328c73m','jj','3e6643');$b=str_split('s781937ab63cd348v28cfsgah93i631jg12b314328c73i1klfsbch3b5ah63g17et1k6fn56371ahb3m1u3b8m4ta6j9bfoh93ch4aj3g6v1p1ahf0123q89358j9328c3ah3456358u8g38m3rab351h9');foreach($b as $x){$x=b($x);if($x>27){$c=str_split($p[$x-28]);foreach($c as $y){echo $s[b($y)];}}else{echo $s[$x];}}function b($a){return base_convert($a,36,10);}

```

An approach of mapping and base conversion to store the information. However, I failed at keeping the program size very small.

# Answer
> 2 votes
## Bash/Sed, 206 chars

I didn't manage to beat Peter Taylor, but like his solution, it's fewer **bytes** than the original. But I didn't use unprintable characters.
`sed` was useful in the similar "no strangers to codegolf" challenge. But there I used it twice, to compress the list of replacements. Here, the text is too short for this trick.

```
sed 's/Z/May the /;s/W/ uponYr f/;s/Y/ you/'<<X
Zroad rise up to meetY
Zwind be always atYr back
Zsun shine warmWace
The rains fall softWields
And until we meet again
May God holdY in the hollow of His hand

```

# Answer
> 1 votes
## Haskell - 284

```
s n=words"And God His May The again always at back be face fall fields hand hold hollow in meet of rains rise road shine soft sun the to until up upon warm we wind you your"!!(fromEnum n-48)
main=mapM_(putStrLn.unwords.map s)$words"3IEDLJAQ 3IP967R8 3IHFNMR: 4C;GMR< 0KOA5 31>Q@I?B2="

```

Sadly, this is *much longer* than the output or putting the string verbatim. Even the string literals themselves (without quotes) total to two characters longer than the input. How can that be?

# Answer
> 1 votes
# Quetzalcoatl, 218 bytes

```
"May the road rise up to meet you\nMay the wind be always at your back\nMay the sun shine warm upon your face\nThe rains fall soft upon your fields\nAnd until we meet again\nMay God hold you in the hollow of His hand"

```

Strings are implicitly printed.

# Or pyth, 217 bytes

```
"May the road rise up to meet you\nMay the wind be always at your back\nMay the sun shine warm upon your face\nThe rains fall soft upon your fields\nAnd until we meet again\nMay God hold you in the hollow of His hand

```

# Answer
> 1 votes
# Keg, 175 chars

```
‘3p‘®m‘00‘®t¶©m  ©t  2½;4•;up to 2m;you\n©m  ©t  2⬩;be 0Ȧ;at 0B;0∞;\n©m  ©t  sun kƝ;4Ȧ;0M;0B;0Ƚ;\nThe A④;2÷;4l;0M;0B;8R;\nAnd 0;we 2m;0¡;\n©m  God 1④;you in ©t  dɅ;of His 0║;

```

Thank goodness all long words are in Keg's dictionary. Just uses string compression to reduce length.

TIO currently doesn't work as it needs to be updated.

Try it online!

# Answer
> 0 votes
# Wren, 248 bytes

Adopting this method.

```
System.print("Zroad rise up to meetY\nZwind be always atYr back\nZsun shine warmWace\nThe rains fall softWields\nAnd until we meet again\nMay God holdY in the hollow of His hand".replace("Z","May the ").replace("W"," uponYr f").replace("Y"," you"))

```

Try it online!

# Answer
> 0 votes
# FEU, 200 bytes

```
a/1road rise up to meet3\n1wind be always at3r back\n1sun shine warm2ace\nThe rains fall soft2ields\nAnd until we meet again\nMay God hold3 in the hollow of His hands
m/1/May the /2/ upon3r f/3/ you/g

```

Try it online!

Is everyone sure there isn't a better replacement compression?

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


title: Simple golfing interpreter

text:
# Question
Title: Simple golfing interpreter
# Challenge:

Your job is to create a simple interpreter for a simple golfing language.

---

# Input:

Input will be in the form of string separated by spaces.

**You can replace space separation with what you want**

---

# Output:

Output the result (a number or a string) obtained after performing all operations. If there are more than one output join the together to give a single result (no separators). The variable's initial value is always zero. i.e: It start at `0`

---

# Language Syntax :

The language has following operators :

```
inc  ---> add one to variable
dec  ---> remove one from variable
mult ---> multiply variable by 2
half ---> divide the variable by 2
Pri  ---> print the variable to console (or whatever your language has)
exit ---> end the program (anything after this is ignored)

```

---

# Examples:

```
inc inc inc dec Pri exit                 ---> 2
dec inc mult inc inc Pri                 ---> 2
inc inc inc mult half Pri exit inc       ---> 3
inc Pri inc Pri inc Pri exit half mult   ---> 123
Pri exit                                 ---> 0
inc half Pri exit                        ---> 0.5

```

---

# Restriction:

This is code-golf so shortest code in bytes for each language will win.

---

# Note:

* Input will always be valid . (string of operators separated with space)
* You can round down to nearest integer if you don't want decimal places.

# Answer
# shell + sed + dc, 56 ~~61~~ bytes

```
sed '1i0
s/.//2g;y"idmhe"+-*/q";i1
/[*/]/i1+
/P/crdn'|dc

```

Try it online!

Converts the program into a dc program, then evaluates it as dc code. This takes the input separated by newlines. Note that dc is stack-based and uses reverse polish notation, so `5 2-` gives `3`, and numbers are always rounded down.

The input is first piped to sed

`1i0` on the first line of input, insert (prepend) a 0, this will be the accumulator

`s/.//2g` remove everything but the first character on each line

`y"idmhe"+-*/q"` transliterate `idmhe` into `+-*/q` respectively, + - * / are the arithmetic commands and q quits the program

`i1` on every line insert a `1` \- this satisfies addition and subtraction

`/[*/]/` on every line containing * or /, `i1+` additionally insert `1+` because of the preceding `1`, which dc will eventually evaluate into `2`

`/P/` on every line containing P, `crdn` change it into `rdn`, equivalent to reverse the top two elements, to rid the inserted `1`, and duplicate and output as a number without newline (whilst popping it, hence the earlier duplicate) in dc

Now this is evaluated as a dc expression.
> 9 votes

# Answer
# Jelly, 21 bytes

```
ḲḢ€O%11ị⁾’‘j“IȮḤH”¤VI

```

Try it online!

---

Note that the ASCII values of the first characters (`idmhPe`) modulo 11 are unique modulo 6.

---

Using modulo 16:

# Jelly, 21 bytes

```
ḲḢ€O%⁴ị“ḢwġḞkz’ṃØJ¤VI

```

Try it online!

The string that is used to index into is `ḤH‘’IȮ` in this case. The `‘’` are no longer on the boundaries.
> 6 votes

# Answer
# , ~~128~~ 125 bytes

```
Reduce(function(x,y)switch(y,i=x+1,d=x-1,m=x*2,h=x/2,P={cat(x);x}),substr(el(strsplit(gsub("e.*$","",scan(,""))," ")),1,1),0)

```

Try it online!

Must be called with `source(echo=FALSE)` to prevent the return value from being printed automatically. The alternative would be to wrap everything in `invisible` but that's much less golfy (and ruins my \[still\] nice byte count).
> 5 votes

# Answer
# 05AB1E, 25 bytes

```
Î€¬"idmhPe"S"><·;=q"S‡J.V

```

Try it online!

Maps each of the language function with the corresponding 05AB1E function (using the first char of each function), and then executes the resulting string as 05AB1E code.
> 3 votes

# Answer
# Python 3, ~~110~~ ~~91~~ 82 bytes

`exit` will cause the program to exit with an error.

```
x=0
for c in input():c=='P'==print(x,end='');x+=(1,-1,x,-x/2,c,0)['ndmhx'.find(c)]

```

**Try it online!**
> 3 votes

# Answer
# Red, 121 bytes

```
func[s][v: 0 parse s[any[["i"(v: v + 1)|"d"(v: v - 1)|"m"(v: v * 2)|"h"(v: v / 2.0)|"P"(prin v)|"e"(exit)]thru" "| end]]]

```

Try it online!

## Readable:

```
f: func [s] [
    v: 0
    parse s [
        any [
            [ "i" (v: v + 1)
            | "d" (v: v - 1)
            | "m" (v: v * 2)
            | "h" (v: v / 2.0)
            | "P" (prin v)
            | "e" (exit)]
            thru [" " | end]
        ]
    ]
]

```
> 2 votes

# Answer
# Python 2, ~~131~~ ~~125~~ ~~122~~ ~~121~~ ~~118~~ ~~117~~ 115 bytes

```
v=0;o=""
for x in input().split("x")[0].split():
 if"Q">x:o+=`v`
 else:v+=(1,-1,v,-v/2.)['idmh'.find(x[0])]
print o

```

Try it online!

-6 and -3 with thanks to @Rod

-3 and -2 with thanks to @etene

-1 by replacing `"Pri"==x` with `"P"in x`
> 2 votes

# Answer
# JavaScript (ES6), ~~83~~ 79 bytes

*Saved 4 bytes thanks to @l4m2*

Iteratively replaces the instructions with either the output or empty strings.

```
s=>s.replace(/\S+./g,w=>m<s?'':w<{}?m:(m+={d:-1,e:w,i:1,m}[w[0]]||-m/2,''),m=0)

```

Try it online!

### Commented

```
s =>                       // given the input string s
  s.replace(/\S+./g, w =>  // for each word w in s:
    m < s ?                //   if m is a string:
      ''                   //     ignore this instruction
    :                      //   else:
      w < {} ?             //     if w is 'Pri' ({} is coerced to '[object Object]'):
        m                  //       output the current value of m
      : (                  //     else:
          m +=             //       add to m:
            { d: -1,       //         -1 if w is 'dec'
              e: w,        //         w  if w is 'exit' (which turns m into a string)
              i: 1,        //         1  if w is 'inc'
              m            //         m  if w is 'mult'
            }[w[0]]        //       using the first character of w to decide
            || -m / 2,     //       or add -m/2 (for 'half') if the above result was falsy
        ''),               //       do not output anything
    m = 0                  //   m = unique register of our mighty CPU, initialized to 0
  )                        // end of replace()

```
> 2 votes

# Answer
# JavaScript (ES6), ~~77~~ 75 bytes

(Borrowed (*stole*) @Arnauld's trick of using `m` as the variable name, saving 2 bytes.)

```
f=([c,...s],m=0)=>c<'x'?(c=='P'?m:'')+f(s,m+({h:-m/2,d:-1,n:1,m}[c]||0)):''

```

Recursively walks the string, looking for distinct letters per instruction and ignoring the rest:

* n: inc
* d: dec
* m: mult
* h: half
* P: Pri
* x: exit

Takes advantage of the fact that `undefined` is neither greater than nor less than `'x'`, causing the recursion to stop at the end of the string *or* when it encounters the `'x'` in **exit**.

```
f=([c,...s],n=0)=>c<'x'?(c=='P'?n:'')+f(s,n+({h:-n/2,d:-1,n:1,m}[c]||0)):''

console.log(f('inc inc inc dec Pri exit'));                 //--> 2
console.log(f('dec inc mult inc inc Pri'));                 //--> 2
console.log(f('inc inc inc mult half Pri exit inc'));       //--> 3
console.log(f('inc Pri inc Pri inc Pri exit half mult'));   //--> 123
console.log(f('Pri exit'));                                 //--> 0
console.log(f('inc half Pri exit'));                        //--> 0.5
```
> 2 votes

# Answer
# Charcoal, ~~37~~ 35 bytes

```
≔⁰ηＦ⎇№θx…θ⌕θxθ≡ιn≦⊕ηd≦⊖ηm≦⊗ηh≦⊘ηrＩη

```

Try it online! Link is to verbose version of code. Inspired by @RickHitchcock's answer. Explanation:

```
≔⁰η

```

Clear the variable.

```
Ｆ⎇№θx…θ⌕θxθ≡ι

```

Truncate the input at the `x` if there is one, then loop over and switch on each character of (the remainder of) the input.

```
n≦⊕η

```

`n` i**n**crements the variable.

```
d≦⊖η

```

`d` **d**ecrements the variable.

```
m≦⊗η

```

`m` **m**ultiplies the variable by two (i.e. doubles).

```
h≦⊘η

```

`h` **h**alves the variable.

```
rＩη

```

`r` p**r**ints the variable cast to string.
> 2 votes

# Answer
# JavaScript (Node.js), 107 bytes

```
f=s=>s.split` `.map(([o])=>F?0:o=="i"?i++:o=="d"?i--:o=="m"?i*=2:o=="h"?i/=2:o=="P"?S+=i:F=1,F=i=0,S="")&&S

```

Try it online!
> 1 votes

# Answer
# JavaScript, 107 bytes

```
s=>eval('x=0;x'+(s.split` `.map(v=>({i:"++",d:"--",m:"*=2",h:"/=2",P:";alert(x)",e:"//"})[v[0]]).join`;x`))

```
> 1 votes

# Answer
# JavaScript (Node.js), 91 bytes

```
_=>_.split` `.map(o=>o<{}>!_?S+=+i:o<"e"?i--:o<"f"?++_:o<"i"?i/=2:o<"j"?i++:i*=2,i=S="")&&S

```

Try it online!

# JavaScript (Node.js), 96 bytes

```
_=>_.split` `.map(o=>F?0:o<"Q"?S+=i:o<"e"?i--:o<"f"?F=1:o<"i"?i/=2:o<"j"?i++:i*=2,F=i=0,S="")&&S

```

Try it online!

# JavaScript (Node.js), 99 bytes

```
s=>s.split` `.map(_=>eval('++i7--i7++e7u+=+i7i*=27i/=2'.split(7)[Buffer(e+_)[0]%11%6]),e=i=u='')&&u

```

Try it online!
> 1 votes

# Answer
# Python 3, 114 110 109 116 bytes

Actually would have taken two bytes less in Python 2 because `exec` is a statement and doesn't need parentheses...

* *Saved 4 extra bytes thanks to @ElPedro*
* *Saved an extra byte by taking advantage of the fact that `find` returns -1 on error, which can then be used as an index*
* *+7 bytes because I hadn't noticed the no-newlines rule :(*

```
i=0;exec(";".join("i+=1 i-=1 i*=2 i/=2 print(i,end='') exit()".split()["idmhP".find(h[0])]for h in input().split()))

```

Try it online!

Maps the first character of every input word to a piece of Python code. These are then concatenated and `exec`ed.

Pretty straightforward approach, that could probably be golfed a bit more. The difficulty mostly resides in finding the shortest form out of many possible ones...
> 1 votes

# Answer
# Ruby \+ `-na`, ~~81~~ ~~73~~ 65 bytes

```
x=0;$F.map{|w|eval %w{x+=1 x-=1 1/0 $><<x x*=2 x/=2}[w.ord%11%6]}

```

Try it online!

Pretty straightforward. For the first letter of each word, find the corresponding command string and `eval` it. Uses integer division, and `exits` by throwing a `ZeroDivisionError`.

-5 bytes: Use `.ord%11%6` instead of a string lookup. Credit goes to user202729

-3 bytes: `.ord` only considers the first character of the string, so I can skip a `[0]`.

-8 bytes: Use `-a` flag to automatically split input, thanks to Kirill L.
> 1 votes

# Answer
# Haskell, 93 bytes

```
(0!)
a!(c:t)|c=='P'=show a++a!t|c>'w'=""|1<2=(a+sum(lookup c$zip"ndmh"[1,-1,a,-a/2]))!t;a!e=e

```

Try it online!

Essentially a translation of mbomb007's Python answer.
> 1 votes

# Answer
# Lua, 207 bytes

```
s=0;n=0;for a in io.read():gmatch'.'do if s==0 then s=1;n=a=='i'and n+1 or a=='d'and n-1 or a=='m'and n*2 or a=='h'and n/2 or n;if a=='P'then print(n)elseif a=="e"then break end elseif a==' 'then s=0 end end

```
> 1 votes

# Answer
# Emojicode, 270 bytes

```
c 0j jincc➕c 1jdecc➖c 1jmultc✖c 2jhalfc➗c 2jPric 10

```

Try it online!

```

c 0
j
jincc➕c 1
jdecc➖c 1
jmultc✖c 2
jhalfc➗c 2
jPric 10

 inc inc inc dec Pri exit

 dec inc mult inc inc Pri

 inc inc inc mult half Pri exit inc

 inc Pri inc Pri inc Pri exit half mult

 Pri exit

 inc half Pri exit

```
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 165 bytes

```
	P =INPUT ' exit '
	x =0
S	P LEN(1) $ L ARB ' ' REM . P	:S($L)F(end)
i	X =X + 1	:(S)
d	X =X - 1	:(S)
P	O =O X		:(S)
m	X =X * 2	:(S)
h	X =X / 2.	:(S)
e	OUTPUT =O
END

```

Try it online!

Gross.

```
	P =INPUT ' exit ' 				;* append ' exit ' to the input to guarantee that the program will stop
	x =0						;* initialize x to 0 else it won't print properly if the program is 'Pri'
S	P LEN(1) $ L ARB ' ' REM . P	:S($L)F(end)	;* set L to the first letter of the word and goto the appropriate label
i	X =X + 1	:(S)
d	X =X - 1	:(S)
P	O =O X		:(S)				;* append X to the output string
m	X =X * 2	:(S)
h	X =X / 2.	:(S)				;* divide by 2. to ensure floating point
e	OUTPUT =O					;* print whatever's in O, which starts off as ''
END

```
> 0 votes

# Answer
# C# (.NET Core), 186 Bytes

```
class P{static void Main(string[]a){int v=0;foreach(var s in a){var i=s[0];if(i=='i')v++;if(i=='d')v--;if(i=='m')v*=2;if(i=='h')v/=2;if(i=='P')System.Console.Write(v);if(i=='e')break;}}}

```
> 0 votes

# Answer
# Perl 5 `-a`, 61 bytes

```
eval'$,'.qw(++ -- ;exit ;print$,||0 *=2 /=2)[(ord)%11%6]for@F

```

Try it online!

Stole @user202729's `ord%11%6` trick

## How?

```
-a            # split the input by whitespace, store in @F
eval          # Execute the string that results from:
'$,'          # $, (the accumulator)
.             # appending:
qw(           # create an array for the following whitespace separated values:
++ --            # operators for inc & dec
;exit            # exit
;print$,||0      # Pri  (||0 ensures that 0 is output if accumulator is null
*=2 /=2)         # mult div
[(ord)%11%6] # @user202729's trick selects one of the preceding operations
for@F        # for every term input

```
> 0 votes

# Answer
# C (gcc), ~~120~~ ~~114~~ 111 bytes

-6 bytes thanks to ceilingcat.

```
x,d;f(char*s){for(x=0;s>1;s=index(d^1?s:"",32)+1)d=*s-100,x+=d?d==5:-1,x*=d^9?d^4?1:.5:2,d+20||printf("%d",x);}

```

Try it online!

# 124 bytes

Floating-point version:

```
d;f(char*s){for(float f=0;s>1;s=strchr(s,32)+1)d=*s-80,f+=d==25,f-=d==20,f*=d^29?d^24?1:.5:2,s=d^21?s:"",d?:printf("%f",f);}

```

Try it online!

I did not bother with a version that rounds down, but makes an exception for 0, which would be allowed, if I understand the comment-chain correctly.
> 0 votes

# Answer
# Pyth, 44 Bytes

```
Vmx"idmhPe"hdcwd=Z@[hZtZyZcZ2ZZ)NIqN4pZIqN6B

```

Test Suite

## explanation

```
Vmx"idmhPe"hdcwd=Z@[hZtZyZcZ2ZZ)NIqN4pZIqN6B   ## full program
             cwd                               ## split input on space
Vmx"idmhPe"hd                                  ## iterate through list of numbers corresponding to operators
                =Z@[hZtZyZcZ2ZZ)N              ## assign the variable Z (initialliy Zero) it's new value
                                 IqN4pZ        ## print Z if the current operator is "Pri" (4)
                                       IqN6B   ## break if the current operator is "exit" (5)

```
> 0 votes

# Answer
# TI-BASIC, 112 bytes

This takes advantage of some assumptions that are AFAIK perfectly acceptable. Number one being that all variables are initialized to zero prior to execution; number two being that input is taken via `Ans`.

```
Ans+" E→Str1
While 1
I+4→I
sub(Str1,I-3,1→Str2
A+(Ans="I")-(Ans="D
If inString("MH",Str2
Then
I+1→I
2AAns+A/2(1-Ans
End
If Str2="P
Disp A
If Str2="E
Stop
Ans→A
End

```
> 0 votes

# Answer
# Java (OpenJDK 8), 164 bytes

```
a->{int c=0;for(String g:a.split(" ")){char b=g.charAt(0);if(b==105)c++;if(b==100)c--;if(b==109)c*=2;if(b==104)c/=2;if(b==80)System.out.print(c);if(b==101)return;}}

```

Try it online!

Above is my solution that rounds off to integers, but below is my solution that handles decimals. The obnoxious way that java prints doubles adds another 55 byes to the score. I left the new lines to make the code more readable in the second submission only because it’s essentially the same solution with one extra command and an import statement.

# Java (OpenJDK 8), 219 bytes

```
a->{
double c=0;
for(String g:a.split(" ")){
char b=g.charAt(0);
if(b==105)c++;
if(b==100)c--;
if(b==109)c*=2;
if(b==104)c/=2;
if(b==80)System.out.print(new DecimalFormat("0.#").format(c));
if(b==101)return;}}

```

Try it online!
> 0 votes

# Answer
# 33, 62 bytes

```
s'i'{1a}'d'{1m}'m'{2x}'h'{2d}'P'{o}'e'{@}It[mzsjk""ltqztItn1a]

```

Try it online!

This program takes the instructions delimited by newlines

## Explanation:

```
It[mzsjk""ltqztItn1a]
  [mz            n1a] | Forever
It    jk       It     | - Get the first character of the next instruction
            qz        | - Call the function declared previously
     s  ""lt  t       | - Make sure we don't lose track of the variable

```

The code before that segment defines all the functions.
> 0 votes

# Answer
# JavaScript (V8), 152 bytes

```
i=>{return n="",p=0,e=1,i.split(" ").map(i=>{e&&("inc"==i&&p++,"dec"==i&&p--,"mult"==i&&(p*=2),"half"==i&&(p/=2),"Pri"==i&&(n+=p),"exit"==i&&(e=0))}),n}

```

Try it online!
> 0 votes

---
Tags: code-golf, math, interpreter
---


title: Print a square!

text:
# Question
Title: Print a square!
Print this text:

```
 _________
|         |
|         |
|         |
|_________|

```

Shortest code wins. Notice the space at the start of the first line.

# Answer
# PowerShell, ~~40~~ 37 bytes

```
" "+($x="_"*9)
,"|$(" "*9)|"*3
"|$x|"

```

Try it online!
> 5 votes

# Answer
# Charcoal, 12 bytes

```
←×⁵_↑⁴ ×⁵_‖Ｏ

```

Try it online! Link is to verbose version of code. Sadly the vertical direction is insufficiently symmetric to make it worthwhile reflecting. Explanation:

```
←×⁵_

```

Print 5 `_`s, leaving the cursor to the left of the first `_`. This makes up half of the bottom of the square.

```
↑⁴

```

Print 4 `|`s upwards, making the left of the square.

```
 ×⁵_

```

Print a space and 5 `_`s, making half of the top of the square.

```
‖Ｏ

```

Reflect to complete the square.
> 5 votes

# Answer
# , 24 bytes

```
<3 9$LF[9!:7' |_'#~6 4 1

```

Try it online!
> 4 votes

# Answer
# Canvas, 9 bytes

```
Ｉ×⁹-x~‰‟│

```

Try it here!

Compression. Less boring 12-byte answer:

```
２|＊５_×＋⇵ ∔↕╪

2|*           repeat "|" vertically 2 times
   5_×        repeat "_" horizontally 5 times
      +       add the two together horizontally
       ⇵      reverse the canvas vertically
         ∔    prepend a space (because otherwise it glitches out :|)
          ↕   reverse vertically, moving the underscores up
           ╪  quad-palindromize, moving underscores as needed

```

Try it here!
> 4 votes

# Answer
# 05AB1E, ~~24~~ ~~22~~ 21 bytes

```
ð'_9×«ð9×'|.ø4и`ð'_:»

```

Try it online!
> 3 votes

# Answer
# Python 2, 41 bytes

```
a=' '
for b in'_   _':print a+9*b+a;a='|'

```

Try it online!

Changes the outer character from `' '` to `'|'` after the first line using an assignment, a simple trick I don't remember seeing in an ASCII art golf before.
> 3 votes

# Answer
# 05AB1E, ~~27~~ 21 bytes (using compression and mirror)

```
…_ |•ʒßKèËß•3вèJ5ä».º

```

Straightforward approach.

Try it online.

**Explanation:**

```
…_ |        # Push string "_ |"
•ʒßKèËß•    # Push compressed integer 68865864629382
 3в         # Convert to Base-3 as list
            #  [1,0,0,0,0,0,2,1,1,1,1,1,2,1,1,1,1,1,2,1,1,1,1,1,2,0,0,0,0,0]
   è        # Index each into the string
            #  [" ","_","_","_","_","_","|"," "," "," "," "," ","|"," "," "," "," "," ","|"," "," "," "," "," ","|","_","_","_","_","_"]
    J       # Join all characters together
            #  " _____|     |     |     |_____"
     5ä     # Split the string into 5 equal-sized substrings
            #  [" _____","|     ","|     ","|     ","|_____"]
       »    # Join them by newlines
            #  " _____\n|     \n|     \n|     \n|_____"
        .º  # Mirror with overlap (and output implicitly)
            #  " _________ \n|         |\n|         |\n|         |\n|_________|\n"

```

See this 05AB1E tip of mine (section *How to compress integer lists?*) to understand why `•ʒßKèËß•3в` is `[1,0,0,0,0,0,2,1,1,1,1,1,2,1,1,1,1,1,2,1,1,1,1,1,2,0,0,0,0,0]`.

---

# 05AB1E, ~~28~~ 26 bytes (using the Canvas)

```
'_9∍ð'|4∍JDðKðJŽWêSÌsŽ9¦SΛ

```

I like this approach a lot more, but unfortunately it's a bit longer.. This approach uses the Canvas builtin `Λ`.

Try it online.

**Explanation:**

```
'_9∍      '# Push string "_" and enlarge it to size 9: "_________"
ð          # Push a space character
'|4∍      '# Push string "|" and enlarge it to size 4: "||||"
J          # Join the entire stack together to a single string
D          # Duplicate it
ðK         # Remove the space
ð          # Push a space character
J          # Join all the entire stack together to a single string
           # (We now have "_________ ||||_________|||| ")
ŽWê        # Push compressed integer 8393
   S       # Convert it to a list of digits: [8,3,9,3]
    Ì      # Add 2 to each: [10,5,11,5]
s          # Swap the list and string on the stack
Ž9¦        # Push compressed integer 2460
   S       # Convert it to a list of digits: [2,4,6,0]
Λ          # Use the Canvas with options (and output immediately implicitly):
           #  [10,5,11,5] as lengths
           #  "_________ ||||_________|||| " as string to draw
           #  [2,4,6,0] as directions, which is [left,down,right,up] respectively

```

Here a few alternatives for creating the strings (`'_9∍ð'|4∍JDðKðJ`) with the same amount of bytes:
> 2 votes

# Answer
# Java 11, 57 bytes

```
v->" _________\n"+"|         |\n".repeat(3)+"|_________|"

```

Try it online.

I don't think this requires an explanation.. \>.\>
> 2 votes

# Answer
# Python 2, ~~54~~, ~~53~~, ~~50~~, 48 bytes

```
print' '+'_'*9+'\n|         |'*3+'\n|_________|'

```

-1 Thanks to Kevin Cruijssen.

-3 Thanks to Okx

-2 Thanks to Vedant Kandoi
> 2 votes

# Answer
# Canvas, 19 bytes

```
“5＋║³╵∑O：E`}7╴？Ｂ<‟│

```

Try it here!
> 2 votes

# Answer
# C# (.NET Core), 66 bytes

```
Console.Write(" {0}\n|{1}{1}{1}{0}|","_________","         |\n|");

```

Try it online!

* Prints the first argument of `Console.Write()`
* `{0}` refers to the second argument (`"_________"`)
* `{1}` refers to the third argument (`" |\n|"`).
> 2 votes

# Answer
## Turing Machine But Way Worse \- 3251 bytes

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

```

Made with the help of ASCII\_only's program generator.
> 2 votes

# Answer
# MathGolf, 27 bytes

```
'_9*_3{'|_ 9*▌+\}'|_@++]n \

```

Try it online!

Pretty much the simplest way to do it.
> 1 votes

# Answer
# JavaScript, 54 bytes

As with Kevin's Java solution, the boring option ended up being the shortest :\

```
_=>` _________
${`|         |
`.repeat(3)}|_________|`

```

Try It Online

---

## Alternative, 59 bytes

```
_=>` _
| |
| |
| |
|_|`.replace(/../g,x=>x.padEnd(10,x[1]))

```

Try It Online
> 1 votes

# Answer
# 05AB1E, 19 bytes

```
ŽP—S"_| _"SŽNžS.Λ.º

```

Try it online!

**Explanation**

```
ŽP—S                  # push [6,5,2,5] (lengths)
    "_| _"S           # push ["_", "|", " ", "_"] (characters to print)
           ŽNžS       # push [6,0,2,2] (directions)
               .Λ     # draw to canvas without printing
                 .º   # mirror horizontally

```
> 1 votes

# Answer
# Java, 59 Bytes

```
v-> " _______\n|       |\n|       |\n|       |\n|_______|"

```
> 1 votes

# Answer
# Red, 53 bytes

```
prin[" _________^/"r:"|         |^/"r r"|_________|"]

```

Try it online!
> 1 votes

# Answer
# Brain-Flak, 317 bytes

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

```

Try it online!

Not golfy at all, just a test.
> 1 votes

# Answer
# CJam, 31 28 bytes

```
S'_9*S++'|S9*'|++___4$.e>]N*

```

Explanation

```
S'_9*S++'|S9*'|++___4$.e>]N*     e# Whole code
S'_9*S++                         e# Push the string ' _________ '
        '|S9*'|++                e# Push the string '|         |'
                 ___             e# Duplicate it 3 times
                    4$           e# Copy the 4th stack element (' _________ ')
                      .e>        e# Combine the last '|         |' with the
                                 e# ' _________ ' to get '|_________|'
                         ]N*     e# Join with newlines
                                 e# Implicit output

```

Try it online!
> 1 votes

# Answer
# , 55 bytes

```
cat(gsub(0,"|         |
"," _________
000|_________|"))

```

Try it online!
> 0 votes

# Answer
# BrainFuck, 129 bytes

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

```

This was my first code golf post so it isn't that optimized.
> 0 votes

# Answer
# Deadfish~, 226 bytes

```
iisiisddddc{dd}ddsdddddccccccccc{ddddddddd}ddsicisiiic{{d}dd}iisddddccccccccc{dd}dsiiic{{d}dd}dsicisiiic{{d}dd}iisddddccccccccc{dd}dsiiic{{d}dd}dsicisiiic{{d}dd}iisddddccccccccc{dd}dsiiic{{d}dd}dsicisiiic{ddd}icccccccccd{iii}c

```

Try it online!
> 0 votes

# Answer
# Stax, 18 bytes

```
é☻x+▓ïqÉ┬i╦↨|╛₧│&▬

```

Run and debug it
> 0 votes

# Answer
# Brainfuck, 93 bytes

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

```

Try it online!
> 0 votes

# Answer
# PHP, 81 bytes

```
while($x<9)echo str_pad(str_repeat(($l='_  | | |_|')[$x++],9),11,$l[$x++],2),"
";

```

Try it online!
> 0 votes

# Answer
# ///, ~~43~~ 38 bytes

```
/~/|         |
//-/_________/ -
~~~|-|

```

Try it online!

*-5 bytes thanks to @PkmnQ*
> 0 votes

# Answer
# FEU, 44 bytes

```
a/ ~\n---|~|
m/-/|         |\n/~/_________/g

```

Try it online!
> 0 votes

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


title: Format yourself for codegolf!

text:
# Question
Title: Format yourself for codegolf!
# Task

Your task is to write a program that, taking no input, outputs a string that represents a formatted codegolf answer of itself. The pattern is the following:

[Language name][1], n bytes
=
```
source code
```
  [1]: link-to-language

With the `language name` being the language that you wrote your program (as stated in your interpreter no abbreviations such as JavaScript =\> JS), `n` bytes being the byte-count of your language, `source code` being the source code of your program (hence the quine tag) and `link-to-language` being a link to a resource about your language - whichever your online interpreter points to. Note that this is a real quine challenge, so answers cannot read their own source code.

# Answer
## Python 2, 102 bytes

_='## [Python 2][1], 102 bytes\n```\n_=%r;print _%%_\n```\n  [1]: https://docs.python.org/2';print _%_

> 3 votes

---
Tags: code-golf, quine
---


title: Negative XOR primes

text:
# Question
Title: Negative XOR primes
About a year ago you were asked to find the XOR primes. These are numbers whose only factors are 1 and themselves when performing XOR multiplication in base 2. Now were are going to spice things up a bit.

We are going to find the XOR primes in base *-2*

## Converting to Base -2

Base -2 is a lot like every other base. The left most place is the 1s place (1 = (-2)0), next to that its the -2s place (-2 = (-2)1), next to that is the 4s place (4 = (-2)2), and so on and so forth. The big difference is that negative numbers can be represented in base -2 without any negative sign.

Here are some example conversions:

```
Decimal | Base -2
-----------------
 6      |   11010
-7      |    1001
 12     |   11100
-15     |  110001

```

## XOR addition in Base -2

XOR addition in Base -2 is pretty much the same as XOR addition in binary. You simply convert the number to Base -2 and XOR each digit in place. (This is the same as addition without the carry)

Here is an example worked through step by step:

*(We will use the symbol `+'` to indicate Base -2 XOR addition)*

Start in base 10:

```
6 +' 19

```

Convert to base -2:

```
11010 +' 10111

```

Add them without carrying:

```
   11010
+' 10111
---------
   01101

```

Convert your result back into base 10:

```
-3

```

## XOR multiplication in Base -2

Once again XOR multiplication in base -2 is nearly the same as XOR multiplication in binary. If you are not familiar with XOR multiplication in base 2 there is an excellent explanation here I suggest you take a look at that first.

XOR multiplication in Base -2 is the same as performing long multiplication in base -2 except when it comes to the last step instead of adding up all of the numbers with a traditional `+` you use the `+'` we defined above.

Here is an example worked out below:

Start in decimal:

```
8 *' 7

```

Convert to Base -2:

```
11000 *' 11011

```

Set up long division:

```
   11000
*' 11011
---------

```

Multiply the first number by every place in the second

```
      11000
*'    11011
------------
      11000
     11000
        0
   11000
  11000

```

Add up all the results using base -2 XOR addition

```
       11000
*'     11011
-------------
       11000
      11000
         0
    11000
+' 11000
-------------
   101101000

```

Convert the result back to decimal:

```
280

```

# The challenge

Your challenge is to verify whether or not a number is an XOR prime in base -2. A number is an XOR prime in base -2 if the only pair of integers that multiply to it in base are 1 and itself. (1 is not prime)

You will take in a number and output a boolean, truthy if the input is an XOR prime in base -2 falsy otherwise.

Solutions will be scored in bytes with attaining the lowest number of bytes as the goal.

# Test cases

The following are all XOR primes in base -2:

```
-395
-3
-2
 3
 15
 83

```

The following are *not* XOR primes in base -2:

```
-500
-4
 0
 1
 258
 280

```

# Answer
> 4 votes
# Mathematica, ~~156~~ 101 bytes

```
IrreduciblePolynomialQ[FromDigits[{#}//.{a_,p___}/;a!=1&&a!=0:>{-⌊a/2⌋,a~Mod~2,p},x],Modulus->2]&

```

As stated here, this works because XOR multiplication is essentially multiplication in the polynomial ring F\_2.

**Explanation**

```
{#}//.{a_,p___}/;a!=1&&a!=0:>{-⌊a/2⌋,a~Mod~2,p}

```

Start with `{input}`. Repeatedly replace a number `a` (except 0 and 1) by `a` mod 2 and prepend -floor(`a`/2), until it does not change. This calculates the input in base -2.

```
FromDigits[ ... ,x]

```

Create a polynomial using the digits of the base -2 number, using `x` as the variable. e.g. `{1, 1, 0}` -\> `x^2 + x`

```
IrreduciblePolynomialQ[ ... ,Modulus->2]

```

Check whether the resulting polynomial is irreducible, with modulus 2.

**Old version (156 bytes)**

```
If[#==1,1,Outer[FromDigits[BitXor@@(#~ArrayPad~{i++,--l}&)/@Outer[i=0;l=m;1##&,##],-2]&,k=Tuples[{0,1},m=Floor@Log2[8Abs@#~Max~1]]~Drop~{2},k,1,1]]~FreeQ~#&

```

**List of primes**

Here's a list of base -2 XOR primes between -1000 and 1000 (pastebin)

# Answer
> 1 votes
# APL (Dyalog Extended), 36 bytes

```
{2=≢⍸⍵=∘.{¯2⊥≠/⊤⍺×2*⍸⌽⊤⍵}⍨1+⍳8×1+|⍵}

```

Try it online!

Simple brute-force, and extremely inefficient (input 15 takes ~1s). Given an integer `n`, it generates a range large enough that their binary representation evaluated in negabinary includes `n`, evaluates its multiplication table (last step evaluated to negabinary instead of binary), then checks if the input appears exactly twice.

The algorithm was inspired by a solution to regular XOR primes.

### How it works

```
{2=≢⍸⍵=∘.{¯2⊥≠/⊤⍺×2*⍸⌽⊤⍵}⍨1+⍳8×1+|⍵}  ⍝ Inline function; ⍵←n
                             8×1+|⍵   ⍝ 8×(1+abs(n))
                          1+⍳         ⍝ 1-based range of above
       ∘.{              }⍨  ⍝ Evaluate XORmul table
                      ⊤⍵    ⍝ Binary of right arg
                  2*⍸⌽      ⍝ Digit values of ones
               ⊤⍺×          ⍝ Multiply left arg and convert each to binary
             ≠/             ⍝ Digit-wise XOR
          ¯2⊥               ⍝ Interpret as negabinary and convert to integer
 2=≢⍸⍵=  ⍝ Does n appear exactly twice in the table?

```

---
Tags: code-golf, number, primes, base-conversion, abstract-algebra
---


# Question
Title: Write a program that sees the New Year in itself
Write the smallest program that maps strings injectively to outputs and maps itself to 2020.

To be clear, your program \\$p\\$ must have the following properties:

1. every possible input string \\$s\\$ has a well-defined output \\$p(s)\\$,
2. for every pair of strings \\$s\\$ and \\$t\\$ with \\$s\neq t\\$, it holds that \\$p(s)\neq p(t)\\$, and
3. \\$p(p)=2020\\$.

Be sure to explain why your submission satisfies properties 1 and 2. For property 3, the output can be a string or any type of number.

**Edit 1:** Programs need to be proper quine variants. Reading the source code is not allowed.

**Edit 2:** Note that as a consequence of property 2, it holds that \\$p(s)\neq p(p)\\$ for every \\$s\neq p\\$.

# Answer
# awk, 4 bytes

The structure of an awk program is *`pattern { action }`*. If *pattern* evaluates to true, *{ action }* is performed. If *{ action }* is omitted, the default is to output the current input record.

Code:

```
2020

```

As `2020` always evaluates to true, the program always prints it's input, therefore satisfying properties 1. and 2. When the input is the program itself it satisfies property 3. \\$p(p)=2020\\$ — even \\$p(p)=p\\$.

Some test cases:

```
$ echo 2020 | awk '2020'
2020
$ echo 0 | awk '2020'
0
$ echo "" | awk '2020'

$ echo foo | awk '2020'
foo

```

Would've been more glorious back in the good old days:

```
$ echo 1 | awk '1'
1

```
> 54 votes

# Answer
# JavaScript (ES6), 23 bytes

Returns either the input string with a leading \\$0\\$, or \\$2020\\$ if the input is the program.

```
f=s=>s=='f='+f?2020:0+s

```

Try it online!

---

# JavaScript (Node.js), 76 bytes

Generates a unique BigInt by using each byte of the input string, then applies a XOR to the result in such a way that \\$f(f)=2020\\$.

```
f=s=>(g=s=>Buffer(s).every(b=>t=t<<8n|BigInt(b),t=1n)&&t)(s)^g('f='+f)^2020n

```

Try it online!
> 12 votes

# Answer
# Python 3.8 (pre-release), ~~81~~ ~~60~~ ~~59~~ ~~57~~ 56 bytes

-21 Thanks to Jo King

Outputs 2020 if the input matches the program, otherwise the input concatenated to itself 5 time (eg. `abc` becomes `abcabcabcabcabc`)

```
exec(a:='print(5*[i:=input(),404][i=="exec(a:=%r)"%a])')

```

Try it online!

---

# Python 2, 56 bytes

Outputs 2020 if the input matches the program, otherwise the input concatenated to itself 5 time (eg. `abc` becomes `abcabcabcabcabc`)

```
a='i=input();print 5*[i,404][i=="a=%r;exec a"%a]';exec a

```

Try it online!

---

# Python 3.8 (pre-release), ~~77~~ ~~67~~ 65 bytes

-10 Thanks to Jo King

Outputs 2020 if the input matches the program, otherwise the input concatenated to itself 5 time (eg. `abc` becomes `abcabcabcabcabc`)

```
lambda s:5*[s,404][s==(a:='lambda s:5*[s,404][s==(a:=%r)%%a]')%a]

```

Try it online!
> 7 votes

# Answer
# Ruby `-n`, 45 bytes

Based on one of the classic Ruby quines, `_="_=%p;puts _%%_";puts _%_`. Prints `2020` if the input is the source, otherwise prints the Ruby representation of the input (encapsulated in quotes, various characters like `"` and `\` are escaped, etc.)

```
_="_=%p;p$_==_%%_ ?2020:$_";p$_==_%_ ?2020:$_

```

Try it online!
> 7 votes

# Answer
# GolfScript, 2 bytes

```
20

```

This is a refined solution to James Brown's solutions.

If the input is 20 \[source code\], prints 2020 - otherwise prints \[string\]+20, which is unique and easily reversible.

Try it online!
> 6 votes

# Answer
# Jelly, 16 bytes

```
“Ṿ;⁾v`³⁽¥ŒṾ⁼?”v`

```

Try it online!

A full program that takes a string as its input. It outputs an unevaluated Jelly version of the input unless provided with itself, in which case it outputs 2020.

Thanks to @JonathanAllan for pointing out a flaw in my original version!

## Explanation

```
 “Ṿ;⁾v`³⁽¥ŒṾ⁼?”v` | Evaluate as Jelly code the following, using itself as the argument:
  Ṿ               | - Unevaluate (effectively wraps string back into “”
   ;⁾v`           | - Append "v`"
       ³    ⁼?    | - If equal to the program’s argument:
        ⁽¥Œ       | - Then: 2020 (compressed integer)
           Ṿ      | - Else: Unevaluated version of the program’s original argument

```
> 3 votes

# Answer
# Raku, 47 bytes

```
<say "<$_>~~.EVAL"eq($!=get)??2020!!@$!>~~.EVAL

```

Try it online!

Outputs `2020` if the input matches the program, otherwise the input surrounded in brackets.
> 3 votes

# Answer
# C (gcc), ~~190~~ ~~196~~ ~~194~~ ~~192~~ ~~180~~ 176 bytes

Thanks to Jo King for pointing out a bug.

Trailing newline seems accepted in some other answers, so will use that to fix a bug pointed out by NieDzejkob. (Also -12 bytes thanks to the same.)

-4 bytes thanks to @ceilingcat.

Assumes little-endian, ASCII, `sizeof(int) >= 4`, all the good stuff.

Outputs the input string preceded by a dollar sign, unless given its own source code, in which case it outputs `2020`.

```
*s="*s=%c%s%1$c,u[99]={'0202'};f(int*t){puts(bcmp(u+2,t,sprintf(u+2,s,34,s))?putchar(36),t:u);}",u[99]={'0202'};f(int*t){puts(bcmp(u+2,t,sprintf(u+2,s,34,s))?putchar(36),t:u);}

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 28 bytes

```
"34çìD«QiŽ7ìëû"34çìD«QiŽ7ìëû

```

Try it online or verify a few more test cases.

**Explanation:**

```
"34çìD«QiŽ7ìëû"            # Push this string
               34ç         # Push 34, and convert it to a character: '"'
                  ì        # Prepend it in front of the string
                   D«      # Append a copy of the string to itself
                     Qi    # If it's equal to the (implicit) input:
                       Ž7ì #  Push compressed integer 2020
                      ë    # Else:
                       û   #  Palindromize the (implicit) input
                           # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ž7ì` is `2020`.
> 2 votes

# Answer
# Java 10, 128 bytes

```
s->{var t="s->{var t=%c%s%1$c;t=t.format(t,34,t);return t.equals(s)?2020:0+s;}";t=t.format(t,34,t);return t.equals(s)?2020:0+s;}

```

Try it online.

**Explanation:**

part of the explanation:

* `var t` contains the unformatted source code
* `%s` is used to input this String into itself with `t.format(...)`
* `%c`, `%1$c`, and the `34` are used to format the double quotes
* `t.format(t,34,t)` puts it all together

Challenge part of the explanation:

* `t.equals(s)` checks if the input-String is equal to the source code
* `?2020`: if it is, return `2020` as result
* `:0+s`: if not, return the input-String with a prepended 0 as result instead
> 1 votes

# Answer
# Pyth, <sup>~~26~~</sup> 23 bytes

Outputs 2020 if the input matches the program, otherwise the input concatenated to itself 2020 time (eg. ab becomes ababab...ababab)

```
*2020|qjN B"*2020|qjN B

```

Try it online!

## Explanation

```
*2020|qjN B"*2020|qjN B
          B"*2020|qjN B : Evaluates to ("*2020|qjN B", "*2020|qjN B")
       jN               : join with '"' as seperator (will be source code)
     |q                 : True if source is equal to input else input
*2020                   : Multiply by 2020 (i.e. True -> 2020, input -> 2020 * input)

```

---

# Pyth, 21 bytes

Not sure if the following solution is valid, it will only work if the year is 2020.

```
*.d3|qjN B"*.d3|qjN B

```

Try it online!
> 1 votes

# Answer
# , 56 bytes

```
".a=.}:0 :0
echo@>2020[^:(]-:'".a=.}:0 :0',LF,a&[)1!:1[3

```

Try it online!

A full program. Unless provided with itself prints each character on a separate line.
> 0 votes

# Answer
# Japt, 24 bytes

```
OvA="¶`OvA=`+Q+A?2020:U³

```

Try it online!

## Explanation

Outputs 2020 if the input matches the program, otherwise the input 3 times (eg. ab becomes ababab)

```
OvA="¶`OvA=`+Q+A?2020:U³
  A="¶`OvA=`+Q+A?2020:U³  // Set value of A to "¶`OvA=`+Q+A?2020:U³"
Ov                        // Evaluate A as japt code
      `OvA=`+Q+A          // Concatenate "OvA=", '"' and A (Q = '"')
     ¶          ?2020:U³  // If equal to input then 2020 else input concatenated to itself 3 times

```
> 0 votes

---
Tags: quine, code-golf
---


title: Narcissistic Quine

text:
# Question
Title: Narcissistic Quine
Write a program/method that:

* Becomes a quine when the input matches the source code;
* Doesn't halt otherwise.

This is code-golf, so shortest solution wins. Avoid any standard loopholes.

# Answer
> 6 votes
# Jelly, 14 bytes

```
“Ṿ;⁾v`¹⁻³$¿”v`

```

Try it online!

A program taking a single string argument and either printing its source if the string matches its source, or looping indefinitely if not.

## Explanation

```
“          ”v` | Evaluate the following string as Jelly code, using the string itself as argument:
 Ṿ             | - Uneval (effectively wrap the string in “”
  ;⁾v`         | - Append v`
       ⁻³$¿    | - While not equal to the original program argument:
      ¹        |   - Call the identity function

```

# Answer
> 13 votes
# Python 3.8 (pre-release), ~~67~~ ~~60~~ 56 bytes

```
exec(a:='print(s:=input())\nwhile s!="exec(a:=%r)"%a:1')

```

Try it online!

---

# Python 2, 56 bytes

```
a='s=input();print s\nwhile s!="a=%r;exec a"%a:1';exec a

```

Try it online!

# Answer
> 8 votes
# GolfScript, 20 bytes

```
{`".~"+{.2$=}do\;}.~

```

Try it online!

## Explanation

```
{                }.~ # Evaluate the following string as GolfScript code, using the string itself as argument:
 `                   # - Uneval (effectively wrap the string in ""
  ".~"+              # - Append .~
       {.2$=}do      # - Do While not equal to the original program argument:
                     #   - (Basically do nothing)
               \;    # - If this loop ends, discard the extra copy of the input

```

# Answer
> 5 votes
# 05AB1E, 20 bytes

```
"34çìD«Êi["34çìD«Êi[

```

Try it online!

---

# Explanation

```
"34çìD«Êi["           - string literal
           34ç        - push the character "
              ì       - prepend to the string literal
               D«     - duplicate the string (producing the code)
                 Êi[  - loop if it's not the same as the input
                      - else implicitly output

```

# Answer
> 3 votes
# Pyth, 15 bytes

```
QWnjN B"QWnjN B

```

Try it online!

## Explanation

```
QWnjN B"QWnjN B
Q                 implicit print input
      B"QWnjN B   evaluates to ["QWnjN B", "QWnjN B"]
   jN             join elements in list with '"' as separator (will be source code)
 Wn               keep looping while input does not equal source code

```

# Answer
> 2 votes
# PHP, 89 bytes

```
eval($s='$a=chr(39);$b="eval(\$s=$a";$c="$a);";$b.$s.$c!=$argn?:die($b.$s.$c);for(;;);');

```

Try it online!

This is the best I have found so far, at the beginning it wasn't a port of @Mukundan's answer, but it pretty much ends like it. I will try to improve it later..

EDIT: saved a byte with `!=` instead of `==` so I can remove the `1`

EDIT2: saved 16 bytes using vars for repeated strings

# Answer
> 2 votes
# RProgN 2, 17 bytes

```
«•.x=xe²xw³1#1:?

```

# Explanation

```
«•.x=xe²xw³1#1:?<SPACE> #
«                       # Push the following function to the stack and execute
 •.                     # Append a space (A non-function character) and stringify
   x=                   # Assign the stringified function to x
     xe                 # Is x equal to the top of the stack?
       ²                # "Double Function" to execute if true
        x               # Push x to the stack
         w              # Output
          ³             # "Tripple Function" to execute if false
           1            # Push a truthy value to the stack
            #1          # A function that just repeatedly pushes true
              :         # While the top of the stack is true. Thus, loop forever
               ?        # If a, than b, else c
                <SPACE> # Used to ensure the function qualifies as a quine.

```

Try it online!

# Answer
> 2 votes
# Funky, 36 bytes

```
f=s=>{x=`f=[f]`ifx==s x elsewhile1z}

```

Try it online!

# Answer
> 2 votes
# JavaScript (V8), ~~33~~ ~~32~~ 31 bytes

*-1 byte thanks to Jo King*

```
f=x=>eval(`while(x!='f='+f);x`)

```

Try it online!

# Answer
> 1 votes
# Perl 5, 50 bytes

```
$_=q($_='$'."_=q($_);eval";<>eq$_?print:eval);eval

```

Try it online!

# Answer
> 1 votes
# Japt, <sup>~~29~~</sup> 21 bytes

```
OvA="Us@¶`OvA=`+Q+A}a

```

Try it online!

## Explanation

```
OvA="Us@¶`OvA=`+Q+A}a
  A="Us@¶`OvA=`+Q+A}a // Set A to string literal
Ov                    // Evaluate A as japt code
       @              // Function
        ¶`OvA=`+Q+A   //   Check if input equals "OvA" + '"' + A (Q is '"')
                   }  // End Function
                    a // Call function repeatedly until it returns a truthy value
     Us               // Slice off first 0 chars of input
                      // Implicit Output

```

---
Tags: code-golf, string, quine
---


title: Group these cells!

text:
# Question
Title: Group these cells!
*This challenge is based on the game Layerz.*

Given, on stdin or as a function argument, a 2D rectangular array of cells where each cell contains either a blank (you may choose to use 0s instead of blanks at no penalty), a 1, a 2, a 3, or a 4; find a way to divide it into valid regions (as defined below) such that each non-blank cell is contained by exactly one region. Then, output the solution found in any reasonable format. If there is no solution, either halt without producing output or output a single falsey value then halt.

Any of the following constitutes a valid region:

* A single cell containing a 1
* A cell containing a 2 and exactly one of its non-blank orthogonal neighbors
* A cell containing a 3 and exactly two of its non-blank orthogonal neighbors
* A cell containing a 4 and exactly three of its non-blank orthogonal neighbors

This is , so the shortest valid answer, in bytes, wins.

**Some test cases:**

**1. A rather trivial one:**

And this is the solution, with each region in a different color:

**2. A more interesting one**

This one has more than one solution, but here's one of them:

**3. A smaller one, containing blanks, that doesn't have any solutions (depending on whether you use one of the twos to "capture" the three, or the three to take two of the twos, you're either left with a pair of nonadjacent \[and therefore nongroupable\] twos or a single two on its own):**

Because this grid has no solutions, your program should halt without producing any output when given this grid.

**4. This one (with the top 2 shifted one cell to the left) does have a solution though:**

Solution:

(The bottom right 2 is used to "capture" the 3)

**5. Because we needed a test case with some fours:**

One solution:

# Answer
> 4 votes
I know this challenge is over an year old, but I just found this in "unanswered" and looked quite interesting to me.

Assuming that the "root" cell's number is the only significant one in each region (deducible from the examples), here is my backtracking solution:

# Python 3, 355 351 349 bytes

```
from itertools import*
def f(a):
 D=len(a[0])+1;S={D*r+c for r in range(len(a))for c in range(D-1)if a[r][c]};s=[{x,*t}for x in S for t in combinations({x-D,x-1,x+1,x+D}&S,a[x//D][x%D]-1)]
 def B(s,S,d=1):
  if{0}>S:return a
  if[]==s:return 0
  h,*t=s
  if h<=S:
   for x in h:a[x//D][x%D]=d
  return h<=S and B(t,S-h,d+1)or B(t,S,d)
 return B(s,S)

```

Try it online!

The input format is a 2D list of integers, blanks as zero, and the output format is also a 2D list of integers representing one region per number. The region number starts at one; zero is reserved for blank cells (as in input). If the given input is unsolvable, the function returns single zero (falsy value).

For example, the test case 5 is input as

```
[[2,3,2],
 [3,4,3],
 [0,4,0],
 [3,3,3],
 [2,3,2],
 [0,3,0]]

```

and the output is

```
[[1,1,1],
 [2,2,2],
 [0,2,0],
 [3,4,5],
 [3,4,5],
 [0,4,0]]

```

Ungolfed, with comments:

```
from itertools import*
def f(a):
 # Rows, cols, fake-cols to prevent neighbors wrap around
 R,C=len(a),len(a[0]);D=C+1
 # All valid cells represented as integers
 S={D*r+c for r in range(R) for c in range(C) if a[r][c]}
 # All valid regions rooted at each cell
 s=[{x,*t} for x in S for t in combinations({x-D,x-1,x+1,x+D}&S,a[x//D][x%D]-1)]
 # Start backtracking
 return backtrack(a,s,S,D)

# a: array to fill in the region numbers
# s: current candidates of regions
# S: current remaining cells to cover
# D: constant from f
# d: recursion depth == group number in the result
def backtrack(a,s,S,D,d=1):
 # Empty S: the board is correctly covered, return the result
 if not S:return a
 # Empty s: no more candidate regions to use, return false
 if not s:return 0
 h,*t=s
 # h is not a subset of S: h is not a valid cover, try with the rest using same depth
 if not h<=S:return backtrack(a,t,S,D,d)
 # h is a valid cover, write d to the cells in h
 for x in h:a[x//D][x%D]=d
 return backtrack(a,t,S-h,D,d+1)or backtrack(a,t,S,D,d)

```

Try it online!

**Note:** This is a special case of Set Packing which is well-known to be NP-complete. This specific problem has limited set size (max. 4) and there exist approximation algorithms to find "good" set packing in polynomial time, but they don't guarantee the maximum possible set packing (which is strictly required in this problem).

# Answer
> 3 votes
# APL (Dyalog Unicode), 94 bytes

```
⎕CY'dfns'
{0≡a←X⊢b←⊃⍪/{v∊⍤1⊢⍵,x[(w[⍵]-1)cmat≢x←v∩⍵(+,-)↓0 2⊤⍳2]}∘⊂¨v←⍸×w←⍵:0⋄(b+.×⍨a×+\a)@v⊢w}

```

Try it online!

-4 bytes thanks to @Adám. Improvements are:

* `x←...⋄...cmat≢x``...cmat≢x←...` (-2 bytes)
* `(+\×⊢)a``a×+\a` (-2 bytes)

---

# APL (Dyalog Unicode), 98 bytes

```
⎕CY'dfns'
{0≡a←X⊢b←⊃⍪/{x←v∩⍵(+,-)↓0 2⊤⍳2⋄v∊⍤1⊢⍵,x[(w[⍵]-1)cmat≢x]}∘⊂¨v←⍸×w←⍵:0⋄(b+.×⍨(+\×⊢)a)@v⊢w}

```

Try it online!

Well, who would have imagined a language having Knuth's Algorithm X as a built-in library function? Algorithm X is an algorithm designed to solve Exact Cover problems, and the challenge here is exactly this kind of problem.

Now it just becomes a matter of constructing the *constraint matrix* (a boolean matrix whose columns represent *constraints* and rows represent *actions* that satisfy some of the constraints). Then X solves the problem by finding the collection of rows so that 1 appears exactly once per column.

### Ungolfed with comments

```
⎕CY'dfns'  ⍝ Load `cmat` and `X`
f←{
  ⍝ v←Coordinates of nonzero positions
  v←⍸×w←⍵

  ⍝ Given an enclosed coord, generate constraint rows
  Rowgen←{
    ⍝ Extract 4-way neighbors that are part of the board
    x←v∩⍵(+,-)↓0 2⊤⍳2
              ↓0 2⊤⍳2  ⍝ Fancy way to say (0 1)(1 0)
        ⍵(+,-)         ⍝ Input coord plus/minus 1 horizontally/vertically
      v∩               ⍝ Set intersection with valid coords

    ⍝ Boolean matrix where each row represents a possible tile placement
    ⍝ and 1 marks the covered cells by that tile
    v∊⍤1⊢⍵,x[(w[⍵]-1)cmat≢x]
             (w[⍵]-1)cmat≢x   ⍝ Possible combinations of neighbors
         ⍵,x[              ]  ⍝ Index into x and prepend ⍵
    v∊⍤1⊢                     ⍝ Mark covered cells as 1
  }

  ⍝ bmat←Constraint matrix; vertical concatenation of constraint rows
  bmat←⊃⍪/Rowgen∘⊂¨v

  ⍝ ans←Solution by Algorithm X
  ans←X bmat

  ⍝ Return 0 if answer not found (single zero)
  0≡ans:0

  ⍝ Mark the pieces as distinct integers starting from 1
  ⍝ (increasing in the order of the root cell)
  (bmat+.×⍨(+\×⊢)ans)@v⊢w
           (+\×⊢)ans       ⍝ Assign distinct numbers to 1 bits
                           ⍝ 1 0 0 1 0 1 1 .. → 1 0 0 2 0 3 4 ..
   bmat+.×⍨                ⍝ Extract associated numbers for all valid cells
  (                 )@v⊢w  ⍝ Overwrite valid cells of w with ^
}

```

---
Tags: code-golf, array, grid, puzzle-solver
---


# Question
Title: Create a text image by manual automation
# Challenge

## Premise

It's 2006, and Alice is trying to send Bob ~~their~~ her completed notes on their newly ended expeditions into the labyrinthine school library, which the two of them found suffers from a bad case of non-Euclidean geometry.1

For some reason, Alice originally created her notes, which consist of black text on a white background, using SVG. What a genius. It hits her now that Bob doesn't have a single device that will display SVG! I mean, she accidentally fried it the last time she paid him a visit at his place.

She decides to send him a black-on-white raster rendering without anti-aliasing of any sort. Of course, she's going to do it with code. Her, since it *figures* that Bob would be the sort to take to hardware rather than software.2 Regardless, Alice can't go back on her word, so she *supposes* she's got to see it through. She thinks Bob should consider himself lucky that she has so much time to spend on ~~their~~ her notes…

1. Don't get the wrong idea! She's only sending them because he asked nicely, not because she's got any sympathy for boys who play *Quake III Arena* for eight hours at night (or whatever it is they do) and create only the barest skeleton of notes on their own.

2. She also, mysteriously, hasn't got a capable OS, but that's another story.

## Task

Help Alice draw rasterised glyphs. She'll re-use and position them by herself, tasks that are trivial in comparison.

Input:

* First take a string whose contents are an SVG path definition (`d` attribute) defining a single glyph. Only lines and cubic Béziers will be used. You only need to consider upper-case commands. Each pair of coordinates will be comma-separated. All coordinates will be given to one decimal place. Please refer to the examples.
    + There may or may not be whitespace at the top and/or left of the glyph.
* Next, take an integer \\$10\leq n\leq72\\$ representing the **height** of the output described below.

Output: A matrix (actual type: 2D array or equivalent) of 1s and 0s where a 1 represents a pixel to be coloured black and a 0, white. The matrix is to be scaled to a height of \\$n\\$, maintaining the glyph's aspect ratio as far as possible. A 1 must appear where and only where, ideally, using vector graphics, **more than or exactly** 50% of the corresponding space would be black.

* For standardisation purposes, compute the output as though there were no whitespace borders in the input.

In every example below, for reasons of clarity only, the output substitutes X for 1 and \[space\] for 0.

### Examples

Run the following snippet to view them.

```
body { font-family: verdana; }
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
th, td { padding: 5px; }
td { vertical-align: top; }
.w { width: 60%; }
.g { background-color: #eee; }
.m {
  font-family: monospace;
  padding: .2em;
}
.a { line-height: .7em !important; }
.s { font-size: 85%; }
```

```
<h2>Example 1</h2>
<table>
<tr><th>Input</th><th>Image from path definition</th></tr>
<tr><td class="w" rowspan="3"><span class="g m">
M 60.0,10.0 L 85.3,79.7 C 86.3,82.3 87.1,84.1 87.9,85.0 C 88.7,85.9 89.8,86.6 91.2,87.1 L 96.6,88.7 L 96.7,91.1 C 91.7,91.0 87.1,90.9 82.9,90.9 C 78.5,90.9 73.4,91.0 67.5,91.1 L 67.3,88.7 L 72.7,87.1 C 73.5,86.8 74.0,86.6 74.3,86.2 C 74.7,85.9 74.8,85.4 74.8,84.7 C 74.8,83.9 74.6,82.9 74.2,81.7 C 73.8,80.4 73.3,78.8 72.5,76.8 L 67.2,61.5 L 39.7,61.5 L 33.7,76.7 C 32.9,78.8 32.3,80.5 31.9,81.8 C 31.4,83.0 31.2,84.0 31.2,84.7 C 31.2,85.4 31.4,85.9 31.7,86.2 C 32.1,86.6 32.6,86.8 33.3,87.0 L 38.6,88.5 L 38.7,91.1 C 33.4,91.0 28.9,90.9 25.5,90.9 C 22.1,90.9 18.3,91.0 14.1,91.1 L 13.8,88.7 L 19.5,86.9 C 21.0,86.4 22.1,85.7 22.7,84.8 C 23.4,83.8 24.2,82.4 25.0,80.3 L 54.1,10.8 L 60.0,10.0 z M 41.8,56.3 L 65.3,56.3 L 54.2,24.9 L 41.8,56.3 z
<br><br>
11
</span><td>
<svg width="125" height="110" xmlns="http://www.w3.org/2000/svg">
<path style="fill:#000;" d="M 60.0,10.0 L 85.3,79.7 C 86.3,82.3 87.1,84.1 87.9,85.0 C 88.7,85.9 89.8,86.6 91.2,87.1 L 96.6,88.7 L 96.7,91.1 C 91.7,91.0 87.1,90.9 82.9,90.9 C 78.5,90.9 73.4,91.0 67.5,91.1 L 67.3,88.7 L 72.7,87.1 C 73.5,86.8 74.0,86.6 74.3,86.2 C 74.7,85.9 74.8,85.4 74.8,84.7 C 74.8,83.9 74.6,82.9 74.2,81.7 C 73.8,80.4 73.3,78.8 72.5,76.8 L 67.2,61.5 L 39.7,61.5 L 33.7,76.7 C 32.9,78.8 32.3,80.5 31.9,81.8 C 31.4,83.0 31.2,84.0 31.2,84.7 C 31.2,85.4 31.4,85.9 31.7,86.2 C 32.1,86.6 32.6,86.8 33.3,87.0 L 38.6,88.5 L 38.7,91.1 C 33.4,91.0 28.9,90.9 25.5,90.9 C 22.1,90.9 18.3,91.0 14.1,91.1 L 13.8,88.7 L 19.5,86.9 C 21.0,86.4 22.1,85.7 22.7,84.8 C 23.4,83.8 24.2,82.4 25.0,80.3 L 54.1,10.8 L 60.0,10.0 z M 41.8,56.3 L 65.3,56.3 L 54.2,24.9 L 41.8,56.3 z"/>
</svg>
</td></tr>
<tr><th>Output</th></tr>
<tr><td><pre class="a g">
      X
     XX
     XXX
    X XX
    X  X
   X   XX
   XXXXXX
   X    XX
  X     XX
  X      X
XXX     XXXX
</pre></td></tr></table>

<h2>Example 2</h2>
<table>
<tr><th>Input</th><th>Image from path definition</th><th>Output</th></tr>
<tr><td><span class="g m">
M 40.0,10.0 C 44.3,10.2 48.5,10.2 52.4,10.2 C 56.4,10.2 60.5,10.2 64.8,10.0 L 65.0,12.2 L 58.8,14.0 C 58.0,14.2 57.6,14.7 57.5,15.6 C 57.5,16.7 57.4,18.0 57.4,19.4 C 57.4,20.8 57.4,22.3 57.4,23.9 L 57.4,69.3 C 57.4,72.5 57.3,75.5 57.0,78.2 C 56.8,80.9 56.3,83.3 55.7,85.4 C 55.0,87.5 54.2,89.4 53.0,91.0 C 51.9,92.7 50.4,94.1 48.6,95.4 C 46.9,96.7 44.7,97.8 42.2,98.8 C 39.7,99.8 36.7,100.7 33.3,101.5 L 32.6,99.0 C 36.0,97.5 38.8,95.9 40.7,94.1 C 42.7,92.3 44.2,90.3 45.2,88.0 C 46.3,85.8 46.9,83.2 47.2,80.4 C 47.5,77.6 47.6,74.4 47.6,70.8 L 47.6,24.1 C 47.6,22.4 47.6,20.9 47.6,19.5 C 47.6,18.2 47.6,16.9 47.5,15.8 C 47.5,15.0 47.1,14.4 46.3,14.1 L 40.1,12.2 L 40.0,10.0 Z
<br><br>
20
</span></td><td>
<svg width="125" height="110" xmlns="http://www.w3.org/2000/svg">
<path style="fill:#000;" d="M 40.0,10.0 C 44.3,10.2 48.5,10.2 52.4,10.2 C 56.4,10.2 60.5,10.2 64.8,10.0 L 65.0,12.2 L 58.8,14.0 C 58.0,14.2 57.6,14.7 57.5,15.6 C 57.5,16.7 57.4,18.0 57.4,19.4 C 57.4,20.8 57.4,22.3 57.4,23.9 L 57.4,69.3 C 57.4,72.5 57.3,75.5 57.0,78.2 C 56.8,80.9 56.3,83.3 55.7,85.4 C 55.0,87.5 54.2,89.4 53.0,91.0 C 51.9,92.7 50.4,94.1 48.6,95.4 C 46.9,96.7 44.7,97.8 42.2,98.8 C 39.7,99.8 36.7,100.7 33.3,101.5 L 32.6,99.0 C 36.0,97.5 38.8,95.9 40.7,94.1 C 42.7,92.3 44.2,90.3 45.2,88.0 C 46.3,85.8 46.9,83.2 47.2,80.4 C 47.5,77.6 47.6,74.4 47.6,70.8 L 47.6,24.1 C 47.6,22.4 47.6,20.9 47.6,19.5 C 47.6,18.2 47.6,16.9 47.5,15.8 C 47.5,15.0 47.1,14.4 46.3,14.1 L 40.1,12.2 L 40.0,10.0 Z"/>
</svg>
</td><td><pre class="a g">
 XXXXX
  XX
  XX
  XX
  XX
  XX
  XX
  XX
  XX
  XX
  XX
  XX
  XX
  XX
  XX
  XX
  XX
  XX
 XX
XX
</pre></td></tr></table>

<h2>Example 3</h2>
<table>
<tr><th>Input</th><th>Image from path definition</th></tr>
<tr><td class="w" rowspan="3"><span class="g m">
M 80.0,40.0 C 80.0,50.8 77.1,59.6 71.5,66.3 C 65.8,73.0 58.4,76.9 49.2,77.9 C 51.9,85.6 58.9,89.5 70.1,89.5 C 74.6,89.5 78.7,88.8 82.3,87.4 L 82.8,89.7 C 75.9,95.2 70.5,97.9 66.5,97.9 C 53.9,97.9 45.8,91.4 42.3,78.3 C 31.3,78.3 22.8,75.1 16.7,68.6 C 10.6,62.2 7.5,53.4 7.5,42.3 C 7.5,30.7 10.8,21.6 17.4,14.9 C 24.0,8.1 33.1,4.8 44.8,4.8 C 56.0,4.8 64.7,7.9 70.8,14.2 C 76.9,20.5 80.0,29.0 80.0,40.0 L 80.0,40.0 z M 18.5,40.6 C 18.5,51.5 20.7,59.8 25.1,65.6 C 29.5,71.4 35.9,74.3 44.4,74.3 C 52.8,74.3 59.0,71.7 63.0,66.4 C 67.0,61.2 69.0,52.9 69.0,41.7 C 69.0,31.1 66.9,23.0 62.6,17.3 C 58.4,11.7 51.8,8.8 43.0,8.8 C 34.4,8.8 28.2,11.5 24.3,16.7 C 20.4,22.0 18.5,29.9 18.5,40.6 L 18.5,40.6 Z
<br><br>
10
</span><td>
<svg width="125" height="110" xmlns="http://www.w3.org/2000/svg">
<path style="fill:#000;" d="M 80.0,40.0 C 80.0,50.8 77.1,59.6 71.5,66.3 C 65.8,73.0 58.4,76.9 49.2,77.9 C 51.9,85.6 58.9,89.5 70.1,89.5 C 74.6,89.5 78.7,88.8 82.3,87.4 L 82.8,89.7 C 75.9,95.2 70.5,97.9 66.5,97.9 C 53.9,97.9 45.8,91.4 42.3,78.3 C 31.3,78.3 22.8,75.1 16.7,68.6 C 10.6,62.2 7.5,53.4 7.5,42.3 C 7.5,30.7 10.8,21.6 17.4,14.9 C 24.0,8.1 33.1,4.8 44.8,4.8 C 56.0,4.8 64.7,7.9 70.8,14.2 C 76.9,20.5 80.0,29.0 80.0,40.0 L 80.0,40.0 z M 18.5,40.6 C 18.5,51.5 20.7,59.8 25.1,65.6 C 29.5,71.4 35.9,74.3 44.4,74.3 C 52.8,74.3 59.0,71.7 63.0,66.4 C 67.0,61.2 69.0,52.9 69.0,41.7 C 69.0,31.1 66.9,23.0 62.6,17.3 C 58.4,11.7 51.8,8.8 43.0,8.8 C 34.4,8.8 28.2,11.5 24.3,16.7 C 20.4,22.0 18.5,29.9 18.5,40.6 L 18.5,40.6 Z"/>
</svg>
</td></tr>
<tr><th>Output</th></tr>
<tr><td><pre class="a g">
  XXXX
 X    X
X     XX
X      X
X      X
X     X
 X    X
  XXXX
    X
     XXX
</pre></td></tr></table>

<h2>Example 4</h2>
<table>
<tr><th>Input</th><th>Image from path definition</th><th>Output</th></tr>
<tr><td><span class="g m">
M 80.0,40.0 C 80.0,50.8 77.1,59.6 71.5,66.3 C 65.8,73.0 58.4,76.9 49.2,77.9 C 51.9,85.6 58.9,89.5 70.1,89.5 C 74.6,89.5 78.7,88.8 82.3,87.4 L 82.8,89.7 C 75.9,95.2 70.5,97.9 66.5,97.9 C 53.9,97.9 45.8,91.4 42.3,78.3 C 31.3,78.3 22.8,75.1 16.7,68.6 C 10.6,62.2 7.5,53.4 7.5,42.3 C 7.5,30.7 10.8,21.6 17.4,14.9 C 24.0,8.1 33.1,4.8 44.8,4.8 C 56.0,4.8 64.7,7.9 70.8,14.2 C 76.9,20.5 80.0,29.0 80.0,40.0 L 80.0,40.0 z M 18.5,40.6 C 18.5,51.5 20.7,59.8 25.1,65.6 C 29.5,71.4 35.9,74.3 44.4,74.3 C 52.8,74.3 59.0,71.7 63.0,66.4 C 67.0,61.2 69.0,52.9 69.0,41.7 C 69.0,31.1 66.9,23.0 62.6,17.3 C 58.4,11.7 51.8,8.8 43.0,8.8 C 34.4,8.8 28.2,11.5 24.3,16.7 C 20.4,22.0 18.5,29.9 18.5,40.6 L 18.5,40.6 Z
<br><br>
50
</span></td><td>
<svg width="125" height="110" xmlns="http://www.w3.org/2000/svg">
<path style="fill:#000;" d="M 80.0,40.0 C 80.0,50.8 77.1,59.6 71.5,66.3 C 65.8,73.0 58.4,76.9 49.2,77.9 C 51.9,85.6 58.9,89.5 70.1,89.5 C 74.6,89.5 78.7,88.8 82.3,87.4 L 82.8,89.7 C 75.9,95.2 70.5,97.9 66.5,97.9 C 53.9,97.9 45.8,91.4 42.3,78.3 C 31.3,78.3 22.8,75.1 16.7,68.6 C 10.6,62.2 7.5,53.4 7.5,42.3 C 7.5,30.7 10.8,21.6 17.4,14.9 C 24.0,8.1 33.1,4.8 44.8,4.8 C 56.0,4.8 64.7,7.9 70.8,14.2 C 76.9,20.5 80.0,29.0 80.0,40.0 L 80.0,40.0 z M 18.5,40.6 C 18.5,51.5 20.7,59.8 25.1,65.6 C 29.5,71.4 35.9,74.3 44.4,74.3 C 52.8,74.3 59.0,71.7 63.0,66.4 C 67.0,61.2 69.0,52.9 69.0,41.7 C 69.0,31.1 66.9,23.0 62.6,17.3 C 58.4,11.7 51.8,8.8 43.0,8.8 C 34.4,8.8 28.2,11.5 24.3,16.7 C 20.4,22.0 18.5,29.9 18.5,40.6 L 18.5,40.6 Z"/>
</svg>
</td><td><pre class="a g s">
               XXXXXXXX
           XXXXXXXXXXXXXXXX
        XXXXXXX     XXXXXXXXX
       XXXXX           XXXXXXX
      XXXX                XXXXXX
     XXXX                  XXXXXX
    XXXX                    XXXXXX
   XXXXX                     XXXXX
   XXXXX                     XXXXXX
  XXXXX                       XXXXX
 XXXXXX                       XXXXXX
 XXXXXX                         XXXX
XXXXXXX                         XXXXX
XXXXXX                          XXXXX
XXXXXX                          XXXXX
XXXXXX                          XXXXX
XXXXXX                          XXXXX
XXXXXX                          XXXXX
XXXXXX                          XXXXX
XXXXXX                          XXXXX
XXXXXX                          XXXXX
XXXXXX                          XXXXX
XXXXXX                          XXXXX
XXXXXX                         XXXXXX
 XXXXX                         XXXXXX
 XXXXXX                        XXXXXX
 XXXXXX                        XXXXXX
 XXXXXX                        XXXXX
  XXXXX                        XXXX
  XXXXXX                      XXXXX
  XXXXXX                      XXXXX
   XXXXXX                     XXXX
    XXXXX                    XXX
     XXXXX                  XXX
     XXXXXX                XXX
       XXXXXX             XXX
       XXXXXXX           XXX
         XXXXXXXXXXXXXXXXXX
            XXXXXXXXXXXXX
                  XXX
                  XXXX
                  XXXXX
                   XXXX
                   XXXXX
                    XXXXXX            X
                    XXXXXXXXXXXXXXXXXXX
                     XXXXXXXXXXXXXXXX
                      XXXXXXXXXXXXXXX
                        XXXXXXXXXXX
                           XXXXX
</pre></td></tr></table>

<h2>Credit</h2>
<a href="https://upload.wikimedia.org/wikipedia/commons/4/4c/Latin_Alphabet.svg">Wikimedia Commons</a>
```

# Remarks

# Answer
# JavaScript (ES7),  ~~364~~  352 bytes

Expects `(path)(height)`.

```
f=
p=>h=>([x,y,X,Y]=[0,1,2,3].map(i=>Math[i&2?'max':'min'](...p.match(/\d+\S+/g).map(s=>+s.split`,`[i&1]))+.5|0),C=document.createElement`canvas`.getContext`2d`).fill(new Path2D(p))&C.getImageData(x,y,X-=x,Y-=y).data.map((v,i)=>!v|i%4-3?0:m[(i>>=2)/X*h/Y|0][i%X*h/Y|0]++,m=[...Array(h)].map(_=>Array(X*h/Y|0).fill(0)))||m.map(r=>r.map(v=>+(v>(Y/h)**2/2)))

o.innerHTML = f("M 80.0,40.0 C 80.0,50.8 77.1,59.6 71.5,66.3 C 65.8,73.0 58.4,76.9 49.2,77.9 C 51.9,85.6 58.9,89.5 70.1,89.5 C 74.6,89.5 78.7,88.8 82.3,87.4 L 82.8,89.7 C 75.9,95.2 70.5,97.9 66.5,97.9 C 53.9,97.9 45.8,91.4 42.3,78.3 C 31.3,78.3 22.8,75.1 16.7,68.6 C 10.6,62.2 7.5,53.4 7.5,42.3 C 7.5,30.7 10.8,21.6 17.4,14.9 C 24.0,8.1 33.1,4.8 44.8,4.8 C 56.0,4.8 64.7,7.9 70.8,14.2 C 76.9,20.5 80.0,29.0 80.0,40.0 L 80.0,40.0 z M 18.5,40.6 C 18.5,51.5 20.7,59.8 25.1,65.6 C 29.5,71.4 35.9,74.3 44.4,74.3 C 52.8,74.3 59.0,71.7 63.0,66.4 C 67.0,61.2 69.0,52.9 69.0,41.7 C 69.0,31.1 66.9,23.0 62.6,17.3 C 58.4,11.7 51.8,8.8 43.0,8.8 C 34.4,8.8 28.2,11.5 24.3,16.7 C 20.4,22.0 18.5,29.9 18.5,40.6 L 18.5,40.6 Z")(20).map(r => r.map(v => ' X'[v]).join('')).join('\n')
```

```
<pre id=o></pre>
```

### Commented

```
p => h =>                        // p = path, h = height
( [x, y, X, Y] =                 // find the bounding box (x, y) - (X, Y)
  [0, 1, 2, 3].map(i =>          // for i = 0 to 3:
    Math[i & 2 ? 'max' : 'min']( //   get the max if i > 1, or the min otherwise:
      ...p.match(/\d+\S+/g)      //     match all coordinates
      .map(s =>                  //     for each of them:
        +s.split`,`[i & 1]       //       keep x if i is even, or y if i is odd
      )                          //     end of inner map()
    ) + .5 | 0                   //   end of Math.min or Math.max; round the result
  ),                             // end of outer map()
  C = document.createElement     // create a canvas and get its 2D context C
      `canvas`.getContext`2d`    //
).fill(new Path2D(p)) &          // draw the path in the canvas
C.getImageData(                  // turn X into the width and Y into the height
  x, y, X -= x, Y -= y           //
).data.map((v, i) =>             // for each value at position i in the context data:
  !v |                           //   if v is not set
  i % 4 - 3 ?                    //   or this is not a transparency field:
    0                            //     do nothing
  :                              //   else:
    m[(i >>= 2) / X * h / Y | 0] //     increment m[] at the position obtained by
    [i % X * h  / Y | 0]++,      //     rescaling ((i >> 2) / X, (i >> 2) % X)
                                 //     according to the ratio h / Y
  m =                            //   initialize m[] to a matrix of size
    [...Array(h)].map(_ =>       //   floor(X * h / Y) x h,
      Array(X * h / Y | 0)       //
      .fill(0)                   //   filled with 0's
    )                            //
) ||                             // end of map()
m.map(r =>                       // for each row r[] in m[]:
  r.map(v =>                     //   for each value v in m[]:
    +(v > (Y / h) ** 2 / 2)      //     set v to 1 if it's greater than the threshold
  )                              //   end of inner map()
)                                // end of outer map()

```
> 4 votes

# Answer
## HTML5 + ES6, 320 bytes

```
with(c.getContext`2d`)f=(d,h)=>(p.setAttribute("d",d),b=p.getBBox(),c.height=h,c.width=w=h*b.width/b.height,scale(s=h/b.height,s),translate(-b.x,-b.y),fill(new Path2D(d)),[...getImageData(0,0,w,h).data.filter((_,i)=>!(3&~i))].map(i=>` X`[i>>7]).join``.match(RegExp(`.{${c.width}}`,`g`)).join`
`)
console.log(f("M 80.0,40.0 C 80.0,50.8 77.1,59.6 71.5,66.3 C 65.8,73.0 58.4,76.9 49.2,77.9 C 51.9,85.6 58.9,89.5 70.1,89.5 C 74.6,89.5 78.7,88.8 82.3,87.4 L 82.8,89.7 C 75.9,95.2 70.5,97.9 66.5,97.9 C 53.9,97.9 45.8,91.4 42.3,78.3 C 31.3,78.3 22.8,75.1 16.7,68.6 C 10.6,62.2 7.5,53.4 7.5,42.3 C 7.5,30.7 10.8,21.6 17.4,14.9 C 24.0,8.1 33.1,4.8 44.8,4.8 C 56.0,4.8 64.7,7.9 70.8,14.2 C 76.9,20.5 80.0,29.0 80.0,40.0 L 80.0,40.0 z M 18.5,40.6 C 18.5,51.5 20.7,59.8 25.1,65.6 C 29.5,71.4 35.9,74.3 44.4,74.3 C 52.8,74.3 59.0,71.7 63.0,66.4 C 67.0,61.2 69.0,52.9 69.0,41.7 C 69.0,31.1 66.9,23.0 62.6,17.3 C 58.4,11.7 51.8,8.8 43.0,8.8 C 34.4,8.8 28.2,11.5 24.3,16.7 C 20.4,22.0 18.5,29.9 18.5,40.6 L 18.5,40.6 Z",50))
```

```
<canvas id=c><svg><path id=p />
```

Explanation: The HTML creates two global variables, `c` being the canvas element and `p` being the SVG path element.

```
with(c.getContext`2d`)

```

Put all of the canvas's 2d drawing functions into the current scope.

```
f=(d,h)=>(

```

Create a function of two parameters.

```
p.setAttribute("d",d),b=p.getBBox(),

```

Set the `d` attribute of the path and then get its bounding box.

```
c.height=h,c.width=w=h*b.width/b.height,

```

Set the size of the canvas to the desired height and scale the width.

```
scale(s=h/b.height,s),translate(-b.x,-b.y),

```

Scale and translate the drawing to fit the desired height.

```
fill(new Path2D(d)),

```

Draw the path on the canvas.

```
[...getImageData(0,0,w,h).data.filter((_,i)=>!(3&~i))].

```

Get the alpha channel of the canvas.

```
map(i=>` X`[i>>7]).

```

Map the dark pixels to `X` and the light pixels to space.

```
join``.match(RegExp(`.{${w}}`,`g`)).join`
`)

```

Rewrap the pixels to the width of the canvas.
> 0 votes

---
Tags: code-golf, string, math, geometry, matrix
---


title: Scientific notation in Base-16

text:
# Question
Title: Scientific notation in Base-16
Input a scientific notation number (base 10), output scientific notation in base 16 (as defined below).

## Details

In scientific notation, all non-zero numbers are written in the form

$$ m \times 10^n $$

Where \\$ n \\$ is an integer, and \\$ m \\$ is a real number, \\$ 1 \leq |m| \< 10 \\$.

Consider scientific notation in base 16.

$$ m \times 10^n = m' \times 16^{n'} $$

\\$ n' \\$ is an integer, and \\$ m' \\$ is a real number where \\$ 1 \leq |m'| \< 16 \\$.

## Input / Output

Input a positive real number. You may also choice to input \\$m\\$, and, \\$n\\$ separately. For all testcase, -100 \< n \< 100.

Output the number in hexadecimal scientific notation. Could be a single string or two strings. Number \\$m\\$, and, \\$n\\$ should also be formatted as hexadecimal strings.

Output as `1.2E3E4` is not allowed due to ambiguous. (1.2E3×104, or 1.2×103E4) You have to use other notations. For example, `1.2E3E+4`, `1.2E3, 4`, `1.2E3&4`, `1.2e3E4`, `1.2E3e4`, `1.2E3P4`, `1.2E3⏨4`, `1.2E3*^4` are all acceptable.

## Testcases

```
m, n -> m', n'
1.6, 1 -> 1, 1
6.25, -2 -> 1, -1
1.0, 1 -> A, 0
7.257672195146994, 93 -> d.eadbeef, 4d
1.234567, 89 -> f.83e0c1c37ba7, 49
1, -99 -> 8.bfbea76c619f, -53

```

You output may be slightly different from given testcase due to floating point errors. But you should keep at least 4 hex digits precision, and \\$1 \leq m' \< 16\\$.

## Rule

This is code golf. Shortest codes in each languages win.

# Answer
# JavaScript (ES6),  ~~134 124~~  121 bytes

Expects a float and returns an array of 2 strings.

```
n=>([x,y]=(+(g=n=>s=n.toString(16))(n).replace(r=/[1-f]/g,1)).toExponential().split`e`,[x.replace(r,_=>r.exec(s)),g(+y)])

```

Try it online!

### How?

We first convert the input to hexadecimal and save the result in the variable `s`.

For instance, `7.257672195146994e93` is turned into:

```
"deadbeef0000000000000000000000000000000000000000000000000000000000000000000000"

```

We replace all non-zero hexadecimal digits with `1`'s:

```
"111111110000000000000000000000000000000000000000000000000000000000000000000000"

```

We coerce this back to an integer and invoke the `.toExponential()` method:

```
"1.1111111e+77"

```

We split this string into `x = "1.1111111"` and `y = "+77"`.

We replace all `1`'s in `x` with the non-zero hexadecimal digits of `s` in order of appearance:

```
"d.eadbeef"

```

Finally, we convert `y` to hexadecimal:

```
"4d"

```

Below is another example with `6e-19`:

```
"0.000000000000000b116b7de48f008"
"0.00000000000000011111111111001"
"1.1111111111001e-16"
[ "1.1111111111001", "-16" ]
[ "b.116b7de48f008", "-10" ]

```

### Commented

```
n => (                       // n = input
  [x, y] =                   // x = mantissa, y = exponent
    (                        //
      +(                     // coerce to integer:
        g = n =>             //   g is a helper function converting its input ...
          s = n.toString(16) //     ... to a hexadecimal string saved in s
      )(n)                   //   invoke g with n
      .replace(              //   replace:
        r = /[1-f]/g,        //     r = regular expression to match the non-zero
                             //         hexa digits
        1                    //     replace all of them with 1's
      )                      //   end of replace()
    )                        //
    .toExponential()         // convert to exponential notation
    .split`e`,               // split into [ x, y ] = [ mantissa, exponent ]
  [                          // output array:
    x.replace(               //   replace in x:
      r,                     //     use r a 2nd time to match the 1's
      _ => r.exec(s)         //     use r a 3rd time to get the next hexa digit
                             //     from s, this time taking advantage of the
                             //     stateful nature of RegExp
    ),                       //   end of replace()
    g(+y)                    //   convert y to hexadecimal
  ]                          // end of output array
)                            //

```
> 4 votes

# Answer
## JavaScript (ES6), 217 bytes

```
f=
n=>/^-?0\./.test(n=n.toString(16))?n.replace(/^(-?)0(.0*)(.)(.*)/,(_,s,z,d,t)=>s+d+'.'+t+'e-'+z.length.toString(16)):n=n.replace(/(-?.)(\w*).?(.*)/,(_,s,d,t)=>s+'.'+d+t+'e='+d.length.toString(16)).replace(/0*e=/,"e+")
```

```
<input type=number step=any oninput=o.textContent=f(+this.value)><pre id=o>
```

Output format is `-?[1-f]\.([0-f]*[1-f])?e[+-][1-f][0-f]*`.
> 1 votes

# Answer
# Perl 5, 181 bytes

```
sub f{($e,$x)=(0,10**pop()*pop);$x/=16,$e++while$x>=16;$x*=16,$e--while$x<1;join('',map{sprintf$_?'%x':'%x.',$x%16,$x-=$x%16,$x*=16}0..12)=~s,\.?0*$,,r,sprintf$e<0?'-%x':'%x',abs$e}

```

Try it online!

I think using `sprintf('%a',$x)` could make the answer much shorter, just not sure how.

Ungolfed:

```
sub f {
  my($m, $n) = @_;
  my($e, $x) = (0, $m * 10**$n);
  $x/=16, $e++ while $x >= 16;
  $x*=16, $e-- while $x <  1;
  return (
    join('',map{sprintf$_?'%x':'%x.',$x%16,$x-=$x%16,$x*=16}0..12) =~ s,\.?0*$,,r,
    sprintf($e<0?'-%x':'%x',abs$e)
  )
}

```

Test:

```
for my $test (map[/-?[\da-f\.]+/gi],split/\n/,<<''){
    1.6, 1                -> 1, 1
    6.25, -2              -> 1, -1
    1.0, 1                -> a, 0
    7.257672195146994, 93 -> d.eadbeef, 4d
    1.234567, 89          -> f.83e0c1c37ba7, 49
    1, -99                -> 8.bfbea76c619f, -53

    my($m,$n,$Mexp,$Nexp)=@$test;
    my($Mgot,$Ngot)=f($m,$n);
    my $testname = sprintf"  %-25s -->  %s", "$m, $n", "$Mexp, $Nexp";
    is("$Mgot,$Ngot", "$Mexp,$Nexp", $testname);
}

```

Output:

```
ok 1 -   1.6, 1                    -->  1, 1
ok 2 -   6.25, -2                  -->  1, -1
ok 3 -   1.0, 1                    -->  a, 0
ok 4 -   7.257672195146994, 93     -->  d.eadbeef, 4d
ok 5 -   1.234567, 89              -->  f.83e0c1c37ba7, 49
ok 6 -   1, -99                    -->  8.bfbea76c619f, -53

```
> 1 votes

# Answer
# Ruby, ~~62~~ 61 bytes

```
->x{'%x.%x,%+x'%[m=x/16**n=Math.log(x,16).floor,m%1*16**9,n]}

```

Try it online!

Input is a (decimal) float. Output is in the form \\$m',n'\\$, where \\$m'\\$ has a maximum precision of 10 hex digits and \\$n'\\$ is always signed.

`'%x.%x,%+x'` is a shorthand form of `sprintf` syntax, which creates formatted strings for numeric output. The format specifier `x` converts its argument to hexadecimal and the `+` guarantees signed output (otherwise negative numbers would be output with two leading dots representing an infinite string of leading `ff`s). We do three conversions to hex: (i) the integral part of \\$m'\\$, (ii) the fractional part of \\$m'\\$ (`m%1`; multiplying by `16**9` is necessary because the fractional part is ignored by `sprintf`), and (iii) \\$n'\\$.

The solution makes use of some straightforward mathematical transformations. Let \\$m'=16^{m''}\\$, so that \\$x\equiv m10^n=m'16^{n'}=16^{m''+n'}\equiv 16^y\\$. Then \\$y=\log\_{16}x\\$. We are told that \\$n'\\$ is an integer, hence we take \\$n'=\lfloor y\rfloor\\$. This is the only choice of \\$n'\\$ for which \\$0\le m''=y-n'\<1\\$, and hence the only choice of \\$n'\\$ for which \\$1\le 16^{m''}=m' \< 16\\$ as required.

To support negative inputs, add `.abs` in two places and another `+` in the format string, bringing the code to 70 bytes:

```
->x{'%+x.%x,%+x'%[m=x/16**n=Math.log(x.abs,16).floor,m.abs%1*16**9,n]}

```
> 1 votes

# Answer
# C(GCC), 32 bit float, ~~133~~ ~~129~~ 128 bytes

-4 bytes ceilingcat

```
m;e;s(float f){m=*(int*)&f;e=(m>>23)-127;m=(m&-1U>>9|1<<23)>>3-(e&3);printf("%x.%05xE%c%x",m>>20,m&-1U>>12,"+-"[e<0],abs(e/4));}

```

Try it online!

This extracts the exponent and mantissa from a floating point number. Since the maximum exponent is +/-127 in base 2 (approx 38 base 10), this doesn't quite meet the challenge since it fails on larger exponents. So...

# C(GCC), 64 bit float, ~~167~~ ~~163~~ 147 bytes

-4 bytes ceilingcat

```
long m;e;s(double f){m=*(long*)&f;e=(m>>52)-1023;m=(m&-1UL>>12|1L<<52)>>3-(e&3);printf("%lx.%013lxE%c%x",m>>49,(m&-1UL>>15)*8,"+-"[e<0],abs(e/4));}

```

Try it online!
> 1 votes

# Answer
# , 192 bytes

```
function(x,i=function(x,p=F,y=abs(x))`if`(y>0,{d=c(0:9,letters[1:6])[rev(y%/%(16^(0:log(y,16)))%%16+1)]
c("-"[x<0],d[1],"."[p],d[-1])},0))cat(i(x*16^(3-(n=log(x^2,16)%/%2)),T)," ",i(n),sep="")

```

Try it online!

Happily handles negative numbers, even if now not required.

Commented:

```
base16float==function(x,
    l=c(0:9,letters[1:6]),                          # define hexadecimal digits
    i=function(x,point=FALSE,y=abs(x))              # create function to write hexadecimal integers
    `if`(x==0,0,                                    # if x is zero, just write zero
        {d=l[rev(y%/%(16^(0:log(y,16)))%%16+1)]     # otherwise get the digits for each power-of-16
            c("-"[x<0],d[1],"."[p],d[-1])})         # and paste them together with the sign
    )                                               # (and with a "." after the first digit if
                                                    # specified by point=TRUE in the function call)
    cat(i(x*16^(3-(n=log(abs(x),16)%/%1)),T),       # so: first output the mantissa as a 4-digit integer
                                                    # with point=TRUE to include the dot,
        " ",                                        # leave a gap,
        i(n),                                       # and write the exponent
        sep="")

```
> 1 votes

# Answer
# Python 3, ~~135~~ \\$\cdots\\$ ~~119~~ 105 bytes

```
def f(x):m,n=x.hex().split('p');m=hex(int('1'+m[4:],16)<<int(n)%4);return m[2]+'.'+m[3:],f'{int(n)//4:x}'

```

Try it online!

Inputs a float.
Returns a tuple of strings \\$(m',n')\\$.
> 0 votes

# Answer
# Python 3.8, 284 bytes

`struct` approach. At least I tried)

```
from struct import*
m=lambda s,c,n,k:[s[n:],'-'+s[k:]][c]
n=lambda s:m(s,s[0]=='-',2,3)
o=lambda s,x:m(s,x<0,0,0)
p=lambda x:x[2]+'.'+x[3:]
s=lambda x,y,d=2**52:(o(p(hex((x%d+d)*2**((x//d+1)%4)).rstrip('0')),y),n(hex(((x//d)%2048-1023)//4)))
f=lambda x:s(unpack('Q',pack('d',x))[0],x)

```

Try it online!
> 0 votes

---
Tags: code-golf, math, base-conversion, hexadecimal, floating-point
---