# Question
Title: Swap prime exponents with their neighbours
*(Follow-up to my question about swapping bits with their neighbours.)*

# Task

Given a positive integer **x = (2a · 3b) · (5c · 7d) · (11e · 13f) · …**, print the integer obtained by swapping the exponents in this factorization for each successive pair of primes, **y = (2b · 3a) · (5d · 7c) · (11f · 13e) · …**

A061898 in the OEIS. This is , so the shortest program (in bytes) wins!

# Test cases

```
1 -> 1
2 -> 3
3 -> 2
10 -> 21
37 -> 31
360 -> 756
12345 -> 11578
67895678 -> 125630871

```

# Answer
> 7 votes
# Jelly, 10 bytes

```
ÆE;0s2UFÆẸ

```

Try it online! or verify all test cases.

### How it works

```
ÆE;0s2UFÆẸ  Main link. Argument: n

ÆE          Yield the exponents of n's prime factorization.
  ;0        Append a zero.
    s2      Split into pairs.
      U     Upend; reverse each pair.
       F    Flatten the resulting list of pairs.
        ÆẸ  Convert the prime exponents to integer.

```

# Answer
> 4 votes
# Jelly, ~~17~~ ~~16~~ 11 bytes

5 bytes thanks to Dennis.

```
ÆfÆC’^1‘ÆNP

```

Try it online!

### Explanation

```
ÆfÆC’^1‘ÆNP   Main monadic chain. Argument: n

Æf            Yield the prime factors of n.
  ÆC          For each factor, count the number of primes below it.
              This effectively yields their indices.
    ’         Decrement [each] by 1.
     ^1       Xor with 1
       ‘      Increment [each] by 1.
        ÆN    Find their corresponding primes.
          P   Yield their product.

```

## Previous 16-byte version

```
ÆnÆRiÐ€Æf’^1‘ÆNP

```

Try it online!

### Explanation

```
ÆnÆRiÐ€Æf’^1‘ÆNP   Main monadic chain. Argument: n

Æn                 Yield the next prime from n.
  ÆR               Yield all primes from 2 to it.
       Æf          Yield prime factors of n
    iÐ€            Yield their index in the prime list.
         ’         Decrement [each] by 1.
          ^1       Xor with 1
            ‘      Increment [each] by 1.
             ÆN    Find their corresponding primes.
               P   Yield their product.

```

## Previous 17-byte version:

```
ÆnÆR©iÐ€Æf’^1‘ị®P

```

Try it online!

### Explanation

```
ÆnÆR©iÐ€Æf’^1‘ị®P   Main monadic chain. Argument: n

Æn                  Yield the next prime from n.
  ÆR                Yield all primes from 2 to it.
    ©               Store to register.
        Æf          Yield prime factors of n
     iÐ€            Yield their index in the prime list.
          ’         Decrement [each] by 1.
           ^1       Xor with 1
             ‘      Increment [each] by 1.
              ị®    Find their corresponding primes in
                    the list in register.
                P   Yield their product.

```

# Answer
> 3 votes
# Python 2, ~~149~~ 139 bytes

10 bytes thanks to Dennis.

```
n=input()
p=f=1;w=[2]
while w[-1]<=n:f*=p;p+=1;w+=[p]*(-~f%p<1)
r=p=1;w=w[1:]
while n>1:
    p+=1
    while n%p<1:n/=p;r*=w[w.index(p)^1]
print r

```

# Answer
> 3 votes
## Mathematica, ~~70~~ 69 bytes

```
1##&@@(Prime[BitXor[PrimePi@#+1,1]-1]^#2&)@@@FactorInteger@#/._@_->1&

```

An unnamed function which takes and returns an integer. It throws an error on input `1` but still computes the correct result.

### Explanation

As usual, due to all the syntactic sugar, the reading order is a bit funny. A `&` on the right defines an unnamed function and its arguments are referred to by `#`, `#2`, `#3`, etc.

```
...FactorInteger@#...

```

We start by factoring the input. This gives a list of pairs `{prime, exponent}` e.g. input `12` gives `{{2, 2}, {3, 1}}`. Somewhat inconveniently, `1` gives `{{1, 1}}`.

```
(...&)@@@...

```

This *applies* the function on the left to the list of integers at level 1, that is the function is called for each pair, passing the prime and exponent in as separate arguments, and then returns a list of the results. (This is similar to mapping the function over the list, but receiving two separate arguments is more convenient than receiving a pair.)

```
...PrimePi@#...

```

We compute the number of primes up to and including the (prime) input using the built-in `PrimePi`. This gives us the index of the prime.

```
...BitXor[...+1,1]-1...

```

The result is incremented, XOR'ed with `1` and decremented again. This swaps `1 <-> 2, 3 <-> 4, 5 <-> 6, ...`, i.e. all 1-based indices. Note that input `1` will yield `0` for `PrimePi` which is then mapped to `-1` in this process. We'll deal with that later.

```
 ...Prime[...]^#2...

```

We now obtain the *n*th prime (where *n* is the result from the previous computation), which is the correctly swapped prime, and raise it to the power of the original prime in the factorisation of the input. At this point `Prime[-1]` will throw an error but will return itself unevaluated. The power in this case is `1` so that the entire process so far yields `{Prime[-1]}` for input `1` and a list of correct prime powers for all other inputs.

```
 1##&@@...

```

Next, we just multiply up all prime powers. `1##&` is a standard golfing trick for the `Times` function. See this tip (section "Sequences of arguments") for how it works.

Finally, we need to take care of input `1` for which all of the above resulted in `Prime[-1]`. We can easily fix that with a simple replacement rule. Remember that `f@x` is short for `f[x]`. We just want to match any expression of that form (since all other results will be integers, i.e. atomic expressions), and replace it with a `1`:

```
.../._@_->1

```

Here, `/.` is short for `ReplaceAll`, `_@_` is a pattern for anything of the form `f[x]` (i.e. any compound expression with a single child) and `->1` says "replace with `1`".

# Answer
> 3 votes
# Python 2, ~~112~~ ~~109~~ ~~108~~ ~~95~~ 94 bytes

```
f=lambda n,k=4,m=6,p=[3,2]:1/n or n%p[1]and f(n,k+1,m*k,m*m%k*[k]+p)or p[len(p)*2%4]*f(n/p[1])

```

Test it on Ideone.

### How it works

When **f** is called, it first computes **1/n**. If the result is non-zero, **n** is **1** and **f** returns **1**.

If **n \> 1**, the following happens.

* If **n** is not divisible by **p\[1\]** (initially **2**), `n%p[1]` yields a truthy value and

```
  f(n,k+1,m*k,m*m%k*[k]+p)

```

gets called.

This branch generates prime number until the penultimate one evenly divides **n**. To do so, it uses the following corollary of Wilson's theorem.

