title: Prime Challenge

text:
# Question
Title: Prime Challenge
*CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?*

```
6779686932717976703238326711110010511010332671049710810810111010310111558327311032116111100971213911532991049710810810111010310144321211111173910810832981013297115107101100321161113211211410511011632116104101321021111081081111191051101033211810111412132115112101991059710832657868321161141059910712132657868321159711610511510212110511010332801141051091013278117109981011144646463332651141013212111111732103111108102101114115321141019710012163

```

**Your task is to output this 442-digit Prime Number**

**Rules**

Your code must not contain any odd decimal digits. So numbers 1,3,5,7,9 (ASCII 49,51,53,55,57) are forbidden.

This is . The shortest code in bytes wins.

So... what is so special about this prime number anyway?
You may find this out yourselves. If you don't, I'll tell you next week!

**EDIT**
Since this challenge is going to close, I will give a hint to my friend @xnor:
The challenge IS the number (this is why it is called "Prime Challenge")

# Answer
> 16 votes
# , 195 bytes

(SPOILER IF YOU WANT TO FIGURE IT OUT YOURSELF)

> ```
> cat(utf8ToInt("CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?"),sep="")
> ```

Try it online!

Not the golfiest language to use for , but it does the trick.

# Answer
> 5 votes
# x86-16 machine code, IBM PC DOS, 206 bytes

Binary:

> ```
> 00000000: be24 01b1 aaac d40a 5086 e0d4 0a05 3030  .$......P.....00
> 00000010: 86e0 3c30 7402 cd29 86e0 cd29 5804 30cd  ..<0t..)...)X.0.
> 00000020: 29e2 e2c3 434f 4445 2047 4f4c 4620 2620  )...CODE GOLF &
> 00000030: 436f 6469 6e67 2043 6861 6c6c 656e 6765  Coding Challenge
> 00000040: 733a 2049 6e20 746f 6461 7927 7320 6368  s: In today's ch
> 00000050: 616c 6c65 6e67 652c 2079 6f75 276c 6c20  allenge, you'll
> 00000060: 6265 2061 736b 6564 2074 6f20 7072 696e  be asked to prin
> 00000070: 7420 7468 6520 666f 6c6c 6f77 696e 6720  t the following
> 00000080: 7665 7279 2073 7065 6369 616c 2041 4e44  very special AND
> 00000090: 2074 7269 636b 7920 414e 4420 7361 7469   tricky AND sati
> 000000a0: 7366 7969 6e67 2050 7269 6d65 204e 756d  sfying Prime Num
> 000000b0: 6265 722e 2e2e 2120 4172 6520 796f 7520  ber...! Are you
> 000000c0: 676f 6c66 6572 7320 7265 6164 793f       golfers ready?
>
> ```

Listing:

> ```
> BE 0124   MOV  SI, OFFSET TXT     ; string offset
> B1 AA     MOV  CL, 170            ; string length
>       CHAR_LOOP:
> AC        LODSB                   ; AL = next char
> D4 0A     AAM                     ; AL = AL % 10, AH = AL / 10
> 50        PUSH AX                 ; save units digits
> 86 E0     XCHG AH, AL             ; swap digits
> D4 0A     AAM                     ; AL = AL % 10, AH = AL / 10
> 05 3030   ADD  AX, '00'           ; ASCII convert
> 86 E0     XCHG AH, AL             ; swap digits
> 3C 30     CMP  AL, '0'            ; is highest digit a '0'?
> 74 02     JZ   TWODIG             ; if so, don't display leading zero
> CD 29     INT  29H                ; display hundreds digit
>       TWODIG:
> 86 E0     XCHG AH, AL             ; swap digits
> CD 29     INT  29H                ; display tens digit
> 58        POP  AX                 ; restore units digit
> 04 30     ADD  AL, '0'            ; ASCII convert
> CD 29     INT  29H                ; display units digit
> E2 E2     LOOP CHAR_LOOP          ; loop until end of string
> C3        RET                     ; return to DOS
>       TXT:
>           DB 'CODE GOLF & Coding Challenges: In today',27H,'s challenge, '
>           DB 'you',27H,'ll be asked to print the following very special '
>           DB 'AND tricky AND satisfying Prime Number...! Are you golfers ready?'
>
> ```

# Answer
> 4 votes
# Io, 186 bytes

> ```
> "CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?"foreach(print)
>
> ```
> Try it online!

## Explanation

> Io's default syntax for defining strings actually defines a "sequence", that is basically a list of ord codes.

> During foreach, Io treats every character of the sequence as it's respective ord code (don't believe it? try `"abc"at(0)`)

> ```
> "..."               // The big string, from other answers
>      foreach(     ) // For every codepoint in this string:
>              print  //     output this codepoint without a newline
>
> ```

# Answer
> 4 votes
# 05AB1E, 93 bytes

```
”›ˆ‚³...!€™”‘€ƒ‘D”Âïªï:€†”‘ƒËŠˆ‘“ÿ & ÿƒÜ's›Ý,€î'll€ï‹Ð€„…¢€€„—‚ÒƒÑ ÿÐËy ÿËØing ÿ€îŠˆersŽä?“ÇJ

```

Try it online.

**Explanation:**

> ```
> ”›ˆ‚³...!€™”  # Push (titlecased) dictionary string "Prime Number...! Are"
> ‘€ƒ‘D         # Push (uppercased) dictionary string "AND" and duplicate it
> ”Âïªï:€†”     # Push (titlecased) dictionary string "Coding Challenges: In"
> ‘ƒËŠˆ‘        # Push (uppercased) dictionary string "CODE GOLF"
> “ÿ & ÿƒÜ's›Ý,€î'll€ï‹Ð€„…¢€€„—‚ÒƒÑ ÿÐËy ÿËØing ÿ€îŠˆersŽä?“
>               # Push (regular) dictionary string "ÿ & ÿ today's challenge, you'll be asked to print the following very special ÿ tricky ÿ satisfying ÿ you golfers ready?",
>               # where the `ÿ` are automatically filled with the strings on the stack
> Ç             # Convert each character to its codepoint integer
> J             # And join all those together
>               # (after which the result is output implicitly)
> ```

> See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `”›ˆ‚³...!€™”` is `"Prime Number...! Are"`; `‘€ƒ‘` is `"AND"`; `”Âïªï:€†”` is `"Coding Challenges: In"`; `‘ƒËŠˆ‘` is `"CODE GOLF"`; and `“ÿ & ÿƒÜ's›Ý,€î'll€ï‹Ð€„…¢€€„—‚ÒƒÑ ÿÐËy ÿËØing ÿ€îŠˆersŽä?“` is `"ÿ & ÿ today's challenge, you'll be asked to print the following very special ÿ tricky ÿ satisfying ÿ you golfers ready?"`.

# Answer
> 3 votes
# Python 3, ~~202~~ 196 bytes

Saved 6 bytes thanks to Manish Kundu!!!

> ```
> print(*map(ord,"CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?"),sep='')
> ```

Try it online!

Port of Giuseppe's R answer.

# Answer
> 3 votes
# Japt, 133 bytes

As will be the case with every solution to this, all credit here belongs to Giuseppe!

```
`CODE GOLF & CoÜA Câ%s: In Üþs å¡e, y'¥ ¼ k  pÎC e èÄg vy special AND Éky AND Ñsfyg PÎX Num¼r...! A y goÓÈs Î%y?`mc

```

Try it

# Answer
> 3 votes
# Pyth, ~~118~~ 175 bytes

```
jkCM"CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?

