title: Simulate walking with collisions

text:
# Question
Title: Simulate walking with collisions
In this challenge, the task is to write a program or function which simulates a number of people walking. Input will be some representation of the people's positions on a 2d grid, and one of four directions (or none) for each.

The movement follows a few rules:

* No person can walk into a space occupied by a person who is not moving
* No two or more people can walk into the same space (none of them move)
* No two adjacent people can swap positions

If a person would not collide with another, they will move one space in the specified direction. You can choose how directions are represented. All coordinates are pairs of integers. No two people will start in the same position.

### Test cases:

Inputs are represented as pairs of coordinates (`[x, y]`), followed by a direction. Outputs are only the resulting coordinates. All of these have four people for simplicity, but inputs can consist of any (non-zero) number of people.

**Input 1:**

```
[[[0, 0], +y], [[-1, 0], +x], [[-2, 0], +x], [[1, 0], -x]]

```

**Output 1:**

```
[[0, 1], [-1, 0], [-2, 0], [1, 0]]

```

**Input 2:**

```
[[[0, 0], none], [[0, 1], +y], [[0, 2], +y], [[0, 3], +x]]

```

**Output 2:**

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

```

**Input 3:**

```
[[[0, -1], +y], [[0, -2], +y], [[0, -3], +y], [[1, -2], -x]]

```

**Output 3:**

```
[[0, 0], [0, -1], [0, -3], [1, -2]]

```

**Input 4:**

```
[[[0, 0] +x], [[1, 0], +y], [[1, 1], -x], [[0, 1], -y], [[2, 0], +x]]

```

**Output 4:**

```
[[1, 0], [1, 1], [0, 1], [0, 0], [3, 0]]

```

**Input 5:**

```
[[[0, 0] +x], [[1, 0], +y], [[1, 1], -x], [[0, 1], -y], [[2, 0], -x]]

```

**Output 5:**

```
[[0, 0], [1, 0], [1, 1], [0, 1], [2, 0]]

```

**Input 6:**

```
[[[0, 1], -y], [[1, 1], -x], [[1, 0], +y], [[0, 0] +x], [[2, 0], +x]]

```

**Output 6:**

```
[[0, 0], [0, 1], [1, 1], [1, 0], [3, 0]]