At all times, **m** is equal to the factorial of **k - 1** (initially **6 = 3!** and **4**. In each iteration, the result of `m*m%k*[k]` gets prepended to the list of primes **p**. By the corollary, `m*m%k` is **1** if **k** is prime and **0** if not, so this prepends **k** to **p** if and only if **k** is a prime number.
* If **n** is divisible by **p\[1\]**, `n%p[1]` yields **0** and

```
  p[len(p)*2%4]*f(n/p[1])

```

gets executed.

If **p** contains an even amount of prime numbers, `len(p)*2%4` will yield **0** and the first multiplicand takes the value of **p\[0\]**. If **p** contains an odd amount of prime numbers, `len(p)*2%4` will yield **2** and the first multiplicand takes the value of **p\[2\]**.

In either case, this is the prime whose exponents has to get swapped with the one of **p\[1\]**, so we divide **n** by **p\[1\]** (decreasing the exponent by **1**) and multiply the result of `f(n/p[1])` by the corresponding prime (increasing the exponent by **1**).

Note that `f(n/p[1])` resets **k**, **m** and **p** to their default values. `f(n/p[1],k,m,p)` would improve efficiency, at the cost of six extra bytes.

# Answer
> 2 votes
# MATL, 17 bytes

```
EZqGYfy&mt2\Eq+)p

```

**Try it online!**

### Explanation

This doesn't use the exponents directly. Instead, it swaps each (possibly repeated) prime factor by the next or the preceding prime.

```
EZq    % Implicit input. Multiply by 2
Zq     % Array with sequence of primes up to that (this is more than enough)
GYf    % Prime factors of input, with possible repetitions
y      % Duplicate array with sequence of primes
&m     % Indices of prime factors in the sequence of primes
t2\    % Duplicate, modulo 2. Gives 0 for even indices, 1 for odd
Eq     % Multiply by 2, add 1. Transforms 0 / 1 into -1 / 1
+      % Add. This modifies the indices to perform the swapping
)      % Apply the new indices into the sequence of primes
p      % Product. Implicit display

```

# Answer
> 2 votes
# Julia, 64 bytes

```
~=primes
!n=prod(t->(~3n)[endof(~t[1])+1$1-1]^t[2],factor(2n))/3

```

Try it online! The last test case requires too much memory for TIO, but I've verified it locally.

### How it works

To avoid special-casing input **1** – the product of an empty dictionary is not defined – we multiply the input **n** by **2** and divide the final result by its pair **3**.

`factor(2n)` gives all positive exponents of prime factors of **2n** as a dictionary. When iterating over the dictionary, we'll get key-value/prime-exponent pairs. The function `prod` will take these pairs, apply the anonymous function `t->...` to them and return the product of the results.

For each pair **t = (p,e)**, `endof(~t[1])` or `endof(primes(t[1]))` return **k**, the number of primes that are less or equal to **p**, meaning that **p** is the **k**th prime.

`+1$1-1` will increment **k**, XOR **k + 1** with **1** and decrement the result. If **k** is odd, **k + 1** is even, so the XOR increments and the final result is **k + 1**. If **k** is even, **k + 1** is odd, so the XOR decrements and the final result is **k - 1**.

Finally, we compute all prime numbers less or equal to **3n** with `(~3n)` or `primes(3n)` (the highest prime factor of **2n** is less or equal to **n** if **n \> 2**, and there's always a prime between **n** and **2n**), select the one at index **k + 1** or **k - 1**, and elevate it to the **e**th power with `^t[2]`.

# Answer
> 1 votes
# Pyth, 25 bytes

```
JfP_TSfP_ThQ*F+1m@Jx1xJdP

```

Test suite.

## Explanation

```
JfP_TSfP_ThQ*F+1m@Jx1xJdP

           Q    get input
          h     add one
      fP_T      find the first prime after it
     S          range from 1 to that prime
 fP_T           filter for the primes
J               assign to J

                        P  prime factorize input
                m      d   for each factor
                     xJ    find its index in J
                   x1      xor with 1
                 @J        find the corresponding entry in J
            *F+1           product of the whole list

```

# Answer
> 1 votes
# Julia, ~~155~~ ~~131~~ 127 bytes

```
n->(x=[sort([merge([p=>0for p=primes(n+1)],factor(n))...]);1=>0];prod([x[i-1][1]^x[i][2]*x[i][1]^x[i-1][2]for i=2:2:endof(x)]))

```

This is an anonymous function that accepts an integer and returns an integer. To call it, assign it to a variable. It requires a Julia version \< 0.5 because the prime functionality has been removed from Base in 0.5.

Ungolfed:

```
function f(n::Int)
    # Create an array of pairs by merging the Dict created from factoring n
    # with all primes less than n+1 with a 0 exponent. Append an extra pair
    # to account for 1 and situations where x would otherwise have odd length.
    x = [sort([(merge([p=>0 for p in primes(n+1)], factor(n))...]); 1=>0]

    # Compute a^d * c^b, where a and c are primes with b and d as their
    # respective exponents.
    prod([x[i-1][1]^x[i][2] * x[i][1]^x[i-1][2] for i = 2:2:endof(x)])
end

```

Try it online! (Includes all test cases)

# Answer
> 1 votes
## Actually, 15 bytes

```
w`i;r♂Pí1^Pn`Mπ

```

Try it online!

Explanation:

```
w`i;r♂Pí1^Pn`Mπ
w                prime factorization
 `          `M   map (for (p,e) in factorization):
  i;               flatten, make a copy of p
    r♂P            [prime[i] for i in range(p)]
       í           index (essentially the 0-based prime index of p)
        1^         XOR with 1
          P        prime[n]
           n       repeat e times
              π  product

```

# Answer
> 1 votes
## 05AB1E, 22 bytes

```
Ó¾‚˜2ô€R˜DgL<Ø)øvy`smP

```

**Explained**

```
Ó¾‚˜                    # list of primeexponents with a 0 appended: n=10 -> [1,0,1,0]
    2ô                  # split into pairs: [[1,0],[1,0]]
      €R˜               # reverse each pair and flatten: [0,1,0,1]
         DgL<Ø          # get list of primes corresponding to the exponents: [2,3,5,7]
              )ø        # zip lists: [[0,2],[1,3],[0,5],[1,7]]
                vy`sm   # raise each prime to its new exponent: [1,3,1,7]
                     P  # product: 21

```

Try it online

# Answer
> 0 votes
# J, 21 bytes

```
([:,_2|.\,&0)&.(_&q:)

```

Gets the prime exponents of *n* as prime powers with zeros. Then partition them into nonoverlapping sublists of size 2 while filling with an extra zero. Then reverse each sublist, and flatten them into a list. Finally, convert back from prime exponents to a number.

## Usage

```
   f =: ([:,_2|.\,&0)&.(_&q:)
   (,.f"0) 1 2 3 10 37 360 12345
    1     1
    2     3
    3     2
   10    21
   37    31
  360   756
12345 11578
   f 67895678x
125630871

```

## Explanation

```
([:,_2|.\,&0)&.(_&q:)  Input: n
                _&q:   Obtain the list of prime exponents
(           )&.        Apply to the list of prime exponenets
         ,&0           Append a zero to the end of the list
    _2  \              Split the list into nonoverlapping sublists of size 2
      |.               Reverse each sublist
 [:,                   Flatten the list of sublists into a list
             &.(    )  Apply the inverse of (Obtain the list of prime exponents)
                       to convert back to a number and return it

```

# Answer
> 0 votes
# Stax, 16 bytes

```
â↕ÿ╓d8‼Qlì"┌nq╟ì

```

Run and debug it

# Answer
> 0 votes
# 05AB1E, 13 bytes

```
Ó0ª2ôí˜ā<ØsmP

```

Try it online or verify all test cases.

Or alternatively:

```
xÅPsÓ0ª2ôí˜mP

```

Try it online or verify all test cases.

**Explanation:**

```
Ó              # Get all prime exponents of the (implicit) input-integer
 0ª            # Append a 0
   2ô          # Split it int parts of size 2
     í         # Reverse each inner pair
      ˜        # Flatten the list
       ā       # Push a list in the range [1,length] (without popping the list)
        <      # Decrease each by 1 to the range [0,length)
         Ø     # Get the n'th prime of each value
          s    # Swap so the earlier list is at the top
           m   # Take the primes to the power of the exponents
            P  # And then take the product
               # (after which the result is output implicitly)

x              # Double the (implicit) input-integer (without popping)
 ÅP            # Pop and push a list of all prime numbers <= this doubled input
   s           # Swap so the input is at the top of the stack
    Ó0ª2ôí˜    # Same as above
           m   # Take each prime to the power of the exponents
               # (any additional trailing primes will be discarded)
            P  # And then take the product
               # (after which the result is output implicitly)

```

---
Tags: code-golf, primes
---


title: Transpose a word cloud

text:
# Question
Title: Transpose a word cloud
## Background

I wanted to make a pretty word cloud, like this:

```
these    are
    words

  floating

```

I computed the `(x,y)`-coordinates of the first letter of each word, plugged them into my word cloud generator, and let it do its job. However, I accidentally used `(y,x)`-coordinates, so the result looks like this:

```
these

   floating

 words

are

```

Since I'm too lazy to re-compute the coordinates, I need you to transpose the word cloud for me.

## Input

Your input is a rectangular grid of lowercase ASCII letters and spaces. This means that every row is padded with spaces to have the same length. The input can be taken as a multi-line string or an array of strings.

A *word* is a horizontal segment of letters, and its *position* is the `(x,y)`-coordinates of its leftmost letter, the upper left corner of the grid being `(0,0)`. There will always be at least one word, and there are no trailing rows or columns of spaces. However, leading rows or columns of spaces may be present.

## Output

Your output is another rectangular grid of characters, obtained by moving every word with position `(x,y)` to position `(y,x)`. Your output **must not contain** extra trailing rows or columns of spaces. Leading rows and columns must be preserved, and the output **must be rectangular**.

You may assume that this transformation does not create overlapping words, and does not merge several words into one. This means that running the program on the output should produce the original input.

## Rules and scoring

You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.

## Test cases

For clarity (and since Stack Exchange dislikes space-only lines), every row ends in a pipe character `|`. **These are not part of the actual input or output**, and you should remove them. Note again that running the program on each output should also produce the corresponding input.

```
Input:
oneword|
Output:
oneword|

Input:
  spaces|
Output:
      |
      |
spaces|

Input:
   |
row|
Output:
 row|

Input:
these    are|
    words   |
            |
  floating  |
Output:
these      |
           |
   floating|
           |
 words     |
           |
           |
           |
are        |

Input:
   same|
 the   |
       |
same   |
Output:
   same|
 the   |
       |
same   |

Input:
  some |
words k|
       |
       |
       |
  still|
Output:
 words    |
          |
some still|
          |
          |
          |
 k        |

Input:
   hello   |
  world hey|
what   up  |
Output:
  what|
      |
 world|
hello |
      |
      |
      |
  up  |
 hey  |

Input:
  a b  a d cc|
 g h  huh nng|
  ye dunnn   |
    dud  yo  |
 wha   g     |
  huh heh hah|
Output:
        |
 g  wha |
a ye huh|
 h      |
b  dud  |
  dunnn |
 huh heh|
a   g   |
        |
d  yo   |
 nng hah|
cc      |

```

# Answer
> 7 votes
# Perl, 58 bytes

Added +2 for `-lp`

Give input on STDIN, run as `perl -lp wordcloud.pl`

`wordcloud.pl`:

```
s/\w+/$l|=$a[pos]|=$"x~-$..$&/eg}for(@a){$_|=$l=~y// /cr

```

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

```
{x←' '⍴⍨×⍨2/⌈/⍴⍵⋄(⌈⌿↑⍸' '≠x)↑x⊣{x⊢←(⊃⍵)@((⊃⌽⍵)∘+¨↓0,⍪1-⍨⍳≢⊃⍵)⊢x}¨↓(⊃,/' '(≠⊆⊢)¨↓⍵),⍪⌽¨⍸2{1 0≡' '=⍺⍵}/' ',⍵}

```

Try it online!

Makes an over-big matrix of spaces, and adds in the required words using `@`. Then, crops back to the required size.

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


title: Print a smiley face

text:
# Question
Title: Print a smiley face
**Requirements**

For the sake of the challenge let's define a *unit*:

> A unit is defined as any point that compose the grid in which the face is drawn (pixels for screen, characters for ASCII art, etc..).

The *minimal requirements* for the face are:

> A smiley face is composed of a shape that resemble a circle (not necessarily perfect) of any radius. There must be at least 1 unit for each of the two eyes and at least 2 units for the mouth. Both eyes and mouth should be within the face shape. The mouth can be oriented however you want (happy, sad, indifferent, etc..).

Here's an example of the output:

```
 0 0 0    . . .
0 . . 0  . o o .
0 --- 0  . \_/ .
 0 0 0    . . .

```

**Goals**

Of course the main goal is to come up with the shortest code possible, but *art* is also important.

**Winner**

The winner is chosen based on the amount of votes from the users, in, at least, the next 5 days.

# Answer
## Javascript, 340

```
var i=0,b=document.body,d=20,n=b.clientWidth,m=b.clientHeight,f="width=10,height=10,"
var o=new Function("f","i","t",'open("","",f+"left="+i+",top="+t)')
for(j=0;j<m/d;++j,i=j*d){
   u=Math.sqrt(i*(m-i))
   t=m/2+u*(j%2-0.5)*2
   o(f,i,t)
   i>m/5&&i<0.8*m&&j%2&&o(f,i,t-m/4);
   ((i<m/3&&i>m/4)||(i<3*m/4&&i>2*m/3))&&o(f,i,m/3)
}

```

---

## Javascript, 283

**optimized version (with some improvements & without unnecessary white spaces)**

```
var i=0,b=document.body,d=20,n=b.clientWidth,m=b.clientHeight,f="width=10,height=10,"
function o(i,t){open("","",f+"left="+i+",top="+t)}for(j=0;j<m/d;i=++j*d){u=Math.sqrt(i*(m-i));t=m/2+j%2*2*u-u;o(i,t);i>m/5&&i<0.8*m&&j%2&&o(i,t-m/4);((i<m/3&&i>m/4)||(i<3*m/4&&i>2*m/3))&&o(i,m/3)}

```

Well.. maybe it isn't as short as you would want to but it's unconventional for sure. It looks better when your browser is maximized. I really enjoyed your question! If you want to increase the details just reduce `d` variable slightly.

edit: Unfortunately I can't run it on jsfiddle ~~but you can paste it to Javascript console in aby browser. Oh, and enable popups on the page :).~~

**edit2:** You can run it making a new html file and paste the code into it:

```
<body>
<script>
var i=0,b=document.body,d=20,n=b.clientWidth,m=b.clientHeight,f="width=10,height=10,"
var o=new Function("f","i","t",'open("","",f+"left="+i+",top="+t)')
for(j=0;j<m/d;++j,i=j*d){
   u=Math.sqrt(i*(m-i))
   t=m/2+u*(j%2-0.5)*2
   o(f,i,t)
   i>m/5&&i<0.8*m&&j%2&&o(f,i,t-m/4);
   ((i<m/3&&i>m/4)||(i<3*m/4&&i>2*m/3))&&o(f,i,m/3)
}
</script>
</body>

```

Then when you run it and nothing happens, just enable the popup windows and reload the page. In addition I paste
> 115 votes

# Answer
# HTML, ~~200~~ 141 characters

Thanks to avail, I've cut this down to 141 characters:

```
<fieldset><legend>\\\\\\\\\\\\ ////</legend><center><input size=1 value=o> <input size=1 value=o /><br><input type=radio><br><button>........

```

Here's the original HTML:

```
<fieldset>
<legend>\\\\\\\\\\\\ ////</legend>
<center><input type=text size=1 value=o />
<input type=text size=1 value=o /><br/>
<input type=radio /><br/>
<button>........</button></center></fieldset>

```

Works best on small screens:
> 69 votes

# Answer
# Brainfuck: 583 characters (without counting whitespace)

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

```

**Output:**

```
\|/ ____ \|/
 @~/ ,. \~@
/_( \__/ )_\
   \__U_/

```
> 56 votes

# Answer
# SVG

```
<svg xmlns="http://www.w3.org/2000/svg">
    <defs>
        <radialGradient id="f" fx="25%" fy="25%" r="60%">
            <stop offset="0" stop-color="#fff"/>
            <stop offset="0.6" stop-color="#ff0"/>
            <stop offset="1" stop-color="#f80"/>
        </radialGradient>
    </defs>
    <circle fill="url(#f)" stroke="#000" stroke-width="2" cx="100" cy="100" r="90"/>
    <ellipse cx="70" cy="70" rx="10" ry="20"/>
    <ellipse cx="130" cy="70" rx="10" ry="20"/>
    <path fill="none" stroke="#000" stroke-width="5" d="M 40 120 S 100 200 160 120"/>
</svg>

```

Renders like this:
> 40 votes

# Answer
## Ruby, 224

Douglas Adams would be horrified. :-P

```
w=?$;"^XA[_AXeMFGIAHJLjKNAEFEJJNHQHNKLAEMINJOJOHLAGKHOJOJ[AG[HQHRFJAH}IH
IGGwIIAHHGwKHAHGHrEUAGQFiGVAGQGfIPAFHKHHbJHAQII]MGASHNSOHATIdIAUJJRLIAWLIQGK
ZOFUA]ZAeSAiPAjOAkL".codepoints{|r|r-=68;$><<(r<0??\n:(w=w==?$?' ':?$)*r)}