```

Try it online!

Due to a rushed answer, my original source didn't give the correct number. I was only checking the first and last numbers and assumed the rest was correct.

# Answer
> 3 votes
# Keg, ~~177~~ 141 bytes

```
`CODE GOLF & Coding Challenges: In nL;'s r⊂;, you'll be 0⑵; to a⑱; the 1⟱; 0K; 4∀; AND ⬨⑺; AND Q&; Prime Number...! Are you :G;ers 1⑾;?`÷^(ⁿ.

```

Try it online!

Yeah, it the same technique as everyone else. Now with string compression.

# Answer
> 3 votes
# Python 2, 202 bytes

```
print''.join(`ord(x)`for x in"CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?")

```

Spoiler tag misinterprets the backticks and anyway, it's probably not necessary any more.

Try it online!

# Answer
> 3 votes
# Deadfish~, 1442 bytes

```
{{i}ddddd}iiiicicciicdddciicddciiicddddddcdciiiiicddddddciiiiiiciicddcdcic{d}iiiciiicdciciiiiicdddddcdciiiicicddddddccccdccicdciiiiicddddccdcicdciiiccdciiiicicddddddcdciiiiciiiiicddcddddddcdc{i}ddc{d}iiicdc{i}ddc{d}iiicdcicccdcicdciiicddcdciccciiiicciiicdddddcdciiiiicddddcddccdciiicdcdcciiiiicdddddccccdcc{i}dcddcddddddcicdciiciiiiiic{d}iicciiiicddcdc{i}dddcc{d}iicdciiiiciiiiicddcddddddcdc{i}ddc{d}iiicdc{i}ddc{d}iiicdcicccdcicdciiicddcdciciiiccdcdcdcicdcccccciiiiiicddddciiiiiic{d}iicdc{i}ddc{d}iiicdc{i}ddcdddddcdc{i}dddcdc{d}iiicdciciicdc{i}dddcddcddddddcciiiicddddcdc{i}dddcddddddcdciccdcciiicdcdcciiiiicdddddccciicdcdccicdcciiicdddcdciiiiicddddccdcicciiiiicdddcdcdcciiiiicdddddcdciiiicdddcdciciicdcdcdciicdccccdc{i}ddc{d}iiicdc{i}ddc{d}iiiccccc{i}ddc{d}iicdciiiiicddddccdcicdciiiccdcdcc{i}dddc{d}iiicdciccciiicdddcicdciicdcdcciiiicddddccicdcdcic{i}ddcc{d}iicdciiiiiciiiicddcddddddcdc{i}ddcdddddcdciiiicdciicicddciicdddddcdcdcciiiiicdddddcciiicdddcdciiiiiciiiicc{d}iicdc{i}dddcddddddcicdciicdciiiicdciicicddciicdddddcdcdcciiiiciiiicddcddddddcciiiiicdddddcdciiiiicddddcciiiicddddcdciicdcicdccdciiiiicddddccdcicdciiiccdciiiiiic{d}iicicciiicdddcdciiiiicddddcdc{i}dc{d}iicdciciicdciiiiicic{d}iiicciiiiiicddddddcdc{i}dccdc{d}iiicdciccciiicciicddciicddciicdddcccdciiiicdcddddcciiicdddcdciciicdcdcicdcccccciiiiiicddddcdcdcdciiicddccccdc{i}ddc{d}iiicdciicdcdciccciiicdddcciiiicddcdcdcciiicdddcdcic{i}ddcddcddddddcdccicicdciiiiicdddc{d}{d}i{c}cc

```

# Answer
> 2 votes
# C (gcc), ~~213~~ ~~211~~ ~~210~~ 211 bytes

```
f(){for(char*s="CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?";*s;)printf("%d",*s++);}

```

Try it online!

# Answer
> 2 votes
# Bash, 237 bytes

> ```
> s="CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?";o=o
> for((i=0;i<${#s};i++));do printf %d \'"${s:$i:${#o}}";done
> ```

Try it online!

Port of Giuseppe's R answer.

# Answer
> 2 votes
# PHP, 200 bytes

> ```
> while($c=ord("CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?"[$i++]))echo$c;
>
> ```

Try it online!

# Answer
> 2 votes
# 05AB1E, 121 bytes

> ```
> '€ƒuð.ø’CODE GOLF & Cod±µ Cí¤ÁÛ¡¾: In ƒÜ's ›Ý, €î'½ž €ï ‹Ð €„ …¢ €€ „— ‚Ò ƒÑÿÐËyÿËØ±µ PØ†e NuîÐ²¡...! A‚™ €î Šˆ²¡s Žä?’ÇJ
> ```

Try it online!

> ```
> '€ƒuð.ø’...’ÇJ  # trimmed program
> '€ƒ             # push "and"...
>    u            # uppercase...
>      .ø         # surrounded by...
>     ð           # spaces
>                 # (ÿ in the long compressed string gets implicitly replaced with this)
>              J  # join...
>             Ç   # charcodes of...
>        ’...’    # "CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?"
>                 # implicit output
> ```

The hardest part of this wasn't writing the code, it was trying to get the Markdown to work.

# Answer
> 2 votes
# Perl 5, 190 bytes

> `say"CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?"=~s/./ord$&/ger`

Try it online!

# Answer
> 1 votes
# Vyxal, 108 bytes

> ``¬⋎ »₅` `& ⟩₆ →ṗ: In ¬¾'s ɾṖ, λ•'ll be •₇ to ⟑Ẇ λλ ∧ṫ ƛ² ¬∪ AND ¦Ṡy AND ¶⊍ing ʁ꘍ ƛṅ...! λ∆ λ• »₅ers €æ?`+Cṅ` Needed to optimize the string little to compress it well

Try it Online!

# Answer
> 1 votes
# Knight, 195 bytes

> ```
> ;=s" CODE GOLF & Coding Challenges: In today's challenge, you'll be asked to print the following very special AND tricky AND satisfying Prime Number...! Are you golfers ready?"W=sGsT LsO++''As'\'
> ```

Try It Online!

---
Tags: code-golf, kolmogorov-complexity, restricted-source, primes
---


title: Draw A Sierpinski Triangle

text:
# Question
Title: Draw A Sierpinski Triangle
The Sierpinsky Triangle is a fractal created by taking a triangle, decreasing the height and width by 1/2, creating 3 copies of the resulting triangle, and place them such each triangle touches the other two on a corner. This process is repeated over and over again with the resulting triangles to produce the Sierpinski triangle, as illustrated below.

Write a program to generate a Sierpinski triangle. You can use any method you want to generate the pattern, either by drawing the actual triangles, or by using a random algorithm to generate the picture. You can draw in pixels, ascii art, or whatever you want, so long as the output looks similar to the last picture shown above. Fewest characters wins.

# Answer
## HTML + JavaScript, 150 characters (see notes for 126 characters)

Whitespace inserted for readability and not counted.

```
<title></title><canvas></canvas><script>
for(x=k=128;x--;)for(y=k;y--;)
  x&y||document.body.firstChild.getContext("2d").fillRect(x-~y/2,k-y,1,1)
</script>

```

The core of it is applying the rule of coloring pixels for which `x & y == 0` by the conditional `x&y||`, which produces a “Sierpinski right triangle”; and `x-~y/2,k-y` are a coordinate transformation to produce the approximately equilateral display.

A less correct (HTML-wise) version is 126 characters:

```
<canvas><script>
for(x=k=128;x--;)for(y=k;y--;)
  x&y||document.body.firstChild.getContext("2d").fillRect(x-~y/2,k-y,1,1)
</script>

```

(The way in which this is less correct is that it omits the `title` element and the end tag of the `canvas` element, both of which are required for a correct document even though omitting them does not change the *interpretation* of the document.)

Three characters can be saved by eliminating `k` in favor of the constant `64`, at the cost of a smaller result; I wouldn't count the `8` option as it has insufficient detail.

Note that a size of 256 or higher requires attributes on the `<canvas>` to increase the canvas size from the default.
> 42 votes

# Answer
## GolfScript (43 42 chars)

```
' /\ /__\ '4/){.+\.{[2$.]*}%\{.+}%+\}3*;n*

```

Output:

```
               /\
              /__\
             /\  /\
            /__\/__\
           /\      /\
          /__\    /__\
         /\  /\  /\  /\
        /__\/__\/__\/__\
       /\              /\
      /__\            /__\
     /\  /\          /\  /\
    /__\/__\        /__\/__\
   /\      /\      /\      /\
  /__\    /__\    /__\    /__\
 /\  /\  /\  /\  /\  /\  /\  /\
/__\/__\/__\/__\/__\/__\/__\/__\

```

Change the "3" to a larger number for a larger triangle.
> 27 votes

# Answer
# Python (234)

Maximal golfing, tiny image:

```
#!/usr/bin/env python3
from cairo import*
s=SVGSurface('_',97,84)
g=Context(s)
g.scale(97,84)
def f(w,x,y):
 v=w/2
 if w>.1:f(v,x,y);f(v,x+w/4,y-v);f(v,x+v,y)
 else:g.move_to(x,y);g.line_to(x+v,y-w);g.line_to(x+w,y);g.fill()
f(1,0,1)
s.write_to_png('s.png')

```

Requires `python3-cairo`.

To get a nice large image I needed **239** characters.
> 27 votes

# Answer
**Mathematica - 32 characters**

```
Nest[Subsuperscript[#,#,#]&,0,5]

```

**Mathematica - 37 characters**

```
Grid@CellularAutomaton[90,{{1},0},31]

```

This will produce a 2D table of 0 and 1, where 1s are drawing Sierpinski Triangle.
> 27 votes

# Answer
## Python, 101 86

Uses the rule 90 automaton.

```
x=' '*31
x+='.'+x
exec"print x;x=''.join(' .'[x[i-1]!=x[i-62]]for i in range(63));"*32

```

This is longer, but prettier.

```
x=' '*31
x+=u'Δ'+x
exec u"print x;x=''.join(u' Δ'[x[i-1]!=x[i-62]]for i in range(63));"*32

```

Edit: playing with strings directly, got rid of obnoxiously long slicing, made output prettier.

Output:

```
                               Δ
                              Δ Δ
                             Δ   Δ
                            Δ Δ Δ Δ
                           Δ       Δ
                          Δ Δ     Δ Δ
                         Δ   Δ   Δ   Δ
                        Δ Δ Δ Δ Δ Δ Δ Δ
                       Δ               Δ
                      Δ Δ             Δ Δ
                     Δ   Δ           Δ   Δ
                    Δ Δ Δ Δ         Δ Δ Δ Δ
                   Δ       Δ       Δ       Δ
                  Δ Δ     Δ Δ     Δ Δ     Δ Δ
                 Δ   Δ   Δ   Δ   Δ   Δ   Δ   Δ
                Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ
               Δ                               Δ
              Δ Δ                             Δ Δ
             Δ   Δ                           Δ   Δ
            Δ Δ Δ Δ                         Δ Δ Δ Δ
           Δ       Δ                       Δ       Δ
          Δ Δ     Δ Δ                     Δ Δ     Δ Δ
         Δ   Δ   Δ   Δ                   Δ   Δ   Δ   Δ
        Δ Δ Δ Δ Δ Δ Δ Δ                 Δ Δ Δ Δ Δ Δ Δ Δ
       Δ               Δ               Δ               Δ
      Δ Δ             Δ Δ             Δ Δ             Δ Δ
     Δ   Δ           Δ   Δ           Δ   Δ           Δ   Δ
    Δ Δ Δ Δ         Δ Δ Δ Δ         Δ Δ Δ Δ         Δ Δ Δ Δ
   Δ       Δ       Δ       Δ       Δ       Δ       Δ       Δ
  Δ Δ     Δ Δ     Δ Δ     Δ Δ     Δ Δ     Δ Δ     Δ Δ     Δ Δ
 Δ   Δ   Δ   Δ   Δ   Δ   Δ   Δ   Δ   Δ   Δ   Δ   Δ   Δ   Δ   Δ
Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ

```
> 24 votes

# Answer
## J

```
,/.(,~,.~)^:6,'o'

```

Not ideal, since the triangle is lopsided and followed by a lot of whitespace - but interesting nonetheless I thought.

Output:

```
o
oo
o o
oooo
o   o
oo  oo
o o o o
oooooooo
o       o
oo      oo
o o     o o
oooo    oooo
o   o   o   o
oo  oo  oo  oo
o o o o o o o o
oooooooooooooooo
o               o
oo              oo
o o             o o
oooo            oooo
o   o           o   o
oo  oo          oo  oo
o o o o         o o o o
oooooooo        oooooooo
o       o       o       o
oo      oo      oo      oo
o o     o o     o o     o o
oooo    oooo    oooo    oooo
o   o   o   o   o   o   o   o
oo  oo  oo  oo  oo  oo  oo  oo
o o o o o o o o o o o o o o o o
oooooooooooooooooooooooooooooooo
o                               o
oo                              oo
o o                             o o
oooo                            oooo
o   o                           o   o
oo  oo                          oo  oo
o o o o                         o o o o
oooooooo                        oooooooo
o       o                       o       o
oo      oo                      oo      oo
o o     o o                     o o     o o
oooo    oooo                    oooo    oooo
o   o   o   o                   o   o   o   o
oo  oo  oo  oo                  oo  oo  oo  oo
o o o o o o o o                 o o o o o o o o
oooooooooooooooo                oooooooooooooooo
o               o               o               o
oo              oo              oo              oo
o o             o o             o o             o o
oooo            oooo            oooo            oooo
o   o           o   o           o   o           o   o
oo  oo          oo  oo          oo  oo          oo  oo
o o o o         o o o o         o o o o         o o o o
oooooooo        oooooooo        oooooooo        oooooooo
o       o       o       o       o       o       o       o
oo      oo      oo      oo      oo      oo      oo      oo
o o     o o     o o     o o     o o     o o     o o     o o
oooo    oooo    oooo    oooo    oooo    oooo    oooo    oooo
o   o   o   o   o   o   o   o   o   o   o   o   o   o   o   o
oo  oo  oo  oo  oo  oo  oo  oo  oo  oo  oo  oo  oo  oo  oo  oo
o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo

```

**A quick explanation:**

The verb `(,~,.~)` is what's doing the work here. It's a hook which first stitches `,.` the argument to itself (`o` -\> `oo`) and then appends the original argument to the output:

```
oo

```

becomes

```
oo
o

```

This verb is repeated 6 times `^:6` with the output of each iteration becoming the input of the next iteration. So

```
oo
o

```

becomes

```
oooo
o o
oo
o

```

which in turn becomes

```
oooooooo
o o o o
oo  oo
o   o
oooo
o o
oo
o

```

etc. I've then used the oblique adverb on append `,/.` to read the rows diagonally to straighten(ish) the triangle. I didn't need to do this, as randomra points out. I could have just reversed `|.` the lot to get the same result. Even better, I could have just used `(,,.~)^:6,'o'` to save the reverse step completely.

Ah well, you live and learn. :-)
> 18 votes

# Answer
# 8086 Machine code - 30 bytes.

NOTE: This is **not my code and should not be accepted as an answer**. I found this while working on a different CG problem to emulate an 8086 CPU. The included text file credits **David Stafford**, but that's the best I could come up with.

I'm posting this because it's clever, short, and I thought you'd want to see it.

It makes use of overlapping opcodes to pack more instructions in a smaller space. Amazingly clever. Here is the machine code:

```
B0 13 CD 10 B3 03 BE A0 A0 8E DE B9 8B 0C 32 28 88 AC C2 FE 4E 75 F5 CD 16 87 C3 CD 10 C3

```

A straight-up decode looks like this:

```
0100: B0 13              mov AL, 13h
0102: CD 10              int 10h
0104: B3 03              mov BL, 3h
0106: BE A0 A0           mov SI, A0A0h
0109: 8E DE              mov  DS, SI
010B: B9 8B 0C           mov CX, C8Bh
010E: 32 28              xor  CH, [BX+SI]
0110: 88 AC C2 FE        mov  [SI+FEC2h], CH
0114: 4E                 dec SI
0115: 75 F5              jne/jnz -11

```

When run, when the jump at 0x0115 happens, notice it jumps back to 0x010C, right into the middle of a previous instruction:

```
0100: B0 13              mov AL, 13h
0102: CD 10              int 10h
0104: B3 03              mov BL, 3h
0106: BE A0 A0           mov SI, A0A0h
0109: 8E DE              mov  DS, SI
010B: B9 8B 0C           mov CX, C8Bh
010E: 32 28              xor  CH, [BX+SI]
0110: 88 AC C2 FE        mov  [SI+FEC2h], CH
0114: 4E                 dec SI
0115: 75 F5              jne/jnz -11
010C: 8B 0C              mov  CX, [SI]
010E: 32 28              xor  CH, [BX+SI]
0110: 88 AC C2 FE        mov  [SI+FEC2h], CH
0114: 4E                 dec SI
0115: 75 F5              jne/jnz -11
010C: 8B 0C              mov  CX, [SI]

```

Brilliant! Hope you guys don't mind me sharing this. I know it's not an answer per se, but it's of interest to the challenge.

Here it is in action:
> 15 votes

# Answer
## Python (42)

I originally wanted to post a few suggestions on boothbys solution (who actually uses rule 18 :), but i didn't have enough reputation to comment, so i made it into another answer. Since he changed his approach, i added some explanation. My suggestions would have been:

1. use '%d'\*64%tuple(x) instead of ''.join(map(str,x)
2. shift in zeros instead of wraping the list around

which would have led to the following code (93 characters):

```
x=[0]*63
x[31]=1
exec"print'%d'*63%tuple(x);x=[a^b for a,b in zip(x[1:]+[0],[0]+x[:-1])];"*32

```

But i optimzed further, first by using a longint instead of an integer array and just printing the binary representation (75 characters):

```
x=2**31
exec"print'%d'*63%tuple(1&x>>i for i in range(63));x=x<<1^x>>1;"*32

```

And finally by printing the octal representation, which is already supported by printf interpolation (42 characters):

```
x=8**31
exec"print'%063o'%x;x=x*8^x/8;"*32

```

All of them will print:

```
000000000000000000000000000000010000000000000000000000000000000
000000000000000000000000000000101000000000000000000000000000000
000000000000000000000000000001000100000000000000000000000000000
000000000000000000000000000010101010000000000000000000000000000
000000000000000000000000000100000001000000000000000000000000000
000000000000000000000000001010000010100000000000000000000000000
000000000000000000000000010001000100010000000000000000000000000
000000000000000000000000101010101010101000000000000000000000000
000000000000000000000001000000000000000100000000000000000000000
000000000000000000000010100000000000001010000000000000000000000
000000000000000000000100010000000000010001000000000000000000000
000000000000000000001010101000000000101010100000000000000000000
000000000000000000010000000100000001000000010000000000000000000
000000000000000000101000001010000010100000101000000000000000000
000000000000000001000100010001000100010001000100000000000000000
000000000000000010101010101010101010101010101010000000000000000
000000000000000100000000000000000000000000000001000000000000000
000000000000001010000000000000000000000000000010100000000000000
000000000000010001000000000000000000000000000100010000000000000
000000000000101010100000000000000000000000001010101000000000000
000000000001000000010000000000000000000000010000000100000000000
000000000010100000101000000000000000000000101000001010000000000
000000000100010001000100000000000000000001000100010001000000000
000000001010101010101010000000000000000010101010101010100000000
000000010000000000000001000000000000000100000000000000010000000
000000101000000000000010100000000000001010000000000000101000000
000001000100000000000100010000000000010001000000000001000100000
000010101010000000001010101000000000101010100000000010101010000
000100000001000000010000000100000001000000010000000100000001000
001010000010100000101000001010000010100000101000001010000010100
010001000100010001000100010001000100010001000100010001000100010
101010101010101010101010101010101010101010101010101010101010101

```

Of course there is also a graphical solution (131 characters):

```
from PIL.Image import*
from struct import*
a=''
x=2**31
exec"a+=pack('>Q',x);x=x*2^x/2;"*32
fromstring('1',(64,32),a).save('s.png')

```

:D
> 14 votes

# Answer
**QBasic 151 Characters**

As an example, here is how it can be done in QBasic.

```
SCREEN 9
H=.5
P=300
FOR I=1 TO 9^6
    N=RND
    IF N > 2/3 THEN
        X=H+X*H:Y=Y*H
    ELSEIF N > 1/3 THEN
        X=H^2+X*H:Y=H+Y*H
    ELSE
        X=X*H:Y=Y*H
    END IF
    PSET(P-X*P,P-Y*P)
NEXT

```
> 13 votes

# Answer
## Haskell (291)

I'm not very good at golfing haskell codes.

```
solve n = tri (putStrLn "") [2^n] n
tri m xs 1 =
  do putStrLn (l1 1 xs "/\\" 0)
     putStrLn (l1 1 xs "/__\\" 1)
     m
tri m xs n=tri m' xs (n-1)
  where m'=tri m (concat[[x-o,x+o]|x<-xs]) (n-1)
        o=2^(n-1)
l1 o [] s t=""
l1 o (x:xs) s t=replicate (x-o-t) ' '++s++l1 (x+2+t) xs s t

```

Output of `solve 4` is:

```
               /\
              /__\
             /\  /\
            /__\/__\
           /\      /\
          /__\    /__\
         /\  /\  /\  /\
        /__\/__\/__\/__\
       /\              /\
      /__\            /__\
     /\  /\          /\  /\
    /__\/__\        /__\/__\
   /\      /\      /\      /\
  /__\    /__\    /__\    /__\
 /\  /\  /\  /\  /\  /\  /\  /\
/__\/__\/__\/__\/__\/__\/__\/__\

```
> 13 votes

# Answer
## APL (51)

```
      A←67⍴0⋄A[34]←1⋄' ○'[1+32 67⍴{~⊃⍵:⍵,∇(1⌽⍵)≠¯1⌽⍵⋄⍬}A]

```

Explanation:

* `A←67⍴0`: A is a vector of 67 zeroes
* `A[34]←1`: the 34th element is 1
* `{...}A`: starting with A, do:
* `~⊃⍵:`: if the first element of the current row is zero
* `⍵,∇`: add the current row to the answer, and recurse with:
* `(1⌽⍵)≠¯1⌽⍵`: the vector where each element is the XOR of its neighbours in the previous generation
* `⋄⍬`: otherwise, we're done
* `32 67⍴`: format this in a 67x32 matrix
* `1+`: add one to select the right value from the character array
* `' ○'[`...`]`: output either a space (not part of the triangle) or a circle (when it is part of the triangle)

Output:

```
                                 ○
                                ○ ○
                               ○   ○
                              ○ ○ ○ ○
                             ○       ○
                            ○ ○     ○ ○
                           ○   ○   ○   ○
                          ○ ○ ○ ○ ○ ○ ○ ○
                         ○               ○
                        ○ ○             ○ ○
                       ○   ○           ○   ○
                      ○ ○ ○ ○         ○ ○ ○ ○
                     ○       ○       ○       ○
                    ○ ○     ○ ○     ○ ○     ○ ○
                   ○   ○   ○   ○   ○   ○   ○   ○
                  ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○
                 ○                               ○
                ○ ○                             ○ ○
               ○   ○                           ○   ○
              ○ ○ ○ ○                         ○ ○ ○ ○
             ○       ○                       ○       ○
            ○ ○     ○ ○                     ○ ○     ○ ○
           ○   ○   ○   ○                   ○   ○   ○   ○
          ○ ○ ○ ○ ○ ○ ○ ○                 ○ ○ ○ ○ ○ ○ ○ ○
         ○               ○               ○               ○
        ○ ○             ○ ○             ○ ○             ○ ○
       ○   ○           ○   ○           ○   ○           ○   ○
      ○ ○ ○ ○         ○ ○ ○ ○         ○ ○ ○ ○         ○ ○ ○ ○
     ○       ○       ○       ○       ○       ○       ○       ○
    ○ ○     ○ ○     ○ ○     ○ ○     ○ ○     ○ ○     ○ ○     ○ ○
   ○   ○   ○   ○   ○   ○   ○   ○   ○   ○   ○   ○   ○   ○   ○   ○
  ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○ ○

```
> 12 votes

# Answer
# 80x86 Code / MsDos - 10 Bytes

As a sizecoder specialized for very tiny intros on MsDos i managed to come up with a program that occupies only 10 bytes.

in hex:

```
04 13 CD 10 20 E9 B4 0C E2 F6

```

in asm:

```
X: add al,0x13
int 0x10
and cl,ch
mov ah,0x0C
loop X

```

The first version i coded was "Colpinski" which is 16 bytes in size, and even interactive in a way that you can change the color with the keyboard and the mouse. Together with "Frag" - another sizecoder - we brought that one down to 13 bytes, allowing for a 10 byte program which just contains the core routine.

It gets a bit more interesting when things are animated, so i'll mention another version, Zoompinski 64 \- trying to mimic the exact behavior of "Zoompinski C64" in 512 bytes - also for MsDos, 64 bytes in size as the name suggests.

It's possible to optimize this further downto 31 Bytes, while losing elegance, colors and symmetry (source and executable available behind the link above)

Download the original and comment on "Pouet"
> 12 votes

# Answer
## C ~~127~~ ~~119~~ ~~116~~ ~~108~~ 65

This one uses the trick of the HTML answer of `^ i & j` getting it to print pretty output would take 1 more char (you can get really ugly output by sacrificing the `a^`).

```
a=32,j;main(i){for(;++i<a;)putchar(a^i&j);++j<a&&main(puts(""));}

```

To make it pretty turn `(32^i&j)` to `(32|!(i&j))` and turn it from `++i<a` to `++i<=a`. However wasting chars on looks seems ungolfish to me.

Ugly output:

```
 ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
""  ""  ""  ""  ""  ""  ""  ""
"# !"# !"# !"# !"# !"# !"# !"#
  $$$$    $$$$    $$$$    $$$$
 !$%$% ! !$%$% ! !$%$% ! !$%$%
""$$&&  ""$$&&  ""$$&&  ""$$&&
"#$%&' !"#$%&' !"#$%&' !"#$%&'
      ((((((((        ((((((((
 ! ! !()()()() ! ! ! !()()()()
""  ""((**((**  ""  ""((**((**
"# !"#()*+()*+ !"# !"#()*+()*+
  $$$$((((,,,,    $$$$((((,,,,
 !$%$%()(),-,- ! !$%$%()(),-,-
""$$&&((**,,..  ""$$&&((**,,..
"#$%&'()*+,-./ !"#$%&'()*+,-./
              0000000000000000
 ! ! ! ! ! ! !0101010101010101
""  ""  ""  ""0022002200220022
"# !"# !"# !"#0123012301230123
  $$$$    $$$$0000444400004444
 !$%$% ! !$%$%0101454501014545
""$$&&  ""$$&&0022446600224466
"#$%&' !"#$%&'0123456701234567
      ((((((((0000000088888888
 ! ! !()()()()0101010189898989
""  ""((**((**0022002288::88::
"# !"#()*+()*+0123012389:;89:;
  $$$$((((,,,,000044448888<<<<
 !$%$%()(),-,-010145458989<=<=
""$$&&((**,,..0022446688::<<>>
"#$%&'()*+,-./0123456789:;<=>?

```

I actually kind of like how it looks. But if you insist on it being pretty you can dock four chars. Pretty Output:

```
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !
  !!  !!  !!  !!  !!  !!  !!  !
  !   !   !   !   !   !   !   !
!!    !!!!    !!!!    !!!!    !
!     ! !     ! !     ! !     !
      !!      !!      !!      !
      !       !       !       !
!!!!!!        !!!!!!!!        !
! ! !         ! ! ! !         !
  !!          !!  !!          !
  !           !   !           !
!!            !!!!            !
!             ! !             !
              !!              !
              !               !
!!!!!!!!!!!!!!                !
! ! ! ! ! ! !                 !
  !!  !!  !!                  !
  !   !   !                   !
!!    !!!!                    !
!     ! !                     !
      !!                      !
      !                       !
!!!!!!                        !
! ! !                         !
  !!                          !
  !                           !
!!                            !
!                             !
                              !
                              !

```

Leaving up the older 108 char, cellular automata version.

```
j,d[99][99];main(i){d[0][31]=3;for(;i<64;)d[j+1][i]=putchar(32|d[j][i+2]^d[j][i++]);++j<32&&main(puts(""));}

```

~~So I don't think I'm going to get it much shorter than this so I'll explain the code.~~ I'll leave this explanation up, as some of the tricks could be useful.

```
j,d[99][99]; // these init as 0
main(i){ //starts at 1 (argc)
  d[0][48]=3; //seed the automata (3 gives us # instead of !)
  for(;i<98;) // print a row
    d[j+1][i]=putchar(32|d[j][i+2]]^d[j][i++]);
    //relies on undefined behavoir. Works on ubuntu with gcc ix864
    //does the automata rule. 32 + (bitwise or can serve as + if you know
    //that (a|b)==(a^b)), putchar returns the char it prints
  ++j<32&&main(puts(""));
  // repeat 32 times
  // puts("") prints a newline and returns 1, which is nice
}

```

Some output

```
                             # #
                            #   #
                           # # # #
                          #       #
                         # #     # #
                        #   #   #   #
                       # # # # # # # #
                      #               #
                     # #             # #
                    #   #           #   #
                   # # # #         # # # #
                  #       #       #       #
                 # #     # #     # #     # #
                #   #   #   #   #   #   #   #
               # # # # # # # # # # # # # # # #
              #                               #
             # #                             # #
            #   #                           #   #
           # # # #                         # # # #
          #       #                       #       #
         # #     # #                     # #     # #
        #   #   #   #                   #   #   #   #
       # # # # # # # #                 # # # # # # # #
      #               #               #               #
     # #             # #             # #             # #
    #   #           #   #           #   #           #   #
   # # # #         # # # #         # # # #         # # # #
  #       #       #       #       #       #       #       #
 # #     # #     # #     # #     # #     # #     # #     # #
#   #   #   #   #   #   #   #   #   #   #   #   #   #   #   #
 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

```
> 11 votes

# Answer
# PostScript, 120 chars

```
-7 -4 moveto
14 0 rlineto
7{true upath dup
2{120 rotate uappend}repeat[2 0 0 2 7 4]concat}repeat
matrix setmatrix
stroke

```

Ghostscript output:

This is drawing the figure by recursively tripling what's already drawn.

First step is drawing a line. The line is saved as a userpath, then the userpath is added two more times after rotating 120 degrees each time. `[2 0 0 2 7 4]concat` moves the "rotation point" to the center of the next big white "center triangle" that is to be enclosed by replications of the triangle we already have. Here, we're back to step 1 (creating a upath that's tripled by rotation).

The number of iterations is controlled by the first number in line 3.
> 9 votes

# Answer
# J (9 characters)

Easily the ugliest, you really need to squint to see the output ;)

```
2|!/~i.32

```

produces the output

```
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 1
0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1
0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 1
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1

```

of course you can display it graphically:

```
load 'viewmat'
viewmat 2|!/~i.32

```
> 7 votes

# Answer
# Python (75)

I'm two years late to the party, but I'm surprised that nobody has taken this approach yet

```
from pylab import*
x=[[1,1],[1,0]]
for i in'123':x=kron(x,x)
imsave('a',x)

```

Uses the Kronecker product to replace a matrix by multiple copies of itself.

I could save two chars by using `x=kron(x,x);x=kron(x,x)` in line three to get a 16x16 pixel image with three visible levels or add another char to the iterator and end up with a 2^16 x 2^16 = 4.3 Gigapixel image and 15 triangle levels.
> 5 votes

# Answer
# APL, ~~37~~ 32 (~~28~~ 23)

### Upright triangle (~~37~~ 32-char)

```
({((-1⌷⍴⍵)⌽⍵,∊⍵)⍪⍵,⍵}⍣⎕)1 2⍴'/\'

```

**Explanation**

* `1 2⍴'/\'`: Create a 1×2 character matrix `/\`
* `{((-1⌷⍴⍵)⌽⍵,∊⍵)⍪⍵,⍵}`: A function that pad the right argument on both sides with blanks to create a matrix double as wide, then laminates the right argument itself doubled onto the bottom.
E.g. `/\` would become

```
 /\
/\/\
```
* `⍣⎕`: Recur the function (user input) times.

**Example output**

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

```

### Skewed Triangle (~~28~~ 23-char)

```
({(⍵,∊⍵)⍪⍵,⍵}⍣⎕)1 1⍴'○'

```

**Explaination**

* `1 1⍴'○'`: Create a 1×1 character matrix
* `{(⍵,∊⍵)⍪⍵,⍵}`: A function that pad the right argument on the right with blanks to create a matrix double as wide, then laminates the right argument itself doubled onto the bottom.
E.g.  would become

```
○
○○
```
* `⍣⎕`: Recur the function (user input) times.

**Example output**

```
○
○○
○ ○
○○○○
○   ○
○○  ○○
○ ○ ○ ○
○○○○○○○○
○       ○
○○      ○○
○ ○     ○ ○
○○○○    ○○○○
○   ○   ○   ○
○○  ○○  ○○  ○○
○ ○ ○ ○ ○ ○ ○ ○
○○○○○○○○○○○○○○○○

```
> 4 votes

# Answer
**matlab 56**

```
v=[1;-1;j];plot(filter(1,[1,-.5],v(randi(3,1,1e4))),'.')

```
> 4 votes

# Answer
**Logo, 75 characters**

59 characters for just the first function, the second one calls the first with the size and the depth/number of iterations. So you could just call the first function from the interpreter with the command: e 99 5, or whatever size you want to output

```
to e :s :l
if :l>0[repeat 3[e :s/2 :l-1 fd :s rt 120]]
end
to f
e 99 5
end

```
> 3 votes

# Answer
**Mathematica 63**

```
ListPlot@ReIm@NestList[#/2+RandomChoice[{0,1,-1}^(1/3)]&,0.,8!]

```

**Mathematica 67**

```
Region@Polygon@ReIm@Nest[Tr/@Tuples[{p,#}/2]&,{p={0,1,-1}^(1/3)},6]

```
> 3 votes

# Answer
# Python (90 chars)

```
from turtle import*
def l():left(60)
def r():right(60)
def f():forward(1)
def L(n):
 if n:n-=1;R(n);l();L(n);l();R(n)
 else:f()
def R(n):
 if n:n-=1;L(n);r();R(n);r();L(n)
 else:f()
l();L(8)

```

**Try it online**

Draw fractal line filling Sierpinsky Triangle
> 3 votes

# Answer
# J (18 characters)

```
' *'{~(,,.~)^:9 ,1

```

## Result

```
*
**
* *
****
*   *
**  **
* * * *
********
*       *
**      **
* *     * *
****    ****
*   *   *   *
**  **  **  **
* * * * * * * *
****************
*               *
**              **
* *             * *
****            ****
*   *           *   *
**  **          **  **
* * * *         * * * *
********        ********
*       *       *       *
**      **      **      **
* *     * *     * *     * *
****    ****    ****    ****
*   *   *   *   *   *   *   *
**  **  **  **  **  **  **  **
* * * * * * * * * * * * * * * *
********************************

```
> 3 votes

# Answer
# APL (Dyalog Classic), 12 bytes

```
×.≥∘⍉⍨↑,⍳⎕⍴2

```

Try it online!
> 3 votes

# Answer
# Asymptote, 152 bytes

I'll add this, mostly since I've seen more or less no answers in asymptote on this site. A few wasted bytes for nice formatting and generality, but I can live with that. Changing A,B and C will change where the corners of the containing triangle are, but probably not in the way you think. Increase the number in the inequality to increase the depth.

```
pair A=(0,0),B=(1,0),C=(.5,1);void f(pair p,int d){if(++d<7){p*=2;f(p+A*2,d);f(p+B*2,d);f(p+C*2,d);}else{fill(shift(p/2)*(A--B--C--cycle));}}f((0,0),0);

```

or ungolfed and readable

```
pair A=(0,0), B=(1,0), C=(.5,1);

void f(pair p, int d) {
    if (++d<7) {
        p *= 2;
        f(p+A*2,d);
        f(p+B*2,d);
        f(p+C*2,d);
    } else {
        fill(shift(p/2)*(A--B--C--cycle));
    }
}

f((0,0),0);

```

So asymptote is a neat vector graphics language with somewhat C-like syntax. Quite useful for somewhat technical diagrams. Output is of course in a vector format by default (eps, pdf, svg) but can be converted into basically everything imagemagick supports. Output:
> 3 votes

# Answer
# Mathematica, 29 bytes

```
Image@Array[BitAnd,{2,2}^9,0]

```

The Sierpinski tetrahedron can be drawn in a similar way:

```
Image3D[1-Array[BitXor,{2,2,2}^7,0]]

```
> 3 votes

# Answer
# , <sup>~~37~~</sup> 35 bytes

*-2 bytes thanks to FrownyFrog*

```
(,.~,~' '&,.^:#)@[&0' /\',:'/__\'"_

```

Try it online!

This is Peter Taylor's ascii art version converted to J. Could save bytes with a less pretty version, but why?

```
       /\
      /__\
     /\  /\
    /__\/__\
   /\      /\
  /__\    /__\
 /\  /\  /\  /\
/__\/__\/__\/__\

```
> 3 votes

# Answer
# Lua script in Golly, 54 bytes

```
g=golly()
g.setrule("W60")
g.setcell(0,0,1)
g.run(512)

```

Golly is a cellular automata simulator with Lua and Python scripting support.

This script sets the rule to Wolfram Rule 60, sets the cell at (0,0) to 1, and runs 512 steps.
> 3 votes

# Answer
# 05AB1E, 9 bytes

```
1=IGx^Db,

```

Try it online!

The number of rows is equal to the input.

# Explanation:

```
1=IGx^Db,
1=         print "1" and push 1
  IG       for N in range(1, I): (where I is the input)
    x      push last element on stack multiplied by 2
     ^     pop last two elements, push their bitwise xor (output is in decimal)
      D    duplicate last element of stack
       b,  replace last element of stack with its binary representation, then print/pop

```

This takes advantage of the fact that a(n+1) = a(n) XOR 2\*a(n), which I found on this relevant OEIS page
> 3 votes

# Answer
# 8086 Machine code - 18 bytes (unknown author) / 27 bytes (mine)

In early 1990s, I organized a small competition on programmer's board on a Croatian BBS, who can write the smallest program to draw the Sierpinski triangle.

My best solution was 27 bytes long, but there were several even smaller and unique solutions, with smallest one being only 18 bytes of machine code. Unfortunately, I forgot the name of the person who wrote it - so if the original author is reading this, please contact me. :)

---

**18 bytes solution by an unknown Croatian programmer**:

```
Bytes: B0 13 CD 10 B5 A0 8E D9 30 84 3F 01 AC 32 04 E2 F7 C3

0100 B013          MOV     AL,13
0102 CD10          INT     10
0104 B5A0          MOV     CH,A0
0106 8ED9          MOV     DS,CX
0108 30843F01      XOR     [SI+013F],AL
010C AC            LODSB
010D 3204          XOR     AL,[SI]
010F E2F7          LOOP    0108
0111 C3            RET

```

Which draws this:

---

**My 27 bytes solution**:

```
Bytes: B0 13 CD 10 B7 A0 8E C3 8E DB BF A0 00 AA B9 C0 9E BE 61 FF AC 32 04 AA E2 FA C3

0100 B013          MOV     AL,13
0102 CD10          INT     10
0104 B7A0          MOV     BH,A0
0106 8EC3          MOV     ES,BX
0108 8EDB          MOV     DS,BX
010A BFA000        MOV     DI,00A0
010D AA            STOSB
010E B9C09E        MOV     CX,9EC0
0111 BE61FF        MOV     SI,FF61
0114 AC            LODSB
0115 3204          XOR     AL,[SI]
0117 AA            STOSB
0118 E2FA          LOOP    0114
011A C3            RET

```

Which draws this:
> 3 votes

# Answer
## C, 106 chars

```
i,j;main(){for(;i<32;j>i/2?puts(""),j=!++i:0)
printf("%*s",j++?4:33-i+i%2*2,i/2&j^j?"":i%2?"/__\\":"/\\");}

```

(It still amuses me that `puts("")` is the shortest way to output a newline in C.)

Note that you can create larger (or smaller) gaskets by replacing the `32` in the `for` loop's test with a larger (smaller) power of two, as long as you also replace the `33` in the middle of the `printf()` with the power-of-two-plus-one.
> 2 votes

# Answer
**Postscript, ~~205~~ 203**

```
[48(0-1+0+1-0)49(11)43(+)45(-)/s{dup
0 eq{exch{[48{1 0 rlineto}49 1 index
43{240 rotate}45{120 rotate}>>exch
get exec}forall}{exch{load
exch 1 sub s}forall}ifelse 1 add}>>begin
9 9 moveto(0-1-1)9 s fill

```

Rewrite using strings and recursion ends up at exactly the same count. But the depth-limitations of the macro-approach are overcome.

*Edit:* `fill` is shorter than `stroke`.

Indented and commented.

```
%!
[   % begin dictionary
    48(0-1+0+1-0) % 0
    49(11)        % 1
    43(+)         % +
    45(-)         % -
    /s{ % string recursion-level
        dup 0 eq{ % level=0
            exch{  % iterate through string
                [
                    48{1 0 rlineto} % 0
                    49 1 index      % 1
                    43{240 rotate}  % +
                    45{120 rotate}  % -
                >>exch get exec % interpret turtle command
            }forall
        }{ % level>0
            exch{  % iterate through string
                load exch  % lookup charcode
                1 sub s    % recurse with level-1
            }forall
        }ifelse
        1 add  % return recursion-level+1
    }
>>begin
9 9 moveto(0-1-1)9 s fill % execute and fill

```

Adding `0 setlinewidth` gives a better impression of how deep this one goes.
> 2 votes

# Answer
# 6502 ASM, 134 bytes

```
start:
lda #$e1
sta $0
lda #$01
sta $1
ldy #$20
w_e:
ldx #$00
eor ($0, x)
sta ($0),y
inc $0
bne w_e
inc $1
ldx $1
cpx #$06
bne w_e
rts

```

Pretty simple. Displays the triangles. Note that the top and left sides of the image are invisible due to the white background of PPCG.
> 2 votes

# Answer
# Haskell, ~~166~~ 154 bytes

*(-12 bytes thanks to Laikoni, (zip and list comprehension instead of zipWith and lambda, better way of generating the first line))*

```
i#n|let k!p=p:(k+1)![m*l*r+(m*(l*r-l-r)+1)*0^mod k(2^(n-i))|(l,m,r)<-zip3(1:p)p$tail p++[1]];x=1<$[2..2^n]=mapM(putStrLn.map("M "!!))$take(2^n)$1!(x++0:x)

```

Try it online!

Explanation:

The function `i#n` draws an ASCII-Triangle of height `2^n` after `i` steps of iteration.

The encoding used internally encodes empty positions as `1` and full positions as `0`. Therefore, the first line of the triangle is encoded as `[1,1,1..0..1,1,1]` with `2^n-1` ones on both sides of the zero. To build this list, we start with the list `x=1<$[2..2^n]`, i.e. the list `[2..2^n]` with everything mapped to `1`. Then, we build the complete list as `x++0:x`

The operator `k!p` (detailed explanation below), given a line index `k` and a corresponding `p` generates an infinite list of lines that follow `p`. We invoke it with `1` and the starting line described above to get the entire triangle, and then only take the first `2^n` lines. Then, we simply print each line, replacing `1` with space and `0` with `M` (by accessing the list `"M "` at location `0` or `1`).

Operator `k!p` is defined as follows:

```
k!p=p:(k+1)![m*l*r+(m*(l*r-l-r)+1)*0^mod k(2^(n-i))|(l,m,r)<-zip3(1:p)p$tail p++[1]]

```

First, we generate three versions of `p`: `1:p` which is `p` with a `1` prepended, `p` itself and `tail p++[1]` which is everything but the first element of `p`, with a `1` appended. We then zip these three lists, giving us effectively all elements of `p` with their left and right neighbors, as `(l,m,r)`. We use a list comprehension to then calculate the corresponding value in the new line:

```
m*l*r+(m*(l*r-l-r)+1)*0^mod k(2^(n-i))

```

To understand this expression, we need to realise there are two basic cases to consider: Either we simply expand the previous line, or we are at a point where an empty spot in the triangle begins. In the first case, we have a filled spot if any of the spots in the neighborhood is filled. This can be calculated as `m*l*r`; if any of these three is zero, then the new value is zero. The other case is a bit trickier. Here, we basically need edge detection. The following table gives the eight possible neighborhoods with the resulting value in the new line:

```
000 001 010 011 100 101 110 111
 1   1   1   0   1   1   0   1

```

A straightforward formula to yield this table would be `1-m*r*(1-l)-m*l*(1-r)` which simplifies to `m*(2*l*r-l-r)+1`. Now we need to choose between these two cases, which is where we use the line number `k`. If `mod k (2^(n-i)) == 0`, we have to use the second case, otherwise, we use the first case. The term `0^(mod k(2^n-i))` therefore is `0` if we have to use the first case and `1` if we have to use the second case. As a result, we can use

```
m*l*r+(m*(l*r-l-r)+1)*0^mod k(2^(n-i))

```

in total - if we use the first case, we simply get `m*l*r`, while in the second case, an additional term is added, giving the grand total of `m*(2*l*r-l-r)+1`.
> 2 votes

# Answer
## Python (~~215~~ 209)

Uses the Chaos Theory method of generating Sierpinski's Triangle.

```
import random as r,pygame as p
d=p.display
x=99;X=49;y=x,x
s=d.set_mode(y)
c=[X,X]
P=(X,0),(0,x),y
while 1:
 a=r.choice(P)
 for i in 0,1:c[i]=(c[i]+a[i])/2
 p.draw.rect(s,[x]*3,p.Rect(c[0],c[1],2,2))
 d.flip()

```
> 1 votes

# Answer
## JavaScript (70 chars):

```
for(y=32;y--;){for(s="",x=32;x--;)s+=(x-y/2)&y?" ":"o";console.log(s)}

```

Using HTML guy's method. This feels like cheating, though. He gets the thread.

```
               oo
               oo
              o oo
              oooo
             o   oo
             oo  oo
            o o o oo
            oooooooo
           o       oo
           oo      oo
          o o     o oo
          oooo    oooo
         o   o   o   oo
         oo  oo  oo  oo
        o o o o o o o oo
        oooooooooooooooo
       o               oo
       oo              oo
      o o             o oo
      oooo            oooo
     o   o           o   oo
     oo  oo          oo  oo
    o o o o         o o o oo
    oooooooo        oooooooo
   o       o       o       oo
   oo      oo      oo      oo
  o o     o o     o o     o oo
  oooo    oooo    oooo    oooo
 o   o   o   o   o   o   o   oo
 oo  oo  oo  oo  oo  oo  oo  oo
o o o o o o o o o o o o o o o oo
oooooooooooooooooooooooooooooooo

```
> 1 votes

# Answer
# Common Lisp, 80 chars

```
(#1=dotimes(i 32)(#1#(j 32)(princ(if(logtest(- j(ash i -1))i)' 'Δ)))(terpri))

```

Output:

```
ΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔ
Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ Δ
 ΔΔ  ΔΔ  ΔΔ  ΔΔ  ΔΔ  ΔΔ  ΔΔ  ΔΔ
 Δ   Δ   Δ   Δ   Δ   Δ   Δ   Δ
  ΔΔΔΔ    ΔΔΔΔ    ΔΔΔΔ    ΔΔΔΔ
  Δ Δ     Δ Δ     Δ Δ     Δ Δ
   ΔΔ      ΔΔ      ΔΔ      ΔΔ
   Δ       Δ       Δ       Δ
    ΔΔΔΔΔΔΔΔ        ΔΔΔΔΔΔΔΔ
    Δ Δ Δ Δ         Δ Δ Δ Δ
     ΔΔ  ΔΔ          ΔΔ  ΔΔ
     Δ   Δ           Δ   Δ
      ΔΔΔΔ            ΔΔΔΔ
      Δ Δ             Δ Δ
       ΔΔ              ΔΔ
       Δ               Δ
        ΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔΔ
        Δ Δ Δ Δ Δ Δ Δ Δ
         ΔΔ  ΔΔ  ΔΔ  ΔΔ
         Δ   Δ   Δ   Δ
          ΔΔΔΔ    ΔΔΔΔ
          Δ Δ     Δ Δ
           ΔΔ      ΔΔ
           Δ       Δ
            ΔΔΔΔΔΔΔΔ
            Δ Δ Δ Δ
             ΔΔ  ΔΔ
             Δ   Δ
              ΔΔΔΔ
              Δ Δ
               ΔΔ
               Δ

```
> 1 votes

# Answer
# JavaFx, 400 bytes

```
import javafx.scene.*;import javafx.scene.canvas.*;public class S extends javafx.application.Application{public void start(javafx.stage.Stage s){Canvas v=new Canvas(640,640);int[]xs={320,0,640},ys={0,640,640};for(int i=0,x=0,y=0,n=0;i<999999;i++){n=new java.util.Random().nextInt(3);v.getGraphicsContext2D().fillRect(x+=(xs[n]-x)/2,y+=(ys[n]-y)/2,1,1);}s.setScene(new Scene(new Group(v)));s.show();}}

```

Operates via the move-halfway-to-a-random-vertex method. 999,999 iterations, 640x640 canvas. I could have golfed a few more bytes by reducing the size or the number of iterations, but when you're at 400 bytes what's the point? No one wants to look at postage stamp-sized output.

Ungolfed, mostly:

```
import javafx.scene.*;
import javafx.scene.canvas.*;

public class S extends javafx.application.Application {
    public void start(javafx.stage.Stage s) {
        Canvas v = new Canvas(640, 640);
        int[] xs = {320,0,640}, ys = {0,640,640};
        for (int i=0, x=0, y=0, n=0; i < 999999; i++) {
            n = new java.util.Random().nextInt(3);
            v.getGraphicsContext2D().fillRect(
                x += (xs[n]-x)/2, y += (ys[n]-y)/2, 1, 1);
        }
        s.setScene(new Scene(new Group(v)));
        s.show();
    }
}

```

JavaFx has a very annoying way of putting every class you might want to use in separate javafx.application, javafx.stage, javafx.scene, javafx.canvas packages. Grr!
> 1 votes

# Answer
# Pyt, 19 bytes

```
02⁵ř↔Á`⁻Đ0⇹Řć2%ǰƥłŕ

```

# Result:

```
1
11
101
1111
10001
110011
1010101
11111111
100000001
1100000011
10100000101
111100001111
1000100010001
11001100110011
101010101010101
1111111111111111
10000000000000001
110000000000000011
1010000000000000101
11110000000000001111
100010000000000010001
1100110000000000110011
10101010000000001010101
111111110000000011111111
1000000010000000100000001
11000000110000001100000011
101000001010000010100000101
1111000011110000111100001111
10001000100010001000100010001
110011001100110011001100110011
1010101010101010101010101010101
11111111111111111111111111111111

```

# Explanation:

```
0                        Push 0
 2⁵                      Push 32
   ř↔                    Pop 32, and push [32,31,30,29,...,3,2,1]
     Á                   Push contents of array onto stack
      `          ł       While the top of the stack is not zero, loop:
       ⁻                 Decrement the number at the top of the stack
        Đ0⇹Řć2%ǰƥ        Calculate the kth row of Pascal's Triangle mod 2 and print
                  ŕ      Remove the 0

```

Try it online!
> 1 votes

# Answer
# asm2bf, 219 bytes

## Code

```
@a
clrr2
@b
pshr1
movr4,r2
@c
movr5,r1
modr5,2
movr6,r4
modr6,2
mulr5,r6
cger5,1
cmor5,1
cjn%d
asrr1
asrr4
jnzr1,%c
jnzr4,%c
clrr3
@d
cger3,1
movr3,42
cmor3,32
outr3
popr1
incr2
cger2,64
cjz%b
out10
incr1
cger1,64
cjz%a

```

## The output
> 1 votes

# Answer
# Applesoft BASIC, 246 bytes

```
1 HGR:HCOLOR=3:HOME:DIM x(3),y(3):x(0)=0:y(0)=160:x(1)=90:y(1)=0:x(2)=180:y(2)=160:FOR i=0 to 2:HPLOT x(i),y(i):NEXT i
2 x=int(RND(1)*180):y=int(RND(1)*150):HPLOT x,y:FOR i=1 to 2000:v=int(rnd(1)*3):x=(x+x(v))/2:y=(y+y(v))/2:HPLOT x,y:NEXT:GOTO 2

```

Not the most efficient, nor does it draw a perfect Sierpinski, but it's fun. May stick pixels in random places or miss a few points depending on your system's pRNG quality.

Ungolfed:

```
100 HGR : HCOLOR=3 : HOME
110 REM set up three points to form a triangle
120 DIM x(3), y(3)
130 x(0) = 0 : y(0) = 160
140 x(1) = 90 : y(1) = 0
150 x(2) = 180 : y(2) = 160
160 REM plot the vertices of the triangle
170 FOR i= 0 to 2
180 HPLOT x(i), y(i)
190 NEXT i
200 REM pick a random starting point
210 x = int(RND(1)*180) : y = int(RND(1)*150)
220 hplot x,y
230 FOR i = 1 to 2000
240 REM randomly pick one of the triangle vertices
250 v = int(rnd(1)*3)
260 REM move the point half way to the triangle vertex
270 x = (x + x(v)) / 2 : y = (y + y(v)) / 2
280 HPLOT x,y
290 NEXT

```
> 0 votes

# Answer
# Bash (94 chars)

Copyed from the html guy of this thread

```
for((y=64;y--;));do s="";for((x=64;x--;));do(((x-y/2)&y))&&s+=" "||s+="Δ";done;echo "$s";done

```
> 0 votes

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


title: Tips for golfing in Kotlin

text:
# Question
Title: Tips for golfing in Kotlin
Given Google's recent announcement of official Kotlin support for Android development, I thought it might be timely to poll the community for some awesome golfing tips for this relatively new JVM language.

Kotlin includes a unique combination of features among it's JVM siblings which makes it potentially attractive for golfing:

So, how do I squeeze the last few bytes out of my Kotlin program? One tip per answer, please.

# Answer
> 7 votes
# Use `+` instead of `toString`

As one might expect, `String` overloads the `+` operator for string concatenation, like so.

```
print("Hel" + "lo")

```

However, checking the docs tells us that it accepts `Any?`, not just `String`. As stated:

> Returns a string obtained by concatenating this string with the string representation of the given other object.

In other words, `String + anything` makes sure to call `.toString()` on the right hand side before concatenating. This allows us to shorten `it.toString()` to `""+it`, a massive 8 byte savings at best and 6 bytes at worst.

---

# Use `fold` instead of `joinToString`

Related to the above, if you're calling `map` and then `joinToString`, you can shorten that by using `fold` instead.

```
list.map{it.repeat(3)}.joinToString("")
list.fold(""){a,v->a+v.repeat(3)}

```

# Answer
> 6 votes
Starting from 1.3 you can omit args in fun main() completely, thus shaving off 18 chars (that is, the length of `args:Array<String>`).

# Answer
> 5 votes
# Submitting Lambdas: A Guide

According to meta consensus the default for most challenges allows submitting lambdas/anonymous function bodies. Part of this consensus is that the declaration/assignment of the lambda doesn't have to be included. Take the typical lambda:

```
val f={a:Int,b:Int->a+b}

```

We can omit the declaration, that being `val f=` which saves us 6 bytes.

```
val f=              // declaration
{a:Int,b:Int->a+b}  // lambda

```

For the rest of this tip I will write the declaration on one line and the lambda body on the next line to make it clear that it is separate. Know that the declaration line won't count to the score; on TIO you'd include it in the Header and put the lambda as the Code (see here.)

## Type Inference and You

Kotlin has a fairly robust system of *type inference*. If the compiler can infer the type of something, you can omit the type information. Lambdas themselves are typed; their type signatures are expressed as:

```
(Param1Type, ...ParamNType) -> ReturnType

```

Therefore, the type of the above is `(Int, Int) -> Int`.

The type information of a lambda can be inferred from two places:

* The lambda body
* The declaration/use site (when assigned to a variable with a type annotation, or passed to a function)

In the given example above, the types of the parameters are stated *in* the lambda body, and the return type of the lambda can be inferred by the expression in the body because the types of everything is known. This is why the type of the lambda doesn't have to be stated in the declaration; the compiler knows its complete type signature!

...but what if we did?

## A Parlor Trick

```
val f:(Int,Int)->Int=
{a,b->a+b}

```

By moving the type information of the lambda into the declaration, it's removed from our actual answer. Thanks to inference, the types of `a` and `b` are known, and the return type is known, so this compiles, and it's free bytes!

## Inferred `it` Parameter for Single-Param Lambdas

If a lambda only takes one parameter and its type can be completely inferred, you don't even have to specify a parameter in the lambda body! The inferred parameter will be named `it`. Take the two examples:

```
val shuf:(List<T>)->List<T>=
{l->l.shuffled()}
                              // -2
val shuf:(List<T>)->List<T>=
{it.shuffled()}

```

The compiler knows that this lambda takes one parameter and it knows what type it is, so if it isn't bound to a name in the lambda body, it is named `it` instead. You can use this to save 2 bytes in the degenerate case above, but if you have to refer to the parameter many times, it will be shorter to simply give it a name as in the former.

```
{it*it*it*it}
{n->n*n*n*n}

```

## Lambdas With Receiver

Kotlin allows you to specify a *receiver* parameter for a lambda. Basically, you can rebind `this` inside. You indicate this lambda takes a receiver by writing the receiver type and a dot before the type signature:

```
Recv.(Param1, ...ParamN) -> Ret

```

Where this is useful is highly dependent on your approach.

```
val f:(Int,Int)->Int=
{a,b->a+b}
                       // -1
val f:Int.(Int)->Int=
{this+it}

```

Of course, what's most useful is that `this` is the implicit receiver of member access. So if your submission consists mostly of a call chain on one of the parameters, or you refer to a field a couple times, this is extremely useful.

```
val shuf:(List<T>)->List<T>=
{l->l.shuffled()}
                               // -5
val shuf:List<T>.()->List<T>=
{shuffled()}

```

It can be a bad call to use `this` instead of `it` e.g.

* If there's only one parameter to the lambda and you don't need to call any methods on it
* You need to destructure the parameter
* etc.

## Some Examples

Examples can help you learn!

# Answer
> 3 votes
# Extension Functions

Extension functions can really help to reduce the names of built in methods, and chains of them, an example could be:

`fun String.c() = this.split("").groupingBy{it}.eachCount()`

but this only helps if:

A) The call is long enough to cancel out the definition

B) The call is repeated

# Use of lambdas rather than methods

Lambdas can return without using the return keyword, saving bytes

# KotlinGolfer

A project I have started here which takes pretty Kotlin code and gives posts with tests and TIO links automatically

# Answer
> 3 votes
# Defining Int's in params

This will likely have some pretty specific use cases where it may be worth it, but in recent question I golfed I found I could save a few bytes by defining my variable as optional parameters rather than defining them in the function.

Example from my answer to this question:

defining variable in the function:

`fun String.j()={var b=count{'-'==it}/2;var a=count{'/'==it};listOf(count{'o'==it}-a,a-b,b)}`

defining variables as params:

`fun String.j(b:Int=count{'-'==it}/2,a:Int=count{'/'==it})=listOf(count{'o'==it}-a,a-b,b)`

because `var a=` is the same length as `a:Int=` it will be the same number of bytes to define them (this is only the case for `Int`) however since I now only have 1 line in the function I can drop the `{}` and I also drop a single `;` (the other is replaced with a `,`)

So if there are any functions that require defining an Int, and would be a 1 liner if you didn't define the int in the function - then doing it as a parameter will save a couple bytes

# Answer
> 3 votes
# You don't need to add a `;` after the imports if the last element is `*`

for instance, you can do this

```
import java.util.*import kotlin.random.*import kotlin.random.Random

```

even this

```
import java.util.*import kotlin.random.*fun main(){}

```

# Answer
> 2 votes
# The `to` infix function

There is a standard infix function named `to` that creates `Pair`s of two values. It's commonly used with `mapOf()` for defining `Map`s but it's can potentially be a lot shorter than the `Pair()` constructor.

```
Pair(foo,bar)   //constructor
foo to bar      //best case
(foo)to(bar)
((foo)to(bar))  //worst case

```

# Answer
> 2 votes
# Destructuring in lambda arguments

Say you want to accept a `Pair<*,*>` in a lambda. Normally, handling this would be annoying. As an example, here's a lambda that takes a `Pair` and checks if the two values are equal:

```
{it.first==it.second}

```

This is long-winded and clumsy. Luckily, Kotlin allows you to destructure any destructable type (any type that implements `componentN()` methods, such as `Pair`, `Triple` etc.) as arguments to a lambda. So, we can rewrite this in the following way:

```
{(a,b)->a==b}

```

It looks similar to pattern matching a tuple in something like F#, and it is in many cases. But a wide variety of types in Kotlin support destructuring (`MatchResult` is a useful one.)

You can take more arguments, though. Say your lambda had to take a `Pair` and an additional value. You'd simply write the lambda signature like this:

```
(a,b),c->  // pair first
a,(b,c)->  // pair second

```

# Answer
> 2 votes
# you can assign the functions (most important case is the main however) an unit type function

for instance instead of doing `fun main(){println("hello world")}`

you can do

`fun main()=println("hello world")`

which shaves off a mere byte

# Answer
> 2 votes
# The `repeat` function sometimes can shave off a few bytes in some cases

the repeat function basically translates to this,

for `repeat(100){something(it)}`

it becomes `for(it in 0..100-1){something(it)}`

the main problem of this is that the it starts from 0 as always and goes until times-1 which might not be ideal for some cases. I'd suggest, for any for loops, converting for loops to repeat loops and checking the byte count, like you might convert it then name the variable i instead of it etc. This will most certainly save you bytes if you use the variable "it" frequent enough.

# Answer
> 0 votes
# Get STDIN

If you want to read a line, you can do `readln()` instead of `readLine()!!`

---
Tags: code-golf, tips
---


# Question
Title: All permutations of range from \$1\$ to \$n\$
Given a positive input \\$n\\$, output all permutations of either \\$\\{0,1,\ldots,n-1\\}\\$ or \\$\\{1,2,\ldots,n\\}\\$.

## Examples

Outputting permutations of \\$\\{1,2,\ldots,n\\}\\$.

| Input | Output |
| --- | --- |
| `1` | `[(1)]` |
| `2` | `[(1, 2), (2, 1)]` |
| `4` | `[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]` |

Standard loopholes are forbidden. The shortest code wins.

# Answer
# Jelly, 2 bytes

```
Œ!

```

Try it online!

Boring builtin answer

---

# Jelly, 4 bytes

```
!Rœ?

```

Try it online!

Slightly less boring mostly-builtin answer

## How it works

```
!Rœ? - Main link. Takes n on the left
!    - Yield n!
 R   - Range; [1, 2, ..., n!]
  œ? - For each 1 ≤ i ≤ n!, get the ith permutation of [1, 2, ..., n]

```
> 3 votes

# Answer
# Python, 54 bytes

Outputs all permutations of \\$\\{0,1,\ldots,n-1\\}\\$.

```
lambda n:permutations(range(n))
from itertools import*

```

Attempt This Online!
> 2 votes

# Answer
## Print out -- Python 3, 58 bytes (@dingledooper)

```
def f(n,*r):[f(n,*r,x)for x in{*range(n)}-{*r}]or print(r)

```

Try it online!

## Return list -- Python, 62 bytes

```
f=lambda n,*p:sum((f(n,*p,i)for i in{*range(n)}-{*p}),[])or[p]
```

Attempt This Online!

Ignoring the standard lib's itertools.permutations.
> 2 votes

---
Tags: code-golf, permutations
---


# Question
Title: Change the quotations as if in Microsoft Word
I noticed that in Microsoft Word, single quotations are either  or , but not in Notepad. Your task today is: given a string `q`, convert all the `'` characters (only) to  or , according to these rules, and then output it:

* If the character before the quote is a space, and after it comes a character, it becomes
* If the character before the quote is a letter, and after it is a space, it becomes
* If the character before and after the quote is a letter, it becomes
* If the character before and after the quote is a space, it becomes
* If the quote comes at the beginning it will be , if it comes at the end it becomes
* If consecutive quotes come one after another, the first 2 become `‘’` and remaining ones become

## Test Cases

```
'Hello'= ‘Hello’ (rules 1 and 2)
'=‘              (rule 5)
H'h=H’h          (rule 3)
 ' = ‘           (rule 4)
'' = ‘’          (rule 6)
a'''b=a‘’’b      (overriding by rule 6)

```

I'm keeping it this because although it is confusing, it is what the output should be, so if I had to make it more clearer, it will come at the expense of understanding it.

You can assume `q` contains only upper and lowercase letters, spaces, and quotation marks.

This is , so shortest answer wins!

**EDIT**: Although in MS Word rule 6 does **not** override all the other rules, since answers have already been posted that assume this case, I will keep it this way

# Answer
# Retina 0.8.2, 28 bytes

```
(?<=^| )'|\b'(?=')
‘
'
’

```

Try it online! Link includes test cases. Explanation:

```
(?<=^| )'|\b'(?=')
‘

```

Quotes become "smart open" quotes at the beginning of the string (by rule 5), after a space (by rules 1, 4 and 6), or after a letter and before a quote (by rule 6).

```
'
’

```

All other quotes become "smart close" quotes.

I tried coding the reverse logic by handling "smart close" quotes first but the best I could do was 29 bytes:

```
(?<=')'|\b'(?!')|'$
’
'
‘

```

Try it online! Link includes test cases. Explanation: Quotes become "smart close" quotes after quotes (by rule 6), after a letter but not before a quote (by rules 2 and 3), or at the end (by rule 5).
> 1 votes

# Answer
# Retina, 42 bytes

```
'('+)
‘$.1*’
(^| )'
$1‘
'($|\w)
’$1

```

Assumes rule 6 takes prio over the other rules.

I have the feeling the first step can be shorter (perhaps with a `+^` loop), but couldn't really find anything yet..

Try it online or try it online with `<`/`>` instead of / so it's a bit more distinguishable).

**Explanation:**

Replace any sequence of two or more quotes with one opening quote and the rest closing quotes:

```
'('+)
‘$.1*’

```

Replace a quote at the start of the string, or a quote with a space before it, with the opening quote:

```
(^| )'
$1‘

```

Replace a quote at the end of the string, or a quote with a after it, with the closing quote:

```
'($|\w)
’$1

```
> 2 votes

# Answer
# sed, 109 bytes

```
:z;s/'''/''’/g;t z;
s/''/‘’/g
s/ '(.)/ ‘\1/g
s/([a-zA-Z])'([a-zA-Z ])/\1’\2/g
s/^'/‘/g
s/'$/’/g

```

Try it online!
> 0 votes

# Answer
# C (clang), 75 bytes

```
x,o;f(*s){for(x=o=0;*s=*s-39?s[x=0]:8216+x|o&!s[x=1]|o>64&s[1]>64;o=*s++);}

```

Try it online!
> 0 votes

# Answer
# brev, 70 bytes

```
(strse x "'""’""’(’+)"(conc "‘" (m 1))" ’"" ‘""^’""‘")

```

Not sure how many bytes this is because Unicode but Steffan kindly counted them and here's the algo:

1. Replace all ' with ’.
2. Do "rule six" specially
3. Replace `^’` and  with opens
> 0 votes

# Answer
# Sed

Here's a shorter version of matteo\_c's answer:

```
:z;s/'''/''’/g;t z;
s/''/‘’/g
s/'/’/g
s/^’/‘/g
s/ ’/ ‘/g

```
> 0 votes

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


title: AlTeRnAtE tHe CaSe

text:
# Question
Title: AlTeRnAtE tHe CaSe
For today's challenge, you must write a program or function that alternates the case of a string. However, you must ignore non-alphabetic characters. This means that every alphabetic character must have a different case than the preceding *and* following alphabetic character. This is slightly more complex than uppercasing every other letter for example. If you take a string such as

```
hello world

```

and convert every other character to uppercase, you'll get:

```
hElLo wOrLd

```

As you can see, the lowercase `o` is followed by a lowercase `w`. This is invalid. Instead, you must ignore the space, giving us this result:

```
hElLo WoRlD

```

All non-alphabetic characters must be left the same. The output can start with upper or lowercase, as long as it consistently alternates. This means the following would also be an acceptable output:

```
HeLlO wOrLd

```

Your program should work regardless of the case of the input.

The input string will only ever contain printable ASCII, so you don't have to worry about unprintable characters, newlines or unicode. Your submission can be either a full program or a function, and you may take the input and output in any reasonable format. For example, function arguments/return value, STDIN/STDOUT, reading/writing a file, etc.

## Examples:

```
ASCII                                   ->  AsCiI
42                                      ->  42
#include <iostream>                     ->  #InClUdE <iOsTrEaM>
LEAVE_my_symbols#!#&^%_ALONE!!!         ->  lEaVe_My_SyMbOlS#!#&^%_aLoNe!!!
PPCG Rocks!!! For realz.                ->  PpCg RoCkS!!! fOr ReAlZ.
This example will start with lowercase  ->  tHiS eXaMpLe WiLl StArT wItH lOwErCaSe
This example will start with uppercase  ->  ThIs ExAmPlE wIlL sTaRt WiTh UpPeRcAsE
A1B2                                    ->  A1b2

```

Since this is , standard loopholes apply and the shortest answer in bytes wins!

# Answer
> 22 votes
## JavaScript (ES6), ~~66~~ 63 bytes

Starts with uppercase.

```
s=>s.replace(/[a-z]/gi,c=>c[`to${(s=!s)?'Low':'Upp'}erCase`]())

```

### Test cases

```
let f =

s=>s.replace(/[a-z]/gi,c=>c[`to${(s=!s)?'Low':'Upp'}erCase`]())

console.log(f("ASCII"))
console.log(f("42"))
console.log(f("#include <iostream>"))
console.log(f("LEAVE_my_symbols#!#&^%_ALONE!!!"))
console.log(f("PPCG Rocks!!! For realz."))
console.log(f("This example will start with lowercase"))
console.log(f("This example will start with uppercase"))
console.log(f("A1B2"))
```

# Answer
> 13 votes
# 05AB1E, ~~11~~ 8 bytes

### Code:

```
lvyJ¤aiš

```

Uses the **05AB1E** encoding. Try it online!

### Explanation:

```
l           # Lowercase the input
 vy         # For each element..
   J        #   Join the entire stack into a single string
    ¤a      #   Check if the last character is alphabetic
      iš    #   If true, swapcase the entire string

```

# Answer
> 12 votes
# GNU Sed, 33

* 5 bytes saved thanks to @TobySpeight

Score includes +1 for `-r` flag to sed.

```
s/([a-z])([^a-z]*.?)/\U\1\L\2/gi

```

Try it online.

# Answer
> 8 votes
# Jelly, 13 bytes

```
nŒsTm2
ŒlŒuÇ¦

```

Try it online!

### How it works

```
ŒlŒsÇ¦  Main link. Argument: s (string)

Œl      Cast to lowercase.
    Ç¦  At indices returned by the helper link...
  Œu        apply uppercase.

nŒsTm2      Helper link. Argument: s (string)

 Œs         Apply swapcase to s.
n           Perform vectorizing not-equal comparison.
   T        Compute the truthy indices.
    m2      Select every other one, starting with the first.

```

# Answer
> 7 votes
# Python 3, ~~86~~ ~~76~~ ~~68~~ ~~66~~ 63 bytes

-2 bytes thanks to DJMcMayhem
-3 bytes thanks to Cyoce

```
x=0
for i in input():print(end=(2*i).title()[x]);x^=i.isalpha()

```

Try it online! or Try all test cases

# Answer
> 7 votes
# Japt, ~~16~~ 14 bytes

```
r"%l"_m"uv"gT°

```

Try it online!

### Explanation

```
r              // RegEx replace input
 "%l"          // [A-Za-z] as first arg to replace
     _         // created function Z=>Z as second arg to replace
       "uv"gT° // alternates "u" & "v"
      m        // map Z to either "u" upper or "v" lower

```

# Answer
> 5 votes
# C (tcc), ~~60~~ ~~57~~ 56 bytes

Thanks to DigitalTrauma for noticing bit 5 is the only difference for ASCII upper/lower case.

Special thanks to zch for golfing off three more bytes.

Save one more byte from RJHunter's idea

```
l;f(char*s){for(;*s=isalpha(*s)?*s&95|++l%2<<5:*s;s++);}

```

Try it online!

# Answer
> 5 votes
# Ruby, ~~57~~ ~~55~~ ~~47~~ 41 bytes

Byte count includes two bytes for command line options.
Run it for example like this: `$ ruby -p0 alternate_case.rb <<< "some input"`

```
gsub(/\p{L}/){($&.ord&95|32*$.^=1).chr}

```

With the `p0` option, the entire input is consumed in one go, and the magical global `$.` is incremented to 1. This is later toggled between 0 and 1 and used for keeping the state.

Works with multiline input; Try it online!

Thanks to Ventero for amazing input -- check the comments for details.

# Answer
> 5 votes
# Alice, 18 bytes

```
/olZlYuN
@iy.u..//

```

Try it online!

### Explanation

This program follows a lesser-known template for odd-length programs that run entirely in ordinal mode. The linearized version of this code is:

```
il.l.uN.YuZyo@

```

Explanation of code:

```
i - push input onto stack            ["Hello world!"]
l - convert to lowercase             ["hello world!"]
. - duplicate                        ["hello world!", "hello world!"]
l - convert to lowercase (should be no-op, but avoids what seems to be a bug in the TIO implementation)
. - duplicate again                  ["hello world!", "hello world!", "hello world!"]
u - convert to uppercase             ["hello world!", "hello world!", "HELLO WORLD!"]
N - difference between sets          ["hello world!", "helloworld"]
. - duplicate reduced string         ["hello world!", "helloworld", "helloworld"]
Y - unzip (extract even positions)   ["hello world!", "helloworld", "hlool", "elwrd"]
u - convert to uppercase             ["hello world!", "helloworld", "hlool", "ELWRD"]
Z - zip evens back into string       ["hello world!", "helloworld", "hElLoWoRlD"]
y - perform substitution             ["hElLo WoRlD!"]
o - output                           []
@ - terminate

```

Without using `l` on the duplicate, the stack after `N` would be `["helloworld", "helloworld"]`. I strongly suspect this is a bug.

# Answer
> 4 votes
# MATL, ~~16~~ 15 bytes

```
Xktkyy-f2L))5M(

```

Try it online! Or verify all test cases.

### Explanation

Consider input 'hello world'

```
Xk    % To upper case
      % STACK: 'HELLO WORLD'
t     % Duplicate top element
      % STACK: 'HELLO WORLD', 'HELLO WORLD'
k     % To lower case
      % STACK: 'HELLO WORLD', 'hello word'
yy    % Duplicate top two elements
      % STACK: 'HELLO WORLD', 'hello word', 'HELLO WORLD', 'hello word'
-     % Difference (of code points; element-wise)
      % STACK: 'HELLO WORLD', 'hello word', [-32 -32 -32 -32 -32 0 -32 -32 -32 -32 -32]
f     % Indices of nonzeros
      % STACK: 'HELLO WORLD', 'hello word', [1 2 3 4 5 7 8 9 10 11]
2L)   % Keep only even-indexed values (*)
      % STACK: 'HELLO WORLD', 'hello word', [2 4 7 9 11]
)     % Reference indexing (get values at indices)
      % STACK: 'HELLO WORLD', 'elwrd'
5M    % Push (*) again
      % STACK: 'HELLO WORLD', 'elwrd', [2 4 7 9 11]
(     % Assignment indexing (write values at indices). Implicit display
      % STACK: 'HeLlO wOrLd

```

'

# Answer
> 4 votes
# Java 8, 99 bytes

```
a->{String r="";int i=0;for(int c:a)r+=(char)(c>64&c<91|c>96&c<123?i++%2<1?c|32:c&~32:c);return r;}

```

**Explanation:**

Try it here.

```
a->{                          // Lambda with char-array parameter and String return-type
  String r="";                //  Result-String
  int i=0;                    //  Flag for alteration
  for(int c:a)                //  Loop over the characters of the input
    r+=(char)                 //   And append the result-String with the following (converted to char):
      (c>64&c<91|c>96&c<123?  //    If it's a letter:
       i++%2<1?               //     And the flag states it should be lowercase:
        (c|32)                //      Convert it to lowercase
       :                      //     Else (should be uppercase):
        (c&~32)               //      Convert it to uppercase
      :                       //    Else:
       c);                    //     Simply append the non-letter character as is
                              //  End of loop (implicit / single-line body)
  return r;                   //  Return result-String
}                             // End of method

```

# Answer
> 3 votes
# Brachylog, 25 bytes

```
{ḷ|ụ}ᵐ.{ḷ∈Ạ&}ˢ¬{s₂{∈Ạ}ᵐ}∧

```

Try it online!

This is both long and slow.

### Explanation

```
{   }ᵐ.                       The Output is the result of mapping on each char of the Input:
 ḷ                              Lowecase the char
  |                             Or
   ụ                            Uppercase the char
       {    }ˢ                In the Ouput, select the chars that:
        ḷ∈Ạ&                    when lowercased are in "abc...xyz" (ie are letters)
              ¬{       }∧     In that new string, it is impossible to find:
                s₂              a substring of 2 consecutive chars
                  {∈Ạ}ᵐ         where both of them are in the lowercase alphabet

```

# Answer
> 3 votes
# Pyth, 11 bytes

```
srR~xZ}dGrZ

```

Try it here

### Explanation

```
              # Z = 0; Q = eval(input())
srR~xZ}dGrZQ  # Auto-fill variables
         rZQ  # lowercase the input
 rR           # Apply the r function to each letter of the input with
   ~xZ}dG     # ... this as the other argument
   ~          # use the old value of the variable Z, then update it with the value of ...
    xZ        # Z xor ...
      }dG     # the variable d is a lowercase letter
              # because of how mapping works in pyth, d will contain the current letter
              # This causes Z to flip between 0 and 1, alternately upper and lower casing
              # the current character if it is a letter

```

# Answer
> 3 votes
# Perl 6,  ~~32~~  30 bytes

```
{S:g/<:L><-:L>*<:L>?/$/.tclc()/}

```

Try it

```
{S:g{<:L><-:L>*<:L>?}=$/.tclc}

```

Try it

## Expanded:

```
{  # bare block lambda with implicit parameter ｢$_｣

  S            # string replace (not in-place) implicitly against ｢$_｣

  :global

  {

    <+ :L >    # a letter
    <- :L >*   # any number of non-letters
    <+ :L >?   # an optional letter

  }

  =

  $/.tclc()    # uppercase the first letter, lowercase everything else
}

```

# Answer
> 3 votes
# q/kdb+, ~~51~~ ~~42~~ 38 bytes

**Solution:**

```
{@[x;;upper]1#'2 cut(&)x in .Q.a}lower

```

**Example:**

```
q){@[x;;upper]1#'2 cut(&)x in .Q.a}lower"hello world"
"HeLlO wOrLd"

```

**Notes:**

```
.Q.a        // abcde...xyz lowercase alphabet
(&) x in    // where, returns indices for where x (hello world) is an alpha
2 cut       // splits list into 2-item lists
1#'         // takes first item of each 2-item list; ie the indices to uppercase
@[x;;upper] // apply (@) upper to x at these indices

```

# Answer
> 3 votes
# Google Sheets, 264 bytes

```
=ArrayFormula(JOIN("",IF(REGEXMATCH(MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1),"[A-Za-z]"),CHAR(CODE(UPPER(MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1)))+MOD(LEN(REGEXREPLACE(LEFT(A1,ROW(OFFSET(A1,0,0,LEN(A1)))),"[^A-Za-z]","")),2)*32),MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1))))

```

It's a big mess but it's a little easier if you expand it out:

```
=ArrayFormula(
  JOIN(
    "",
    IF(REGEXMATCH(MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1),"[A-Za-z]"),
      CHAR(
        CODE(UPPER(MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1)))
        +
        MOD(LEN(REGEXREPLACE(LEFT(A1,ROW(OFFSET(A1,0,0,LEN(A1)))),"[^A-Za-z]","")),2)*32
      ),
      MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1)
    )
  )
)

```

The pseudo-logic would run like this:

```
For each character {                                    // ArrayFormula()
  If (character is a letter) {                          // REGEXMATCH(MID())
    Return CHAR(                                        // CHAR()
      CODE(UPPER(letter))                               // CODE(UPPER(MID()))
      +
      If (nth letter found and n is odd) {32} else {0}  // MOD(LEN(REGEXREPLACE(LEFT())))
    )
  } else {
    Return character                                    // MID()
  }
}

```

# Answer
> 2 votes
# , ~~17~~, 13 bytes

```
VUÍáƒ¨áü$©/ì&

```

Try it online!

Or Verify all test cases!

HeXdUmP:

```
00000000: 5655 cde1 83a8 e1fc 24a9 2fec 26         VU......$./.&

```

Explanation:

This uses a *compressed regex*™, so before explaining it, let's expand the regex out:

```
:%s/\v\a.{-}(\a|$)/\l&

```

The `VU` converts everything to uppercase. Then we run this:

```
:%                      " On every line:
  s/\v                  "   Substitute:
      \a                "     A letter
        .{-}            "     Followed by as few characters as possible
            (\a|$)      "     Followed by either another letter or an EOL
                  /     "   With:
                   \l   "     The next character is lowercased
                     &  "     The whole text we matched

```

---

Old/more interesting answer:

```
:se nows
Vuò~h2/á

```

# Answer
> 2 votes
# CJam, ~~26~~ 24 bytes

```
qeu{_'[,65>&,T^:T{el}&}%

```

Try it online!

### Explanation

```
q         e# Read all input.
eu        e# Uppercase it.
{         e# For each character:
 _        e#  Duplicate it.
 '[,65>&  e#  Set intersection with the uppercase alphabet.
 ,        e#  Length (either 0 or 1 in this case).
 T^:T     e#  XOR with T (T is initially 0), then store the result back in T.
 {el}&    e#  If The result of the XOR is true, lowercase the character.
}%        e# (end for)

```

# Answer
> 2 votes
# PHP, 71 Bytes

```
for(;a&$c=$argn[$i++];)echo ctype_alpha($c)?(ul[$k++&1].cfirst)($c):$c;

```

Try it online!

# Answer
> 2 votes
**C 64 bytes**

```
B;R(char *s){for(;*s=isalpha(*s)?(B=!B)?*s|=32:*s&=~32:*s;s++);}

```

Takes advantage of ascii encoding where upper and lower case letters are offset by 0x20.

# Answer
> 2 votes
# Retina, 32 bytes

```
T`l`L
01T`L`l`[A-Z][^A-Z]*[A-Z]?

```

Try it online!

First converts the input to uppercase, and then groups the input into matches containing up to two capital letters. The only time it will contain only one letter is if the last letter doesn't have a pair. Then it lowercases the first letter of each of these matches.

The `01` in the second stage translates roughly to: do not change the behaviour of this stage based on the match number, but only apply the changes to the first character of each match.

# Answer
> 2 votes
## PowerShell, 86 bytes

```
-join($args[0]|%{if($_-match"[a-z]"-and($i=!$i)){"$_".toupper()}else{"$_".tolower()}})

```

Input is a `[char[]]` array.

### Comments in code for explanation

```
# Join the array of string and char back together.
-join
    # Take the first argument and pass each element ([char]) down the pipe.
    ($args[0]|%{
        # Check if this is a letter. Second condition is a boolean that changes at every pass
        # but only if the current element is a letter. If not the condition never fires
        if($_-match"[a-z]"-and($i=!$i)){
            # Change the character to uppercase
            "$_".toupper()
        }else{
            # Output the character to lowercase.
            # Special characters are not affected by this method
            "$_".tolower()
        }
    })

```

# Answer
> 2 votes
# Haskell, ~~105~~ 83 + ~~2~~ 4 + 1 byte of separator = ~~108~~ ~~86~~ 88 Bytes

```
import Data.Char
f#(x:y)|isLetter x=([toUpper,toLower]!!f)x:(1-f)#y|1>0=x:f#y
_#l=l

```

Function is `(1#)`, starts lowercase. Try it online!

~~The sad thing is that this is longer than the Java and C# answers~~ Thanks to Ørjan Johansen for saving 22 bytes by merging three lines into one!

# Answer
> 2 votes
# Perl 5, 24 bytes

**23 bytes + 1 byte for `-p`.**

Thanks to @Dada for -2 bytes.

```
s/\pl/--$|?uc$&:lc$&/eg

```

Try it online!

# Answer
> 2 votes
# Perl 5 `-p`, 17 bytes

```
s/\pL/<`>|uc$&/ge

```

Try it online!

# Answer
> 1 votes
# Retina, 46 bytes

```
T`L`l
T`l`L`.(?=([^a-z]*|[a-z][^a-z]*[a-z])*$)

```

Try it online! Includes test cases.

# Answer
> 1 votes
# PHP 5, 54 bytes

```
<?=preg_filter('/\pL/e','($0|" ")^a^aA[$i^=1]',$argn);

```

# Answer
> 1 votes
# C#, 100 bytes

```
s=>{var r="";int m=0;foreach(var c in s)r+=char.IsLetter(c)?(char)(++m%2>0?c|32:c&~32):c;return r;};

```

# Answer
> 1 votes
# Python 3, 192 bytes

```
x=list(input())
s=[]
for i in x[1::2]:
 s.append(i)
 x.remove(i)
s.reverse()
while len(x)<len(s):
 x.append("")
while len(x)>len(s):
 s.append("")
for i in range(len(x)):
 print(end=x[i]+s[i])

```

Try it online!

# Answer
> 1 votes
# Groovy, 79 bytes

```
{x=0;it.toUpperCase().collect{(it==~/\w/)?x++%2?it:it.toLowerCase():it}.join()}

```

# Answer
> 1 votes
# Japt v2.0a0, ~~11~~ 10 bytes

```
r\lÈgYguiv

```

Try it

# Answer
> 1 votes
# *Acc!!*, 110 bytes

```
N*8
Count i while _/256 {
_+_/520*(727/_)*2+_/776*(983/_)*4
Write _/8+32*(_%4/3-_%8%5/4)
(_+(_%8+2)/4)%2+N*8
}

```

Try it online!

### Algorithm

```
Set toLower flag to 0
Read a character
While not EOL:
  Calculate isUpper and isLower flags
  If isUpper && toLower, output (character + 32)
  If isLower && !toLower, output (character - 32)
  Else, output character unchanged
  If isUpper or isLower, toggle toLower
  Reset isUpper and isLower, and read a new character

```

### Accumulator partitioning

We reserve the lowest three bits of the accumulator for storing the flags: toLower in the 1's place, isUpper in the 2's place, and isLower in the 4's place. The rest of the accumulator, at the 8's place and above, stores the input character.

For example, with input of `Hello World`, after reading the `H` and calculating flags, the accumulator has a value of 578, or in binary:

```
1001000 0 1 0
   |    | | \-> toLower (false)
   |    | \---> isUpper (true)
   |    \-----> isLower (false)
   \----------> ASCII code for 'H'

```

After reading the space, the accumulator is 257:

```
0100000 0 0 1
   |    | | \-> toLower (true)
   |    | \---> isUpper (false)
   |    \-----> isLower (false)
   \----------> ASCII code for ' '

```

### Code

**Line 1**

```
N*8

```

Stores the first input character and sets all the flags to 0.

**Line 2**

```
Count i while _/256 {

```

Loops while the accumulator value is \>= 256 (i.e. the character's ASCII code is at least 32).

**Line 3**

```
_+_/520*(727/_)*2+_/776*(983/_)*4

```

Calculates the isUpper and isLower flags. The main trick here is using integer division for the inequalities. For example, if `x` is a printable-ASCII code, then `65 <= x` is equivalent to `x/65` with integer division: values smaller than 65 become 0, values between 65 and 126 become 1, and we don't have to worry about anything larger than 126. We can use this approach for all four inequalities (keeping in mind that the ASCII codes are all multiplied by 8 in the accumulator).

isUpper:

```
65 <= char <= 90
65*8 <= acc <= 90*8+7
acc/520 == 1 && 727/acc == 1

Expression: _/520*(727/_)

```

isLower:

```
97 <= char <= 122
97*8 <= acc <= 122*8+7
acc/776 == 1 && 983/acc == 1

Expression: _/776*(983/_)

```

This line, then, takes the accumulator and adds `isUpper*2 + isLower*4` to it.

**Line 4**

```
Write _/8+32*(_%4/3-_%8%5/4)

```

Outputs the character, swapping case if necessary.

There are two instances in which we need to modify the ASCII value before output:

1. isUpper is 1, toLower is 1
    * We need to convert the uppercase letter to lowercase by adding 32
    * The three flag bits are 011, i.e. acc%4 == 3
2. isLower is 1, toLower is 0
    * We need to convert the lowercase letter to uppercase by subtracting 32
    * The three flag bits are 100, i.e. acc%8 == 4

We can simulate the equality test using mod and int-div. For example, `acc%8 == 4` is equivalent to `acc%8%5/4`:

```
acc%8      0 1 2 3 4 5 6 7
     %5    0 1 2 3 4 0 1 2
       /4  0 0 0 0 1 0 0 0

```

This line, therefore, takes 1 if we need to convert upper-to-lower, subtracts 1 if we need to convert lower-to-upper, multiplies that by 32, adds it to the ASCII code, and outputs it.

**Line 5**

```
(_+(_%8+2)/4)%2+N*8

```

Toggle the toLower flag if necessary; inputs and stores a new character.

We need to toggle toLower if the character was a letter, i.e. either isUpper or isLower was set. The possible flag bit values are `010`, `011`, `100`, and `101`--i.e. 2 through 5 (note that 6 and 7 are not possible because a letter can't be both upper- and lowercase). This expression gives 1 for those values and 0 otherwise:

```
 _%8       0 1 2 3 4 5
    +2     2 3 4 5 6 7
(     )/4  0 0 1 1 1 1

```

Call this value isLetter. Then we want the new value of toLower to be `toLower XOR isLetter` (if isLetter is true, swap the value of toLower; otherwise, leave it unchanged). We can do XOR by adding the two values mod 2. Finally, we also read another character with `N`, multiply it by 8, and add it in.

# Answer
> 1 votes
# MUMPS, 98 bytes

```
 f i=1:1:$l(s) s c=$e(s,i) s:c?1A u=c?1U,f=$s(f="":u,1:'f),$e(s,i)=$c(2*f-1*-'(f=u)*32+$a(c))
 w s

```

Try it online!

* `f i=1:1:$l(s)`: Set `i=1` and loop over this line of code until `i` reaches the length of the input string `s` (inclusive). `i` is incremented by 1 each loop.
* `s c=$e(s,i)`: Assign the `i`th character of `s` to `c` using the `$extract` function.
* `s:c?1A`: Execute the following `set` statements if `c` is an alphabetical character (uppercase or lowercase). This line and the next use M's built-in string matching system.
* `u=c?1U`: Make `u` a boolean storing whether `c` is an uppercase character. There is only one data type in M so `u`'s value will be `1` for true or `0` for false.
* `f=$s(f="":u,1:'f)`: Make `f` a boolean storing whether `c` should be an uppercase character. `f`'s value will also be `1` or `0`. It's assigned `u` if this is the first alphabetic character because the first alphabetic character is in the right case by definition. Otherwise its value is flipped from its previous value using the `not` operator `'`.
* `$e(s,i)=$c(2*f-1*-'(f=u)*32+$a(c))`: The left-hand side is the `i`th character of `s` again; we're setting it equal to the right-hand side which modifies `s` itself. `$a` (for `$ascii`) and `$c` (for `$char`) are inverses: the former converts characters to the corresponding ASCII number and the latter converts numbers back into characters. The argument of `$c` is a compact way to add 32 to `$a(c)` if `c` is lowercase but should be uppercase, subtract 32 from `$a(c)` if `c` is uppercase but should be lowercase, and add 0 if `c` is already in the right case. Note that M's operator precedence is strictly left to right, so `2*f-1*x` is unintuitively the same as `(2*f-1)*x`.
* Finally, `w s` prints the now-alternating `s`.

Both lines have a leading space so that their first characters are interpreted as commands and not labels.

# Answer
> 1 votes
# Vyxal `r`, 8 bytes

```
ʀTy?⇩⁽⇧V

```

Try it Online!

The `r` flag shouldn't be needed, but bugs, bugs, bugs.

# Answer
> 0 votes
# Convex, 16 bytes

```
¯{_U&,R^:R{¬}&}%

```

Try it online!

Convex port of @Business Cat's answer.

# Answer
> 0 votes
# Python 3, 95 bytes

Not nearly as golfed as @Rod's, but I'm posting it nevertheless.

```
lambda s:"".join([s[i],[s[i].lower(),s[i].upper()][i%2]][s[i].isalpha()]for i in range(len(s)))

```

Try it online!

# Answer
> 0 votes
# , 40 bytes

```
(2|+/\@:e.&Alpha_j_)`(tolower,:toupper)}

```

Try it online!

This follows almost directly from the definition of Composite Item (`}`):

We stack the upper and lowercase version of the input for our two possibilities using `(tolower,:toupper)`.

Next we create a boolean list to indicate whether each character is alphabetic: `e.&Alpha_j_` and take the scan sum of that: `+/\@:` which creates a monotonically increasing list which increases only on alphabetic characters. Finally we turn *that* into a boolean list where evens are 0 and odds are 1: `2|`.

Putting those parts together means we alternate between the lower and uppercase versions of our input whenever we encounter a new alphabetic character, and only then.

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 84 bytes

```
int m,c;for(;(c=Read())>0;)Write((char)(c>64&c<91|c>96&c<123?m++%2>0?c|32:c&~32:c));

```

Try it online!

Modified version of The Lethal Coder's answer that takes advantage of some of the features of the interactive compiler.

# Answer
> 0 votes
Javascript, 104 bytes

I'm kind of new to this but wanted to submit anyway.

`x=>x.split('').forEach((s,i)=>x+=i%2?s.toUpperCase():s.toLowerCase())||x.substring(x.length/2,x.length);`

It takes in a string, splits it into an array so it can loop through with `forEach` and fit in as a one-liner, then goes through each character and index and adds the uppercase or lowercase version of the character depending on if the index is odd or not, then "or"s it with what I want to return (since otherwise it's undefined) and returns the second half of the string, so I don't have to clear the string to begin with or declare a new one.

However, this doesn't work with non-letter characters, so here's my pseudocode for something that would do that:

```
const sarcasticText = str=> {
    let newStr = '', numSkip = 0;
    for(let i=0; i<str.length; i++) {
        numSkip += str[i].match(/[a-z]/i) ? 0 : 1;
        newStr += (i + numSkip) % 2 ? str[i].toUpperCase() : str[i].toLowerCase();
    }
    return newStr;
};

```

Basically, I'd implement a counter to check how many characters to offset.

# Answer
> 0 votes
# SM83, 29 bytes

Input pointer in `hl`, output in `de`, trashes `bc`, `a`, flags.

```
06 55 2A 4F CB AF D6 41
38 0C FE 1A 30 08 CB A9
CB 08 38 02 CB E9 79 12
13 B7 20 E6 C9

```

Disassembled:

```
fun:
    ld  b,$55       ;; 06 55    ; set b to alternating bits
loop:
    ld  a,(hl+)     ;; 2A       ; load char
    ld  c,a         ;; 4F       ; and into c
    res 5,a         ;; CB AF    ; turn a-z into A-Z
    sub 65          ;; D6 41    ; subtract 'A'
    jr  c,store     ;; 38 0C    ; if was less, not a letter
    cp  26          ;; FE 1A    ; compare to 26
    jr  nc,store    ;; 30 08    ; if not less, not a letter
    res 5,c         ;; CB A9    ; it is a letter; make uppercase
    rrc b           ;; CB 08    ; rotate b and check low bit
    jr  c,store     ;; 38 02    ; every other time skip next bit
    set 5,c         ;; CB E9    ; actually, make lowercase
store:
    ld  a,c         ;; 79       ; store faster this way
    ld  (de),a      ;; 12       ; store
    inc de          ;; 13       ; and increment
    or  a           ;; B7       ; quick test against 0
    jr nz,loop      ;; 20 E6    ; if not 0 continue
    ret             ;; C9       ; else return

```

# Answer
> 0 votes
# brev, 103 bytes

```
(define h(make-parameter #f))(over(if(char-alphabetic? x)((if(h(not(h)))char-upcase char-downcase)x)x))

```

Are the examples wrong? How do you get to `InClUdE` from `AsCiI`?

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