```

This is , shortest answer in bytes per language wins!

# Answer
# , 60 58 50 47 bytes

```
[:+/(*1,:1-(1<1#.+/=/+/)+{.(~:*[=i.{_,~])+/)^:_

```

Try it online!

Takes input as a matrix of complex numbers -- starting positions in the 1st row, steps to walk in the 2nd row.

Passes all test cases including those suggested by tsh and the cycle of 4 suggested by xnor.

## tldr how

We iteratively adjust the steps to be 0 for impossible moves (same destination `(1<1#.+/=/+/)` or `+` swaps `{.(~:*[=i.{_,~])+/`) until they reach a fixed point `^:_`. Iteration is needed because some steps only become illegal after a walker changes from someone who will move to someone standing still. There's a chain reaction.

After that iteration, impossible steps will have been converted to 0, and legal steps will remain what they were.

Once that's done, we just add those steps to the starting positions `[:+/`.
> 10 votes

# Answer
# Python 2, ~~127~~ ~~112~~ 104 bytes

```
def f(l):r=map(sum,l);exec"r=[[p,x][r.count(p)>1or[x+d,-d]in l]for p,[x,d]in zip(r,l)];"*len(l);return r

```

Try it online!

Takes input as a list of pairs of complex numbers, outputs a list of complex numbers. Initially has everyone walk unless they would swap and then repeatedly sends back anyone who collided until there are no collisions left.

-8 bytes thanks to xnor!
> 4 votes

# Answer
# Charcoal, 48 bytes

```
Ｗφ«≔⁰φＦθ¿∧§κ¹∨№θ⟦Σκ±§κ¹⟧⊖№ＥθΣλΣκ«≔⊟κφ⊞κ⁰»»Ｅθ⭆¹Σι

```

Try it online! Link is to verbose version of code. Takes input as an array of pairs of complex numbers and outputs a list of complex numbers. Explanation:

```
Ｗφ«

```

Repeat while a flag value is non-zero.

```
≔⁰φ

```

Zero out the flag value.

```
Ｆθ

```

Loop over the people.

```
¿∧§κ¹

```

If they want to move, and...

```
∨№θ⟦Σκ±§κ¹⟧

```

... they would be swapping with the person at their destination, or...

```
⊖№ＥθΣλΣκ«

```

... another person would end up at the same destination, then:

```
≔⊟κφ

```

Set the flag value by removing that person's desired movement, and...

```
⊞κ⁰

```

Replace their movement with standing still.

```
»»Ｅθ⭆¹Σι

```

Print the final positions. (I've printed them on separate lines as that's what Charcoal's default output should be, although Charcoal doesn't know how to output complex numbers, so I've had to cheat slightly. I could extend that cheat and simply output the whole list as a Python array which would save two bytes.)
> 2 votes

---
Tags: code-golf, grid
---


# Question
Title: Subarrays With At Least N Distinct Integers
Given a sequence of integers and an integer `N`, output the number of contiguous subsequences that contain at least `N` distinct integers. Each integer in the sequence is non-negative and will not be larger than the size of the sequence.
For example, with the sequence `1,2,2,3` and `N=2`, there are 5 contiguous subsequences that contain at least 2 distinct integers:

```
1,2
1,2,2
2,2,3
2,3
1,2,2,3

```

**The asymptotic time complexity must be linearithmic in the size of the input sequence. (The time complexity must be at most amortized `O(S*logS)` where `S` is the size of the input sequence.)**

### Testcases:

| Sequence | N | Output |
| --- | --- | --- |
| 1,2,3 | 2 | 3 |
| 1,2,2,3 | 2 | 5 |
| 6,1,4,2,4,5 | 3 | 9 |
| 1,1,2,2,2,3,4,4 | 4 | 4 |
| 8,6,6,1,10,5,5,1,8,2 | 5 | 11 |
| https://pastebin.com/E8Xaej8f (1,000 integers) | 55 | 446308 |
| https://pastebin.com/4aqiD8BL (80,000 integers) | 117 | 3190760620 |

# Answer
# JavaScript (ES6), 93 bytes

*Saved 18 bytes thanks to @user81655*
*Saved 2 bytes thanks to @tsh*

Expects `(N)(sequence)`.

```
n=>C=a=>eval('for(i=j=a.length,c=s=0;~j;c+=c<n?(C[v=a[--j]]=-~C[v])<2:-!--C[s-=~j,a[--i]])s')

```

Try it online!
> 5 votes

# Answer
# C (gcc), ~~108~~ 104 bytes

*-4 bytes thanks to @Noodle9*

Takes three inputs, \\$ A \\$ *(the array)*, \\$ S \\$ *(the size of the array)*, and \\$ N \\$ *(the minimum distinct integers allowed)*.

```
s;f(A,S,N)int*A;{int c[1<<20]={},n=0,l=S;for(s=S*S;S;s-=l)for(n+=!c[A[--S]]++;n/N;)n-=!--c[A[--l]];s=s;}

```

The two-pointer method is used to achieve a runtime of \\$ O(S) \\$. Note that the `c[1<<20]` automatically caps the input \\$ S \\$ at \\$ 2^{10} \\$, but it can be adjusted to meet the constraints.

Try it online!
> 4 votes

# Answer
# Python 3.8 (pre-release), 138 bytes

```
def f(a,n):
 c=0;l=1+max(a);m=[0]*l;j=len(a)
 for v in a:
  while(n>(d:=l-m.count(0)))*j:m[a[-j]]+=1;j-=1
  c-=~j*(d>=n);m[v]-=1
 return c

```

Try it online!

Credit to Noodle9 for the overall idea. I would have just commented on that answer but I am a new user with no rep, so I have to post a new one, sorry!

Doing away with the dictionary and its method calls saves 11 bytes (at the cost of requiring Python 3.8, though I have a different solution saving 4 bytes without the walrus). We can save another 3 bytes by replacing `a[S-j]` with `a[-j]` and doing away with `S` (4 bytes if used twice as in the original answer).
> 3 votes

# Answer
# Python 3, <sup>~~189~~ \\$\cdots\\$ ~~157~~</sup> 152 bytes

Saved a whopping ~~16~~ 32 bytes thanks to ovs!!!
Saved 5 bytes thanks to Jonathan Allan!!!

```
def f(a,n):
 c=0;m={};S=j=len(a)
 for v in a:
  while(n>len(m))*j:m[a[S-j]]=m.get(a[S-j],0)+1;j-=1
  c-=~j*(len(m)>=n);m[v]-=1;m[v]<1<m.pop(v)
 return c

```

Try it online!

Has \\$O(S)\\$ time complexity.
> 2 votes

# Answer
# JavaScript (Node.js), ~~82~~ 78 bytes

```
n=>s=>s.map(A=_=>{for(n-=!A[_],A[_]=-~A[_];!n;)n+=!--A[s[i++]];m+=i},i=m=0)&&m

```

Try it online!
> 0 votes

---
Tags: code-golf, array, restricted-complexity
---


title: Minimally Making Change

text:
# Question
Title: Minimally Making Change
This problem is an extension of what happens to me on a regular basis: I have to have $1.00 in coins and have to be able to give change to somebody. I discovered rather quickly that the ideal coins to have were 3 quarters, 1 dime, 2 nickels, and 5 pennies. This is the smallest number of coins (11 total) that allows me to make any number of cents 1-99.

### The Challenge

Write a program that, given an integer input \\$x\\$ between 2 and 100 (inclusive), outputs the smallest arrangements of coins that does *both* of the following:

1. The total value of the coins is \\$x\\$ cents.
2. You can use those same coins to make every number of cents less than \\$x\\$.

### Rules

* This is so shortest code (in bytes) wins.
* Standard loopholes are forbidden
* The output can be a list, a four-digit number, or any reasonable representation of the number of coins needed. These coins must be in either ascending or descending order but they do not need to be clearly denoted, only consistently formatted.
    + In other words, all of the following are valid: `[1, 2, 3, 4]` `[1 2 3 4]` `4321` `1 2 3 4` `1P 2N 3D 4Q` `PNNDDDQQQQ`. Simply state somewhere whether your output is listed in ascending or descending order; it must be the same order for all outputs.
* In the case that an optimal solution has *none* of a given coin, your output *must* contain a "0" (or other similar character, so long as it is used exclusively and consistently for "0"). This rule does not apply if you use the PNDQ or QDNP format.
* The only coins that exist are the penny, nickel, dime, and quarter, being worth 1, 5, 10, and 25 cents respectively.
* An arrangement of coins is considered "smaller" than another if the total *number* of coins is less; all coins are weighted equally.

### Test Cases

```
x      Output (Ascending four-digit number)

2      2000
3      3000
4      4000
5      5000
6      6000
7      7000
8      8000
9      4100
10     5100
11     6100
12     7100
13     8100
14     4200
15     5200
16     6200
17     7200
18     8200
19     4110
20     5110
21     6110
22     7110
23     8110
24     4210
25     5210
26     6210
27     7210
28     8210
29     4120
30     5120
31     6120
32     7120
33     8120
34     4220
35     5220
36     6220
37     7220
38     8220
39     4130
40     5130
41     6130
42     7130
43     8130
44     4230
45     5230
46     6230
47     7230
48     8230
49     4211
50     5211
51     6211
52     7211
53     8211
54     4121
55     5121
56     6121
57     7121
58     8121
59     4221
60     5221
61     6221
62     7221
63     8221
64     4131
65     5131
66     6131
67     7131
68     8131
69     4231
70     5231
71     6231
72     7231
73     8231
74     4212
75     5212
76     6212
77     7212
78     8212
79     4122
80     5122
81     6122
82     7122
83     8122
84     4222
85     5222
86     6222
87     7222
88     8222
89     4132
90     5132
91     6132
92     7132
93     8132
94     4232
95     5232
96     6232
97     7232
98     8232
99     4213
100    5213

```

# Answer
> 9 votes
# JavaScript (ES6), 57 bytes

A significantly shorter version suggested by @tsh, who managed to get rid of the edge case \\$n\<9\\$.

Returns an array of 4 integers in reverse order (quarters to pennies).

```
n=>[z=(n-=x=(n-4)%5+4)/25-.7|0,(n=n/5-5*z-1)/2|0,n%2+1,x]

```

Try it online!

---

# Original version, 73 bytes

Returns an array of 4 integers.

```
n=>n<9?[n,0,0,0]:[x=4-~n%5,y=(z=n/25-.96|0)+(n-=x)/5&1||2,n/5-y-z*5>>1,z]

```

Try it online!

# Answer
> 5 votes
# Excel, 106 bytes

```
=IF(A1<9,A1*1000,LET(p,MOD(A1+1,5)+4,b,(A1-p)/5-1,q,(b>2)*INT((b-3)/5),c,b-5*q,p&(MOD(c,2)+1)&INT(c/2)&q))

```

# Answer
> 5 votes
## JavaScript (ES6), ~~47~~ ~~45~~ 44 bytes

```
f=
n=>[25,10,5,1].map(v=>(n-=v*=c=-~n/v-1|0,c))
```

```
<input type=number min=2 max=100 oninput=o.textContent=f(this.value)><pre id=o>
```

Port of my latest Charcoal answer, so outputs in reverse order.

# Answer
> 3 votes
# Jelly (cairdcoinheringaahing's fork), ~~23~~ 19 bytes

```
ŒṗŒP§ḟ@ɗƥRḟƥ“¢¦½ı‘Ṫ

```

Extremely inefficient, and probably also bad in terms of golf. The highest number I could test it on is 18.

Outputs a list of the needed coins in ascending order.

The naive conversion to Jelly would be +2 bytes. You can Try it online!

*-4 bytes by changing the output format*

## Explanation

```
ŒṗŒP§ḟ@ɗƥRḟƥ“¢¦½ı‘Ṫ   Main monadic link
Œṗ                    Integer partitions, sorted from longest to shortest
        ƥ             Keep those where the result is empty:
       ɗ              (
  ŒP                    Power set
    §                   Sum each sublist
     ḟ@                 Remove the resulting numbers
         R                from the range [1..input]
       ɗ              )
           ƥ          Keep those where the result is empty:
          ḟ             Filter out
            “¢¦½ı‘        [1,5,10,25]
                  Ṫ   Tail (last item)

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), ~~90~~ 87 bytes

```
MinimalBy[Length@Expand@Exp[Log[1+$^d].#]>#.d&&#&/@FrobeniusSolve[d={1,5,10,25},#],Tr]&

```

Try it online!

```
FrobeniusSolve[d={1,5,10,25},#]     (* Find nonnegative integer vectors s where {1,5,10,25}.s==x. *)
Length@Expand@                      (* If the number of terms in the expansion of *)
              Exp[Log[1+$^d].s]     (*   (1+$)^s1(1+$^5)^s2(1+$^10)^s3(1+$^25)^s4 *)
 >#.d&&#&/@ %                       (*  for each s is not greater than x (=x+1), discard it. *)
MinimalBy[ % ,Tr]&                  (* Select the s with the least sum. *)

```

# Answer
> 2 votes
# Retina 0.8.2, ~~80~~ 71 bytes

```
.+
$*
(1{25}(?=1{24}))*(1{10}(?=1{9}))*(1{5}(?=1{4}))*(1+)
$.4$#3$#2$#1

```

Try it online! Link includes test suite that automatically generates numbered results ranging from `2` to the input value. Explanation:

```
.+
$*

```

Convert to unary.

```
(1{25}(?=1{24}))*

```

Match quarters, but leaving at least 24 cents.

```
(1{10}(?=1{9}))*

```

Match dimes, but leaving at least 9 cents.

```
(1{5}(?=1{4}))*

```

Match nickels, but leaving at least 4 cents.

```
(1+)

```

Match the remaining cents.

```
$.4$#3$#2$#1

```

Output the remaining cents, plus the number of nickels, dimes and quarters.

38 bytes if outputting a list of coin values is acceptable:

```
.+
$*
M!`1(1{24}|1{9}|1{4}|)(?=\1)
%`1

```

Try it online! No test suite yet. Explanation:

```
.+
$*

```

Convert to unary.

```
M!`1(1{24}|1{9}|1{4}|)(?=\1)

```

Try all coin values in descending order. For each coin value, ensure that there are enough cents left for one less than that value.

```
%`1

```

Convert to decimal.

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

```
Counts@Join[h={1,5,10,25},FirstCase[IntegerPartitions[#,#,h],s_/;Tr[1^Union[Tr/@Subsets@s]]>#]]-1&

```

Try it online!

-13 bytes from @att

# Answer
> 1 votes
# Brachylog, 23 bytes

Quite inefficient, TIO only reaches 15.

```
~+{1|5|10|25}ᵐ.&⟦~{⊇+}ᵛ

```

Try it online!

```
~+{1|5|10|25}ᵐ.&⟦~{⊇+}ᵛ
~+                         A list of numbers (which sum is the input)
  {1|5|10|25}ᵐ             where each number is 1, 5, 10, or 25
              .            is the output.
               &⟦          For [0,1,…,N]:
                 ~{⊇+}ᵛ    every element is the sum of a subset of the output.

```

# Answer
> 1 votes
# Charcoal, ~~61~~ ~~51~~ ~~30~~ 29 bytes

```
ＮθＦ⟦²⁵χ⁵¦¹⟧«≔÷↔⁻ι⊕θιηＩη≧⁻×ιηθ

```

Try it online! Link is to verbose version of code. Edit: Reversed the order in which coins are printed to save bytes. Explanation:

```
Ｎθ

```

Input `x`.

```
Ｆ⟦²⁵χ⁵¦¹⟧«

```

Loop over all the denominations in descending order. (Charcoal's predefined `c` variable for `10` conveniently avoids two of the separators here.)

```
≔÷↔⁻ι⊕θιη

```

Find how many coins I can use. Unless the original input was less, we need to be able to form an amount one less than this coin's value, so we take the absolute difference from this value (which handles inputs less than the value of the coin) before integer dividing by the coin's value.

```
Ｉη

```

Print that number.

```
≧⁻×ιηθ

```

Subtract the value of the coins.

---
Tags: code-golf, integer-partitions
---


title: Print the new site header

text:
# Question
Title: Print the new site header
The new site header has some bits of source code from various questions as the background. Here are the first 3 lines:

```
--<-<<+[+[<+>--->->->-<<<]>]<<--.<++++++.<<-..<<.<+.>>.>>.<<<.+++.>>.>>-.<<<+. Hello, World! IT'S SHOWTIME TALK TO THE HAND "Hello, World!" YOU HAVE BEEN TERMINATED "9!dlroW ,olleH"ck,@ 72a101a+7aa+3a44a32a87a111a+3a-6a-8a33a Take Circle Line to Paddington Take Circle Line to Wood Lane Take Circle L
alert'Hello, World!' target byteorder little;import puts;export main;section"data"{s:bits8[]"Hello, World!\0";}foreign"C"main(){foreign"C"puts("address"s);foreign"C"return(0);} aeeeaeeewueuueweeueeuewwaaaweaaewaeaawueweeeaeeewaaawueeueweeaweeeueuw H class H{public static void main(String[]a){System.
World!");}}+[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++[.>]<<<<.+++.------.<<-.>>>>+. "Hello, World!"o| :after{content:"Hello, World!" H;e;P1;@/;W;o;/l;;o;Q/r;l;d;2;P0 ('&%:9]!~}|z2Vxwv-,POqponl$Hjihf|B@@>,=<M:9&7Y#VV2TSn.Oe*c;(I&%$#"mCBA?zxxv*Pb8`qo42mZF.{Iy*@dD'<;_?!\}}|z2VxSSQ main(){puts("Hello, W

```

However, a few microseconds of extra load time can cause the user to click away from the site, so the page header download really should be optimized as much as possible.

Write a program that takes no input and produces the (first 3 lines of) text from the new header as output.

* Trailing newline is optional
* Must include the line breaks from the original header
* , so shortest code wins!

# Answer
# Stax, ~~601~~ ~~584~~ ~~574~~ ~~564~~ ~~553~~ 539 bytes

```
«=¬█j▼sw│╥═7♫çÿñ╦*‼e"!‼╤Å╟D·εWÜå╖L♂@#î╚å♫▐ô;(┤┼»Kî→δäû║h◘│¶zurΘ█┐£ë}∞è┼$÷gôwg¬≤╒Ñ╧]∙ì▄╦╕ís│\☺'┴♫Φ^┐╤å{1█♠₧ï∩∙↑▀⌂d▲╡⌡3J‼¡qâ╧3¥Çƒwe▀≡╔MjZΣΩyüO╬ªÉΩö^Y╡►8K₧óN·ÿjg≈Cö9^◘■~Ä_ßx▐Å┌ Q>/♫╤QΩzN╤V½▓▀◙ß╗╗◄►(╔☺╡┘Ah╙¢√ß▼GΩ→ù◄:─◘#♫úq•ø≤>↨)Å│╤[ïmgBX┤╛v\ⁿ╛å╘╕7d╪TµbW#2¶ø╙╜~êê[↨>K►♪0∞#XJ°ñntG∞⌐V♥Z<ÿº'║☺;┤é⌡♠gáσßÑ+♂z♥‼S9 l≈╫ºÜT»↕▀τ♣¡gWe¥_çà(┬f╜n[╗╤fσ╞R₧▲V▌═◙úKÆÜ▄☺╥s1▼╩ûû╗▌▌Ω■g∞Y╡9╦tè┴y♂w∟⌂┌'╣W▀M╓·uBôúPm◘ ☻ⁿFh<╘sú▲Ö╘¶¿_2♦Θb{╪δC\lô+▀9¶ß§╡╓)ú}○8∟⌡nÑôI )╓îFbH[î║╞e&"¶↓~A#ç╔▄─áσ∙:═Æ▬ª▄ÄêQSNM◙∞Z╜≈±╘▬LIÿ|#.¿Φµ║▌Lväv▓♣;└Æ▲▄♣↕{╪½)╚φ╡♦:oÉ▀j╠ΔP<ç↔|±╦=╣▓Φ▒─4D▄■ìà>↓┐

```

Run and debug it

It does at least attempt to use different strategies for different pieces.
I've still got some hope for a few sections, but here's an explanation of the approaches so far.

```
                                    The general approach is to push a bunch of stuff on the stack.
                                    Then join it all together and split it in thirds.
'                                   just a space
`jaH1"jS3!`X                        compressed literal for "Hello, World!" assigned to the x register
`38dZl;i#D]|@Y@*`                   compressed literal for "It's showtime talk to the hand"
^                                   convert to upper case; it compresses better in lower case
n'"|SY                              Wrap the x register in quotes and save it in the y register
`=j("sx6c1 ob`^                     compressed literal for "you have been terminated" in upper
."9                                 literal for '"9'
yrD                                 register y (quoted hello world), reversed, first character dropped
"ck,@ "                             literal
"^h{ai{W>bJ,^T+NLDK(G$s@+"!         crammed array [725, 101597559, 354, 45325875, 1115935, -65, -85335]
$"5a9+"|t                           concat as strings, then map '5' to 'a' and '9' to '+'
`='9%[mh++PxF!`                     compressed literal for " Take Circle Line to "
`~J@[E<`n                           compressed literal for "Paddington"; copy the one about the circle
`jj_kmZ5`                           compressed literal for "Wood Lane"
n7T                                 copy " Take Circle Line to " and truncate last 7 characters
"alert'"x''                         some literals and x register
`~lLKPq'III^) .tI:G8?uMolVwpnT&u#`  compressed literal with commas in place of semi-colons
.,;|t                               replace with semi-colons, which aren't allowed in compressed literals
`/zOXzN`",data,{s:bits8[],`x\0_;}`cC,main(){`cC,puts(,address,s);` C,return(0);} ".,"|t
                                    compressed literal for "foreign", followed by a string template
"Nm\{<\3VdH,FF:c~7&u!n"96|E         carefully chosen string literal interpreted in base 96
"eawu":B                            encoded in custom base "eawu"
`dzJxVHC"`'{`pS7yzeENLM%_'`         two compressed literals with a '{' in the middle
"(String[]a){System."               literal
x6)                                 last 6 characters of register x
"`");}}"                            literal with escaped uote
"0;pKll>r&.sSP}JLNL==(>eP>-2\6fc8|)4&.:,1jA66O{t0>GpALk4I{.iDM:Gr_50ga"
90|E                                literal of ascii characters decoded in base 90
"[+-><],.":B                        re-encoded with a custom base of brainfuck
72:/                                split at position 72
~                                   push the right half to the input stack, effectively the beginning
" `yo| :after{content:`y H;e;P1;@/;W;o;/l;;o;Q/r;l;d;2;P0 ('&%:9]!~}|z2Vxwv-,POqponl$Hjihf|B@@>,=<M:9&7Y#VV2TSn.Oe*c;(I&%$#`"mCBA?zxxv*Pb8``qo42mZF.{Iy*@dD'<;_?!\}}|z2VxSSQ main(){puts("
                                    big string template including y register a few times
y9(                                 first 9 characters of y
Lr$                                 wrap all stacks in array and concatenate
3Mm                                 split into 3 equal parts and print as lines

```
> 19 votes

# Answer
# Jelly, 568 bytes

```
“¢lẊḊ%ñẇÄNị¡ẸVþṾɲXØ?^ÆÐX⁷®bWċ’b7ị“-+[>].<”” “3ḅaė;œ»©“×;-¢İiĖƝÞth⁴"Ạ⁺Xṙ{»Œu®“JṁkKɼġʋḲỴ9|ḤḲ»Œu®U“ƭJ&çȯ»” Ȯø“¡ŻAÆ¡ ⁾Ʋ⁵(S0-’b122_⁵ȯ€“”ṭ"3,5,10Ṭ×”+¤j”a“Æ¬>hPḢ¤Ġ2fɠjẆȤ¬ṬwḷÇRy_ỴṬƓO¶~^YG³ẸṂḊỤÇ»®“¡ñA¦ɗɱṪḅạðEṘ/Ḋ_³ṢÑ⁺ċßs³m0>*Ḥıo7Ʋ>[;ɼ⁽¢OẆ9Ɓ€»®“¤Z!ƤḂĊlðiƝṘŻqọ6³Ṣṡḃ8Þœn⁶ʠẉ>yuẆ{»Ḳj“ṢẈ,ẊL»” ø“×©K⁸ƁƬ÷FġƬṘ¹^Ẉ§ṭƁḅ’b4ị“wuae”“£¦ƊNỴŻw;ƊFɦȦnœĠÐẇṀu½X*ṠOJ8ȷḍu&)ṫ)⁼ẏµ×ẏ`ȯ»ø“¡-P⁽Rȯ$@°ḤėXƙ€ṭ⁶Vė7-²ɦ{NỌQ’b7ị“+-><].[”⁾ "®“ıȷ®⁻ʂ£Þȷ⁹ṣp°⁷»®ø“Ṛ|ġcßỵiṃ^ɱrÐẏNạŀiUĠ¥ĿSʂĊ⁷Ð+¦ŻvIṖj~ż¹kĿƥð¿ƘeḶZƤLɱ ṭṡ¥⁷ė$ ėƬ ċ⁵Ṛ¿⁷¢²_ṛż⁽p£⁽n#/i½ɱ`M3BƓḳ?¥ạuẹ09ʠ;"J!ṢIMkIoÐȯ²&_ẋẓṗḲ>½Q>ẈȯĠ ŀJṇḢC.(Eı’b128ịØJ“¡ʂh;⁼µ:ȮçṛƤb7ḋ2ṢR»

```

Try it online!

I tried to add optimizations per section. The optimized string compressor compresses this to 730 bytes (which *should* be the best possible just using basic Jelly syntactical constructs rather than any actual methods), so it appears I have done something.

(Fun fact: after I posted this answer, Chrome started suggesting translating this page to Vietnamese :P)
> 14 votes

# Answer
# SOGL V0.12, ~~542~~ 527 bytes

```
Hello, World!”³³"ī←≥/ī⁹βņ	fi▼pΛtι¤Υ8Th4ΚT~v‛θ5→č■⌡‘o"′]◄⅟ō&÷2}≠Θ←⁷┌∙‽↓æ³ΘZ°β╔¶ļ¹‘U┌⁷ŗo±"ē‛V)≥u∆↕]ē׀~σφ‰τ┘^|i≡»┼y3┐X3Η‛Χ4±2‘o"ΣΤ°ε⁵↑p$J↑³∫ū²▼!⁄B²⌠3τ}σS⁷bu¹1∆Ν²‘ū#Ƨtoŗo"JνΠ◄ī÷$λ⅜Zø@Pθθ╚XΔBPø√:┘¦z#│y⁹oΣ⁄½Λ'7⅞Fģ′σv+&≥μ_¦≠⅔v]lπlsβ╥^D#,℮⁾§Aα‛ķκņ▼%ķW═g!ōΜ¬`}⅛čņ█≠⁄⅔‛mZÆ~⁴πzWl─xτ▼'Η↓#ΗΩ►φL8!Ƨ:e¡′ž|Τr^+≡▒GπεΓW≥7±λxw׀ Κν⁷cP\ιYΤp|A╝æƧO∑b►\÷Q²OΟč⅔⁽(╬( ρn⁽BoG=Υ→m▒‽¤/►iΟ√PqΩ∙φ4√VΥæl‽υΧ$f0╬Dkμ⌠Lāč¾↓′∫Ε╚Βæ║↑Ν▲γB#⁶5⁹B|l↔ƨ╗6Σŗ⁄⅟ω±μξydA┼*ģ⁴Z►xa^■7O═ģΖ4Γ⅞6═¾χ‰⁷‛[‚⅓D⅞π▓z⁶‼Æņ2Υ√θ']7┐⁰īS╗<čfφ┘lθ⁄{=æ⁹Δ<¡⁾Υ□ι¹λzFΗ▲-β▒╤ÆAΩ/xff⁰ΞΠIæ┘*⁾h⁷╗ΧG─`⁾⁄@p*‘p

```

Try it here!

Almost all compression, but broken up every now and then because English compression works only on lowercase words and case is important. I still had to split the text up in compressible parts though.

This finally made me fix a bug in the compressor, making it unresponsive sometimes (the result still works in the previous versions though)
> 13 votes

# Answer
# Retina, 793 bytes

```

--<-<<+[+[<+>--->->->-<<<]>]<<--.<6*+.<<-..<<.<+GG.<<<.+++GG-.<<<+. ^ IT'S SHOWTIME TALK TO THE HAND "^" YOU HAVE BEEN TERMINATED "9!dlroW ,olleH"ck,@ 72a101a+7aa+3a44a32a87a111a+3a-6a-8a33aXine to PaddingtonXine to Wood LaneX¶alert'^' target byteorder little;import puts;export 5;section"data"{s:bits8[]"^\0";}J5(){Jputs("address"s);Jreturn(0);} aeeeaeeewueuueweeueeuewwaaaweaaewaeaawueweeeaeeewaaawueeueweeaweeeueuw H class H{public static void 5(String[]a){System.¶World!");}}+[-->-[>>+>5*-<<]<--<---]>-G>+G..+++[.>]4*<.+++.6*-.<<-G>>+. "^"o| :after{content:"^" H;e;P1;@/;W;o;/l;;o;Q/r;l;d;2;P0 ('&%:9]!~}|z2Vxwv-,POqponl$Hjihf|B@@>,=<M:9&7Y#VV2TSn.Oe$*c;(I&%$#"mCBA?zxxv$*Pb8`qo42mZF.{Iy$*@dD'<;_?!\}}|z2VxSSQ 5(){puts("Hello, W
5
main
G
.>>
J
foreign"C"
X
 Take Circle L
\^
Hello, World!

```

Try it online! Well, I tried. The desired output uses all but five printable ASCII characters, but fortunately I could only find five strings with enough repetition to be worth compressing. There are also four characters repeated more than three times in a a row; these are run length encoded. Would be 1 byte longer in Retina 0.8.2 as the four run length encodings cost an extra byte each but it's then no longer necessary to quote the three desired `*`s.
> 3 votes

# Answer
# Deadfish~, 6462 bytes

```
{iiii}iiiiicc{i}iiiiic{d}dddddc{i}iiiiicc{dd}iiic{iiiii}ddc{ddddd}iic{iiiii}ddc{ddd}dc{dd}iiic{ii}dc{dd}iiiccc{ii}dddc{dd}iiic{ii}dddc{dd}iiic{ii}dddc{dd}iiic{i}iiiiiccc{iii}iiic{ddd}dc{iii}ic{ddd}dddcc{d}dddddccic{i}iiiic{dd}iiicccccciiic{i}iiiicc{d}dddddcicc{i}iiiicc{d}ddddc{i}iiiic{dd}iiiciiic{i}iiiiiicc{d}ddddddc{i}iiiiiicc{d}ddddddc{i}iiiiccc{d}ddddcdddccciiic{i}iiiiiicc{d}ddddddc{i}iiiiiicc{dd}iiicic{i}iiiiccc{dd}iiiciiic{d}ddddc{iiii}c{iii}dc{i}dddcciiic{{d}iii}iiic{d}ddc{iiiii}iiiiic{ii}iiiiciiicddddddc{d}iic{{d}iii}iiicdc{iiii}ic{i}ic{dddd}dddddc{iiii}iiiic{ddddd}dc{iiiii}ic{d}dc{i}dddc{i}ddcdddc{d}dciiiic{d}iic{dddd}iiic{iiiii}iic{dd}ic{i}icdc{dddd}dddc{iiiii}iicdddddc{ddddd}iiic{iiiii}iic{d}ddcdddc{dddd}iiic{iiii}c{d}iiic{i}iiic{d}c{ddd}ddddddciic{iiii}ddc{iii}dc{i}dddcciiic{{d}iii}iiic{d}ddc{iiiii}iiiiic{ii}iiiiciiicddddddc{d}iic{{d}iii}iiicicddc{iiiiii}dddc{d}ciiiiiic{ddddd}dddc{iiii}c{d}iiic{ii}ic{dd}iiic{dddd}iiic{iii}iiiiciiicc{i}dc{dddd}ddddddc{iiiii}iic{d}dddddc{i}iiicdddddcddddciiiiic{d}dddc{ii}dc{d}dddddcdc{ddd}ddddddciic{ii}iiic{dd}ddddc{{i}ddd}dddc{i}ddciiiiiicdddc{dd}ddddc{ddddd}dddddc{i}iic{{i}ddd}dddcdddcc{d}iiic{ddd}ic{dddd}iic{iiiiii}iiiiic{i}ddc{dddddd}dddc{ii}c{ddd}ddc{ii}iiicdddddc{iiiii}dddc{ddddd}iicdcic{iiiii}ddc{ddddd}ddddc{i}iic{iiii}iicc{ddddd}ddddc{i}ddc{iiii}iiiiiic{dddd}dddddcc{iiii}iiiiic{dddd}ddddddcdc{iiiii}dddc{dddd}dcdc{iiii}iic{ddddd}iiccc{iiiii}ddc{ddddd}ddddc{i}ddc{iiii}iiiiiic{ddddd}ddc{i}dc{iiii}iiic{ddddd}ddc{i}ic{iiii}ic{dddd}ddddddcc{iiii}iiiiiic{dddddd}dddddc{iiiii}iic{i}iiic{i}cddddddc{{d}iii}ic{iii}iiiiic{iiii}ddc{i}dc{d}dddddc{i}dc{d}iiic{{d}iii}ic{iiii}iiiic{iii}dciiiiic{d}ic{{d}iii}ic{{i}dd}iiiicdddddc{{d}ii}ic{iiiii}ddc{ii}dddciiicciiiiiciiiiic{d}iiic{i}iiicdddddcdc{{d}ii}iic{iiiii}iic{i}iiic{i}cddddddc{{d}iii}ic{iii}iiiiic{iiii}ddc{i}dc{d}dddddc{i}dc{d}iiic{{d}iii}ic{iiii}iiiic{iii}dciiiiic{d}ic{{d}iii}ic{{i}dd}iiiicdddddc{{d}ii}ic{iiiii}iiiiic{ii}iiiicc{d}dc{{d}iii}iic{iiii}iiiic{ii}ic{i}iiic{d}ic{{d}iii}ic{iiiii}iic{i}iiic{i}cddddddc{{d}iii}ic{iii}iiiiic{iiii}ddc{i}dc{d}dddddc{i}dc{d}iiic{{d}iii}ic{iiii}iiiic{ii}ic{i}ic{d}iiic{i}iiiciic{{d}ii}iiic{iii}iiic{iii}dc{i}dddcciiic{{d}iii}iiic{d}ddc{iiiii}iiiiic{ii}iiiiciiicddddddc{d}iic{{d}iii}iiiciiiiiic{d}iiic{{i}dd}iiiic{dd}ic{ii}dddc{d}dcddc{i}iiiiic{{d}ii}ddddc{iiiiii}iiiiiic{ii}iiicdddddc{d}dddddc{i}ciiic{d}ddddcic{i}iiic{{d}ii}ddc{{i}ddd}iiiiiicdddc{i}icc{d}iic{d}iiic{dddd}ddc{iiii}iiiiiiciiiiciiicdciiiciic{{d}ii}ddddc{{i}dd}ciiiiicdcdc{ddddd}ddddddc{iiii}iic{ii}dc{d}iicdciiiciic{{d}ii}ddddc{{i}dd}dddc{d}ddc{i}ddciiiiic{ddddd}dc{iiiii}iiiiiic{d}ddddcddc{ii}dddc{d}dciiiiiicdc{{d}iii}ddddddc{iiiiii}iiiiiicdddc{ii}dc{dd}ic{dddddd}dddc{{i}d}dc{d}iic{dddddd}iiic{iiii}c{i}dddc{i}icdc{dddddd}ic{iii}iiiiiciic{dddddd}ic{iiii}ddc{iii}dc{i}dddcciiic{{d}iii}iiic{d}ddc{iiiii}iiiiic{ii}iiiiciiicddddddc{d}iic{{d}iii}iiic{iiiiii}dc{dddd}ddddc{d}ddddc{ii}iiiiic{iiiiii}iiiiiic{dd}dddc{i}dciiic{d}dddciiiicddc{i}dddc{{d}iii}ddddddc{iii}iiic{ddd}dddc{{i}ddd}iiiiic{d}ddc{i}ddciiiiic{{d}iii}cic{{i}dd}iic{dd}dc{i}dciiic{d}dddciiiicddc{i}dddc{{d}iii}ddddddc{iii}iiic{ddd}dddc{{i}dd}ddciiiiicdcdc{{d}iii}dddddcddddddc{iiiiii}iiiciiicc{i}iiiic{d}dddc{i}iiiicc{{d}ii}dc{{i}dd}ic{{d}iii}ddddc{ii}ddc{iiii}iiic{i}dciiic{d}dddciiiicddc{i}dddc{{d}iii}ddddddc{iii}iiic{ddd}dddc{{i}dd}c{d}dddc{i}iiiiicicdddcddddc{{d}iii}c{i}ddc{d}iiic{ii}ddc{iiiiii}iiiiiic{{d}i}dddc{iiiiii}iiiiiciiiicccddddciiiiccc{ii}ddcddc{d}ddddddc{i}iiiiiicc{d}ddddddc{ii}ddc{dd}iicc{i}iiiiiic{d}ddddddcc{i}iiiiiic{d}ddddddc{ii}ddcc{dd}ddccc{ii}iic{dd}iicddddcciiiic{ii}ddc{dd}ddciiiicddddcc{ii}iicddc{d}ddddddc{ii}ddc{dd}iicccddddciiiiccc{ii}ddc{dd}ddccc{ii}iicddc{d}ddddddcc{i}iiiiiic{d}ddddddc{ii}ddc{dd}iiccddddc{ii}iic{dd}iiccc{i}iiiiiic{d}ddddddc{i}iiiiiiciic{{d}i}iiic{iiii}c{dddd}c{{i}ddd}dddc{i}dc{d}dc{ii}ddcc{{d}ii}dddc{iiii}c{iiiii}ic{d}dciiiiic{dd}ic{i}cdddcddddddc{{d}iii}iiic{{i}dd}iiicic{dd}ic{ii}dc{d}dcddddddc{{d}iii}iiic{{i}dd}iiiiiic{d}iiicddddddcdddddc{{d}iii}iic{{i}dd}dddc{d}ddc{i}ddciiiiic{{d}iii}c{iiii}iiic{iii}iiicddc{d}iciiiiic{d}iiic{d}ddciiciiiic{ddddd}ddddddc{{i}dd}iic{dddd}c{iiii}ddcddddddcic{d}dddddc{i}ddc{dddddd}dddc{iiii}ic{ii}iiiiciiicddddddc{d}iic{{d}iii}iiicic{i}dddc{ii}ddc{iiiiii}iiiiiicc{{d}ii}ddc{iiiii}ddc{dddd}ddddddcc{ii}dddc{dd}iiic{iiii}iiiiiic{ddd}icc{dd}ic{ii}dc{dd}iiiccccc{i}iiiiicc{iii}iiic{ddd}dddc{d}dddddcc{i}iiiiic{d}dddddccc{iiiii}ddc{ddd}dc{dd}iiicic{i}iiiiiiccc{dd}iciiic{i}iiiiiicc{d}ddddddccdddccc{iiiii}ddc{dddd}dddddc{i}iiiiiic{iii}ic{ddd}dddcccc{d}ddddcdddccciiicdccccccic{i}iiiicc{d}dddddcic{i}iiiiiicccc{dd}iciiic{d}ddddciic{iiii}ddc{iii}dc{i}dddcciiic{{d}iii}iiic{d}ddc{iiiii}iiiiic{ii}iiiiciiicddddddc{d}iic{{d}iii}iiicic{{i}dd}dddc{i}iiic{{d}i}ddc{ii}iiiiiic{iiii}dciiiiic{i}iiiic{d}dddddc{i}iiic{i}dc{dd}ddddc{i}iicdciiiiiic{d}dddddc{i}dciiiiiic{dddddd}iic{dd}ddddc{iiii}ddc{iii}dc{i}dddcciiic{{d}iii}iiic{d}ddc{iiiii}iiiiic{ii}iiiiciiicddddddc{d}iic{{d}iii}iiicicddc{iiii}c{d}dddc{iiii}iic{dddd}ddc{ii}ic{ddd}dc{i}ciiiiic{dd}iiic{i}iic{iii}ddc{ddd}iic{iiiii}iic{ddddd}ddc{d}ddc{iiiiii}ic{ddddd}icc{iiiii}iic{ddddd}ddc{ii}iic{ddd}ddddc{{i}ddd}dddc{ddddd}dddddc{iiiii}dc{ddddd}ic{iiii}ic{dddd}dc{d}ic{i}dc{ii}ic{ddd}ddc{d}ddddddc{i}ddcdcdcdc{ii}icdc{iii}iiiiiic{dddddd}c{{i}d}iiicdcdcddc{{d}iii}ddc{iii}iiiiiic{iii}iiiicdcdc{{d}iii}dddcdc{iii}iiiiiicdc{iii}iiiicdcdcdcddc{{d}iii}ddc{iii}iiiiiic{iii}iiiicdcdcddc{ii}iic{dddddd}iicddccddc{dd}iic{ii}dddcdc{ii}dddc{dd}icdc{dd}ic{ii}dddc{iii}iiiic{ddddd}ddddc{iiiii}icc{ddd}ddddddc{iii}iiiicdc{iii}dddc{dddddd}ddddc{iii}iiic{ii}iic{dddddd}ic{iiiiii}dddc{dddd}c{dd}ic{iii}iiic{ddd}dddddcdcdcdcdc{{i}ddd}iiiiic{dddd}ddcdcdcddc{iiiiii}dcddccddc{{d}iii}ddddddc{iiii}ddc{ii}ddc{dddd}ddc{iiii}c{ii}dddcddc{dddddd}icddc{iiiiii}dc{dd}ic{dd}c{dd}ddddc{{i}dd}dddc{ddddd}c{iiiii}ddc{{d}ii}ic{ii}iic{iii}iiiiiic{ddd}ddc{ddd}ic{ii}icdc{iii}iiiiiic{ddd}ddc{ddd}c{iiiiii}dc{iii}iiiccdcddc{{d}iii}ddc{iii}iiiiiic{iii}iiiic{dddd}iiiccddc{ddddd}ic{{i}dd}dddc{d}ddc{i}ddciiiiic{{d}iii}cic{{i}dd}iic{d}dciiiiicdcdc{{d}iii}dddddcddddddc{iiii}ddc{iii}dc{i}dddcciiic{{d}iii}iiic{d}ddc{iiiii}iiiiic{i}iiiiiciiiciiic{d}iiic{dddd}dddc{d}dccc{{i}ddd}cddc{d}ddddc{i}iiicic{{d}iii}iic{iiiii}ic{i}dcddddddciiiic{i}ic{d}ddc{dddddd}iiic{iiiii}iiic{i}ic{d}ddc{ii}ddc{d}iic{d}iic{i}dciiiiiicdc{{d}iii}iic{iiiii}iiiiiic{i}ddc{d}ddddddc{ii}ic{d}dddddc{i}iiiicic{{d}iii}ic{iiiiii}dc{d}ic{ii}ic{dd}dc{ddddd}c{iiiiii}ddciiiiic{d}cic{ii}dc{{d}iii}ddddc{iiiiii}ddc{i}iic{d}iiicdc

```
> 0 votes

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


# Question
Title: The first published picture of the Mandelbrot set
Here’s the picture of the first published picture of the Mandelbrot set.

Use the fewest bytes possible to write a program or function that outputs the following.

A trailing new line is permitted. Character `*` cannot be replaced by any other character.

Useful information: Center is \\$(-0.75, 0)\\$, \\$\Delta x = 0.035\\$, and \\$\Delta y = 1.66\Delta x\\$. Iteration count is 250.

As text (for checking):

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

```

Thanks @Sisyphus for providing the parameters.

# Answer
# Ruby 2.5, 98 bytes

```
-15.upto(15){|y|68.times{|x|z=0;250.times{z=0.035*x-1.9751+y/17.21i+z*z};putc z.abs<2?42:32};puts}

```

Try it online!

Very straightforward implementation, with a little bit of trickery to allow using `times` instead of `upto` in the inner loop.

Unfortunately, loop merging is two bytes longer, although it may help in other languages:

```
-1034.upto(1104){|x|z=0;250.times{z=x%69*0.035-2.0101+x/69/17.21i+z*z};putc x%69>0?z.abs<2?42:32:10}

```
> 20 votes

# Answer
# Wolfram Language (Mathematica), ~~86~~ ~~85~~ 84 bytes

-1 thanks to sanchez

```
Print@@@Array[If[Re@Nest[#^2+c&,c=.035#2+I.0581#,199]<2,"*"," "]&,8{4,9},-5{3,79/7}]

```

Try it online!

Uses the constants found by Sisyphus.

Mathematica does have such functions as `MandelbrotSetIterationCount` and `MandelbrotSetMemberQ` (which, with the default 1000 iterations, produces a slightly different image). Unfortunately, `MandelbrotSetIterationCount`'s name is a bit too long, while setting the `MaxIterations` option for `MandelbrotSetMemberQ` makes it even more verbose.
> 11 votes

# Answer
# MATL, 45 bytes

*Some numerical constants have been taken from Sisyphus' answer*

*Thanks to @Arnauld for a correction!*

```
O8W:"U-1.9751:.035:.4-15:15!17.21j/++]|2<42*c

```

**Try it online!**

### How it works

```
O                  % Push 0
8W                 % Push 2^8, that is, 256
:                  % Range. Gives [1 2 ... 256]
"                  % For each. This iterates 256 times
  U                %   Square, element-wise
  -1.9751:.035:.4  %   Push range from -1.9751 to 0.4 (actually to 0.37) with step 0.035
  -15:15           %   Push range from -15 to 15 (with step 1)
  !                %   Transpose into a column vector
  17.21j/          %   Divide by 17.21j, element-wise
  +                %   Add with broadcast. Gives the complex grid
  +                %   Add element-wise to result from previous iteration
]                  % End
|                  % Absolute value, element-wise
2<                 % Less than 2? Element-wise
42*                % Multiply by 42 (ASCII code of '*'), element-wise
c                  % Convert to char (char 0 is displayed as space). Implicit display

```

As a curious note, the program uses `:` with three different meanings:

* Unary range function (`:` appplied to `256`)
* Ternary range literal (`-1.9751:.035:.4`)
* Binary range literal (`-15:15`)
> 10 votes

# Answer
# 05AB1E, 56 bytes

Feels very long.

```
67ÝƵú*Ž
@-тn/15D(Ÿт*Ž6À/δ‚εε₅FDnÆsP·‚y+DnO4›©#}„* ®è]øJ»

```

Try it online!

Since *05AB1E* does not support complex numbers the computation is done in a more manual way, keeping complex numbers as pairs `[a, b]`:

$$(a+bi)^2 = (a^2-b^2) + 2abi$$

```
D        # duplicate the pair
 n       # square each part: [a^2, b^2]
  Æ      # reduce by subtraction: a^2-b^2
   s     # swap to copy
    P    # take the product: a*b
     ·   # double it: 2*a*b
      ‚  # pair both results: [a^2-b^2, 2*a*b]

```

$$|a+bi|\>2 \Leftrightarrow \sqrt{a^2+b^2}\>2 \Leftrightarrow a^2 + b^2 \> 4$$

```
n        # square each part: [a^2, b^2]
 O       # take the sum: a^2+b^2
  4›     # is this larger than 4: a^2+b^2>4

```

Complete code commented:

```
67ÝƵú*Ž\n@-тn/          # generate the x coordinates: ([0..67]*350-19751)/10000
67Ý                     # push the range [0 .. 67]
   Ƶú*                  # multiply each value by 350
      Ž\n@-             # subtract 19751 from each
           тn/          # divide by 100**2

15D(Ÿт*Ž6À/             # generate the y coordinates: [15..-15]*100/1721
15D                     # push 15 twice
   (                    # negate one copy
    Ÿ                   # take the inclusive range [15 .. -15]
     т*                 # multiply each value by 100
       Ž6À/             # divide by 1721

δ‚                      # create a grid of all x-y pairs
  ε                     # map over each line:
   ε                    #  map over each pair:
    ₅F                } #  iterate 255 times
                        #  (produces the same output as 250 iterations)
      DnÆsP·‚           #    square the current value
             y+         #    add the coordinate
               D        #    duplicate current value
                nO4›©   #    check if the magnitude is larger than 2
                     #  #    if this is the case, stop the loop
                        #    this is necessary because the program will actually crash if trying to continue with infinite values
    „* ®è               #  index with the last result of |z|>2 into the string "* "
 ]                      # close all loops
ø                       # transpose the grid
 J                      # join each line into a single string
  »                     # join lines by newlines

```
> 9 votes

# Answer
# , ~~151~~ 138 bytes

*Edit: -13 bytes thanks to Giuseppe*

```
write(matrix(unlist(Map(rep,c(" ","*"),utf8ToInt("T `#^%^$Y  (S\" /Q3 !I8I;E>D=8  $$?6*!?5, >2! - =!_#")-31)),68)[,c(1:16,15:1)],1,68,,"")

```

Try it online!

Encodes the run lengths of s and `*`s for the top half as a text string, converts these to a matrix (together with itself reversed by row), and outputs using `cat`.

Bearing in mind that actually calculating the Mandelbrot set in  costs only 123 bytes, including full-colour graphic display, this might not be the golfiest solution... but the text encoding was fun anyway...
> 9 votes

# Answer
# Charcoal, ~~74~~ 73 bytes

```
Ｆ¹⁶«Ｆ⁶⁸«≔⁰θ≔⁰ηＦφ«≔⁺⊕×·⁰³⁵⁻κ⁸⁵⁻×θθ×ηηζ≔⁺∕ι¹⁷·²¹⊗×θηη≔ζθ»§ *‹⁺×θθ×ηη⁴»⸿»‖Ｏ↑

```

Don't try it online! Link is to verbose version of code. Performs 1,000 iterations, so it's too slow for TIO. It can be made faster by halving the number of iterations, which costs a byte:

```
Ｆ¹⁶«Ｆ⁶⁸«≔⁰θ≔⁰ηＦ⊘φ«≔⁺⊕×·⁰³⁵⁻κ⁸⁵⁻×θθ×ηηζ≔⁺∕ι¹⁷·²¹⊗×θηη≔ζθ»§ *‹⁺×θθ×ηη⁴»⸿»‖Ｏ↑

```

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

Previous 74-byte compression-based version:

```
”}∧q÷W9r¤1αlIχ‽§heＹ⟧>℅ν⊞P ～E .Q×jn⁵\6⧴<¤< Ｕ#V‽↶³≧JJＤ‴>π v‹»λê= ↨∨｜>zθ9”‖Ｏ↓

```

Try it online! Link is to verbose version of code. Explanation: Works by printing the top half as a compressed string literal and reflecting it.

I also tried printing the bottom half and reflecting, but this increased the byte count to 78 bytes. I also tried printing the reflection of the image and for the bottom half this reduced the byte count to 75 bytes but for the top half it actually increased it to 81 bytes.

I also tried using manual run length encoding but I couldn't even get it as low as 81 bytes.

Previous 75-byte even faster pure Charcoal calculation version (uses the original 250 iterations):

```
Ｆ¹⁶«Ｆ⁶⁸«≔⁰θ≔⁰ηＦ²⁵⁰«≔⁺⊕×·⁰³⁵⁻κ⁸⁵⁻×θθ×ηηζ≔⁺∕ι¹⁷·²¹⊗×θηη≔ζθ»§ *‹⁺×θθ×ηη⁴»⸿»‖Ｏ↑

```

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

If Python exponentiation worked on `inf` then it would have been only 73 bytes:

```
Ｆ¹⁶«Ｆ⁶⁸«≔Ｅ²¦⁰θＦ²⁵⁰ＵＭθ⎇ν⁺∕ι¹⁷·²¹⊗×μ§θ⁰⁺⊕×·⁰³⁵⁻κ⁸⁵⁻Ｘμ²Ｘ§θ¹¦²§ *›⁴ΣＸθ²»⸿»‖Ｏ↑

```

Don't try it online! Link is to verbose version of code.

With some hacky uses of `PythonEvaluate` and `EvaluateVariable` to get around the fact that the version of Charcoal on TIO doesn't support complex numbers I can do it in 58 bytes:

```
Ｆ¹⁶«Ｆ⁶⁸«≔⁰θＦ²⁵⁰≔⁺⁺∕ιＵＶ17.21j⊕×·⁰³⁵⁻κ⁸⁵×θθθ§ *‹▷absθ²»⸿»‖Ｏ↑

```

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

54 bytes using the newer version of Charcoal on ATO:

```
Ｆ¹⁶«Ｆ⁶⁸«≔⁰θＦ²⁵⁰≔⁺⁺∕ιＩ17.21j⊕×·⁰³⁵⁻κ⁸⁵×θθθ§ *‹↔θ²»⸿»‖Ｏ↑

```

Attempt This Online! Link is to verbose version of code. Saves 1 byte by using `Cast("17.21j")` instead of `PythonEvaluate("17.21j")` and 3 bytes by using `Abs(q)` instead of `EvaluateVariable("abs", q)`.
> 7 votes

# Answer
# JavaScript (ES6),  ~~128 ... 124~~  123 bytes

Based on the parameters used by @Sisyphus.

```
f=(k=2138)=>k?`
 *`[k--%69&&-~(g=X=>++n>>8?X*X+Y*Y<4:g(X*X-Y*Y-k%69*.035+.3699,Y=2*X*Y-(16+~(k/69))/17.21))(Y=n=0)]+f(k):''

```

Try it online!

### Commented

```
f = (k = 2138) =>            // f is a recursive function taking a counter k
                             // which encodes: x = k mod 69
                             //                y = floor(k / 69) - 15
k ?                          // if k is not equal to 0:
  `\n *`[                    //   character lookup:
    k-- % 69 &&              //     append a linefeed if k mod 69 = 0
                             //     (decrement k afterwards)
    -~(                      //     otherwise use the result of ...
      g = X =>               //     ... the recursive function g which takes X
                             //     and also uses Y and an iteration counter n
      ++n >> 8 ?             //       increment n; if it's not equal to 256:
        X * X + Y * Y < 4    //         return true if X² + Y² is less than 4
      :                      //       else:
        g(                   //         do a recursive call to g with:
          X * X - Y * Y      //           the updated X:
          - k % 69 * .035    //             X² - Y² - x * 0.035 + 0.3699
          + .3699,           //
          Y = 2 * X * Y      //           the updated Y:
          - (16 + ~(k / 69)) //             2XY + y / 17.21
          / 17.21            //
        )                    //         end of recursive call
    )(Y = n = 0)             //     initial call to g with X = Y = n = 0
  ]                          //   end of character lookup
  + f(k)                     //   append the result of a recursive call
:                            // else:
  ''                         //   stop the recursion

```
> 7 votes

# Answer
# Python 3, <sup>~~218 217 200~~</sup> 191 bytes

```
lambda:a+['*'*64]+a[::-1]
D=2**31
a=[f'{y:68b}'.translate(' *'*25)for y in[4**7,30<<12,63<<12,31<<12,3143680,125828992,33554412,D//8-8,D//4-2,D-1,D-2,6082*D-1,16378*D-1,32766*D-2,458750*D-4]]

```

Try it online!

Terrible score, but I wanted to see how it would look with bitmasks in the style of a typical challenge

*-1 thanks to @thedefault*

*-17 thanks to @xnor*

*-9 thanks to @benrg*

---

# Python 3, 165 bytes

```
lambda:a+["*"*64]+a[::-1];a=[''.join((i-31)%64*' *'[i-31>>6]for i in j)for j in b'T`@Rc@Qe@Rd@M` h@Hb o@Js a!@Gx@F{@D~@D}@7` d$\x7f@6j!\x7f@5l ~@1a m }'.split(b"@")]

```

Try it online!

Run-length encoded.
> 6 votes

# Answer
# Perl 5, 127 bytes

```
say for@o='e1q4o6o5j119d31@bD12ZIZLVOUNI1155PG;2PF=1OC21>1N2p4'=~s/./($i++%2?'*':$")x(-48+ord$&)/ger=~/.{68}/g,reverse@o[0..14]

```

Try it online!

```
say                                        #prints each line + \n newline at end
for @o=                                    #for all lines, also saved in array @o
'e1q4o6o5j119d31@bD12ZIZLVOUNI1155PG;2PF=1OC21>1N2p4' #lengths for spaces and *s
=~ s/./ ($i++%2?'*':$") x (-48+ord$&) /ger #...decode into lengths and output
                                           #...space or * of each length
=~ /.{68}/g,                               #...partition lines on every 68th char
reverse@o[0..14]                           #add mirror of first 15 lines

```
> 6 votes

# Answer
# Bubblegum, 97 bytes

Using `zopfli --i 10000 --deflate -c mandlebrot.txt | xxd` and no trailing spaces. Increasing iterations beyond 10000 doesn't seem to make a difference.

```
00000000: c595 a901 c040 0c80 7ca6 8866 ff01 2bb1  .....@..|..f..+.
00000010: 574c f0d0 debf 05a6 4850 3c88 e216 9105  WL......HP<.....
00000020: f869 829a f63b 5ab2 30c1 6f3f 81c4 06d2  .i...;Z.0.o?....
00000030: 23a5 e19a 9908 1124 4700 0933 a2f4 d618  #......$G..3....
00000040: 3afd 1ffa 545c ac49 df1d 619b f6c6 c1c1  :...T\.I..a.....
00000050: 15e4 ee0e eb97 a8b0 c114 4e5e a8d9 02f3  ..........N^....
00000060: 01                                       .

```

Try it online!
> 6 votes

# Answer
# Python 2.6, 128 bytes

```
print"x\xda\xbd\x94\xa1\x15\x001\x0c\x85|\xa7@\xb3\xff\x80'\xbf\x0e\xe2\xf0\xf0\xfa\xda4\x14|E\xd2\xe2i\x14)\xa2\xa8\x1eM\x9dv\xb7\x99\xeb@_\xf4\xc7\x0b\x81\xd6p\xf4Hl\x88\xaaK\x84\x88#G\x1c\xca\xbd\xa1xi<;\xfd\x0c\xfd*\xfe\x7f\x93>\x1d}LC\xe3\xff\x8f\x1b\xd6G\x88\xf0\xe7\x12\xad\xcb{T\xd1*R=\xf0\x03-<\x12|".decode("zip")

```

This is an ASCII-fied version of the program. The actual program is encoded in latin-1 and looks like:

```
00000000: 7072 696e 7422 78da bd94 a115 5c78 3030  print"x.....\x00
00000010: 310c 857c a740 b3ff 8027 bf0e e2f0 f0fa  1..|.@...'......
00000020: da34 147c 45d2 e269 1429 a2a8 1e4d 9d76  .4.|E..i.)...M.v
00000030: b799 eb40 5ff4 c70b 81d6 70f4 486c 88aa  ...@_.....p.Hl..
00000040: 4b84 8823 471c cabd a178 693c 3bfd 0cfd  K..#G....xi<;...
00000050: 2afe 7f93 3e1d 7d4c 43e3 ff8f 1bd6 4788  *...>.}LC.....G.
00000060: f0e7 12ad cb7b 54d1 2a52 3df0 032d 3c12  .....{T.*R=..-<.
00000070: 7c22 2e64 6563 6f64 6528 227a 6970 2229  |".decode("zip")

```

Since Python 2.7, the default encoding of a file is now ASCII instead of Latin-1, so you need to prepend the file with `#coding=L1` for the smaller version to run.

Try it online!

This is quite a boring answer: I zipped the original image into a string S then run `print S.decode('zip')`.
> 3 votes

# Answer
# C (gcc), ~~212~~ 200 bytes

```
double atof(),x;s;Y=16;main(a,b)int**b;{for(;--Y+16;puts(""))for(x=-1.975;s=x<2;x+=.035,printf(L" *"+s/251))for(_Complex y=x+Y*.0581i,z=a/3*y;s++<251&cabs(z=z*z+(a>2?atof(b[1])+1i*atof(b[2]):y))<2;);}

```

Try it online!

Thanks to @KevinCruijssen for -1. Julia set coordinates can be added as command line args.

Slightly golfed less.

```
double atof(),x;s;
Y=16;
main(a,b)int**b;{
  for(;--Y+16;puts(""))
    for(x=-1.975;s=x<2;x+=.035,printf(L" *"+s/251))
      for(_Complex y=x+Y*.0581i,z=a/3*y;s++<251&cabs(z=z*z+(a>2?atof(b[1])+1i*atof(b[2]):y))<2;);
}

```
> 2 votes

# Answer
# C, gcc, ~~141~~ ~~140~~ ~~138~~ ~~137~~ 136 bytes

Try it

```
y=16,x;main(i){for(;--y+16;puts(""))for(x=68;x--;printf(L" *"+i/221))for(typeof(0.i)z=i=0;cabs(z)<2&i++<220;z=z*z-x*.035+.37+y*.0581i);}

```

Compile using gcc. `-lm` may be required.
> 2 votes

# Answer
# Pyth, 87 bytes

```
jsX0_Bms.e*b@" *"kCMdc."n
K{„‹–¥\dmnl4’_·N—2#‘¦óE,Á–¦#Óç>§óÔí¤:—A1åìJV~t…Á"\n*\*64
```

Try it here!

*Above preview does not display all characters in the code! The link leads to a working and copyable source.*
> 1 votes

# Answer
# Deadfish~, 1700 bytes

```
{i}{i}{i}ii{c}{c}{c}{c}{c}ccc{i}c{d}{c}cccc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{c}c{i}cccc{d}{c}ccc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{c}{i}cccccc{d}{c}cc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{c}c{i}ccccc{d}{c}cc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}cccccc{i}c{d}c{i}ccccccccc{d}{c}c{d}{d}ddc{i}{i}ii{c}{c}{c}{c}c{i}ccc{d}c{i}{c}cccccc{d}ccccccc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}ccc{i}{c}{c}{d}c{i}cc{d}cc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{i}{c}{c}ccccc{d}ccc{d}{d}ddc{i}{i}ii{c}{c}{c}ccccccccc{i}{c}{c}cccccccc{d}c{d}{d}ddc{i}{i}ii{c}{c}{c}ccccccc{i}{c}{c}{c}c{d}{d}{d}ddc{i}{i}ii{c}{c}{c}ccccccc{i}{c}{c}{c}{d}c{d}{d}ddc{i}{i}ii{c}{c}cccc{i}c{d}c{i}ccccc{d}ccccc{i}{c}{c}{c}cc{d}{d}{d}ddc{i}{i}ii{c}{c}ccc{i}{c}c{d}cc{i}{c}{c}{c}cc{d}{d}{d}ddc{i}{i}ii{c}{c}cc{i}{c}ccc{d}c{i}{c}{c}{c}c{d}c{d}{d}ddc{i}{i}ii{c}cccccccc{i}cc{d}c{i}{c}cccc{d}c{i}{c}{c}{c}{d}cc{d}{d}ddc{i}{i}{i}ii{c}{c}{c}{c}{c}{c}cccc{d}cccc{d}{d}ddc{i}{i}ii{c}cccccccc{i}cc{d}c{i}{c}cccc{d}c{i}{c}{c}{c}{d}cc{d}{d}ddc{i}{i}ii{c}{c}cc{i}{c}ccc{d}c{i}{c}{c}{c}c{d}c{d}{d}ddc{i}{i}ii{c}{c}ccc{i}{c}c{d}cc{i}{c}{c}{c}cc{d}{d}{d}ddc{i}{i}ii{c}{c}cccc{i}c{d}c{i}ccccc{d}ccccc{i}{c}{c}{c}cc{d}{d}{d}ddc{i}{i}ii{c}{c}{c}ccccccc{i}{c}{c}{c}{d}c{d}{d}ddc{i}{i}ii{c}{c}{c}ccccccc{i}{c}{c}{c}c{d}{d}{d}ddc{i}{i}ii{c}{c}{c}ccccccccc{i}{c}{c}cccccccc{d}c{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{i}{c}{c}ccccc{d}ccc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}ccc{i}{c}{c}{d}c{i}cc{d}cc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}c{i}ccc{d}c{i}{c}cccccc{d}ccccccc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}cccccc{i}c{d}c{i}ccccccccc{d}{c}c{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{c}c{i}ccccc{d}{c}cc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{c}{i}cccccc{d}{c}cc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{c}c{i}cccc{d}{c}ccc{d}{d}ddc{i}{i}ii{c}{c}{c}{c}{c}ccc{i}c{d}{c}cccc{d}{d}ddc

```

Try it online!
> 0 votes

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


title: Draw an ASCII Lightning Bolt

text:
# Question
Title: Draw an ASCII Lightning Bolt
## Introduction

Partly inspired by this StackOverflow question, let's draw an ASCII Lightning Bolt.

Write a program that takes a positive Integer `n` via STDIN or command line and outputs the ASCII Lightning Bolt below.

**Input**

Positive Integer `n` representing the number of lightning zig-zag tiers to draw.

**Example Output**

n=1

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

```

n=2

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

```

n=3

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

```

n=4

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

```

. . . etc

---

**Additional notes**

* You may write a function that takes `n` as the only argument and prints or returns the string.
* Trailing spaces and new lines are okay.
* No leading spaces except where appropriate for the designated pattern.
* **Shortest code in bytes wins.**

# Answer
# Java, ~~201~~ ~~196~~ ~~189~~ ~~186~~ 182 bytes

Obviously not the best, but it *is* in Java.

```
class I{public static void main(String[]a){System.out.print(("__\na a"+new String(new byte[new Byte(a[0])-1]).replace("\0","__a\\  __\\\n a")+"  a   \\/").replace("a","\\ \\\n"));}}

```
> 19 votes

# Answer
# CJam, 41 bytes

```
":¡ö cQïO[nu÷&,"255b6b"
 _\/X"f='X/~ri(*\

```

I can probably squeeze a few more bytes out, but here's some compression. I picked a base which would lead to no unprintables.

Try it online.

The lightning bolt is split into `top + middle * (input-1) + bottom`, where `top`, `middle`, `bottom` (compressed using base conversion) are

```
__
\.

  \
.\.\
__\.\
\..__

    \
.\.\
..\.\
...\/

```

*(Spaces are marked with `.`s)*

## 40 bytes

Thanks to Optimizer

```
"¹Ñ³Û-+ÎDx^áÐ"254b6b"
_\ 0/"f=)/~ri(*\
```
> 10 votes

# Answer
# JavaScript (*ES6*) 76

Using template string, the 3 newlines are significant and counted.

Test running the snippet (Firefox only)

```
f=n=>`__
1 1${`__1\\  __\\
 1`.repeat(n-1)}  1   \\/`.replace(/1/g,`\\ \\
`)

// TEST

go=_=>O.innerHTML=f(I.value)

go()
```

```
N: <input id=I value=3><button onclick='go()'>Test</button>
<pre id=O></pre>
```
> 8 votes

# Answer
## PowerShell, 72 63 bytes

Stupid Windows and your \r\n... This could have been 67 59 bytes!

```
%{$a="\ \
";"__
$a"+" $a`__$a\  __\
"*($_-1)+" $a  $a   \/"}

```
> 7 votes

# Answer
# Pyth, 60 54 bytes (Thanks @isaacg)

My first attempt at Pyth, probably very bad.

```
"__
\ \ "VtQ" \ \
__\ \
\  __\ ")" \ \
  \ \
   \/

```

Verify it here.
> 6 votes

# Answer
# PHP - ~~84 79~~ 78 bytes

```
<?php
define('N',3); // <- didnt count these bytes as TS said I could take var N as input
?>
<?="__
\ \
 \ \ ".str_repeat("
__\ \
\  __\
 \ \ ",N-1)."
  \ \
   \/"

```

View the result source or wrap in `<pre />` to check results. The newlines are required in the code.
The -1 could be moved to the `define`, but I considered that a cheat.

1st improvement: replace `\n` with actual newlines
2nd: Since I can define a var, I used a CONTANT, safes the `$`. +an unneeded space in str\_repeat
3rd: Accidentally removed the -1, but saved a byte by using `<?=` instead of echo.
> 6 votes

# Answer
## \>\<\> (Fish), 409 bytes

Run by `fish.py bolt.fish --value n` where `bolt.fish` is the program name and `n` is your positive integer input.

```
\
\         "__"       a
\         "\ \"      a
\         " \ \"     a
\r1-:?!vr "__\ \"    a
\     !0  "\  __\"   a
\     !6  " \ \"  a04.
>r   9a.  "__\ \"    \
      /   "\  __\"  \
       /  " \ \"   \
        / "  \ \" \
         /"   \/"\
                 aaaaa
|o|!~r           /
         \        /
        \          /
       \            /
      \              /

```

It's not short, but it looks cool. My attempt was to try to make it look like a lightning strike. Also, it always errors on completion.
> 5 votes

# Answer
## CJam, 50 bytes

```
"__
\ \
"q~(" \ \
__\ \
\  __\
"*" \ \
"_S\"   \/"

```

Try it here
> 4 votes

# Answer
## Brainfuck, 164 bytes

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

```

With comments:

```
Initialise n and character set with i as counter
Memory = in♪\ _/
,<++++++++++++++++[>--->+>++++++>++>++++++>+++<<<<<<-]>->--->---->>->-

Draw top of lightning bolt
<..<<<.>.>.<.<.>>.<.>.<.<.<

Draw lightning bolt zigzags
[>>>>..<<.>.<.<.>.>..>..<<.<.>>.<.>.<.<.<-]

Draw lightning bolt tip
>>>..<.>.<.<.>>...<.>>>.

```

Okay, how this Brainfuck answer beating Java and C#?
> 4 votes

# Answer
# Perl, 69+1

69 characters, plus 1 for the `-n` command line switch to fetch input from stdin.

```
$s="\\ \\$/";print"__$/$s $s".("__$s\\  __\\$/ $s"x--$_)."  $s   \\/"

```

### Usage example:

```
perl -ne '$s="\\ \\$/";print"__$/$s $s".("__$s\\  __\\$/ $s"x--$_)."  $s   \\/"' <<<"2"
__
\ \
 \ \
__\ \
\  __\
 \ \
  \ \
   \/

```
> 3 votes

# Answer
# Javascript (ES6), 86

Not gonna win, but I love 1-line solution and I hate slashes.

```
f=n=>atob("X18KXCBc"+"CiBcIFwKX19cIFwKXCAgX19c".repeat(n-1)+"CiBcIFwKICBcIFwKICAgXC8")

```
> 3 votes

# Answer
# C, 101 bytes

My not so original implementation in c

```
f(n){puts("__\n\\ \\");for(;--n;puts(" \\ \\\n__\\ \\\n\\  __\\"));puts(" \\ \\\n  \\ \\\n   \\/");}

```
> 3 votes

# Answer
# C#, 166 bytes

```
class I{static void Main(string[]a){System.Console.Write(("__\na a"+"".PadLeft(int.Parse(a[0])-1).Replace(" ",@"__a\  __\
 a")+@"  a   \/").Replace("a",@"\ \
"));}}

```

**EDIT 1:** improved the result from 186B to 173B
**EDIT 2:** saved 1B by using `PadLeft` instead of `PadRight`
**EDIT 3:** saved 8B by dropping `PadLeft`'s second parameter and using verbatim string literals
> 3 votes

# Answer
# C#, 221 Bytes

```
class C{static void Main(string[]n){int e=System.Int32.Parse(n[0]);var o=@"__{0}\ \{0} \ \{0}";while(e>1){o+=@"__\ \{0}\  __\{0} \ \{0}";e--;}System.Console.WriteLine(o + @"  \ \{0}   \/{0}",System.Environment.NewLine);}}

```

This isn't the best, or the smallest answer, but I figured I'd give it a try. Fsacer's answer is much shorter and I think you should check it out. I just decided to do this just as an alternative method really.
> 3 votes

# Answer
# Awk, 101+8 bytes

101 characters, plus 8 for `-v n=$1` to get integer from shell.

```
'{l="\\ \\";print"__\n"l"\n "l;for(i=1;i<n;++i)print"__"l"\n\\  __\\\n "l}END{print"  "l"\n   \\/"}'

```

New to this SE site, unclear if those parameters should count.

### Ungolfed

```
awk
-v n=$1
'{
  l="\\ \\";
  print "__\n"l"\n "l;
  for(i=1; i<n; ++i)
    print "__"l"\n\\  __\\\n "l
}
END
{
  print "  "l"\n   \\/"
}'

```

### Usage example:

```
lightning() { echo | awk -v n=$1 '{l="\\ \\";print"__\n"l"\n "l;for(i=1;i<n;++i)print"__"l"\n\\  __\\\n "l}END{print"  "l"\n   \\/"}'; }
lightning 3
__
\ \
 \ \
__\ \
\  __\
 \ \
__\ \
\  __\
 \ \
  \ \
   \/

```
> 3 votes

# Answer
# Python 97 82 78char:

```
print(("__\nl l"+"__l\  __\\\n l"*~-input()+"  l   \/").replace('l','\ \\\n'))

```

This is my first code golf

# @(^\_^)@

Test here
> 3 votes

# Answer
# Python 3, ~~126~~ ~~118~~ 117 bytes

Just something to get us started with.

```
n=int(input())
p=print
p('__\n\\ \\')
for i in[0]*~-n:p(r''' \ \
__\ \
\  __\
''',end='')
p(r''' \ \
  \ \
   \/
''')

```
> 2 votes

# Answer
# C, ~~119~~ 108 bytes

```
p(t){for(;t;t/=4)putchar(" \\_\n"[t%4]);}main(c){for(p(13434);p(836),--c;p(57154842));p(265488);puts("/");}

```

# First attempt, 150 bytes

```
v(a){putchar(a);}s(b){b--?v(32),s(b):v(92);}l(b){s(b);s(1);v(10);}main(c){for(puts("__\n\\ \\");l(1),--c;puts("__\\ \\\n\\  __\\"));l(2);s(3);v(47);}

```

`main` is accepting an int argument, so run like this: `./lightning . . .` to pass `4` as argument.
> 2 votes

# Answer
# Python 2, 76 bytes

```
print'__\n\ \\\n \ \\\n'+r'''__\ \
\  __\
 \ \
'''*~-input()+'  \ \\\n   \/'

```

Just print the first three lines, then print the next three lines `n-1` times, and then print the final 2 lines. All in one go.

And here is a nice try at an alternative that (unfortunately) uses exactly the same number of bytes:

```
print('__\n| |'+'__|\  __\\\n |'*~-input()+'  |   \/').replace('|','\ \\\n')

```
> 2 votes

# Answer
## F#, 98 characters, 105 bytes

```
let l n=(@"__♪◙\z"+String.replicate(n-1)@" \z__\z\  __\♪◙"+ @" \z  \z   \/").Replace("z"," \\\n")

```
> 2 votes

# Answer
# Pascal: ~~149~~ ~~142~~ ~~141~~ 137 characters

```
var n:Word;begin
Read(n);Writeln('__'#10'\ \'#10' \ \');for n:=2to n do Writeln('__\ \'#10'\  __\'#10' \ \');Write('  \ \'#10'   \/')end.

```

After all, Pascal's only golfing strength is that backslashes need no escaping…
> 2 votes

# Answer
# CJam 54 Chars

not the shortest, but since i started CJam today, im happy with it.

```
rd(:T;{'__}:W~N{'\:XSXN}:V~SV{WVXSSWXNSV;N}T*SSVSSSX'/

```

Try it
> 2 votes

# Answer
# Google Sheets, 60 Bytes

Anonymous worksheet function that takes input from range `[A1]` and outputs to the calling cell.

```
="__
\ \
 \ \
"&REPT("__\ \
\  __\
 \ \
",A1-1)&"  \ \
   \/

```
> 2 votes

# Answer
# Perl 5, 58 + 1 (`-n`) = 59 bytes

```
say'__
\ \
 \ \
'.'__\ \
\  __\
 \ \
'x--$_.'  \ \
   \/'

```

Try it online!
> 2 votes

# Answer
# SpecBAS - 135 104 bytes

The apostrophe in PRINT statements moves cursor to a new line.

SpecBAS lets you incorporate ASCII characters in a string via way of `#n`, so have built in some carriage returns (ASCII 13).

Built a string up using carriage returns and other characters, then used `REP$` to repeat it the required number of times.

```
1 LET b$="\ \": INPUT n: PRINT "__"'b$+REP$(#13" "+b$+#13"__"+b$+#13"\  __\",n-1)'" ";b$'"  ";b$'"   \/"

```
> 1 votes

# Answer
# PHP 155

```
$l=PHP_EOL;echo$l;echo "__$l";for($i=0;$i<$argv[1];$i++){if($i>=1)echo "__\\ \\$l\\  __\\$l";else echo "\\ \\$l";echo " \\ \\$l";}echo "  \\ \\$l   \\/$l";

```

Ungolfed Version

```
$n = $argv[1];

echo PHP_EOL;
echo '__'.PHP_EOL;
for($i=0;$i<$n;$i++)
{
    if($i>=1) {
        echo '__\\ \\'.PHP_EOL.'\\  __\\'.PHP_EOL;

    }
    else
    {
        echo '\\ \\'.PHP_EOL;
    }
    echo ' \\ \\'.PHP_EOL;

}
echo '  \\ \\'.PHP_EOL;
echo '   \\/';
echo PHP_EOL;

```
> 1 votes

# Answer
# Java, ~~183~~ 180 bytes

```
class L{public static void main(String[]a){String b="__\n\\ \\\n \\ \\\n";for(int i=1;i<new Long(a[0]);++i)b+="__\\ \\\n\\  __\\\n \\ \\\n";System.out.print(b+"  \\ \\\n   \\/");}}

```

# Lua, 110 bytes

```
function l(n)print("__\n\\ \\\n \\ \\\n"..string.rep("__\\ \\\n\\  __\\\n \\ \\\n",n-1).."  \\ \\\n   \\/")end

```
> 1 votes

# Answer
# Retina, 46 bytes

```
.+
__#r r$0x  r   \/
1x

1
__r\  __\# r
r
\ \#

```

Takes input as unary.

Each line should go to its own file and `#` should be changed to newline in the files. This is impractical but you can run the code as is, as one file, with the `-s` flag, keeping the `#` markers. You can change the `#`'s to newlines in the output for readability if you wish. E.g.:

```
> echo -n 11|retina -s lightning|tr # '\n'
__
\ \
 \ \
__\ \
\  __\
 \ \
  \ \
   \/

```

The algorithm is very simple. The pairs of lines (regex - substitute pairs) do the following substitution steps:

* Surround input with the top and bottom of the lightning.
* Subtract `1` from the unary input.
* Change every unary digit into the middle part of the lightning.
* Decompress the compressed `\ \` parts of the lightning to get the desired output.
> 1 votes

# Answer
# Powershell, 59 bytes

```
'__
\ \'
,' \ \
__\ \
\  __\'*--$args[0]
' \ \
  \ \
   \/'

```

Test script:

```
$f = {

'__
\ \'
,' \ \
__\ \
\  __\'*--$args[0]
' \ \
  \ \
   \/'

}

&$f 1
&$f 2
&$f 3
&$f 4

```

Output:

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

```

Explanation:

This script is traditional `top`+`middle`+`bottom`. There is only one smart thing: the comma before the middle string force to repeat an array element rather than a string. Therefore, each `middle` is displayed on a new line.
> 1 votes

# Answer
### x86\_16 machine code - 84 bytes

```
8B CB      MOV CX, BX
49         DEC CX
B4 09      MOV AH, 09H
        HEAD:
BA 02 01   MOV DX, OFFSET LIGHTNING_HEAD
CD 21      INT 21H
85 C9      TEST CX, CX
74 09      JE TAIL
        BODY:
BA 1F 01   MOV DX, OFFSET LIGHTNING_LOOP_STR
CD 21      INT 21H
E3 02      JCXZ TAIL
E2 F7      LOOP BODY
        TAIL:
BA 12 01   MOV DX, OFFSET LIGHTNING_TAIL
CD 21      INT 21H
B8 00 4C   MOV AX, 4C00H
CD 21      INT 21H

LIGHTNING_HEAD      DB 05FH, 05FH, 00AH, 00DH, 05CH, 020H, 05CH, 00AH, 00DH, 020H
                    DB 05CH, 020H, 05CH, 00AH, 00DH, 024H
LIGHTNING_TAIL      DB 020H, 020H, 05CH, 020H, 05CH, 00AH, 00DH, 020H, 020H, 020H
                    DB 05CH, 02FH, 024H
LIGHTNING_LOOP_STR  DB 05FH, 05FH, 05CH, 020H, 05CH, 00AH, 00DH, 05CH, 020H, 020H
                    DB 05FH, 05FH, 05CH, 00AH, 00DH, 020H, 05CH, 020H, 05CH, 00AH
                    DB 00DH, 024H

```

Tested using DOSBox
> 1 votes

# Answer
# CSASM v2.1.2.3, 144 bytes

```
func main:
in ""
conv i32
pop $a
push "__\n\\ \\\n \\ \\\n"
push "__\\ \\\n\\  __\\\n \\ \\\n"
dec $a
push $a
mul
add
push "  \\ \\\n   \\/"
add
print
ret
end

```

**Commented:**

```
func main:
    ; Get the input, convert it to an integer then store it in the accumulator
    in ""
    conv i32
    pop $a

    ; Push the first section of the lightning bolt
    push "__\n\\ \\\n \\ \\\n"

    ; Duplicate the middle section of the lightning bolt
    push "__\\ \\\n\\  __\\\n \\ \\\n"
    dec $a
    push $a
    mul

    ; Append the duplicated sections
    add

    ; Append the third section of the lightning bolt
    push "  \\ \\\n   \\/"
    add

    ; Print the result
    print
    ret
end

```
> 1 votes

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


title: Make some Prime Squares!

text:
# Question
Title: Make some Prime Squares!
**What is a Prime Square?**

A Prime Square is a square where all four edges are different prime numbers.
But which ones?
And how do we construct them?

**Here is an example of a 4x4 Prime Square**

```
1009
0  0
3  0
1021

```

First we start from the upper left corner. We are working **clockwise**.
We pick the smallest prime number having `4` digits which is **1009**.

Then we need the smallest prime number having `4` digits, which starts with a `9`. This is **9001**

The third (4-digits) prime number must have `1` as its last digit (because **9001** ends with `1`)
and also be the smallest 4-digit prime with this property that has **not been used before as an edge**.
This prime number is **1021**

The fourth prime number must have `4` digits, **start** with a `1` (because **1009** starts with a `1`) and **end** with a `1` (because **1021** starts with a `1`)
The smallest 4-digit prime number with this property that *has not been used before as an edge* is **1031**

**Your TASK**

You will be given an integer `n` from `3 to 100`
This number will be the dimensions of the `n x n` square
Then you must **output this square exactly in the form of the following test cases**

**Test Cases**

```
n=3
Output

101
3 0
113

n=5
Output

10007
0   0
0   0
9   0
10061

n=7
Output

1000003
0     0
0     0
0     0
0     0
8     1
1000037

n=10
Output

1000000007
0        0
0        0
0        0
0        0
0        0
0        0
1        0
8        0
1000000021

n=20
Output

10000000000000000051
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                  0
0                  0
9                  8
10000000000000000097

```
* Input and output can be given by any convenient method.
* You can print it to STDOUT or return it as a function result.
* Either a full program or a function are acceptable.
* Any amount of extraneous whitespace is acceptable, so long as the numbers line up appropriately
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

**EDIT**
This is possible for all `n`
Here are the primes for `n=100`

```
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000289
9000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000091
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000711
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002191

```

And for those of you that you don't think this is possible \[here are ALL the test cases\]\[1\]

# Answer
# 05AB1E, ~~64~~ ~~63~~ ~~56~~ ~~53~~ ~~48~~ 46 bytes

```
°ÅPIùćÐ4FˆθUKD.ΔθyXÅ?yXÅ¿)¯gè}ÐNĀiR}¦}I¯JŽ9¦SΛ

```

-1 byte thanks to *@Mr.Xcoder*
-5 bytes thanks to *@Grimy*.

Try it online. (Times out for \\$n\>4\\$. Here the slightly faster **53 bytes** version which times out for \\$n\>7\\$ instead.)

**Explanation:**

```
°                 # Raise the (implicit) input to the power 10
 ÅP               # Get a list of primes within the range [2, n^10]
   Iù             # Only keep those of a length equal to the input
ć                 # Extract the head; push the remainder-list and first prime separately
 Ð                # Triplicate this first prime
4F                # Loop 4 times:
  ˆ               #  Add the (modified) prime at the top of the stack to the global array
  θU              #  Pop and store the last digit of the prime in variable `X`
  K               #  Remove this prime from the prime-list
  D               #  Duplicate the prime-list
   .Δ             #  Find the first prime `y` in the prime list which is truthy for:
     θ            #   Get the last digit of prime `y`
     yXÅ?         #   Check if prime `y` starts with variable `X`
     yXÅ¿         #   Check if prime `y` ends with variable `X`
     )            #   Wrap the three results above into a list
      ¯g          #   Get the amount of items in the global array
        è         #   And use it to index into these three checks
                  #   (Note that only 1 is truthy for 05AB1E, so the `θ` basically checks
                  #    if the last digit of prime `y` is 1)
    }Ð            #  Triplicate the found prime
      NĀi }       #  If the loop index is 1, 2, or 3:
         R        #   Reverse the found prime
      ¦           #  And then remove the first digit of the (potentially reversed) prime
}                 # After the loop:
 I                # Push the input as length
 ¯J               # Push the global array joined together to a single string
 Ž9¦S             # Push compressed integer 2460 converted to a list of digits: [2,4,6,0]
 Λ                # Draw the joined string in the directions [2,4,6,0] (aka [→,↓,←,↑])
                  # of a length equal to the input
                  # (which is output immediately and implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ž9¦` is `2460`. And see this 05AB1E tip of mine to understand how the square is output with the `Λ` Canvas builtin.

The relevant code for printing the Canvas in a square is: `NĀiR}¦` and `I¯JŽ9¦SΛ`. Let's take `n=4` as example. The primes it will find with the rest of the code are `[1009,9001,1021,1031]`. The first code-part mentioned in this paragraph will save them as this instead: `[1009,"001","201","301"]`. The second code part of this paragraph will then use the Canvas builtin `Λ` with options:
\- \\$a\\$ (side-length) = `I`: the input
\- \\$b\\$ (string to print) = `¯J`: the global array joined together (so `"1009001201301"` for `n=4`)
\- \\$c\\$ (direction) = `Ž9¦S`: the directions `[2,4,6,0]`, which will be `[→,↓,←,↑]` respectively
> 4 votes

# Answer
# 05AB1E, ~~35~~ ~~33~~ ~~32~~ 31 bytes

*-1 byte thanks to Kevin Cruijssen*

```
°ÅPIùΔÐXθÅ?Ïн©KX®¦«UNií]IXŽ9¦SΛ

```

Try it online!

Explanation:

```
°                 # 10 to the power of the input
 ÅP               # list of primes up to that
   Iù             # keep only those with the same length as the input

Δ                 # repeat until the list doesn't change
# This ends up doing a ton of unneeded work. 4F (to loop 4 times) would be
# enough, but Δ is shorter and the extra iterations don’t cause issues.
# At the start of each iteration, the stack only contains the list of primes,
# and the variable X contains the current list of digits we’ll want to print.
# Conveniently, X defaults to 1, which is our first digit.

 Ð    Ï           # push a filtered copy of the list, keeping only…
    Å?            # numbers that start with…
  Xθ              # the last character of X
       н          # get the first element: this is our next prime

 ©                # save this number to the register
  K               # remove it from the list of candidate primes
   X              # push X
    ®             # restore the number from the register
     ¦            # remove its first character
      «           # concatenate it to X
       U          # save the result to X

 Ni               # if N == 1 (second time through the loop)
   í              # reverse all elements in the list of candidate primes
    ]             # closes both this if and the main loop

      Λ           # Draw on a canvas…
I                 # using the input as length…
 X                # using X as the string to draw…
  Ž9¦S            # using [2,4,6,0] (aka [→,↓,←,↑]) as the directions to draw in

```
> 4 votes

# Answer
# JavaScript (ES8),  ~~205 ... 185 177~~  173 bytes

Times out on TIO for \\$n\>8\\$ because of the very inefficient primality test.

```
n=>([a,b,c]=[0,-1,--n,0].map(p=o=i=>o[(g=n=>{for(k=n++;n%k--;);k|o[n]|p[i]-n%10?g(n):p=n+''})((~i?1:p%10)*10**n)|p]=p),[...p].map((d,i)=>i?i<n?d.padEnd(n)+b[i]:c:a).join`
`)

```

Try it online!

## How?

### Step #1: computing the 4 primes

```
[a, b, c] =               // save the 3 first primes into a, b and c
                          // (the 4th prime will be saved in p)
  [ 0, -1, --n, 0 ]       // decrement n and iterate over [ 0, -1, n, 0 ]
  .map(p =                // initialize p (previous prime) to a non-numeric value
       o =                // use o as a lookup table
  i =>                    // for each value i in the list defined above:
    o[                    //   update o:
      (g = n => {         //     g = recursive function taking n
        for(k = n++;      //       set k = n and increment n
            n % k--;);    //       decrement k until it's a divisor of n
                          //       (notice that k is decremented *after* the test)
        k |               //       if k is not equal to 0 (i.e. n is not prime)
        o[n] |            //       or n was already used
        p[i] - n % 10 ?   //       or the last digit of n does not match the connected
                          //       digit (if any) with the previous prime:
          g(n)            //         do a recursive call
        :                 //       else:
          p = n + ''      //         stop recursion and save n coerced to a string into p
      })(                 //     initial call to g with:
        (~i ? 1 : p % 10) //       either 10 ** n if i is not equal to -1
        * 10 ** n         //       or (p % 10) * 10 ** n if i = -1
      ) | p               //     yield p
    ] = p                 //   set o[p] = p
  )                       // end of map()

```

### Step #2: formatting the output

```
[...p].map((d, i) =>      // for each digit d at position i in the last prime:
  i ?                     //   if this is not the first digit:
    i < n ?               //     if this is not the last digit:
      d.padEnd(n)         //       append d, followed by n - 1 spaces
      + b[i]              //       append the corresponding digit in the 2nd prime
    :                     //     else (last digit):
      c                   //       append the 3rd prime
  :                       //   else (first digit):
    a                     //     append the first prime
).join`\n`                // end of map(); join with carriage returns

```
> 2 votes

# Answer
# Jelly, ~~89~~ 82 bytes

```
1ịÆn⁺f®$¿
’⁵*;Æn$©µDṪṪ×ḢÇ©;@©µ;Ç⁺;0ị®¤%⁵n/Ɗ¿$$©;Ç⁺%⁵’$¿$$µŒœṪDZUḊṖj€⁶x³¤ḊḊ¤;@Ḣ;2ị$

```

Try it online!

Could definitely be golfier, but works efficiently for big numbers.
> 2 votes

# Answer
# Jelly, 59 bytes

```
DṪṪ=DZḢṪṪ3ƭƊ}Tịḟ@Ḣ
’;⁸⁵*æR/µḢ;ç¥⁺⁺µŒœṪDZUḊṖj€⁶x³¤ḊḊ¤;@Ḣ;2ị$

```

Try it online!

Shorter but much less efficient Jelly answer.
> 2 votes

# Answer
# JavaScript, 484 bytes

```
i=a=>a?(l=a=>a[(L=a=>a.length-1)(a)])(a)==9?i(r(a))+0:(r=a=>a.substr(0,L(a)))(a)+(+l(a)+1)%10:"1";s=(a,b)=>b?a==b?"":s(l(a)<l(b)?s(r(a),1):r(a),r(b))+Math.abs(l(a)-l(b)):a;m=(a,b)=>!a||!((c=L(a)-L(b))<0||!c&&a<b)&&m(s(a,b),b);p=(a,b="2")=>a/2<b||!(m(a,b)||!p(a,i(b)));a=>{for(M=1+(R=a=>"0".repeat(b))(z=a-1);!p(M=i(M)););for(N=M[z]+R(z);!p(N=i(N)););for(O=1+R(x=a-2);!p(O+n[z]);O=i(O));for(P=R(x);!p(m[0]+P+O[0]);P=i(P));for(S="\n",j=0;j<x;)S+=P[i]+R(x)+N[++i]+"\n";return M+S+O+N[z]}

```

The last unnamed function returns the ASCII art.

Original code

```
function inc(a){
  if (!a) return "1";
  if (a[a.length-1]=="9") return inc(a.substr(0,a.length-1))+"0";
  return a.substr(0,a.length-1)+(+a[a.length-1]+1)%10;
}
function sub(a,b){
  if (!b) return a;
  if (a==b) return "";
  var v=a.substr(0,a.length-1);
  if (a[a.length-1]<b[b.length-1]) v=sub(v,1);
  return sub(v,b.substr(0,b.length-1))+Math.abs(a[a.length-1]-b[b.length-1])
}
function multof(a,b){
  if (!a) return true;
  if (a.length<b.length||a.length==b.length&&a<b) return false;
  return multof(sub(a,b),b);
}
function isprime(a){
  for (var i="2";a/2>i;i=inc(i)){
    if (multof(a,i)) return false;
  }
  return true;
}
function square(a){
  for (var m="1"+"0".repeat(a-1);!isprime(m);m=inc(m)){}
  for (var n=m[a-1]+"0".repeat(a-1);!isprime(n);n=inc(n)){}
  for (var o="1"+"0".repeat(a-2);!isprime(o+n[a-1]);o=inc(o)){}
  for (var p="0".repeat(a-2);!isprime(m[0]+p+o[0]);p=inc(p)){}
  var s="";
  for (var i=0;i<a-2;i++) s+=p[i]+"0".repeat(a-2)+n[i+1]+"\n";
  return m+"\n"+s+o+n[a-1];
}

```

Best and average time complexity: Ω(100nn) in Knuth's big-omega notation(n steps for subtracting n digit numbers, 10n substractions per divisibility check, 10n divisibility check for prime check, and Ω(1) prime checks done).

Worst time complexity: Ω(1000nn) in Knuth's big-omega notation(n steps for subtracting n digit numbers, 10n substractions per divisibility check, 10n divisibility check for prime check, and 10n prime checks done).

I suspect `n=100` takes around 10203 calculations.

~~Sidenote: I validated syntax using UglifyJS 3, and it golfed it way better than I did, saving 47.13% more and earning 282 bytes. However, I decided not to make that my score since I feel like it is cheating.
```
i=(s=>s?9==(l=(l=>l[(L=(l=>l.length-1))(l)]))(s)?i(r(s))+0:(r=(l=>l.substr(0,L(l))))(s)+(+l(s)+1)%10:"1"),s=((L,i)=>i?L==i?"":s(l(L)<l(i)?s(r(L),1):r(L),r(i))+Math.abs(l(L)-l(i)):L),m=((l,r)=>!l||!((c=L(l)-L(r))<0||!c&&l<r)&&m(s(l,r),r)),p=((l,s="2")=>l/2<s||!(m(l,s)||!p(l,i(s))));

```~~

It just deleted the last function since they are never used. It actually became worse if it was assigned and not deleted, imcluding the additional code I added.
> 1 votes

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

```
n=>(g=(m,d=1n)=>((Q=(n,k)=>k?Q(n*n%m,k/2n)*n**(k%2n)%m:1n)(2n,m)==2)>(m in g)?(g[m]=m):g(m+d,d),c=10n**~-n,A=g(c),B=g(A%10n*c),C=g(c+B%10n,10n),[...g(-~c,10n)+''].map((c,i)=>i?i+1<n?c.padEnd(~-n+'')+(''+B)[i]:C:A).join`
`)

```

Try it online!

Reasonable time for large \\$n\\$, only check if \\$2^n≡2\\$ as prime test
> 1 votes

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


title: Can we spell a third number?

text:
# Question
Title: Can we spell a third number?
You are given two strings, each consisting of the English word for a number between **1** and **13**:

```
one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen

```

Your program or function must find out whether it's possible to spell at least one other word from the same list without using any of the letters used in the two input words.

You can follow this link to see a naive, ungolfed implementation along with the table of all possible I/O.

### Examples

* If the input is `['six', 'four']`, we can spell `'ten'`, `'eleven'` or `'twelve'` so the answer is **yes**.
* If the input is `['five', 'seven']`, we can only spell `'two'` but the answer is still **yes**.
* If the input is `['one', 'six']`, we cannot spell any other number so the expected answer is **no**.

### Rules

* You may take the words in any reasonable format. They can be in either lower case (`'one'`), upper case (`'ONE'`) or title case (`'One'`), but it must be consistent.
* You may be given twice the same word.
* The order of the words is not guaranteed (i.e. your code must support both `['four', 'six']` and `['six', 'four']`).
* You may return either truthy / falsy values (inverting the meaning is permitted) or two distinct and *consistent* values of your choice.
* This is .

# Answer
> 28 votes
# , 19 bytes

Takes input as `six four`. As the input range is limited, I just deleted characters while the output stayed the same. :-) Reads like "if there is no `e` in the input, or if there are no `t` and `o` in the input, … then we can spell another number."

```
e.e`to`for`si-.~&><

```

Try it online!

```
e.e`to`for`si-.~&><
                &>< boxing stuff
  e`to`for`si       for each e, to, for, si:
             -.~      delete from the input any character from the list
e.                  is the input still in the results, i.e. is there any
                      case were no character got deleted?

```

# Answer
> 6 votes
# Jelly, 15 bytes

```
“Œ}İs~#²ð»Ḳḟ@€i

```

Try it online!

Adaptation of xash's J answer. Returns a non-zero integer (truthy) for **yes** and `0` (falsey) for **no**. The footer generates all test cases and tests them (mapping truthy and falsey to `1` and `0` for readability)

My original answer was 38 bytes:

```
“}ICẸƁÄĊ}¿ȥ~ṢṄO4⁴ƓX9Ỵ9ÑẠỤẠḣ|¿;»ḲiⱮ€Q§Ạ

```

Try it online!

Returns a falsey value if the answer is **yes** and a truthy value otherwise

Basic naive compression approach, ~~I'm sure there's a shorter answer out there that exploits some property that's shorter~~

Both input in the form `six four`

## How they work

```
“Œ}İs~#²ð»Ḳḟ@€i - Main link. Takes s on the left
“Œ}İs~#²ð»      - "e to for si"
          Ḳ     - ["e", "to", "for", "si"]
             €  - Over each k of these:
           ḟ@   -   Yield s with characters in k removed
              i - Index of s in this list or 0

```

And the 38 byte compression version:

```
“}ICẸƁÄĊ}¿ȥ~ṢṄO4⁴ƓX9Ỵ9ÑẠỤẠḣ|¿;»ḲiⱮ€Q§Ạ - Main link. Takes s on the left
“}ICẸƁÄĊ}¿ȥ~ṢṄO4⁴ƓX9Ỵ9ÑẠỤẠḣ|¿;»        - "one two ... twelve thirteen"
                               Ḳ       - Split on spaces
                                   Q   - s deduplicated
                                  €    - Over each number n:
                                 Ɱ     -   Over each character c in s:
                                i      -     Index of c in n else 0
                                    §  - Sums
                                     Ạ - Does not contain 0

```

# Answer
> 5 votes
# K (oK), ~~28~~ 24 bytes

```
{|/(x~x^)'$`e`to`for`si}

```

A port of @xash's excellent J answer.

Try it online!

# Answer
> 5 votes
# Retina 0.8.2, 23 bytes

```
G`t|o
G`f|o|r
G`s|i
G`e

```

Try it online! Link includes all 169 possible inputs. Leaves the input unchanged if no numbers are possible, but outputs nothing if other numbers are possible. Explanation:

```
G`t|o

```

The input must contain `t` or `o` in order to prevent `two` from being possible; only `two` and `twelve` contain `w`, so if there's a `w` then `t` is already present.

```
G`f|o|r

```

The input must contain `f`, `o` or `r` in order to prevent `four` from being possible; only `four` contains `u`, so if there's a `u` then `f`, `o` and `r` are already present.

```
G`s|i

```

The input must contain `s` or `i` in order to prevent `six` from being possible; only `six` contains `x`, so if there's an `x` then `s` and `i` are already present.

```
G`e

```

The input must contain `e` in order to prevent `eleven` from being possible; only `eleven` and `twelve` contain `l`, only `five`, `seven`, `eleven` and `twelve` contain `v`, and only `one`, `seven`, `nine`, `ten`, `eleven` and `thirteen` contain `n`, so if there's an `l`, a `v` or an `n` then `e` is already present. Additionally, only `two`, `four` and `six` do not contain an `e`, so no other letters need to be tested.

# Answer
> 4 votes
# 05AB1E, ~~35~~ 34 bytes

```
J“€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿áÓÁÏ“#€SåO0å

```

> You must compress, if not, be distressed.

Inputs as lowercase.

Try it online!

# How?

```
J                                     # Join the two input numbers into a string
 “€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿áÓÁÏ“           # Push the number words from "one" to "thirteen"
                            Så        # Are each character in the input?numbers? 1 if yes, 0 if not
                           €  O       # Sum the results for each word
                               0å     # Is there a 0 on a word?
                                      # (implicitly) Print the answer

```

# Answer
> 4 votes
# Japt `-x`, 14 bytes

Adaptation of xash's J solution so be sure to upvote them, too.

Input as a single lowercase delimited string, outputs a positive integer for true and `0` for false.

```
`èJ-n£`qÍ£¶kX

```

Try it or try all possible pairs (with `1` used for true)

# Answer
> 4 votes
# Perl 5 `-p`, ~~83~~ ~~28~~ 26 bytes

*Credit to @NahuelFouilleul for saving 2 bytes*

```
$_=/e/&/t|o/&/[for]/&/i|s/

```

Try it online!

Switched to @xash's method. This script inverts the output: `0` means that another number can be formed; `1` means that another number cannot be made.

# Answer
> 4 votes
# Python 3, 67 bytes

```
lambda s:sum(max(c in p for c in s)for p in'e to for si'.split())<4

```

Try it online!

Uses xash's idea from his J answer.

# Answer
> 4 votes
# C (gcc), ~~130~~ ~~128~~ 102 bytes

Saved 2 bytes thanks to ceilingcat!!!
Saved a whopping 26 bytes thanks to AZTECCO!!!

```
a,b,i;f(s,j)char*s,*j;{for(a=b=0,i=11;i--;i%3||(b+=!a,a=0))for(j=s;*j;)a+="e..to.forsi"[i]==*j++;b=b;}

```

Try it online!

Uses xash's idea from his J answer.

Inputs a string of two words separated by a space and returns a truthy value if it's possible to spell at least one other word from the given list without using any of the letters used in the two input words or a falsy value otherwise.

# Answer
> 3 votes
# Python 2, 56 bytes

```
lambda s:all(set(x)&set(s)for x in"e to for si".split())

```

Try it online!

Take inputs like `two four`, outputs negated. Checks whether the string has an `e`, and intersects the non-`e` numbers of `two`, `four`, and `six`.

52 bytes in Python 3 using `{*x}` for `set(x)`.

# Answer
> 3 votes
# Bash, ~~85~~ ~~74~~ ~~61~~ 53 bytes

Supply the input as an argument of the program. Output is via exit code.

```
[[ -z `for i in e to for si;{ grep -v [$i]<<<$1;}` ]]

```

Try it online!

# Answer
> 2 votes
# Ruby 2.7 `-n`, 45 bytes

*+1 to the idea of xash in his J's answer!*

```
p %w[e to for si].any?{$_.chars&_1.chars==[]}

```

Try it online!

# Ruby 2.7 \+ `gem install humanize`, 61 bytes

```
require'humanize'
f=->v{(1..13).any?{_1.humanize.count(v)<1}}

```

# Ruby 2.7 `-n`, ~~104~~ 90 bytes

*Saved 10 bytes by removing duplicate chars from number names.*

```
p %w[one two thre four five six sevn eight nie ten elvn twelv thiren].any?{_1.count($_)<1}

```

Try it online!

TIO uses an older version of Ruby, while in Ruby 2.7, we've numbered parameters, i.e., `_1`, which saves 2 bytes.

# Answer
> 2 votes
# Python 3.8 (pre-release), ~~175~~ ~~164~~ 146 bytes

```
def f(x):w="oe two tre for fie si se eit ie te e twe tire".split();return[[(w:=[*filter(lambda a:c not in a,w)])for c in i]for i in x][-1][-1]!=[]

```

Try it online!

saved 8 bytes with the help of member SunnyMoon

saved 18 bytes with the help of member Neil

normal version of the code:

```
def f(x):
    w="oe two tre for fie si se eit ie te e twe tire".split()
    for i in x:
        for c in i:
            w = [*filter(lambda a:c not in a, w)]
    return w != []

```

# Answer
> 2 votes
# Jelly, ~~39~~ 37 bytes

```
ị“½ĠWufṠ`ßṡƝ0:Ƒ’bȷ¤æ»
OUḅ96%191%⁵)ç/Ḃ

```

Try it online!

*-2 bytes thanks to @xigoi*

Takes input as a list of two words in lowercase.

### How it works

Uses a lookup table for all pairs. Instead of a 13×13 lookup table, this uses a 10×10 table because a few number/words (1&3, 2&4, 7&9, 10&12) have the same table values, so I engineered a hash with very specific collisions using a brute force script.

A 9×9 table is theoretically possible, but I doubt that it will save bytes due to a more complex hash function.

Lookup table generator after computing the hashes.

```
OUḅ96%191%⁵            # hash function
OUḅ96                    # character codepoints interpreted in reverse as a base 96 number
     %191%⁵              # mod 191 then mod 10

ị“½ĠWufṠ`ßṡƝ0:Ƒ’bȷ¤æ»  # lookup table
ị“½ĠWufṠ`ßṡƝ0:Ƒ’bȷ¤      # get the correct row from a list of 10 rows corresponding to the hash of the first word
                         # (base-250 compression then interpret as base 1000)
                   æ»    # bitshift by the amount corresponding to the hash of the second word

Ñ€ç/Ḃ     # apply the lookup table and hash. For some reason I couldn't get ÑçÑḂ to work.

```

# Answer
> 2 votes
# Charcoal, 19 bytes

```
⊙⪪”&↓εg⌕⁸¡⁼”a⬤ι¬№θλ

```

Try it online! Port of my Retina answer, but I was able to output a Charcoal boolean, i.e. `-` for possible, nothing for impossible. Explanation:

```
  ”&↓εg⌕⁸¡⁼”        Compressed string `eatoaforasi`
 ⪪          a       Split on `a`
⊙                   Any substring satisfies
             ⬤ι     All characters of substring satisfy
               ¬№θλ Character not present in input
                    Implicitly print

```

# Answer
> 2 votes
# Husk, ~~14~~ 12 bytes

*Edit: -2 bytes thanks to Razetime*

```
Λn⁰w¨toƒr¹∫e

```

Try it online!

Outputs falsy (`0`) if we can spell another letter without the input letters, truthy (non-zero) otherwise.

Uses approach of checking whether any of the input letters are present in `"to"`, `"for"`, `"is"` or `"e"`, as pioneered by xash's answer.

```
Λ               # are all these elements truthy?
 n              # are there intersecting elements of
  ⁰             # input
                # in each of
   w¨toƒr¹∫e    # "to","for","is","e"

```

# Answer
> 2 votes
# Zsh `-Fe`, 30 bytes

```
for i (e to for si)grep [$i] f

```

Try it online! (includes all combinations)

Takes input from a file named `f`, outputs via exit code (`0` = we can't spell a third word, `1` = we can).

The option `-F` disables globbing; without it, we would have to escape the square-brackets. `-e` makes `zsh` exit on the first command that fails - it's like a short-circuiting NOR over all the commands executed, similar to the approach in this great J answer. Also takes inspiration from this Bash answer.

# Answer
> 1 votes
# Haskell, 44 bytes

```
f a=any(not.any(`elem`a))$words"e to for si"

```

Try it online!

* Uses xash's idea from his J answer.
* Takes input as "one,two" and returns True for yes, False for not.
* I think it reads well as it is so no explanation.

# Answer
> 1 votes
# , 87 bytes

```
function(x,u=utf8ToInt)all(sapply(c('to','for','si','e'),function(m)any(u(m)%in%u(x))))

```

Try it online!

Reversed output: `TRUE` if we cannot spell another number without the input letters.

Started with the full vector `"one","two","three" ... "thirteen","fourteen"`, then removed the duplicate letters, then removed the only-in-one-number letters, then removed the letters in words that consistently had another letter. This brought the vector to `"oe","to","tre" ... "e","te","tire"`. At this point it was obvious that we can delete all numbers containing an "e" except `"e"` (which is what's left of `"eleven"`).

And then I realised that I'd just re-created xash's answer.

Well done, xash!

# Answer
> 1 votes
# 05AB1E, 14 bytes

```
“e€‡€ˆ€„“#€мQà

```

Port of *@xash*' J answer, so make sure to upvote him!

Also takes the input as a single (space-delimited) string.

Try it online or verify all test cases.

**Explanation:**

```
 “e€‡€ˆ€„“       # Push dictionary string "e for is to"
          #      # Split it on spaces: ["e","for","is","to"]
           €м    # For each: remove all those characters from the (implicit) input
             Q   # Then check for each if they're still equal to the (implicit) input
              à  # And check if any of the four were truthy by taking the maximum
                 # (after which this result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `“e€‡€ˆ€„“` is `"e for is to"`.

# Answer
> 0 votes
# JavaScript (Node.js), ~~99~~ ~~95~~ 78 bytes

```
x=>y=>!'e to for si'.split` `.filter(m=>![...m].some(k=>(x+y).includes(k)))[0]

```

Try it online!

Uses xash's idea from his J answer.

Returns false for yes and true for no (counterintuitive I know, deal with it). Uses currying syntax - `(x)(y)`.

Explanation:

```
x=>                           //declare function
  y=>                         //declare function 2
    !                         // necessary for consistent result
    'e to for si'             //see xash's J answer
    .split` `                 // to array
    .filter(                  //keep value only if following true
      m=>                     //function with value m
        !                     //if following is false
        [...m]                //m into array of letters
        .some(                //replace each with
          k=>                 //function of k
            (x+y).includes(k) //if includes true (input contains one of word
        )
       )                      // array now has any items only if it contains something
   [0]                        //0th item, undefined if no answers, one of strings above if does, then negated by ! at top.

```

There's got to be a better way to do all the .includes.

# Regex (any)

```
^([^e]*|[^to]*|[^for]*|[^si]*)$

```

Just using @xash's trick again. Takes a single string.

# Javascript, 44 bytes (using regex)

```
x=>/^([^e]*|[^to]*|[^for]*|[^si]*)$/.test(x)

```

I mean it works, but I like the other one because it took more than 2 minutes. Takes a single string.

---
Tags: code-golf, decision-problem
---