```

Output:

```
                          $$$$$$$$$$$$$$$$$$$$
                       $$$$$$$$$$$$$$$$$$$$$$$$$$$
                    $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$         $$   $$$$$
    $$$$$$        $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$       $$$$$$$$$$
 $$ $$$$$$      $$$$$$$$$$    $$$$$$$$$$$$$    $$$$$$$$$$       $$$$$$$$
 $$$$$$$$$     $$$$$$$$$$      $$$$$$$$$$$      $$$$$$$$$$$    $$$$$$$$
   $$$$$$$    $$$$$$$$$$$      $$$$$$$$$$$      $$$$$$$$$$$$$$$$$$$$$$$
   $$$$$$$$$$$$$$$$$$$$$$$    $$$$$$$$$$$$$    $$$$$$$$$$$$$$  $$$$$$
    $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$     $$$$
     $$$   $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$     $$$$$
    $$$$   $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$       $$$$
    $$$    $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$
   $$$$$$$$$$$$$  $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$   $$$$$$$$$$$$$$$$$$
   $$$$$$$$$$$$$   $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$     $$$$$$$$$$$$
  $$$$       $$$$    $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$      $$$$
             $$$$$     $$$$$$$$$$$$$$$$$$$$$$$$$         $$$
               $$$$          $$$$$$$$$$$$$$$           $$$$
                $$$$$                                $$$$$
                 $$$$$$      $$$$$$$$$$$$$$        $$$$$
                   $$$$$$$$     $$$$$$$$$$$$$   $$$$$$$
                      $$$$$$$$$$$  $$$$$$$$$$$$$$$$$
                         $$$$$$$$$$$$$$$$$$$$$$
                                 $$$$$$$$$$$$$$$
                                     $$$$$$$$$$$$
                                      $$$$$$$$$$$
                                       $$$$$$$$

```

---

## Ruby, 110

Same technique. Less code. Less artful. Looks like someone melted a plastic smiley. :-}

```
w=?$;"TXANdAKQGZAHSI[AGaGRAFaIRAFPGeAGQJ_AHURQAJkANc
TX".codepoints{|r|r-=68;$><<(r<0??\n:(w=w==?$?' ':?$)*r)}

```

Output:

```
                $$$$$$$$$$$$$$$$$$$$
          $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
       $$$$$$$$$$$$$   $$$$$$$$$$$$$$$$$$$$$$
    $$$$$$$$$$$$$$$     $$$$$$$$$$$$$$$$$$$$$$$
   $$$$$$$$$$$$$$$$$$$$$$$$$$$$$   $$$$$$$$$$$$$$
  $$$$$$$$$$$$$$$$$$$$$$$$$$$$$     $$$$$$$$$$$$$$
  $$$$$$$$$$$$   $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
   $$$$$$$$$$$$$      $$$$$$$$$$$$$$$$$$$$$$$$$$$
    $$$$$$$$$$$$$$$$$              $$$$$$$$$$$$$
      $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
          $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
                $$$$$$$$$$$$$$$$$$$$

```
> 38 votes

# Answer
# QBasic ASCII, 134 (unoptimized)

```
SCREEN 1
PRINT CHR$(1)
FOR i = 0 TO 64
  x = i \ 8
  y = i MOD 8
  LOCATE y + 2, x + 1
  IF POINT(x, y) THEN PRINT "X"
NEXT

```

This answer totally cheats by using ASCII character 1 for its smiley. However, unlike the BF and "plain text" answers, it actually obeys the rules by making ASCII art based on the pixels of the smiley character, rather than just plainly printing the character as its full solution. The unoptimized version represents how QBasic's IDE saves the files. The IDE is "helpfully" fixing up the syntax for us and adding a lot of whitespace where "needed".

Output:

# QBasic ASCII, 80 (optimized)

```
SCREEN 1
?"☺"
FOR i=0TO 64
x=i\8
y=i MOD 8
LOCATE y+2,x+1
?CHR$(POINT(x,y))
NEXT

```

This is an optimized version of the first code sample, which still loads in QBasic. Things that were done:

* Removed all unnecessary whitespace. (D'uh!)
* Changed the CRLF line breaks to LF only.
* Replaced `CHR$(1)` with a string containing the actual character. (Here illustrated with a matching Unicode character. If you actually want to try the code, please replace it with a real ASCII character 1 using a hex editor.)
* Replaced `PRINT` with `?`, as the BASIC tradition allows for.
* Replaced the `IF` line with a line that prints characters based on the source pixel value. This will be be either 0 or 3. 0 is the color black. Character 0 prints a null character which is treated like a space. 3 is the color white in CGA's 4-color palette. ASCII character 3 is a heart.

Output:

# QBasic graphical, 83 (whitespace optimized)

```
SCREEN 1
CIRCLE(50,50),50
CIRCLE(50,50),30,,4,5.4
CIRCLE(30,40),10
CIRCLE(70,40),10

```

But wait, I here you ask, can't you just use QBasic's built-in graphics commands? Sure, but that won't actually save you any bytes, because of the verbosity of the language. But it does have a built-in function to only draw a circle arc between two given angles, which is nice. The angles are given in radians, and `4` and `5.4` approximate a circle arc symmetrically centered around `π*3/2`, or if you've joined the good side, `τ*3/4`.

Output:

Note: The sizes in this answer denote how big the file is in, in bytes.
> 24 votes

# Answer
# APL, 97 chars/bytes\*

```
(63⍴1 0)\' /%'[1+(12≥⊃+/¨2*⍨m+¨⊂6 ¯6)+((⍉18<(⍴n)⍴⍳32)∧28≥|100-n)+256≥n←⊃+/¨2*⍨m←x∘.,|x←¯16.5+⍳32]

```

It works by computing a few circle equations. Tested on GNU APL.

**Output** ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
<sup>\*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long.</sup>
> 12 votes

# Answer
# Bash, 63 chars

```
echo $'$the_cow=""'>.cow;cowsay -f ./.cow $'O O\n\n\_/';rm .cow

```

Output:

```
 _____
/ O O \
|     |
\ \_/ /
 -----

```

Artistry:

Cows.
> 11 votes

# Answer
# Bash, 22 chars

```
wget x.co/3WG0m -q -O-

```

Sample output:

Edit: this could be golfed further as suggested by several people. The shortest self-contained version found so far is:

```
curl -L x.co/3WG0m

```

(thanks nitro2k01)
> 9 votes

# Answer
**Python 247 230 227 Characters - and a cuter version**

```
from matplotlib.pyplot import*
from numpy import*
y=x=arange(-8,11,.1)
x,y=meshgrid(x,y)
contour(x,y,(x*x*(x**2+2*y*y-y-40)+y*y*(y*y-y-40)+25*y+393)*((x+3)**2+(y-5)**2-2)*((x-3)**2+(y-5)**2-2)*(x*x+(y-2)**2-64),[0])
show()

```

**Python 243 Characters - Using colors**

```
from pylab import*
from numpy import*
y=x=arange(-9,11,.1)
x,y=meshgrid(x,y)
contourf(x,y,(x*x*(x**2+2*y*y-y-40)+y*y*(y*y-y-40)+25*y+393)*((x+3)**2+(y-5)**2-2)*((x-3)**2+(y-5)**2-2)*(x*x+(y-2)**2-64),1,colors=("#F0E68C",'#20B2AA'))
show()

```
> 9 votes

# Answer
# C++ - 122 characters without unnecessary spaces

This is the most realistic I could come up with:

```
#include <iostream>

int main() {
  std::cout << "  |||||\n 0 . . 0\n0   ^   0\n0  \\_/  0\n 0     0\n  00000\n   888\n    8\n\n";
}

```

For those of you who are missing out, it creates this:
> 8 votes

# Answer
```
cowsay -f calvin Hey, What´s up?
 _________________
< Hey, What´s up? >
 -----------------
 \                   .,
   \         .      .TR   d'
     \      k,l    .R.b  .t .Je
       \   .P q.   a|.b .f .Z%
           .b .h  .E` # J: 2`     .
      .,.a .E  ,L.M'  ?:b `| ..J9!`.,
       q,.h.M`   `..,   ..,""` ..2"`
       .M, J8`   `:       `   3;
   .    Jk              ...,   `^7"90c.
    j,  ,!     .7"'`j,.|   .n.   ...
   j, 7'     .r`     4:      L   `...
  ..,m.      J`    ..,|..    J`  7TWi
  ..JJ,.:    %    oo      ,. ....,
    .,E      3     7`g.M:    P  41
   JT7"'      O.   .J,;     ``  V"7N.
   G.           ""Q+  .Zu.,!`      Z`
   .9.. .         J&..J!       .  ,:
      7"9a                    JM"!
         .5J.     ..        ..F`
            78a..   `    ..2'
                J9Ksaw0"'
               .EJ?A...a.
               q...g...gi
              .m...qa..,y:
              .HQFNB&...mm
               ,Z|,m.a.,dp
            .,?f` ,E?:"^7b
            `A| . .F^^7'^4,
             .MMMMMMMMMMMQzna,
         ...f"A.JdT     J:    Jp,
          `JNa..........A....af`
               `^^^^^'`

```
> 6 votes

# Answer
# PHP, many other languages... - 1601 characters

```
                          oooo$$$$$$$$$$$$oooo
                      oo$$$$$$$$$$$$$$$$$$$$$$$$o
                   oo$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$o         o$   $$ o$
   o $ oo        o$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$o       $$ $$ $$o$
oo $ $ "$      o$$$$$$$$$    $$$$$$$$$$$$$    $$$$$$$$$o       $$$o$$o$
"$$$$$$o$     o$$$$$$$$$      $$$$$$$$$$$      $$$$$$$$$$o    $$$$$$$$
  $$$$$$$    $$$$$$$$$$$      $$$$$$$$$$$      $$$$$$$$$$$$$$$$$$$$$$$
  $$$$$$$$$$$$$$$$$$$$$$$    $$$$$$$$$$$$$    $$$$$$$$$$$$$$  """$$$
   "$$$""""$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$     "$$$
    $$$   o$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$     "$$$o
   o$$"   $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$       $$$o
   $$$    $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$" "$$$$$$ooooo$$$$o
  o$$$oooo$$$$$  $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$   o$$$$$$$$$$$$$$$$$
  $$$$$$$$"$$$$   $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$     $$$$""""""""
 """"       $$$$    "$$$$$$$$$$$$$$$$$$$$$$$$$$$$"      o$$$
            "$$$o     """$$$$$$$$$$$$$$$$$$"$$"         $$$
              $$$o          "$$""$$$$$$""""           o$$$
               $$$$o                                o$$$"
                "$$$$o      o$$$$$$o"$$$$o        o$$$$
                  "$$$$$oo     ""$$$$o$$$$$o   o$$$$""
                     ""$$$$$oooo  "$$$o$$$$$$$$$"""
                        ""$$$$$$$oo $$$$$$$$$$
                                """"$$$$$$$$$$$
                                    $$$$$$$$$$$$
                                     $$$$$$$$$$"
                                      "$$$""

```

Smiley source: Asciiworld.com : Smiley
> 5 votes

# Answer
# JavaScript 262 251

**Edit:** added better eyes.

Prints a smiley face into the console.

Could lose quite a few characters to make my bitmask simpler and print a less pretty face, or use a circle equation instead of an ellipse to account for character spacing - but that's not the spirit.

You can change the `r` variable to change the size and get a more or less detailed face; any number `>=7 && <=99` will give a good result and stay within the character limit.

```
function c(e,t,n){return t/2*Math.sqrt(1-e*e/(n*n))+.5|0}r=42;p=r/2;q=p/5;s="";for(y=-p;++y<p;){for(x=-r;++x<r;){d=c(y,r*2,p);e=c(y+q,r/5,q);f=e-p;g=e+p;h=c(y,r*1.3,r/3);s+=x>=d||x<=-d||x>=-g&&x<f||x<=g&&x>-f||y>q&&x>-h&&x<h?" ":0}s+="\n"}console.log(s)

```

Human readable:

```
function c(y,w,h){return w/2*Math.sqrt(1-y*y/(h*h))+0.5|0}
r = 42
p = r/2
q = p/5
s = ''
for (y = -p; ++y < p;) {
  for (x = -r; ++x < r;) {
    d = c(y,r*2,p)
    e = c(y+q,r/5,q)
    f = e - p
    g = e + p
    h = c(y,r*1.3,r/3)
    s+=(x>=d||x<=-d||(x>-g&&x<f)||(x<g&&x>-f)||(y>q&&(x>-h&&x<h)))?' ':0
  }
  s += '\n'
}
console.log(s)

```

**Output:**

My first game of golf so likely to be some improvements.
> 5 votes

# Answer
## html, css

I know it's neither short nor real coding, but I still wanted to post this

```
<head>
<style>

#a{
width:100px;
height:100px;
border-radius:50px;
border: 1px solid black;
}
#b{
position: absolute;
top:30px;
left:30px;
width:20px;
height:20px;
border-radius:10px;
border: 1px solid black;
}
#c{
position: absolute;
top:0px;
left:40px;
width:20px;
height:20px;
border-radius:10px;
border: 1px solid black;
}#d{
position: absolute;
top:30px;
left:-30px;
width:40px;
height:20px;
border-radius:10px;
border: 1px solid black;
}
</style>
</head>
<body>
<div id="a">
<div id="b"/>
<div id="c"/>
<div id="d"/>
</div>
</body>

```

jsFiddle
> 4 votes

# Answer
## Rebmu, 24 chars

Oh, the m-i-n-i-m-a-l humanity. :-) Least impressive Rebmu program yet, so purposefully embedding pHp as a tribute to the blue pill in the programming world:

`H{ -- }pHp{|..|^/|\/|}pH`

**Execution:**

```
>> rebmu [H{ -- }pHp{|..|^/|\/|}pH]
 --
|..|
|\/|
 --

```

**Explanation**

Rebmu is just a dialect of Rebol. It inherits the parse constraints, uses abbreviated terms without spaces separated by runs of capitalization. It has a special treatment when the first run is capitalized vs uncapitalized.

*(So rather than separating terms like `AbcDefGhi` it can use the difference between `ABCdefGHI` and `abcDEFghi` to squeeze out a bit of information. Sequences whose runs start in all capitalized are separated so the first term represents a "set-word!", often contextually interpreted as a desire for an assignment. see video)*

If you want to translate this to native Rebol, you have to accept things like that it starts with a capital H to mean that's actually an `h:` and not an `h`. The source is thus analogous to:

```
h: { -- }
print h
print {|..|^/|\/|}
print h

```

Assigns the string `--` to h (using asymmetric string delimiters because `print {"Isn't it nice," said {Dr. Rebmu}, "when you have asymmetric multi-line string delimiters with no need for escaping matched nested pairs, and that accept apostrophes and quotes too?"}`

Prints h once, prints another string where `^/` is the escape sequence for newline *(carets being less used in software than backslashes which appear often in paths)*, prints h again.
> 4 votes

# Answer
**Perl, 106 chars**

It is a Perl oneliner, just have to C&P it on command prompt, provided the Perl `Acme::EyeDrops` module is already installed on the machine.

```
touch temp && perl -MAcme::EyeDrops='sightly' -e 'print sightly({Shape=>"smiley", SourceFile => "temp" } );'

```

Another way , a smiley with Pulling a face

```
     touch temp && perl -MAcme::EyeDrops='sightly' -e 'print sightly({Shape=>"smiley2",SourceFile=>"temp"});'

```

Yet another way,a smiley with Pulling a face upside down,

```
 touch temp && perl -MAcme::EyeDrops='sightly' -e 'print sightly({Shape=>"smiley2",SourceFile=>"temp",RotateFlip=>'true',Rotate=>'180'});'

```
> 4 votes

# Answer
# Bash + ImageMagick: 137 characters

```
c=circle
convert -size 99x99 xc: -draw "fill #ff0 $c 49,49,49" -fill 0 -draw "$c 30,35,30,30 $c 70,35,70,30 ellipse 50,60,25,20,0,180" x:

```

Sample output:

But as this is an challenge…

# Bash + ImageMagick: 172 characters

```
d=-draw
p=-pointsize
convert -size 99x99 xc: -font times.ttf $p 140 -stroke 0 -fill \#ff0 $d 'text 0,96 O' $p 40 $d 'text 25,50 "o 0"' $p 50 $d 'rotate 95 text 50,-40 D' x:

```

Sample output:
> 4 votes

# Answer
# GolfScript, 27

This outputs the 2nd example exactly as given.

```
' .'3*.'
. o o .
. \_/ .
'\

```

First one can be done the same way, but I think the 2nd one looks nicer :)
> 3 votes

# Answer
# Brainf\*** - 2

```
+.

```

Prints  or ascii value 1. (might not work with some platforms)
> 2 votes

# Answer
# Bash - one liner: 442 characters

```
c(){ e "define a(i){scale=scale(i);return(sqrt(i*i));};""$@"|bc -l;};e(){ echo "$@";};s(){ h=$1;c=$2;if [ -z $c ];then c=" ";fi;while (($((h=h-1))>0));do e -n "$c"; done; };m(){ t=`c 2*$1`;while (($((t=t-1))));do l=`c a\($1-$t\)+1`;s $l;q=`c 2*\($1-$l\)`;w=`s $q`;if (($l>$t&&$l<($t+3)&&$q>2)); then w=" "`s $((q-2)) 0`" ";elif (($t>($1+1)&&$q>3));then g=`s $(((q-1)/2)) 0`;w=" $g $g ";fi;e -n +;if [ ! -z "$w" ];then e -n "$w+";fi;e;done;};

```

Example output: (called by `m 8`)

```
       +
      + +
     +   +
    + 0 0 +
   + 00 00 +
  + 000 000 +
 +           +
+             +
 +           +
  +         +
   +       +
    + 000 +
     +   +
      + +
       +

```

Kind of crazy, but I chose to use a diamond instead of a circle. The eyes are covered by safety goggles.

# BASH - 252 characters (thanks @manatwork)

```
s(){ (($1>1))&&echo -n "${2:- }"&&s $[$1-1] $2;};m(){ ((t=2*$1));while ((t=t-1));do v=$[$1-t];l=$[${v#-}+1];s $l;q=$[2*($1-l)];w=`s $q`;((l>t&&l<t+3&&q>2))&&w=" `s $[q-2] 0` ";((t>$1+1&&q>3))&&{ g=`s $[(q-1)/2] 0`;w=" $g $g ";};echo "+${w:+$w+}";done;}

```
> 2 votes

# Answer
**HTML + CSS, 83**

```
<div><a>o<a>o</a><hr><hr><style>a,div{width:2em;border:2px solid;border-radius:8px

```

screenshot(using firefox):

too bad that I'm too late with my answer (got +10 rep also quite late ...)
> 2 votes

# Answer
# GolfScript, 18

This program uses some binary-encoded values which appear as weird/invalid characters in a text editor.

Here's the hex dump:

```
00000000  27 c1 94 80 a2 9c c1 27  7b 32 62 61 73 65 20 70  |'......'{2base p|
00000010  7d 25                                             |}%|

```

Note: it doesn't work in a UTF-8 locale, but works fine with ISO-8859-1 for example.

The expanded version with escaped characters:

```
"\xc1\x94\x80\xa2\x9c\xc1"{2base p}%

```

Output:

```
[1 1 0 0 0 0 0 1]
[1 0 0 1 0 1 0 0]
[1 0 0 0 0 0 0 0]
[1 0 1 0 0 0 1 0]
[1 0 0 1 1 1 0 0]
[1 1 0 0 0 0 0 1]

```

For nicer output, you can replace the block with `{2base{38+}%n}` which brings the binary version to 23 bytes. Expanded version:

```
"\xc1\x94\x80\xa2\x9c\xc1"{2base{38+}%n}%

```

Output:

```
''&&&&&'
'&&'&'&&
'&&&&&&&
'&'&&&'&
'&&'''&&
''&&&&&'

```
> 1 votes

# Answer
# Python

~~```
smileyFace = '''
       000000000000000
      00000000000000000
     000000   00   00000
    0000000 . 00 . 000000
   00000000   00   0000000
  0000000000000000000000000
 000000 . 00000000 . 0000000
  000000 . 000000 . 0000000
   0000000 ....... 0000000
    000000000000000000000
     0000000000000000000
      00000000000000000'''
print(smileyFace)

```~~
```
print('  _________\n /         \\\n |  /\\ /\\  |\n |    -    |\n |  \\___/  |\n \\_________/');

```

Output:

```
  _________
 /         \
 |  /\ /\  |
 |    -    |
 |  \___/  |
 \_________/

```
> 1 votes

# Answer
# JavaScript

This code must be run in `f12` on this page:

```
console.log(document.getElementsByTagName("code")[0].innerHTML)

```

Output:

```
 0 0 0    . . .
0 . . 0  . o o .
0 --- 0  . \_/ .
 0 0 0    . . .

```
> 1 votes

# Answer
# CJam, 18

I decided to go for short code... Try it here.

```
" ##O#- #"2/{_(N}%

```

## Explanation

```
" ##O#- #"      "Push a string onto the stack";
2/              "Split it into an array of two-character groups";
{_(N}%          "For each item in the array, execute _(N : duplicate the element,
                 remove the first character and place it onto the stack after what's left,
                 and push a new line.";

```

This exploits the symmetry of the smiley face I designed.

## Output

```
 ##
#OO#
#--#
 ##

```
> 1 votes

# Answer
## Javascript console

a frog:

```
prompt("◉◉ ", ' '.repeat(25)+"⊂(‿)つ")

```

table flip

```
prompt("┻━┻", ' '.repeat(24)+"ʕノ•ᴥ•ʔノ")

```

and i am not sure what this one is

```
prompt('◕  '.repeat(24),prompt("◕              ◕", '  ▇  '.repeat(24)))

```
> 1 votes

# Answer
## Python, 42

```
print ' 0 0 0 \n0 . . 0\n0 --- 0\n 0 0 0 '

```
> 0 votes

# Answer
HTML 5 : 321 Characters

```
<canvas id=a><script>_=document.getElementById("a"),c=_.getContext("2d"),p=Math.PI,P=2*p;C();c.arc(95,85,40,0,P);B();c.lineWidth=2;c.stroke();c.fillStyle="red";C();c.arc(75,75,5,0,P);B();C();c.arc(114,75,5,0,P);B();C();c.arc(95,90,26,p,P,true);B();function C(){c.beginPath()};function B(){c.closePath();c.fill()}</script>

```

Fiddle : http://jsfiddle.net/wfNGx/

Source : http://www.codecademy.com/courses/web-beginner-en-SWM11/0/1
> 0 votes

# Answer
# Shell command or builtin

```
$ echo -e ' ,---.\n/ o o \\\n\ \\_/ /\n `---´'
 ,---.
/ o o \
\ \_/ /
 `---´
$ printf ' ,---.\n/ o o \\\n\ \\_/ /\n `---´\n'
 ,---.
/ o o \
\ \_/ /
 `---´

```

Depending on the flavour of your shell or command set, `echo` may or may not interprete control characters with or witout `-e`... (...and I demand that I may or may not be Vroomfondel!) just try... and if all else fails, using `printf` should be a safe bet...
> 0 votes

# Answer
## C 178 characters:

source (whitespace added - all can be removed except at `int x`

```
int x,y;
c(a,b,r)
{
  return  (x-a)*(x-a) + (y-b)*(y-b) < r*r;
}

main()
{
  for(x=9;x>=-9;--x)
  {
     for(y=-9;y<=9;++y)
       putchar(32<<(
         c(0,0,10)&&!(c(4,4,2)|c(4,-4,2)|c(3,0,8)&!c(7,0,10))
       ));
     putchar(10);}
 }

```

output:

```
     @@@@@@@@@
    @@@@@@@@@@@
  @@@@@@@@@@@@@@@
  @@@@@@@@@@@@@@@
 @@@   @@@@@   @@@
@@@@   @@@@@   @@@@
@@@@   @@@@@   @@@@
@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@
@@@ @@@@@@@@@@@ @@@
@@@  @@@@@@@@@  @@@
@@@@           @@@@
@@@@@@       @@@@@@
 @@@@@@@@@@@@@@@@@
  @@@@@@@@@@@@@@@
  @@@@@@@@@@@@@@@
    @@@@@@@@@@@
     @@@@@@@@@

```
> 0 votes

# Answer
## T-SQL, 628

For SQL Server 2012+

This is a query I did some time ago as a bit of fun and to show my kids.
It uses the string in @ to determine a few parameters B = base, O = offset, M = multiplier, D = divisor. These are then used to create a SQL Server Geometry (2012+).

It's not particularly golfed.

```
DECLARE @ varchar(30)='Don''t Worry, Be Happy';
WITH P AS(
    SELECT LEN(PARSENAME(F,1))D,
        LEN(PARSENAME(F,2))M,
        LEN(PARSENAME(F,3))B,
        LEN(PARSENAME(F,4))O
    FROM (VALUES(REPLACE(@,' ','.')))S(F)
    )
SELECT @, Geometry::Point(B*M,B*M,0).STBuffer(B*M).STDifference((
    SELECT Geometry::UnionAggregate(g)
    FROM (
        SELECT Geometry::Point(B*M-O,B*M+O,0).STBuffer(B/D*M)FROM P
        UNION ALL
        SELECT Geometry::Point(B*M+O,B*M+O,0).STBuffer(B/D*M)FROM P
        UNION ALL
        SELECT Geometry::STGeomFromText(
            CONCAT('CIRCULARSTRING(',
                B*M-O,' ',B*M-O,',',
                B*M,' ',(B*M-O)-((B*M)/(B*M-O)),',',
                B*M+O,' ',B*M-O,')'),0).STBuffer(B/D)FROM P
            )A(G)
        ))
FROM P

```

When run in SSMS it shows the following in the spatial results tab
> 0 votes

# Answer
# Javascript, 857 bytes

Just some idle obfuscation.

```
un="̤̤Ո͈̤ՇՇ̤͆F͆Ë̠̠́̈́ ՃC̠B̠͂ՁՁ̠Հ@ ̿̿Ԡ̾͜ծ̽̽>̼͂̾̾Ի̽;͂Ժͅ$Թ̹͈8՜̢77Շ̶Է̷̵554̓ͯ3oͯԲHͯ18̤̰0̰/ͣoͮͳol̮ͥլ̨ͯͧՠ̻Ծ̈́22̰ԲԲԺD2/ͯԽ̻̲̓/F1@̳̤C͈̠o̤̽Գ $̠2́3̯0ͯ?HԠ͈̠1̤̽2 ̤ ̤̠7̤̳̓9̰̤͂BFG̱?Ԥ1̱̤̽6$Ա̤̈́3Թ̸̱̀̀͂ͅՅ=DF͇B̸Հ̸@̰Ը≠̰̈́B0$Ղ0Ḧ̵̶́̽̓64/̯̤A̶=Ղ͇3/̯͈A̷̤1Խ̳͈7Ճ/ԯ͇̤̿Ա=C͇B/̰̹Է ̶$̱2̲H1Խ̈́o$1̲̤ͯ͆Dԯ̰$̳̰Ն̤̽Dͅ6$Cԯ9$A̴̴̴̠͆̽Կ͆͂7̯F7̓3G̼7̤̱́57԰ՆՈ̷H̷> ͇<D̤1̾̈́7H5FH4Ծ̳͇<̓H̱̻̠2̳͇̾̈́7̻̽7H̱C3͆17͈1̳̻́͆̽̈́Զ1ͯ́5HԱG̱3̵̺͆̈́ 5G̱̲oD7̤1̹57̺͂5͆$1oԠ̹̤?:>B4̸̾Ժ̻̰̿Ժ̻̠9̷̤̺̀ԻD̶4=͠ԩ",=window;for( in {escape:="un"})for(_=[`${}${}`]([](un).replace(/u../g,[]));__=/[/-H]/.exec(_);)with(_.split(__ ))_=join(shift());setTimeout(_,0)

```
> 0 votes

# Answer
# ConTeXt/MetaPost (~~104~~ 89 bytes)

This is a rather minimalistic smiley and you need at least 1000% zoom to see that poker face:

```
\startMPpage
let D=draw;D fullcircle scaled 5;D left;D right;D(-1,-1)--(1,-1)
\stopMPpage

```

You can compile the document here as a PDF
> 0 votes

---
Tags: ascii-art, popularity-contest
---


# Question
Title: Determine the Base where a Given Equation is True
Given 3 integers, determine the lowest possible base for the first two integers to multiply into the third. If you think of the Answer to the Ultimate Question of Life, The Universe, and Everything, 6 * 9 == 42, is true in Base 13.

The inputs can include any numbers whose digits use the characters 0-9, a-z, and A-Z, where `a` equals 10 in Base 10, and `Z` is 61 in Base 10.

The inputs should be inputted in any way you like (except for hard-coding), and you can write either an individual function or an entire program.

The maximum base that must be considered is Base 62, and the minimum base is Base 2.

You can assume that the first two values are smaller than the third. You can also conclude that the minimum base is one greater than the highest digit/character from the inputs (for example, if the inputs are `3 1a 55`, the minimum base would be Base 11, because `a` is the highest digit).

If there is no such base, return a junk value of your choice.

This is code golf, so the shortest code wins.

**Test Cases**

```
6 9 42     -->   13
a a 64     -->   16
aA bB 36jk -->   41
2 3 20     -->   <junk value>
10 10 100  -->   2

```

# Answer
## CJam, ~~52~~ ~~51~~ 48 bytes

```
63,{_ea{i32b~\([G-35-9]=-_Xe>:X;}f%fbW%~*=\X>*}#

```

Test it here. The online tester doesn't support input via ARGV. The closest alternative is to put put the input like `6 9 42` into STDIN and use:

```
lS/:E;
63,{_E{i32b~\([G-35-9]=-_Xe>:X;}f%fbW%~*=\X>*}#

```

This prints `-1` if no valid base up to 62 can be found.

Many thanks to Peter for the digit parsing code!

I fixed a lot of problems which added 14 bytes to the count. The following explanation is still for my original submission, and I'll update it some time tomorrow.

```
63,{_ea{i32b~\([G-35-9]=-_Xe>:X;}f%fbW%~*=\X>*}#
63,                                              "Push the array [0 1 .. 62].";
   {                                          }# "Find the first index for which the block returns
                                                  a truthy value.";
    _                                            "Duplicate the current base.";
     ea                                          "Read ARGV into an array of strings.";
       {                        }f%              "Apply this block to each character.";
        i32b                                     "Convert to code point, and then to base-32. The
                                                  most significant digit now identifies the 'type'
                                                  of digit.";
            ~\(                                  "Unwrap the array. Swap the digits. Decrement.";
               [G-35-9]                          "Push array [16 -35 -9] of digit offsets.";
                       =-                        "Select the relevant offset and subtract it from
                                                  the least significant digit.";
                         _                       "Duplicate the current digit D.";
                          Xe>:X;                 "X := max(X,D). X is predefined as 1.";
                                   fb            "Convert all numbers to the current base.";
                                     W%          "Reverse the list of numbers.";
                                       ~         "Unwrap the array.";
                                        *=       "Multiply factors. Check equality with product.";
                                          \      "Swap result with current base.";
                                           X>    "Ensure base is greater than X.";
                                             *   "Multiply boolean results.";

```

The index is printed automatically at the end of the program.
> 3 votes

# Answer
# APL (Dyalog Unicode), 30 bytesSBCS

```
⊢{3⊃e=×/2↑e←⍵⊥⍺:⍵⋄⍺∇⍵+1}1+⌈/∘,

```

Try it online!

Thanks to Adám for the help.

Explanation:

```
⊢{3⊃e=×/2↑e←⍵⊥⍺:⍵⋄⍺∇⍵+1}1+⌈/∘, ⍝
⊢                              ⍝ left argument ⍺: the vector (do nothing)
                        1+⌈/∘, ⍝ right argument ⍵: our starting base.
                             , ⍝             start by flattening the matrix of arguments                               ⌈/   ⍝             reduce by max (find the highest number)
                            ∘  ⍝             compose both of these together
                        1+     ⍝             increment by one
 {         ⍵⊥⍺         }       ⍝ convert inputs to the current base
 {       e←            }       ⍝ store the converted values in 3
 {      2↑             }       ⍝ take the first 2 values
 {    ×/               }       ⍝ multiply them together (reduce-multiply)
 {  e=                 }       ⍝ compare with e (the converted inputs)
 {3⊃                   }       ⍝ only keep the result of the comparison with the 3rd element (expected result)
 {             :⍵      }       ⍝ if truthy, return the current base.
 {               ⋄     }       ⍝ otherwise...
 {                ⍺∇⍵+1}       ⍝ ...recurse with the base incremented

```

We use a helper function, `In`, to receive the input into a more palatable format. Otherwise the input is received a matrix of 3 columns.

`'3 9 42'` would give, for example (read top-down then left-to-right):

```
0 0 4
3 9 2

```

And for `'aA bB 36jk'` (same here. `a` is 10, `b` is 11, `A` is 36, etc)

```
 0  0  3
 0  0  6
10 11 19
36 37 20

```
> 7 votes

# Answer
## CJam, 53 bytes

```
lA,s'{,97>+'[,65>+f#_$W=1e>)63,>_@Wa/W%f{fb~*=}1#\0+=

```

Takes the three input from STDIN like

```
6 9 42

```

Prints `0` if product in any base is not possible

Will try to golf it further.

Try it here
> 2 votes

# Answer
# Python 2 - ~~197~~ 213

What a monster... (compared to CJam)

```
from string import*
I=raw_input()
x,y,z=I.split()
B=lambda s,b:sum(b**i*(digits+lowercase+uppercase).find(s[-i-1])for i in range(len(s)))
print([b for b in range(B(max(I),10)+1,62)if B(x,b)*B(y,b)==B(z,b)]+[0])[0]

```

Unfortunately `int`'s base conversion can only handle bases up to 36. So I needed to implement it by myself. (See this wonderful solution.)
> 2 votes

# Answer
# JavaScript (E6) 129 ~~139~~

Recursively try all bases from 2 up to 62, returning -1 if no value is ok.
JavaScript parseInt function works with base up to 36, so a little help is needed for greater bases.
Beware, the parameters x,y,z are strings, not numbers.
It's more difficult than it seems. Thanks to Martin for pointing out a basic bug in the first version.

```
F=(x,y,z,b=2,N=n=>[for(d of(t=0,n))t=(v=parseInt(d,36)+(d>'@'&d<'a')*26)<b?t*b+v:NaN]&&t)=>b<63?N(x)*N(y)!=N(z)?F(x,y,z,b+1):b:-1

```

**Less golfed**

```
F=(x,y,z,b=2,
   D=d=>parseInt(d,36)+(d>'@'&d<'a')*26, // parse a single digit
   N=n=>[for(d of(t=0,n))t=(v=D(d))<b?t*b+v:NaN]&&t // parse a string
)=>b<63?N(x)*N(y)!=N(z)?F(x,y,z,b+1):b:-1

```

**Test** In FireFox/FireBug console.
The test tries 1000 numbers with different bases (up to 36, not 62). It's worth noting that the found base could be correct but less than the base that generated the test case.

```
for(i=0;i<1000;i++)
{
   x=Math.random()*100|0,y=Math.random()*100|0,z=x*y,b=Math.random()*35+2|0
   bx=x.toString(b),by=y.toString(b),bz=z.toString(b),
   nb=F(bx,by,bz)
   nx=parseInt(bx,nb),ny=parseInt(by,nb),nz=parseInt(bz,nb)
   // if (nx*ny != nz) // uncomment to se output for errors only
     console.log(x,y,z,'base '+b,bx,by,bz, 'found base '+nb,nx,ny,nz,nx*ny)
}

```
> 1 votes

# Answer
# Prolog - 195 bytes

Basically the same idea as my Erlang answer:

```
:-use_module(library(main)).
main(A):-between(2,62,B),maplist(x(B),A,[F,G,P]),0is F*G-P,write(B).
c(I,B,Q,O):-Q=[H|T]->(H<65->D=48;H<97->D=29;D=87),H-D<B,c(I*B+H-D,B,T,O);O=I.
c(B)-->name,c(0,B).

```

In readable:

```
:- use_module(library(main)).

main(Args) :-
    between(2, 62, Base),
    maplist(convert(Base), Args, [Factor1, Factor2, Product]),
    0 is Factor1 * Factor2 - Product,
    write(Base).

convert(Accumulator, Base, List, Output) :-
    List = [Head|Tail] ->
        (   Head < 65 -> Offset = 48;
            Head < 97 -> Offset = 29;
                         Offset = 87),
        Head - Offset < Base,
        convert(Accumulator * Base + Head - Offset, Base, Tail, Output);
    Output = Accumulator.

convert(Base, Input, Output) :-
    name(Input, List),
    convert(0, Base, List, Output).

```

Invocation:

```
$ swipl -qg main x.pl 6 9 42
13
$ swipl -qg main x.pl aA bB 36jk
41
$ swipl -qg main x.pl 2 3 20
ERROR: Unknown message: goal_failed(main([2,3,20]))

```
> 1 votes

# Answer
# Charcoal, 28 bytes

```
Ｉ⌊Φ…⊕⍘⌈⁺⁺θηζ⁶²¦⁶³⁼×⍘θι⍘ηι⍘ζι

```

Try it online! Link is to verbose version of code. Outputs `None` if no valid base can be found. Explanation:

```
         θ                      First input
        ⁺                       Concatenated with
          η                     Second input
       ⁺                        Concatenated with
           ζ                    Third input
      ⌈                         Maximum character (by ordinal)
     ⍘                          Converted from base
            ⁶²                  Literal 62
    ⊕                           Incremented
   …                            Range up to
               ⁶³               Literal 63
  Φ                             Filtered by
                    θ           First input
                   ⍘            Converted from base
                     ι          Current value
                  ×             Multiplied by
                       η        Second input
                      ⍘         Converted from base
                        ι       Current value
                 ⁼              Equals
                          ζ     Third input
                         ⍘      Converted from base
                           ι    Current value
 ⌊                              Minimum
Ｉ                               Cast to string
                                Implicitly print

```
> 1 votes

# Answer
# Jelly, 16 bytes

```
62ḊḅṪ=PƊ¥@ƇeoḢ{ɗ

```

Try it online!

Takes input similar to the APL answer. For example, `aA bB 36jk` is input as `[10, 36], [11, 37], [3, 6, 19, 20]`. The Footer does this for you.

If this isn't acceptable, +10 bytes to convert from a list of strings.

Outputs `1` as the junk value.

## How it works

I'll explain the preceding 10 bytes for the longer version first, as both share the same ending 16 bytes:

```
ØBŒsiⱮⱮ⁸’µ - Main link. Takes a list of strings on the left
ØB         - Yield '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
  Œs       - Swap-case
      Ɱ⁸   - Over each string in the left argument:
     Ɱ     -   Over each character:
    i      -     1-based index
        ’  - Decrement to 0-index
         µ - Use this list of numbers as the argument from now on

62ḊḅṪ=PƊ¥@ƇeoḢ{ɗ - Main link. Takes an list of lists of integers on the left
62               - Yield 62
  Ḋ              - Dequeue; [2, 3, 4, ..., 62]
          Ƈ      - Filter this array...
        ¥        -    ...on the following, ...
         @       -    ...with the list on the right:
   ḅ             -   Convert from base
       Ɗ         -   To this array of integers:
    Ṫ            -     Does the tail...
     =           -     equal...
      P          -     ...the product without the tail?
               ɗ - Using the input on the right and the filtered array on the left:
           e     -   Is the filtered array in the input?
             Ḣ{  -   Yield the first element of the filter
            o    -   If the filtered array is in the input, return 1, else the first element

```
> 1 votes

# Answer
# Erlang (escript) - 200

```
main(X)->m(2,X).
m(63,_)->0;m(C,X)->try[F,G,I]=[c(0,C,Y)||Y<-X],I=F*G,io:fwrite("~p",[C])catch _:_->m(C+1,X)end.
c(A,B,[H|T])->D=H-if$A>H->$0;$a>H->29;0<1->87end,if D<B->c(A*B+D,B,T)end;c(A,_,_)->A.

```

Add two leading newlines which must be present.

In readable:

```
#!/usr/bin/env escript

main(Args) -> test(2, Args).

test(63, _) -> 0;
test(Base, Args) ->
    try
        [Factor1, Factor2, Product] = [convert(0, Base, Arg) || Arg <- Args],
        Product = Factor1 * Factor2,
        io:fwrite("~p", [Base])
    catch _:_ ->
        test(Base + 1, Args)
    end.

convert(Accumulator, Base, [Head|Tail]) ->
    Digit = Head - if Head < $A -> $0;
                      Head < $a -> $A - 10 - 26;
                      true      -> $a - 10
                   end,
    if Digit < Base ->
        convert(Accumulator * Base + Digit, Base, Tail)
    end;
convert(Accumulator, _, _) -> Accumulator.

```

Invocation:

```
$ escript x.erl 6 9 42
13
$ escript -i x.erl a a 64
16
$ escript -i x.erl aA bB 36jk
41
$ escript -i x.erl 2 3 20
(no output)
$ escript -i x.erl 10 10 100
2

```
> 0 votes

# Answer
# Haskell 216 char (177?)

Tried to golf this as much as possible. If imports are counted, then this is my shortest code (216)

```
import Data.Char
import Data.List
m=maximum
j[]=0;j(x:_)=x
f=reverse.map(\x->ord x-48)
g[]_=0;g(m:n)x=m+x*g n x
main=do
l<-getLine
let k@[x,y,z]=words l
print$j[n|n<-[2..62],g(f x)n*g(f y)n==g(f z)n,n>(m.map(m.f)$k)]

```

However, were imports not counted, then this is my best version (177):

```
import Data.Char
import Data.List
import Control.Applicative
m=maximum
j[]=0;j(x:_)=x
f=reverse.map(\x->ord x-48)
g[]_=0;g(m:n)x=m+x*g n x
main=words<$>getLine>>= \k@[x,y,z]->print$j[n|n<-[2..62],g(f x)n*g(f y)n==g(f z)n,n>(m.map(m.f)$k)]

```

This treats each number as a polynomial P(x) where x is the base, on condition that no coefficient is larger than x; I then evaluate the polynomials over each possible base, stopping when I reach one that satisfies the equality P(x)\*Q(x)=R(x). The 'base is bigger than largest digit' rule is enforced with the last guard in the pattern match, namely `n>(m.map(m.f)$k)`. I know that different golfing challenges and different challenge-makers have different policies regarding imports vis-a-vis scoring, so take the second one with a grain of salt.
> 0 votes

# Answer
# Julia, 122 bytes (79 with bending rules)

Julia has an in-built up to base 62 integer parser, but the problem is uppercase characters come before lowercase

```
f(l,n=2)=try
L=[parse(Int,join(i+32(i>'9')-64(i>'Z') for i=j),base=n) for j=l]
L[1]L[2]==L[3]||$
n
catch
n<62&&f(l,n+1)end

```

`$` isn't define and will raise an error when the equality isn't right

Try it online!

# Julia, 79 bytes by swapping uppercase and lowercase

If I'm allowed to swap lowercase and uppercase, It would shave off a lot of bytes (or at least if there was a `swapcase` function)

```
f(l,n=2)=try
L=parse.(Int,l,base=n)
L[1]L[2]==L[3]||$
n
catch
n<62&&f(l,n+1)end

```

Try it online!
> 0 votes

---
Tags: code-golf, number, base-conversion
---


title: Parse the Markdown-like Markup!

text:
# Question
Title: Parse the Markdown-like Markup!
# The Challenge

In this challenge, you are supposed to write a program or function that takes in a String, which will contain the simplified Markdown-like Markup, and outputs the corresponding HTML Markup.

---

# The Input

You can take input in whatever way you wish to. The `type` of the input should be String.

---

# The Output

You can output the result in any way you want. Logging to Console or Terminal, printing on screen, returning from function etc. are perfectly valid.

---

# The Rules

* Convert each occurrence of `*foo*` and `_foo_` to `<em>foo</em>`.
* Convert each occurrence of `**foo**` and `__foo__` to `<strong>foo</strong>`.
* Convert each occurrence of `<tab or four spaces here>foo\n` to `<pre><code>foo</code></pre>`.
* Convert each occurrence of `#foo\n` to `<h1>foo</h1>`.
* Convert each occurrence of `##bar\n` to `<h2>bar</h2>`.
* Convert each occurrence of `###bar\n` to `<h3>bar</h3>`.
* Convert each occurrence of `####bar\n` to `<h4>bar</h4>`.
* Convert each occurrence of `#####bar\n` to `<h5>bar</h5>`.
* Convert each occurrence of `######bar\n` to `<h6>bar</h6>`.
* Convert each occurrence of `[foo](https:\\www.bar.com)` to `<a href="https:\\www.bar.com">foo</a>`.
* Convert each occurrence of `![foo](https:\\www.bar.com)` to `<img src="https:\\www.bar.com" alt="foo"/>`.
* Convert each occurrence of `>foo\n` to `<blockquote>foo</blockquote>`.
* Convert each occurrence of `- foo\n` as `<li>foo</li>` (add `<ul>` before the `li` if the `-` is the first of its consecutive series and add `</ul>` if it is the last.)
* Convert each occurrence of `n. foo\n` (where the first `n` denotes an Integer such as 12,1729 etc.) as `<li>foo</li>` (add `<ol>` before the `li` if the element is the first of its consecutive series and add `</ol>` if it is the last.)
* Although there exist many more rules of conversion, you are supposed to follow only the abovementioned ones (for the sake of simplicity).
* You are supposed to output only the corresponding HTML Markup for the given String. No need to add extra elements that are necessary for creating a valid HTML file (like `<body>`, `<html>` etc.). However, if they are present in the input String, then you will have to output them too, that is, replace `<` and `>` with `<` and `>`, repspectively.
* *You must NOT use any built-in! (I doubt whether there exists one)*

**Note :** In the abovementioned rules, `foo`, `bar` and `https:\\www.bar.com` are only placeholders. Your program or function must be flexible enough to work for Strings different than these too.

---

# Scoring

This is , so the shortest code in bytes wins!

---

# Test Cases

```
"**Hello**" -> "<strong>Hello</strong>"

"#IsThisAwesome?\n" -> "<h1>IsThisAwesome?</h1>"

">![Image](http:\\www.somewhereontheinternet.com) -> "<blockquote><img src='https:\\www.somewhereontheintenet.com' alt='Image'/></blockquote>"

">Some Content\n- Item1\n- Item2\n- Item3\n" -> "<blockquote>Some Content</blockquote><ul><li>Item1</li><li>Item2</li><li>Item3</li></ul>"

"1.Hello\n2.Bye\n3.OK\n" -> "<ol><li>Hello</li><li>Bye</li><li>OK</li></ol>"

```

---

# Special Thanks to FakeRainBrigand!

This challenge was originally proposed by @FakeRainBrigand in the Sandbox. He granted me the permission to post this challenge on the regular website. Due to unclear and broad specifications, the challenge was closed. Now, it has been reopened with clearer and fewer specs by @Arjun.

# Answer
> 4 votes
# PHP, 770 Bytes

Online Version

There are some rules to make html with this markup

the replacement of blockquote must before all others

h6,h5,h4,h3,h2,h1 is the next order

strong, em

img, a

and (li ,ul, li,ol) or (li ,ol, li,ul)

```
$s=[
"%>(.*)\n%Us"
,'%(\*|_)\1(.+)\1\1%Us'
,'%(\*|_)(.*)\1%Us'
,'%######(.*)\n%Us'
,'%#####(.*)\n%Us'
,'%####(.*)\n%Us'
,'%###(.*)\n%Us'
,'%##(.*)\n%Us'
,'%#(.*)\n%Us'
,'%- (.*)\n%Us'
,'%(?<!</li>)<li>%Us'
,'%</li>(?!<li>)%Us'
,'%\d+\. (.*)\n%Us'
,'%(?<!li>|ul>)<li>%Us'
,'%</li>(?!<(li|/ul)>)%Us'
,'%(\t|    )(.*)\n%Us'
,'%!\[(.*)\]\((.*)\)%Us'
,'%\[(.*)\]\((.*)\)%Us'
];
$r=[
'<blockquote>\1</blockquote>'
,'<strong>\2</strong>'
,'<em>\2</em>'
,'<h6>\1</h6>'
,'<h5>\1</h5>'
,'<h4>\1</h5>'
,'<h3>\1</h5>'
,'<h2>\1</h5>'
,'<h1>\1</h5>'
,'<li>\1</li>'
,'<ul><li>'
,'</li></ul>'
,'<li>\1</li>'
,'<ol><li>'
,'</li></ol>'
,'<pre><code>\2</code></pre>'
,'<img src="\2" alt="\1"/>'
,'<a href="\2">\1</a>'
];
echo preg_replace($s,$r,$i);

```

# Answer
> 2 votes
# Lua, 641 bytes

```
t={"<","&lt","^.+(>)","&gt","^(#+)(.*)",function(a,b)return("<h%d>%s</h%d>"):format(#a,b,#a)end,"^>(.*)","<blockquote>%1</blockquote>","^[\t ]+(.*)","<pre><code>%1</code>","!%[(.-)%]%((.-)%)",'<img src="%2" alt="%1"/>',"%[(.-)%]%((.-)%)",'<a href="%2">%1</a>',"%*%*","","__","","%b","<strong>%1</strong>","","","%b**","<em>%1</em>","%*","","%b__","<em>%1</em>","_",""}for l in io.lines()do u,U=l:match("^- ")or u and print("</ul>"),u o,O=l:match("^%d%. ")or o and print("</ol>"),o for i=1,#t,2 do l=l:gsub(t[i],t[i+1])end print((l:gsub("^- (.*)",(U and""or"<ul>").."<li>%1</li>"):gsub("^%d%. (.*)",(O and""or"<ol>").."<li>%1</li>")))end

```

Try it online!

### Readable Version and Explanation

```
t = { -- Table used for simple replacements
    "<", "&lt",
    "^.+(>)", "&gt", -- Cannot be at the beginning of a line because of blockquotes
    "^(#+)(.*)", function(a,b)return("<h%d>%s</h%d>"):format(#a,b,#a)end, -- Combined h# replacement
    "^>(.*)", "<blockquote>%1</blockquote>",
    "^[\t ]+(.*)", "<pre><code>%1</code>",
    "!%[(.-)%]%((.-)%)", '<img src="%2" alt="%1"/>',
    "%[(.-)%]%((.-)%)", '<a href="%2">%1</a>',
    "%*%*", "", -- Using the actual control character is shorter than using an escape code
    "__", "",
    "%b", "<strong>%1</strong>",
    "", "",
    "%b**", "<em>%1</em>",
    "%*", "",
    "%b__", "<em>%1</em>",
    "_", ""
}

for l in io.lines() do -- For every line in STDIN
    u,U=l:match("^- ") or u and print("</ul>"),u -- Some compact logic to print the end of the lists and mark things as such
    o,O=l:match("^%d%. ") or o and print("</ol>"),o

    for i=1,#t,2 do
        l=l:gsub(t[i],t[i+1]) -- Run through the table of replacements
    end

    print(( -- Use two parentheses so that we only print the first return value
        l:gsub("^- (.*)", (U and "" or "<ul>") .. "<li>%1</li>") -- Rest of the list logic
        :gsub("^%d%. (.*)", (O and "" or "<ol>") .. "<li>%1</li>")
    ))
end

```

I can expand upon specific things if wanted, but it's very late as-of posting this so it'll have to wait until later.

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


title: Circular Limited Sums

text:
# Question
Title: Circular Limited Sums
# Challenge

Let's imagine an `N`-tuple of integers between 0 and `M` inclusive, and let's call it `F`.

There are `(M + 1) ** N` possible `F`s in total.

How many such `F`s satisfy all of the following inequalities (index is one-based)?

* `F[n] + F[n+1] <= M` for `1 <= n < N`
* `F[N] + F[1] <= M`

Write a program or function that takes two **positive integers** `N` and `M` and outputs the answer in any convenient form.

## Test Cases

```
(N,M) => Answer

(1,1) => 1
(2,1) => 3
(3,1) => 4
(4,1) => 7

(1,2) => 2
(2,2) => 6
(3,2) => 11
(4,2) => 26

(10,3) => 39175
(10,4) => 286555
(10,5) => 1508401

(25,3) => 303734663372
(25,4) => 43953707972058
(25,5) => 2794276977562073

(100,3) => 8510938110502117856062697655362747468175263710
(100,4) => 3732347514675901732382391725971022481763004479674972370
(100,5) => 60964611448369808046336702581873778457326750953325742021695001

```

## Explanation

```
M (max value of element) = 1

F[1] + F[1] <= 1; F = [0]
(1,1) => 1

F[1] + F[2] <= 1; F = [0,0], [0,1], [1,0]
(2,1) => 3

F = [0,0,0], [0,0,1], [0,1,0], [1,0,0]
(3,1) => 4

F = [0,0,0,0], [0,0,0,1], [0,0,1,0], [0,1,0,0], [0,1,0,1], [1,0,0,0], [1,0,1,0]
(4,1) => 7

---

M = 2

F[1] + F[1] <= 2; F = [0], [1]
(1,2) => 2

F = [0,0], [0,1], [0,2], [1,0], [1,1], [2,0]
(2,2) => 6

F = [0,0,0], [0,0,1], [0,0,2], [0,1,0], [0,1,1], [0,2,0], [1,0,0], [1,0,1],
[1,1,0], [1,1,1], [2,0,0]
(3,2) => 11

(4,2) => 26 (left as exercise for you)

```

# Rules

* This is a challenge. **The time complexity of your code should be polynomial in `M` and `N`** (e.g. you can't generate all `(M + 1) ** N` tuples and then check for the condition). Please explain your approach in your submission.
* Standard rules apply. The shortest answer in bytes wins.

# Answer
> 8 votes
# Python with numpy, 59 bytes

```
lambda M,N:trace(mat(tri(M+1)[::-1])**N)
from numpy import*

```

Try it online!

Uses matrix multiplication to count paths. If float precision is an issue, the `mat` could specify `mat(...,int)`.

# Answer
> 4 votes
# Pyth, 27 bytes

```
.N?Ys:RTtYh-QNgQ+NTs:Rdtszh

```

Demonstration

Expects input in the format:

```
M
N

```

This is classic dynamic programming, over the left end of the values set so far, the right end, and the current size of the gap.

How it works, in pseudocode/Python:

```
.N          | define memoized fill(left, right, gap):
?           | if cap > 0 then
s:RTtY      | sum(fill(i, right, gap - 1)
h-QN        |     for i in range(M - left + 1))
gQ+NT       | else M >= left + right
            | output:
s:Rdtsz     | sum(fill(i, i, N - 1)
h           |     for i in range(M + 1))

```

`Q` is used for `M`, `z` is used for `N`, `:` is `fill`, `N` is `left`, `T` is `right`, `Y` is `gap`.

# Answer
> 4 votes
# MATL, ~~13~~ 12 bytes

```
Q:&>~PiY^Xds

```

Try it online! This is a direct translation of xnor's Python answer and my first MATL answer, so it's most likely not optimal. E.g. there is likely a shorter way to get an upper-left triangular matrix of ones than `t&lYRP`. *Edit: And it turns out there is, namely `:&>~P`. Thanks to Luis Mendo for -1 byte!*

```
               M is the first input and N the second
Q:             increment M and generate range from 1 to M+1
  &>           compare vector element wise with itself with greater-than function
               results in a upper-right triangular matrix
    ~          inverse to get lower-left triangular matrix
     P         flip rows to get upper-left triangular matrix
      i        input N
       Y^      take the matrix to the power of N
         Xds   compute the sum of the main diagonal

```

# Answer
> 3 votes
# Stax, 17 bytes

```
°(√&╒íÆ½╨⌂'├╖▼1_Z

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
^1](    [1, 0, ... 0] with M zeroes
:)      get all rotations of the array
{       begin block
  {:+rm map each array to reverse(prefixSums(arr))
},v*    execute preceding block N-1 times
F       for each array, execute the rest of the program
  iT    remove the last i elements from the array, where i is the iteration index
  F+    add the remaining elements to the running total
        implicitly print output

```

Run this one

# Answer
> 2 votes
# , 72 bytes

```
function(M,N)sum(diag(Reduce(`%*%`,rep(list(outer(0:M,0:M,"+")<=M),N))))

```

Try it online!

Ports xnor's approach.

Fails for larger test cases as R only has 32-bit integer support (they get cast to `double` once the max int value is reached), so using `gmp` or another arbitrary precision arithmetic library would be required.

Strangely, R lacks a matrix power operator, as `^` always applies elementwise.

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

```
+/1 1⍉+.×⍣(⎕-1)⍨⌽∘.≤⍨⍳1+⎕

```

Try it online!

A full program which takes N, then M as inputs.

Follows the same algorithm as xnor's Python solution.

-6 bytes from Bubbler.

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


title: Coordinate Connecting

text:
# Question
Title: Coordinate Connecting
**Input:**

Ten unique integer coordinates, between `(0,0)` and `(100,100)`.

**Output:**

The coordinates arranged in the order/an order such that a path drawn between the coordinates in that order is the shortest path possible.

This is code golf so the shortest code wins!

# Answer
# Wolfram Language (Mathematica), 40 bytes

```
MinimalBy[ArcLength@*Line]@*Permutations

```

Try it online! (7 points)

Times out for longer inputs.

Accepts a list of points with *approximate-number* coordinates.

To accept exact (`Integer`) input, **+3 bytes**:

```
MinimalBy[N@*ArcLength@*Line]@*Permutations

```

Try it online!

This is because `MinimalBy` uses Mathematica's canonical ordering, which compares objects structurally, rather than numerical ordering. Thus, for example, `3` is "less than" `1+Sqrt[2]`. This is only an issue when using exact numbers, where the length can include `Sqrt`s.
> 7 votes

# Answer
# Husk, ~~12~~ 11 bytes

*Edit: -1 byte thanks to a tip from Leo*

```
◄oṁ√Ẋδṁo□-P

```

Try it online (with only 8 points to avoid timing-out...)

**How?**

```
          P  # from all permutations of the input
◄o           # get the one that minimizes the result of
  ṁ√         # sum of all the square roots of
    Ẋ        # applying to all adjacent sets of coordinates
     δṁo     # sum of all the
        □-   # squares of the differences

```
> 5 votes

# Answer
# Haskell, <sup>~~107~~</sup> 100 bytes

```
import Data.List
f=head.sortOn(sum.(zipWith(\(x,y)(m,n)->sqrt$(x-m)^2+(y-n)^2)<*>tail)).permutations

```

Try it online!

*-7 by @xnor and @benrg*
> 4 votes

# Answer
# 05AB1E, 10 bytes

```
œΣü-nOtO}н

```

Try it online! Times out on TIO with 10 coordinates.

**Commented**:

```
œ             # all permutations of the coordinates
 Σ       }    # sort on ...
  ü           #   for each pair of adjacent coordinates ...
   -          #     take the element-wise difference
    nOt       #   Euclidean norm for each difference (square, sum, square root)
       O      #   sum all distances
         н    # take the first element

```
> 3 votes

# Answer
# JavaScript (ES6), 124 bytes

Processing 10 points on TIO takes about 35 seconds.

```
f=(a,X,Y,d=m=1/0,p=[])=>a.map(([x,y],i)=>f(a.filter(_=>i--),x,y,1/d&&d+Math.hypot(x-X,y-Y),[...p,[x,y]]))+a?o:d>m||(m=d,o=p)

```

Try it online!

### Commented

A recursive function that tries all permutations of the input points, computing the length of the path for each of them and keeping track of the shortest one.

```
f = (                   // f is a recursive function taking:
  a,                    //   a[] = input
  X, Y,                 //   (X, Y) = coordinates of the previous point
  d = m = 1 / 0,        //   d = total distance, m = minimum distance
                        //   (both initialized to +Infinity)
  p = []                //   p[] = current path
) =>                    //
a.map(([x, y], i) =>    // for each point (x, y) at position i in a[]:
  f(                    //   do a recursive call:
    a.filter(_ => i--), //     with the i-th entry removed from a[]
    x, y,               //     using (x, y) as the previous point
    1 / d               //     set the distance d to 0 if this is the 1st point
    &&                  //     otherwise:
      d +               //       update d by adding
      Math.hypot(       //       the Euclidean distance between
        x - X, y - Y    //       the points (X, Y) and (x, y)
      ),                //
    [...p, [x, y]]      //     append the point (x, y) to the path
  )                     //   end of recursive call
)                       // end of map()
+ a ?                   // if a[] is not empty:
  o                     //   just return o[]
:                       // else (complete path):
  d > m                 //   unless the new distance is greater than m,
  || (m = d, o = p)     //   update m to d and set the output o[] to p[]

```
> 3 votes

# Answer
# Java (JDK), 213 bytes

```
l->{double d=1e9,e;var r=l.clone();for(int i=0,z,x[]=new int[10];i<10;)if(x[i]<i){var t=l[z=i%2*x[i]++];l[z]=l[i];l[i]=t;for(e=z=i=0;z<9;)e+=l[z].distance(l[++z]);if(e<d){d=e;r=l.clone();}}else x[i++]=0;return r;}

```

Try it online!

It takes roughly 1 second to process.

## Explanations

This is basically the iterative heap's algorithm with the distance computation and comparison integrated, because there are no native way to get permutations and because recursion in Java is expensive, byte-wise.

I'm using `java.awt.geom.Point2D` which has a `distance(Point2D)` method but it's not reflected in the code since I try by all means to avoid writing such a long class name to spare bytes. This is why I use `l.clone()` twice and `var t`.
> 2 votes

# Answer
# Jelly, 10 bytes

```
Œ!ÆịạƝSƊÞḢ

```

Try it online!

Test case is 8 points arranged into a pseudo-regular octagon. TIO times out on 10 points, but the program should work in theory.

## Explanation

```
Œ!ÆịạƝSƊÞḢ   Main monadic link
Œ!           Permutations
        Þ    Sort by
       Ɗ     (
  Æị           Convert to complex numbers
    ạ          Absolute difference
     Ɲ           of each neighboring pair
      S        Sum
       Ɗ     )
         Ḣ   First element

```
> 1 votes

# Answer
# Python 2, ~~138~~, 135 bytes

Saved **3 Bytes** due to a suggestion from Noodle9 to use `lambda` instead of `print`!

```
lambda a:min(permutations(a),key=lambda p:sum([sum([(p[i][j]-p[i+1][j])**2for j in 0,1])**.5for i in range(9)]))
from itertools import*

```

Essentially, this program loops through all possible `permutations` of the path and prints the path with the minimum length. The `key` argument of the `min` function is a `lambda` function that calculates the sum of the "distance" between consecutive points in `p`.

Try it online!
> 0 votes

---
Tags: code-golf, geometry, sorting, path-finding
---