# Question
Title: Help, I'm trapped in a Sierpinski triangle!
Drawing the Sierpinski triangle has been done to death. There's other interesting things we can do with it though. If we squint hard enough at the triangle, we can view upside-down triangles as nodes of a fractal graph. Let's find our way around that graph!

First, let's assign a number to each node. The largest upside-down triangle will be node zero, and then we just go down layer by layer (breadth-first), assigning consecutive numbers in the order top-left-right:

Click for larger version where the small numbers are a bit less blurry.

(Of course, this pattern continues ad infinitum inside the blue triangles.) Another way to define the numbering is that the centre node has index `0`, and the children of node `i` (adjacent triangles of the next-smaller scale) have indices `3i+1`, `3i+2`, and `3i+3`.

How do we move around this graph? There are up to six natural steps one can take from any given triangle:

* One can always move through the midpoint of one of the edges to one of the three children of the current node. We'll designate these moves as `N`, `SW` and `SE`. E.g. if we're currently on node `2`, these would lead to nodes `7`, `8`, `9`, respectively. Other moves through the edges (to indirect descendants) are disallowed.
* One can also move through one of the three corners, provided it doesn't touch the edge of the triangle, to either the direct parent or one of two indirect ancestors. We'll designate these moves as `S`, `NE` and `NW`. E.g. if we're currently on node `31`, `S` would lead to `10`, `NE` would be invalid and `NW` would lead to `0`.

## The Challenge

Given two non-negative integers `x` and `y`, find the shortest path from `x` to `y`, using only the six moves described above. If there are several shortest paths, output any one of them.

Note that your code should work for more than just the 5 levels depicted in the above diagram. You may assume that `x, y < 1743392200`. This ensures that they fit inside a 32-bit signed integer. Note that this corresponds to 20 levels of the tree.

Your code must process any valid input in **less than 5 seconds**. While this rules out a brute force breadth-first search, it should be a fairly loose constraint — my reference implementation handles arbitrary input for depth 1000 in half a second (that's ~480-digit numbers for the nodes).

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

The output should be a flat, unambiguous list of the strings `N`, `S`, `NE`, `NW`, `SE`, `SW`, using any reasonable separator (spaces, linefeeds, commas, `","`...).

Standard rules apply.

## Test Cases

The first few test cases can be worked out by hand using the diagram above. The others ensure that answers are sufficiently efficient. For those, there may be other solutions of the same length that are not listed.

```
0 40                    => N N N N
66 67                   => S SW N N N
30 2                    => NW NW -or- NE SW
93 2                    => NE SW
120 61                  => NW NW NW NW N SE SW N
1493682877 0            => S S NW NW
0 368460408             => SW SW N N SW SW SE SW SW N SE N N SW SW N SE SE
1371432130 1242824      => NW NW NE NW N SE SW SW SW SE SE SW N N N N SW
520174 1675046339       => NE NW NE NE SE SE SW SW N SE N SW N SW SE N N N N SE SE SW SW
312602548 940907702     => NE NW S SW N N SW SE SE SE SW SE N N SW SE SE SE SW
1238153746 1371016873   => NE NE NE SE N N SW N N SW N SE SE SW N SW N N SE N SE N
547211529 1386725128    => S S S NE NW N N SE N SW N SE SW SE SW N SE SE N SE SW SW N
1162261466 1743392199   => NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE

```

# Answer
# Python 2, ~~208~~ ~~205~~ 200 bytes

```
A=lambda n:n and A(~-n/3)+[-n%3]or[]
f=lambda x,y:f(A(x),A(y))if x<[]else["SSNEW"[m::3]for m in
y[len(x):]]if x==y[:len(x)]else min([["NNSWE"[m::3]]+f(x[:~x[::-1].index(m)],y)for
m in set(x)],key=len)

```

A function, `f`, taking a pair of node numbers, and returning the shortest path as a list of strings.

## Explanation

We start by employing a different addressing scheme for the triangles; the address of each triangle is a string, defined as follows:

* The address of the central triangle is the empty string.
* The addresses of the north, south-west, and south-east children of each triangle are formed appending `0`, `1`, and `2`, respectively, to the address of the triangle.

Essentially, the address of each triangle encodes the (shortest) path from the central triangle to it. The first thing our program does is translating the input triangle numbers to the corresponding addresses.

Click the image for a larger version.

The possible moves at each triangle are easily determined from the address:

* To move to the north, south-west, and south-east children, we simply append `0`, `1`, and `2`, respectively, to the address.
* To move to the south, north-east, and north-west ancestors, we find the last (rightmost) occurrence of `0`, `1`, and `2`, respectively, and trim the address to the left of it. If there is no `0`, `1`, or `2` in the address, then the corresponding ancestor doesn't exist. For example, to move to the north-west ancestor of `112` (i.e., its parent), we find the last occurrence of `2` in `112`, which is the last character, and trim the address to the left of it, giving us `11`; to move to the north-east ancestor, we find the last occurrence of `1` in `112`, which is the second character, and trim the address to the left of it, giving us `1`; however, `112` has no south ancestor, since there is no `0` in its address.

Note a few things about a pair of addresses, `x` and `y`:

* If `x` is an initial substring of `y`, then `y` is a descendant of `x`, and therefore the shortest path from `x` to `y` simply follows the corresponding child of each triangle between `x` and `y`; in other words, we can replace each `0`, `1`, and `2` in `y[len(x):]` with `N`, `SW`, and `SE`, respectively.
* Otherwise, let `i` be the index of the first mismatch between `x` and `y`. There is no path from `x` to `y` that doesn't pass through `x[:i]` (which is the same as `y[:i]`), i.e., the first common ancestor of `x` and `y`. Hence, any path from `x` to `y` must arrive at `x[:i]`, or one of its ancestors, let's call this triangle `z`, and then continue to `y`. To arrive from `x` to `z`, we follow the ancestors as described above. The shortest path from `z` to `y` is given by the previous bullet point.

If `x` is an initial substring of `y`, then the shortest path from `x` to `y` is easily given by the first bullet point above. Otherwise, we let `j` be the smallest of the indices of the last occurrences of `0`, `1`, and `2` in `x`. If `j` is greater than, or equal to, the index of the first mismatch between `x` and `y`, `i`, we simply add the corresponding move (`S`, `NE`, or `NW`, respectively) to the path, trim `x` to the left of `j`, and continue. Things get trickier if `j` is less than `i`, since then we might get to `y` fastest by ascending to the common ancestor `x[:j]` directly and descending all the way to `y`, or we might be able to get to a different common ancestor of `x` and `y` that's closer to `y` by ascending to a different ancestor of `x` to the right of `i`, and get from there to `y` faster. For example, to get from `1222` to `1`, the shortest path is to first ascend to the central triangle (whose address is the empty string), and then descend to `1`, i.e., the first move takes us to the left of the point of mismatch. however, to get from `1222` to `12`, the shortest path is to ascend to `122`, and then to `12`, i.e., the first move keeps us to the right of the point of mismatch.

So, how do we find the shortest path? The "official" program uses a brute-force-ish approach, trying all possible moves to any of the ancestors whenever `x` is not an initial substring of `y`. It's not as bad as it sounds! It solves all the test cases, combined, within a second or two.

But then, again, we can do much better: If there is more than one directly reachable ancestor to the left of the point of mismatch, we only need to test the rightmost one, and if there is more than one directly reachable ancestor to the right of the point of mismatch, we only need to test the leftmost one. This yields a linear time algorithm, w.r.t. the length of `x` (i.e., the depth of the source triangle, or a time proportional to the logarithm of the source triangle number), which zooms through even much larger test cases. The following program implements this algorithm, at least in essence—due to golfing, its complexity is, in fact, worse than linear, but it's still very fast.

**Python 2, ~~271~~ ~~266~~ 261 bytes**

```
def f(x,y):
 exec"g=f;f=[]\nwhile y:f=[-y%3]+f;y=~-y/3\ny=x;"*2;G=["SSNEW"[n::3]for
n in g];P=G+f;p=[];s=0
 while f[s:]:
    i=len(f)+~max(map(f[::-1].index,f[s:]));m=["NNSWE"[f[i]::3]]
    if f[:i]==g[:i]:P=min(p+m+G[i:],P,key=len);s=i+1
    else:p+=m;f=f[:i]
 return P

```

Note that, unlike the shorter version, this version is written specifically not to use recursion in the conversion of the input values to their corresponding addresses, so that it can handle very large values without overflowing the stack.

## Results

The following snippet can be used to run the tests, for either version, and generate the results:

```
def test(x, y, length):
    path = f(x, y)
    print "%10d %10d  =>  %2d: %s" % (x, y, len(path), " ".join(path))
    assert len(path) == length

#         x           y        Length
test(          0,          40,    4   )
test(         66,          67,    5   )
test(         30,           2,    2   )
test(         93,           2,    2   )
test(        120,          61,    8   )
test( 1493682877,           0,    4   )
test(          0,   368460408,   18   )
test( 1371432130,     1242824,   17   )
test(     520174,  1675046339,   23   )
test(  312602548,   940907702,   19   )
test( 1238153746,  1371016873,   22   )
test(  547211529,  1386725128,   23   )
test( 1162261466,  1743392199,   38   )

```

**Golfed Version**

```
         0         40  =>   4: N N N N
        66         67  =>   5: S SW N N N
        30          2  =>   2: NE SW
        93          2  =>   2: NE SW
       120         61  =>   8: NW NW NW NW N SE SW N
1493682877          0  =>   4: S S NW NW
         0  368460408  =>  18: SW SW N N SW SW SE SW SW N SE N N SW SW N SE SE
1371432130    1242824  =>  17: NW NW NE NW N SE SW SW SW SE SE SW N N N N SW
    520174 1675046339  =>  23: NE NE NE NE SE SE SW SW N SE N SW N SW SE N N N N SE SE SW SW
 312602548  940907702  =>  19: NE NW S SW N N SW SE SE SE SW SE N N SW SE SE SE SW
1238153746 1371016873  =>  22: NE NE NE SE N N SW N N SW N SE SE SW N SW N N SE N SE N
 547211529 1386725128  =>  23: S S S S NW N N SE N SW N SE SW SE SW N SE SE N SE SW SW N
1162261466 1743392199  =>  38: NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE

```

**Efficient Version**

```
         0         40  =>   4: N N N N
        66         67  =>   5: S SW N N N
        30          2  =>   2: NW NW
        93          2  =>   2: NE SW
       120         61  =>   8: NW NW NW NW N SE SW N
1493682877          0  =>   4: NE S NW NW
         0  368460408  =>  18: SW SW N N SW SW SE SW SW N SE N N SW SW N SE SE
1371432130    1242824  =>  17: NW NW NE NW N SE SW SW SW SE SE SW N N N N SW
    520174 1675046339  =>  23: NE NW NE NE SE SE SW SW N SE N SW N SW SE N N N N SE SE SW SW
 312602548  940907702  =>  19: NE NW S SW N N SW SE SE SE SW SE N N SW SE SE SE SW
1238153746 1371016873  =>  22: NE NE NE SE N N SW N N SW N SE SE SW N SW N N SE N SE N
 547211529 1386725128  =>  23: S S S S NW N N SE N SW N SE SW SE SW N SE SE N SE SW SW N
1162261466 1743392199  =>  38: NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE NE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE SE

```
> 48 votes

# Answer
# Ruby, ~~195~~ ~~194~~ ~~190~~ 184 bytes

**Original:** With apologies to Ell, as this is essentially a port of their answer and with many thanks to Doorknob for their help in debugging this answer. There's probably another algorithm for this problem - something to do with `*f[x[0,**however far x matches with y**],y]` \- but I will save that for another time.

```
a=->n{n<1?[]:a[~-n/3]+[-n%3]}
f=->x,y{j=x.size
(Array===x)?x==y[0,j]?y[j..-1].map{|m|%w[SE SW N][m]}:x.uniq.map{|m|[%w[NW NE S][m],*f[x[0,x.rindex(m)],y]]}.min_by(&:size):f[a[x],a[y]]}

```

**EDIT:** ~~The greedy algorithm doesn't work for `h[299792458, 1000000]`. I have returned the byte count to 195, while I repair my algorithm once more.~~ Fixed it only for the byte count to rise to 203. *Sigh*

**Under construction:** This program uses a greedy algorithm to find common ancestors `x[0,j]==y[0,j]` (note: there may be several common ancestors). The algorithm is based very loosely on Ell's recursive ancestor search. The first half of the resulting instructions are how to get to this common ancestor, and the second half is getting to y based on `y[j..-1]`.

Note: `a[n]` here returns a base-3 bijective numeration using the digits `2,1,0` instead of `1,2,3`.

As an example, let's run through `f[59,17]` or `f[[2,0,2,1],[2,1,1]]`. Here, `j == 1`. To get to `x[0,j]`, we go `0` or `NW`. Then, to get to `y`, go `[1,1]` or `SW SW`

```
a=->n{n<1?[]:a[~-n/3]+[-n%3]}
h=->m,n{x=a[m];y=a[n];c=[];j=x.size
(j=x.uniq.map{|m|k=x.rindex(m);x[0..k]==y[0..k]?j:k}.min
c<<%w[NW NE S][x[j]];x=x[0,j])until x==y[0,j]
c+y[j..-1].map{|m|%w[SE SW N][m]}}

```
> 5 votes

# Answer
# APL (Dyalog Unicode), ~~144~~ ~~132~~ ~~129~~ ~~118~~ ~~133~~ ~~132~~ ~~130~~ ~~124~~ 117 bytesSBCS

Thank you very much to Ven and ngn for their help in golfing this in The APL Orchard, a great place to learn the APL language. `⎕IO←0`. Golfing suggestions welcome.

**Edit:** -12 bytes thanks to Ven and ngn by changing how `n` is defined and switching from 1-indexing to 0-indexing. -3 due to fixing a bug where not everything was switched to 0-indexing. -11 bytes due to changing how `P` and `Q` are defined. +15 bytes due to fixing a problem where my algorithm was incorrect with many thanks to ngn for help with figuring the `s[⊃⍋|M-s]` section. -2 bytes from rearranging the method of finding the backtracking path and +1 byte to bug fixing. -2 bytes thanks to Adám from rearranging the definition of `I`. -6 bytes thanks to ngn from rearranging the definition of `'S' 'NE' 'NW' 'N' 'SW' 'SE'` and from rearranging how `t` is defined (it is no longer a separate variable). -7 bytes thanks to ngn from golfing how `s` is defined.

```
{M←⊃⍸≠⌿↑1+P Q←⍵{(⍵/3)⊤⍺-+/3*⍳⍵}¨⌊3⍟1+⍵×2⋄(∪¨↓6 2⍴'SSNENWNNSWSE')[P[I],3+Q↓⍨⊃⌽I←⍬{M≥≢⍵:⍺⋄(⍺∘,∇↑∘⍵)s[⊃⍋|M-s←⌽⊢.⊢⌸⍵]}P]}

```

Try it online!

### An explanation of the bug in the algorithm

The basic problem is that I went thought the shortest path went directly through the common ancestor, and could not, in fact, go through an ancestor of the common ancestor. This is incorrect as the following examples will demonstrate.

**From 66 to 5**

```
66 → 0 2 2 2 → 0 2 2 2
5  → 0 1     → 0 1
      ↑ common ancestor

The two ancestors of 0 2 2 2 are:
0 2 2
(empty)

(empty) has the shorter path back to 0 1 as it only needs two forward moves,
while 0 2 2 requires two more backtracks and one more forward move.

```

**From 299792458 to 45687**

```
299792458 → 0 2 1 1 0 1 1 2 1 1 1 2 1 0 2 2 2 0
45687     → 0 2 1 1 0 1 1 1 2 2
                         ↑ common ancestor

The three ancestors of 299792458 are:
0 2 1 1 0 1 1 2 1 1 1 2 1 0 2 2 2
0 2 1 1 0 1 1 2 1 1 1 2            ← choose this one
0 2 1 1 0 1 1 2 1 1 1 2 1 0 2 2

And the three ancestors of 0 2 1 1 0 1 1 2 1 1 1 2 are:
0 2 1 1
0 2 1 1 0 1 1 2 1 1
0 2 1 1 0 1 1 2 1 1 1

0 2 1 1 0 1 1 1 2 2    ← 45687 for reference
             ↑ common ancestor

While it seems like `0 2 1 1` is the shorter path,
it actually results in a path that is 8 steps long
(2 backtracks, 6 forward steps to 45687).

Meanwhile, `0 2 1 1 0 1 1 2 1 1` is at an equal distance
to the common ancestor and has the following ancestors:
0 2 1 1
0 2 1 1 0 1 1 2 1
0 2 1 1 0 1 1

0 2 1 1 0 1 1 1 2 2    ← 45687 for reference
             ↑ common ancestor

Clearly, this is the superior path, as with three backtracks, we have reached
the point of the common ancestor. With 3 backtracks and 3 forward moves,
we have a path that is 6 steps long.

```

## Explanation of the code

```
                       ⍝ ⍵ should be an array of 2 integers, x y
SierpinskiPath←{⎕IO←0  ⍝ 0-indexing
        ⍝ P Q←{...}¨⍵  ⍝ First, the bijective base-3 numeration of x and y
    P Q←{
        n←⌊3⍟1+⍵×2  ⍝ The number of digits in the numeration
        z←+/3*⍳n    ⍝ The number of numerations with ≤ n digits
        (n/3)⊤⍵-z   ⍝ And a simple decode ⊤ (base conversion) of ⍵-z
    }¨⍵             ⍝ gets us our numerations, our paths

    A←↑1+P Q      ⍝ We turn (1+P Q) into an 2-by-longest-path-length array
                  ⍝ ↑ pads with 0s and our alphabet also uses 0s
                  ⍝ So we add 1 first to avoid erroneous common ancestor matches
    Common←⊃⍸≠⌿A  ⍝ We find the length of the common ancestor, Common

        ⍝ I←⍬{...}P  ⍝ Now we get the shortest backtracking path from P
    I←⍬{
        Common=≢⍵:⍺       ⍝ If P is shorter than Common, return our backtrack path
        s←⌽⊢.⊢⌸⍵          ⍝ Get the indices of the most recent N SW SE
        t←s[⊃⍋|Common-s]  ⍝ and keep the index that is closest to Common
                          ⍝ and favoring the ancestors to the right of
                          ⍝ Common in a tiebreaker (which is why we reverse ⊢.⊢⌸⍵)
        (⍺,t)∇t↑⍵         ⍝ Then repeat this with each new index to backtrack
    }P                    ⍝ and the path left to backtrack through

    Backtrack←P[I]   ⍝ We get our backtrack directions
    Forward←(⊃⌽I)↓Q  ⍝ and our forward moves to Q
                     ⍝ starting from the appropriate ancestor
    (∪¨↓6 2⍴'SSNENWNNSWSE')[Backtrack,Forward]    ⍝ 'S' 'NE' 'NW' 'N' 'SW' 'SE'
}                    ⍝ and return those directions

```

## Alternative solution using Dyalog Extended and dfns

If we use `⎕CY 'dfns'`'s `adic` function, it implements our bijective base-n numeration (which was the inspiration for the version I use) for far fewer bytes. Switching to Dyalog Extended also saves quite a number of bytes and so here we are. Many thanks to Adám for his help in golfing this. Golfing suggestions welcome!

**Edit:** -8 bytes due to changing how `P` and `Q` are defined. -14 bytes due to switching to Dyalog Extended. -2 due to using a full program to remove the dfn brackets `{}`. +17 bytes due to fixing a problem where my algorithm was incorrect with many thanks to ngn for help with figuring the `s[⊃⍋|M-s]` section. +1 byte to bug fixing. -2 bytes thanks to Adám from rearranging the definition of `I` ~~and -1 byte from remembering to put my golfs in both solutions~~. -3 bytes thanks to ngn by rearranging the generation of the cardinal directions, +1 byte from correcting a buggy golf, and -3 bytes thanks to ngn by rearranging how `t` is defined (it is no longer a separate variable). -7 bytes thanks to ngn by rearranging how `s` is defined.

### APL (Dyalog Extended), ~~123~~ ~~115~~ ~~101~~ ~~99~~ ~~116~~ ~~117~~ ~~114~~ ~~109~~ 102 bytes

```
M←⊃⍸≠⌿↑1+P Q←(⍳3)∘⌂adic¨⎕⋄(∪¨↓6 2⍴'SSNENWNNSWSE')[P[I],3+Q↓⍨⊃⌽I←⍬{M≥≢⍵:⍺⋄(⍺∘,∇↑∘⍵){⍵[⊃⍋|M-⍵]}⌽⊢.⊢⌸⍵}P]

```

Try it online!
> 5 votes

---
Tags: code-golf, graph-theory, path-finding, fractal
---


# Question
Title: Accentuated abjad English (ōcćnt̮ōt̖d ōbj̄d óngḷsh)
An Abjad is a writing system where each symbol stands for a consonant, and where vowels are omitted. An impure Abjad is an abjad in which there are additionals symbols for vowels, usually diacritics.

Write a program or function that, given a string of lowercase text (i.e. nothing but ASCII letters from `a` to `z`, commas and spaces), outputs a corresponding impure abjad English transcript with the following rules:

### Representation of vowels

Each vowel (i.e. `a e i o u`) is represented as an accent on the immediately preceding consonant. For instance, assuming the accent representing the vowel `e` is `́`, the word `wet` will be transcribed as `ẃt`.

If a vowel is not preceded by a consonant (two or more vowels in a row, or a word starting with a vowel), the symbol `o` is used as a "blank consonant". For example, the word `peep` will be transcribed as `ṕóp`

### Accent placement

Consonants that have ascenders are unpleasant to read when accentuated. Therefore, for those consonants, the symmetric accent will be displayed below the symbol instead of above. For instance, the letter combination `te` will be written  rather than `́t`

Those consonants are `b d f h k l t`.

### Accents for vowels

We are using Unicode combining characters to display accents on every consonant possible. The combining characters used can be found here. Combining accents are placed directly after the symbol they are to be put on.

The accents are presented on arbitrary consonants in this list.

* **a**

Above accent: U+0x0304, example:

Below accent: U+0x0320, example:
* **e**

Above accent: U+0x0301, example:

Below accent: U+0x0316, example:
* **i**

Above accent: U+0x0307, example:

Below accent: U+0x0323, example:
* **o**

Above accent: U+0x030c, example:

Below accent: U+0x032d, example:
* **u**

Above accent: U+0x0311, example:

Below accent: U+0x032e, example:

Here is the list of all possible characters:

```
b̠ b̖ ḅ b̭ b̮
c̄ ć ċ č c̑
d̠ d̖ ḍ ḓ d̮
f̠ f̖ f̣ f̭ f̮
ḡ ǵ ġ ǧ g̑
h̠ h̖ ḥ h̭ ḫ
j̄ j́ j̇ ǰ j̑
k̠ k̖ ḳ k̭ k̮
l̠ l̖ ḷ ḽ l̮
m̄ ḿ ṁ m̌ m̑
n̄ ń ṅ ň n̑
p̄ ṕ ṗ p̌ p̑
q̄ q́ q̇ q̌ q̑
r̄ ŕ ṙ ř ȓ
s̄ ś ṡ š s̑
t̠ t̖ ṭ ṱ t̮
v̄ v́ v̇ v̌ v̑
w̄ ẃ ẇ w̌ w̑
x̄ x́ ẋ x̌ x̑
ȳ ý ẏ y̌ y̑
z̄ ź ż ž z̑
ō ó ȯ ǒ ȏ

```

### Test cases

* Input: `programming puzzles and code golf`

Output: `přgr̄mṁng p̑zzl̖s ōnd čd̖ ǧlf`

* Input: `the quick brown fox jumps over the lazy dog`

Output: `th̖ q̑ȯck břwn f̭x j̑mps ǒv́r th̖ l̠zy ḓg`

* Input: `beautiful`

Outpu: `b̖ōȏṭf̮l`

* Input: `one ring to rule them all, one ring to find them, one ring to bring them all and in the darkness bind them`

Output: `ǒń ṙng ṱ ȓl̖ th̖m ōll, ǒń ṙng ṱ f̣nd th̖m, ǒń ṙng ṱ bṙng th̖m ōll ōnd ȯn th̖ d̠rkńss ḅnd th̖m`

### Scoring

This is , so the shortest program or function in bytes wins.

# Answer
> 3 votes
# CJam, ~~63~~ 62 bytes

```
Qq{_"aeiou"#:I){;___eu='o*\"bdfhklt"&"F<IST""*'-27"?I=730+}&}/

```

Try it online in the CJam interpreter.

### How it works

```
Qq             e# Push an empty string and read from STDIN.
{              e# For each character in the input:
               e#   Push a copy of the character.
  "aeiou"#     e#   Find its index in "aeiou" (-1 for not found).
  :I)          e#   Save in I and add 1.
  {            e#   If I + 1 != 0:
    ;          e#     Discard the character.
    ___        e#     Copy the previous character (or the empty array) three times.
    eu=        e#     Convert the last copy to uppercase and check for equality.
               e#     This pushes 1 for non-letters and 0 for letters.
    'o*        e#     Push a string of that many o's.
    \          e#     Swap the last copy with the string of o's.
    "bdfhklt"& e#     Intersect with that string.
    "F<IST"    e#     Push that string.
    "*'-27"    e#     Push that string.
    ?          e#     Select the first iff the intersection is non-empty.
    I=         e#     Retrieve the character at index I.
    730+       e#     Add 730 to its code point.
  }&           e#
}/             e#

```

# Answer
> 9 votes
# GNU sed, 168 158 134 105 98 85 byt̖s

ǒr 75 ch̠rs (b̭th ȯncl̮ḍng +1 f̭r th̖ `-r` fl̠g).

```
s/([bdfhklt])([aeiou])/\1\u\2/g;y/aeiouAEIOU/̠̖̣̭̮̄́̇̌̑/;s/\B[^ ,a-z]/o&/g

```

### óxpl̠n̄ṭǒn

Wó s̄v́ ō ḅt ȏṡng th̖ čnstr̄ȯnt th̠t ȯnp̑t ȯs ōll ḽẃr-c̄ś. Wó ȏpc̄ś ōny v̌ẃl f̭lḽẇng ō čnšn̄nt, b̖f̭ŕ čnv́rṭng ōll v̌ẃls ṱ ōcćnts.

```
#!/bin/sed -rf

s/([bdfhklt])([aeiou])/\1\u\2/g  # upcase vowel following ascender
y/aeiouAEIOU/̠̖̣̭̮̄́̇̌̑/
s/\B[^ ,a-z]/o&/g                # precede with 'o' if needed

```

Th̖ ǒdd-ḽǒḳng ch̠r̄ct̖rs ōŕ `//` čnt̠ȯṅng ōll t̖n ōcćnts (`/̠̖̣̭̮̄́̇̌̑/`). óxp̄nd̖d ǒȏt ẇth sp̄ćs, th̖y w̌ȏld ḽǒk ḷk̖ `/ ̄ ́ ̇ ̌ ̑ ̠ ̖ ̣ ̭ ̮ /`.

### ǒȏtp̑t

> ```
> přgr̄mṁng p̑zzl̖s ōnd čd̖ ǧlf
> th̖ q̑ȯck břwn f̭x j̑mps ǒv́r th̖ l̠zy ḓg
> b̖ōȏṭf̮l
> ǒń ṙng ṱ ȓl̖ th̖m ōll, ǒń ṙng ṱ f̣nd th̖m, ǒń ṙng ṱ bṙng th̖m ōll ōnd ȯn th̖ d̠rkńss ḅnd th̖m
>
> ```

# Answer
> 3 votes
# Ŕṭn̄ 0.8.2, 71 byt̖s

```
T`aei\ou`̄́̇̌̑
T`̄́̇̌̑`̠̖̣̭̮`[bdfhklt]*.
+`([^a-z])([̠̖̣̭̮̄́̇̌̑])
$1o$2

```

Try ȯt ǒnḷń!

### Óxpl̠n̄ṭǒn

```
T`aei\ou`̄́̇̌̑          ŕpl̠ćs th̖ ch̠r̄ct̖rs aeiou ẇth th̖ črŕsp̌nṡng ḍōcṙṭcs ōb̭v́.
T`̄́̇̌̑`̠̖̣̭̮`[bdfhklt]+.    ŕpl̠ćs th̖ ḍōcṙṭcs ōb̭v́ ẇth ḍōcṙṭcs b̖ḽw ȯf pŕćd̖d by ǒń ǒr śv́r̄l ch̠r̄ct̖rs ẇth ōsćnd̖rs.
+`([^a-z])([̠̖̣̭̮̄́̇̌̑])     ȏnṭl th̖ ȯnp̑t sṱps ch̠nġng, ŕpl̠ć óv́ry ḍōcṙṭc ňt pŕćd̖d by ō l̖tt̖r...
$1o$2              ...ẇth th̖ s̄ḿ ch̠r̄ct̖rs b̮t ẇth ōn o b̖tẃón th̖m.

```

# Answer
> 2 votes
# Julia, 269 bytes

This is really long and can probably be golfed further, but I'm just psyched that I was able to come up with a working solution at all!

```
s->(u=700+[72,69,75,80,85];l=800+[0,-10,3,13,14];R=replace;r(m)=(i=findin("aeiou",m[2])[1];j=m[1]∈"bdfhklt"?l[i]:u[i];string(m[1],char(j)));t(m)=string("o",char(u[findin("aeiou",m)[1]]));R(R(R(s,r"(?![eiou])[b-z][aeiou]",r),r"(?<=^| )[aeiou]",t),r"(?<=\S)[aeiou]",r))

```

This creates an unnamed function that accepts a string and returns a string.

Ungolfed + explanation:

```
function f(s)
    # Construct arrays of integers representing the unicode accents
    # u is for the upper accents and l is for the lower
    u = 700 + [72,69,75,80,85]
    l = 800 + [0,-10,3,13,14]

    # Define a function to accent consonants followed by vowels
    r(m) = begin
        # m is the consonant-vowel pair from the regex match
        i = findin("aeiou", m[2])[1]
        j = m[1] ∈ "bdfhklt" ? l[i] : u[i]
        string(m[1], char(j))
    end

    # Define a function to accent vowels
    t(m) = string("o", char(u[findin("aeiou", m)[1]]))

    # Accent consonants
    rep1 = replace(s, r"(?![eiou])[b-z][aeiou]", r)

    # Accent vowels at the start of a string or before a space
    rep2 = replace(rep1, r"(?<=^| )[aeiou]", t)

    # Accent remaining unaccented vowels
    rep3 = replace(rep2, r"(?<=\S)[aeiou]", t)

    # Return
    rep3
end

```

Examples:

```
julia> println(f("beautiful"))
b̖ōȏṭf̮l

julia> println(f("programming puzzles and code golf"))
přgr̄mṁng p̑zzl̖s ōnd čd̖ ǧlf

```

Note that if you look at the raw text in the post, the "t" in the first example is accented correctly but for some reason it doesn't display that way in the rendered markdown, at least for me.

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


title: Implement the named labels for assembly

text:
# Question
Title: Implement the named labels for assembly
Let's assume we've got an imaginary assembler. The assembler supports numerical labels. An infinite loop example:

```
:1
    jmp 1

```

Your task is, to write a preprocessor for this assembler supporting named labels (instead of numerical ones; with up to 8 characters in length), so the label name is replaced to it's numerical value.

The assembler uses a dot (.) to express a character constant, for example:

```
mov dl, .A

```

Will store ASCII(65) - 'A', in the register dl. The assembler supports string constants in double quotes too:

```
:20
db "Hello, world!"

```

So, to sum things up, you need to be aware of character constants, and the fact that you can't perform any substitution inside quote-enclosed strings.

The label declaration character and reference character is up to your choice, but for the sake of completness I will use a `$` to refer to a label, and `@` to denote a label.

The label' number might be any natural number not equal to zero.

**You may assume that assembly on the input is perfectly valid.**

Let's look at a few examples:

```
@loop
    jmp $loop

```

```
:1
    jmp 1

```

---

```
jmp $skip
mov dl, .@
@skip
cmp dl, .$

```

```
jmp 1
mov dl, .@
:1
cmp dl, .$

```

---

```
@x
db "$a @b"
@a
    jmp $a
    @b
        jmp $b

```

```
:1
db "$a @b"
:2
    jmp 2
    :3
        jmp 3

```

This is a code golf, so the smallest answer wins. Standard rules and loopholes apply.

You can safetly assume that the user won't use numerical labels anymore, and the labels contain just A-Za-z letters.

Label declaration and reference character has to be different.

# Answer
> 4 votes
# JavaScript (ES6), 96 bytes

Uses `@label` for a declaration and `%label` for a reference.

```
s=>s.replace(o=/^\s*@(.+)/gm,(_,s)=>':'+(o[s]=++n),n=0).replace(/".*?"|%(\w+)/g,(s,x)=>x?o[x]:s)

```

Try it online!

### Commented

*(alternate slash characters are used below to prevent the SE syntax highligter from going mad)*

```
s =>                  // s = input string
  s.replace(          // 1st pass:
    o =               //   assign the regex object to o; we'll use it to store the labels
    ∕^\s*@(.+)∕gm,    //   look for [start] + [optional whitespace] + '@' + [label]
    (_, s) =>         //   replace with:
      ':' +           //     ':' + label ID
      (o[s] = ++n),   //     increment n and store the label in o
    n = 0             //   start with n = 0
  )                   // end of replace()
  .replace(           // 2nd pass:
    ∕".*?"|%(\w+)∕g,  //   look for either ".*?" (non-greedily) or %label
    (s, x) =>         //   replace with:
      x ? o[x]        //     o[label] if x is defined,
        : s           //     or the original string otherwise
  )                   // end of replace()

```

# Answer
> 2 votes
# PHP (7.4), ~~148~~ 143 bytes

-5 bytes by stealing RegEx idea from @Arnauld.

```
<?=preg_replace_callback('/".*?"|([@_]\w+)/',fn($m)=>$m[1]?[':'][$m[0][0]>A].($_GET[$w=substr($m[0],1)]?:$_GET[$w]=++$_GET[0]):$m[0],$argv[1]);

```

Try it online!

Define labels with `@` and refer to them with `_`.

Captures any `@<label>` or `_<label>` which aren't inside double quotes (`"..."`) and replaces them with a unique number for every unique label, starting from `1`. Also adds the `:` when replacing labels that have `@` before them.

PHP's global variable `$_GET` is used to store and access last used id and unique ids for each label inside the arrow function. `$_GET[0]` holds last used id and `$_GET[<label>]` holds unique id for `<label>`.

# Answer
> 2 votes
# Retina 0.8.2, 97 bytes

```
ms(1`^@
:@
+`(.*^:(1*).*?^)@
$1:1$2@
^:1*
:$.&
\$(.+?)$(?<=(?=.*^:(\d+)@\1$).+)
$2
^(:\d+).*?$
$1

```

Try it online! Uses the provided symbols (could save 1 byte by using a different symbol). Explanation:

```
ms(

```

Run everything in single multiline mode, where `.` matches newlines and `^` and `$` match at the beginning and end of each line.

```
1`^@
:@

```

Prefix a `:` to the first label.

```
+`(.*^:(1*).*?^)@
$1:1$2@

```

Number the labels in unary.

```
^:1*
:$.&

```

Convert to decimal.

```
\$(.+?)$(?<=(?=.*^:(\d+)@\1$).+)
$2

```

Find all matching references and replace them with the number.

```
^(:\d+).*?$
$1

```

Delete the label names.

# Answer
> 2 votes
# Python 3, 136 117 bytes

New and improved:

```
import re;d={}
f=lambda s:re.sub(r'(".+?")|([@$])(\w+)',lambda m:m[1]or d.setdefault(m[3],f":{m.end()}")[m[2]<='@':],s)

```

Try it online!

Uses the position of the match.end() as the integer for a label.

Old code

```
import re;d={};n=[*range(9999)]
f=lambda s:re.sub(r'(".+?")|([@$])(\w+)',lambda m:m[1]or d.setdefault(m[3],f":{n.pop()}")[m[2]<='@':],s)

```

Try it online!

Labels start at 9998 and count downward. Some numbers may be skipped. It will handle about 5000 labels, which should be enough for any sane asm program, but the number can be increased at 1 byte for each order of magnitude increase in range.

# Answer
> 2 votes
# Perl 5 (`-p`), 57 bytes

```
s/^\s*\K@(\w+)/":".($$1=++$,)/mge;s/".*?"\K|\$(\w+)/$$1/g

```

Try it online!

* `$,` : global variable used as counter
* `s/^\s*\K@(\w+)/":".($$1=++$,)/mge` : replaces labels `"@[label]"` by `":[counter]"`, increment counter and store counter in variable label name's variable
* `".*?"\K|` : regex part used to ignore strings between `""`
* `s/...\$(\w+)/$$1/g` : replaces references by variables value

# Answer
> 0 votes
# Javascript ES6, 71 char

```
s=>s.replace(/(;.*|".*?")|:(:?)(\w+)/gm,(m,s,c,l)=>s||c+parseInt(l,36))

```

Conditions:

* `::` to introduce the label
* `:` to use the label
* Labels are case insensitive
* `;` starts comment till the end of the line
* Quoted strings may not have `"` or linebreak inside
* Charecter constants may not be followed by colon or letter like `.:a` or `.::`
* Classic numeric labels starting from `:` are disallowed

Test:

```
console.log((

s=>s.replace(/(;.*|".*?")|:(:?)(\w+)/gm,(m,s,c,l)=>s||c+parseInt(l,36))

)(`
::loop
    jmp :loop

jmp :skip
mov dl, .:
::skip
cmp dl, .:

::x
db ":a ::b"
::a
    jmp :a
    ::b
        jmp :b
`))
```

```
.as-console-wrapper.as-console-wrapper{max-height:100vh}
```

---
Tags: code-golf, assembly, substitution
---


# Question
Title: type in a random mess of capital letters
SOMe PEOPle lIkE tO TYpE iN A LoGiCAL MAnNER, WITh CapITals aT tHe bEGiNnIng Of ThE SENtENCE and smaLl LETTErS EVeRYWHErE eLsE. NOT Us. NOt Us. Your joB iS to tAkE A SenTEncE Of A LL SMAlL LeTTeRS, And rANDOmly ChAnGe sOMe to caPiTAl. ThiS iS a Code gOLF so tHE SmaLleST coDE WIll win.

the input will always be small letters and spaces with punctuation only.

random meaning running the code multiple times will always yield different results.

test cases for this will be hard since it involves random elements.

here is a shitty example with python

https://onlinegdb.com/Hy0\_gEEKH

# Answer
# Python 3, 59 bytes

```
i=input()
while i:print(end={i,i.upper()}.pop()[0]);i=i[1:]

```

Try it online!

*-4 bytes thanks to Chas Brown*

Uses `set.pop()` to randomize.
> 4 votes

# Answer
# APL (Dyalog Extended), 6 bytesSBCS

Anonymous tacit prefix function. Assumes `⎕IO←0` (0-based indexing)

```
⊢×∘?2¨

```

Try it online!

number two for each character

`?` random index among the first that many indices (i.e. 0 or 1 for each character)

then

`×` use that to change case (0:lower; 1:upper) on the following:

the unmodified argument
> 4 votes

# Answer
# K (oK), 32 bytes

```
{,/{`c$x-32*1?2*(x<123)*x>96}'x}

```

Try it online!
> 2 votes

# Answer
# Red, ~~80~~ ~~78~~ 58 bytes

```
func[s][foreach c s[prin do pick[c[uppercase c]]random 2]]

```

Try it online!
> 1 votes

# Answer
# Japt `-m`, 5 bytes

```
c^HÑö

```

Try it
> 1 votes

# Answer
# Japt `-m`, 4 bytes

```
+u)ö

```

Try it

```
-m    //Map all characters in input
+     //Input prepended to
  u)  //Input to uppercase
    ö //Random character

```
> 1 votes

# Answer
# Python 2, 72 bytes

```
lambda i:"".join(choice(x)for x in zip(i,i.upper()))
from random import*

```

Try it online!
> 1 votes

# Answer
# PowerShell, ~~60~~ ~~46~~ 43 bytes

-3 bytes thanks to mazzy

```
-join($args|%{"$_"|%('t*g','*per'|random)})

```

Try it online!
> 1 votes

# Answer
# Jelly, 5 bytes

```
żŒuX€

```

Try it online!

Stolen from totallyhuman's solution to Random Capitalization.

My original solution, since I forgot Jelly has `ż`:

# Jelly, 6 bytes

```
Œu,X¥"

```

Try it online!

`,ŒuXƊ€` works for the same byte count.

```
     "    For every element of the input and every corresponding element of
Œu        the input capitalized,
  ,X¥     choose one or the other at random.

```
> 0 votes

# Answer
# PHP, ~~51~~ 50 bytes

```
for(;$l=$argn[$i++];)echo$l>_&&rand()%2?$l^' ':$l;

```

Try it online!

---

# PHP, ~~51~~ 50 bytes

```
for(;$l=$argn[$i++];)echo rand()%2?ucfirst($l):$l;

```

Try it online!
> 0 votes

# Answer
# Perl 5, 22 bytes

```
s/./.5<rand?uc$&:$&/ge

```

Try it online!
> 0 votes

# Answer
# C# (Visual C# Interactive Compiler), 59 bytes

```
x=>x.Select(l=>z.Next()<1?l.ToUpper():l);var z=new Random()

```

Try it online!
> 0 votes

# Answer
# C (gcc), ~~109~~ 46 bytes

Thanks to Johan du Toit for -63 bytes

```
f(char*s){for(;*s++-=(*s-97u<26&rand())*32;);}

```

Try it online!
> 0 votes

# Answer
# Charcoal, 8 bytes

```
⭆Ｓ‽⁺↥ι↧ι

```

Try it online! Link is to verbose version of code. Trivial modification of my answer to Random Capitalization.
> 0 votes

# Answer
# Python 3, 94 bytes

```
s=input();from random import*;print("".join([i.upper() if randint(0,1)==1 else i for i in s]))

```

Try it online!
> 0 votes

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


title: Visualize a large int

text:
# Question
Title: Visualize a large int
Convert a large int (e. g. 1234567890) into a string containing the usual decimal prefixes k, M, G, T, etc. for kilo, mega, giga, tera, etc. The result shall be groups of three digits, interspersed by the prefixes (e. g. `1G234M567k890`), so that it is easy to glance the order of magnitude of the number without counting the digits.

It shall work for numbers of all digit counts up to 15. Only non-negative numbers are allowed as input.

More test cases:

```
0 → 0
123 → 123
1234 → 1k234
1000 → 1k000
1000000000 → 1G000M000k000

```

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

Takes input as a string.

```
f=(n,i=0,[d,t]=n.split(/(...)$/))=>t?f(d,i+1)+['kMGT'[d&&i]]+t:d

```

Try it online!

### How?

The regular expression `/(...)/$` matches the last three digits of the integer, or nothing at all if there are less than 3 digits remaining.

Because there's a capturing group, these digits -- if present -- are included in the output of the `.split()` method.

*Examples:*

```
'123456789'.split(/(...)$/) // --> [ '123456', '789' '' ]
'123'.split(/(...)$/))      // --> [ '', '123' ]
'12'.split(/(...)$/))       // --> [ '12' ]
''.split(/(...)$/))         // --> [ '' ]

```

### Commented

```
f = (                 // f is a recursive function taking:
  n,                  //   n = input
  i = 0,              //   i = index of next prefix
  [d, t] =            //   d = either the leading digits without the last 3 ones,
                      //       or all remaining digits if there are less than 3
    n.split(/(...)$/) //   t = last three digits (or undefined)
) =>                  //
  t ?                 // if t is defined:
    f(d, i + 1) +     //   append the result of a recursive call with d and i + 1
    ['kMGT'[d && i]]  //   append the prefix if d is defined, or an empty string otherwise
    + t               //   append the last 3 digits
  :                   // else:
    d                 //   stop recursion and return the remaining digits

```

# Answer
> 4 votes
# 05AB1E, ~~15~~ 14 bytes

```
R3ô"kMGTP"øSR¦

```

Try it online!

Thanks to Kevin Cruijssen for -1 byte

```
R       reverse input
3ô      split it into groups of 3 digits
"kMGTP" push the prefixes
ø       zip the groups of numbers with them
S       split to a list of characters
R       reverse again
¦       drop the first element
        implicitly print

```

# Answer
> 4 votes
# Python 2, 57 bytes

```
f=lambda s,p="":s and f(s[:-3],p[1:]+"kMGT")+s[-3:]+p[:1]

```

Try it online!

Takes input as a string. If the output may have a trailing space, we can avoid some workarounds and save 3 bytes.

**54 bytes**

```
f=lambda s,p=" kMGT":s and f(s[:-3],p[1:])+s[-3:]+p[0]

```

Try it online!

One potentially-useful observation is that the string format `'{:,}'.format` puts commas in the places we want to insert letters:

```
'{:,}'.format(1234567) == "1,234,567"

```

However, I haven't found a short enough way to use this.

# Answer
> 4 votes
# Brachylog, 17 bytes

```
↔ġ₃;"
kMGT"↔z₀cc↔

```

Input as a string, returns through output the result, with a trailing newline :)
Explanation:

```
            More or less a translation of Jelly answer:
↔           Reverse input string
 ġ₃         Group into triples, excluding last group with length in range (0,3]
   ;        Pair those groups with:
    "
kMGT"       A string containing a newline followed by the symbols in reverse order
     ↔      Reverse the pair so the string comes before the list of digit triplets
      z₀    Zip the pair until the smallest list is depleted
        cc  Concatenate the zipped lists together, then concatenate the strings together
          ↔ Reverse the result

```

Try it online

# Answer
> 3 votes
# Perl 5 (-p), 40 bytes

```
y/ kMG/kMGT/while s/\d\K((\d{3})+$)/ $1/

```

Try it online!

# Answer
> 3 votes
# Jelly, 14 bytes

<sup>**13** if input formatted as a string is acceptable for languages which *can* handle large integers (remove  and quote the argument)</sup>

```
ṾṚs3żFtṚʋ“kMGT

```

A full program accepting the non-negative number as a command line argument which prints the result

**Try it online!**

### How?

```
ṾṚs3żFtṚʋ“kMGT - Main Link: integer         e.g. 12345
Ṿ              - un-evaluate the integer         ['1', '2', '3', '4', '5']
 Ṛ             - reverse                         ['5', '4', '3', '2', '1']
  s3           - split into chunks of three      [['5', '4', '3'], ['2', '1']]
         “kMGT - literal list of characters      ['k', 'M', 'G', 'T']
        ʋ      - last four links as a dyad  i.e. f([['5', '4', '3'], ['2', '1']], ['k', 'M', 'G', 'T'])
    ż          -   zip                           [[['5', '4', '3'], 'k'], [['2', '1'],'M'], ['G'], ['T']]
     F         -   flatten                       ['5', '4', '3', 'k', '2', '1','M', 'G', 'T']
      t        -   trim (from either side)       ['5', '4', '3', 'k', '2', '1']
       Ṛ       -   reverse                       ['1', '2', 'k', '3', '4', '5']
               - implicit (smashing) print       12k345

```

# Answer
> 2 votes
# PHP, ~~67~~ 65 bytes

```
for(;''<$d=$argn[-++$i];)$r=$d.' kMGT'[$i%3==1?$i/3:5].$r;echo$r;

```

Try it online!

Loops on input digits from right to left and concatenates each digit to `$r` variable in reversed order. When we are on 4th, 7th, etc... digit, the respective prefix is concatenated to `$r` as well. Output has a trailing space.

```
for(;''<$d=$argn[-++$i];) // loop on input digits from right to left, $d is current digit and $i is incremental (1, 2, ...)
  $r=$d                   // concatenate current digit to beginning of $r
  .' kMGT'                // string of prefixes, first item is space for first digit and causes a trailing space in output
    [$i%3==1?$i/3:5]      // if $i is 1, 4, 7, etc... concatenate letter at index of $i/3 (1/3=0.33, 4/3=1.33, 7/3=2.33, etc...)
                          // PHP uses integer part of decimal indexes, so 1.33 will return the letter at index 1
                          // for any other $i, use index 5 which doesn't exist and is equal to an empty string
  .$r;                    // concatenate $r itself to the end, so everything will be in reversed order of reading (which itself is in reversed order of input)
echo$r;                   // output $r when the loop is finished

```

A schematic example for how an output is created for input of `1234`:

```
| Current Digit | Concatenation | $r    |
|---------------|---------------|-------|
| 4             | 4             | 4     |
| 3             | 3             | 34    |
| 2             | 2             | 234   |
| 1             | 1k            | 1k234 |

```

# Answer
> 2 votes
# Icon, ~~76~~ 71 bytes

```
procedure f(s)
k:=0
s[i:=*s-2to 2by-3:i]:="kMGT"[k+:=1]&\z
return s
end

```

Try it online!

Takes input as a string.

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

```
f=(n,i=0)=>n.replace(/.+(?=...)/,d=>f(d,i+1)+'kMGT'[i])

```

Try it online!

# Answer
> 2 votes
# Poetic, 485 bytes

```
honestly
i lived my life
i faced a boatload of brutal challenges
i desire a day of bliss-i want badly to forget a day where things backfire
i desire a day-i covet a week-and of course i want solitude around everyone
i desire a day-i crave a year-finding no faults i seem to create everyday
i desire a day-i plead,i pray-for an answer i need,i should deserve
fea-r-s,smea-r-s
really,i have a stupid aim
oh world,why was i on earth
o,i suggest venus
o,i deserve a way i go to space
by-by

```

Try it online!

Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols.

The point of the language is to allow for programs to be written in free-verse poetry. It was fun to write this one (though usually two consecutive ones would be written as 11-letter words; it was hard to golf this poem and make it sound interesting!).

This poem is equivalent to the following brainfuck program, which others are more than welcome to golf:

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

```

# Answer
> 1 votes
# Red, 85 bytes

```
func[n][p: copy"kMGT"parse reverse n[any[3 skip ahead skip insert(take p)]]reverse n]

```

Try it online!

Takes the input as a string.

# Answer
> 1 votes
# APL+WIN, 46 bytes

Prompts for integer as a string

```
∊(n/m),¨(n←3>+/¨' '=¨m←((3/⍳5)⊂¯15↑⎕))/'TGMk '

```

Try it online! Courtesy of Dyalog Classic

# Answer
> 1 votes
# PowerShell, ~~81~~ ~~73~~ ~~71~~ ~~69~~ 64 bytes

```
($a=$args)|%{$r=$a[--$i]+' kMGT'[$j+5*!$k]+$r;$j+=$k=!($i%3)}
$r

```

Try it online!

Takes argument as a splatted string.

# Answer
> 1 votes
# Gema, 88 characters

```
\A=@subst{?=\@push\{p\;?\};TGMk }
*=@reverse{@subst{<d3>=\$p\$1\@pop\{p\};@reverse{$0}}}

```

Boring double reverse approach, but looping in Gema would be painfully long.

Sample run:

```
bash-5.0$ echo -n '1234567890' | gema '\A=@subst{?=\@push\{p\;?\};TGMk };*=@reverse{@subst{<d3>=\$p\$1\@pop\{p\};@reverse{$0}}}'
1G234M567k890

```

Try it online!

# Answer
> 1 votes
# C (clang), ~~65~~ 62 bytes

```
f(char*n,z){for(;z--;z%3||printf(L" kMGT"+z/3))putchar(*n++);}

```

Try it online!

Taking a char array as input.

Saved 3 thanks to @ceilingcat

# C (clang), 68 bytes

```
f(n,s){!s|n&&f(n/10,s+1)+printf(s%3?"%d":"%d%c",n%10," kMGT"[s/3]);}

```

Try it online!

Taking an int as input

Recursive function which first call itself and outputs after.

```
f(n,s) // Idk if it's acceptable or if I have to wrap with a g(n){f(n,0);}
{
!s| // to allow 0 value calls
n&& // when n=0 exit recursion
f(n/10,s+1)+printf(
s%3?"%d":"%d%c" // select format string
,n%10, // digit to print
" kMGT"[s/3]);} // if second format selected add character

```

# Answer
> 1 votes
# Bash, 83 bytes

```
a=('' k M G T)
s=
(($1>99))&&s=${1: -3}
echo `$0 ${1:0:-3} $[$2+1]`${s:-$1}${a[$2]}

```

Try it online! (link shows 82 bytes, but uses function recursion instead of `$0`-recursion)

Nice little recursive solution.

Bash doesn't like invalid string indexing, which both helps (gives us our exit condition for free) and hurts (we have to have separate logic for when our number has n != 0 mod 3 digits).

# Answer
> 1 votes
# Perl 6, 39 bytes

```
{flip [~] <<''k M G T>>Z~.flip.comb(3)}

```

Try it online!

# Answer
> 0 votes
# Python3, ~~89~~ ~~83 bytes~~ 65 chars

(or 65 bytes, if you use just ASCII, but I fancy the Unicode superscript small letters)

```
f=lambda n,p='ᵏᴹᴳᵀ':len(n)<4 and n or f(n[:-3],p[1:])+p[0]+n[-3:]

```

Try it online!

Python3, 89 bytes:

```
import re;print(''.join(sum(zip(re.findall('..?.?',str(x)[::-1]),'kMGT.'),()))[::-1][1:])

```

Try it online!

I didn't try to shorten this dramatically. See it as an incentive to beat me :) This is my first challenge in this forum; by now I understand the asker isn't supposed to post an answer right away. Next time I will wait a little longer before doing it. But since I couldn't really undo the post (deleting the post leaves it visible to too many people anyway), I saw no use in even trying to.

# Answer
> 0 votes
# Python 2, ~~84~~ 74 bytes

```
i=input();o=""
for x in"kMGT ":o=(i,x+i[-3:])[len(i)>3]+o;i=i[:-3]
print o

```

Try it online!

Previous version for 84 bytes

```
i=input()[::-1];o=""
for x in"kMGT ":o+=(i,i[0:3]+x)[len(i)>3];i=i[3:]
print o[::-1]

```

Try it online!

* ~~Reverse the input~~
* Step ~~through~~ backwards in threes ~~appending~~ prepending the next letter
* ~~Reverse and print~~

Not sure that this is the most efficient approach but it's the best I can come up with at the moment.

# Answer
> 0 votes
# JavaScript (V8), 71 bytes

Takes input as number

```
b=(a,l=10e11,x=0,c=a/l|0)=>(l-1)?(c?c+'TGMk'[x]:'')+b(a%l,l/1000,x+1):c

```

Try it online!

# Answer
> 0 votes
# Retina 0.8.2, 31 bytes

```
r`\B...
,$.'$&
T`9630,`TGMk_`,.

```

Try it online! Explanation:

```
r`\B...

```

Match groups of three digits starting from the end but ensure that there is at least one more digit before the match.

```
,$.'$&

```

Prefix each match with a marker comma and the number of digits after the match (`0` for the last match, then `3`, `6` and `9` respectively).

```
T`9630,`TGMk_`,.

```

Replace the marker and following number with the appropriate suffix.

# Answer
> 0 votes
# Python 2, 72 bytes

```
f=lambda n,p=' kMGT':(n>M and f(n/M,p[1:])or'')+`n%M+M`[-3:]+p[0]
M=1000

```

Try it online!

# Answer
> 0 votes
# Zsh, 53 bytes

```
a=kMGT
for z y x (${(Oas::)1})s=$x$y$z$a[i++]$s
<<<$s

```

Try it online!

`(s::)` splits the stirng, `Oa` reverses the characters. Zsh arrays and strings are 1-indexed, so `$a[0]` on the first iteration substitutes nothing.

# Answer
> 0 votes
# Haskell, 99 bytes

```
f n=concatMap(\(a,b)->a++b)$reverse$zip(reverse<$>chunksOf 3(reverse$show n))(["","k","M","G","T"])

```

Try it online!

The function `f` takes a number, converts it into a string and splits it backwards into chunks of 3 characters, e.g.

```
reverse<$>chunksOf 3(reverse$show 1234) == ["234","1"]

```

it then zips the list of chunks with the list of magnitue identifieres `["","k","M","G","T"]`. Then the list is reversed and with `concatMap` converted to one string. It uses the function `chunksOf` from the package `Data.List.Split`

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

```
: f s" kMGT" bounds <# do
1000 /mod tuck if
0 # # # d. i c@ hold then loop
0 #s #> ;

```

Try it online!

A function that takes a number from the stack, and returns a string as (address, length) pair, which is the standard representation for a string in Forth. Produces lots of garbage under the returned string, and a few zeros on stdout.

Forth has a dedicated set of facilities for customized number-to-string formatting, and this challenge seemed to be the right place to showcase it.

On the golfing perspective, I found that `do .. if .. then loop` (test and ignore the rest of the body) is shorter than `begin .. while .. repeat` (test and break simple loop) or `do .. if leave then .. loop` (test and break counted loop).

### How it works

```
: f ( n -- addr len )
  s" kMGT"            \ Create a local string "kMGT"; gives its address and length
  bounds              \ Convert (addr, len) to (addr+8*len, addr)
  <#                  \ Initialize the buffer for number-to-string conversion
  do                  \ Loop; i = addr .. addr+8*len; stack=(n)
    1000 /mod         \   Calculate n%1000 and n/1000
    tuck if           \   Stack=(n/1000 n%1000); if n/1000 is nonzero...
      0 # # # d.      \     emit three digits from n%1000 and discard it
      i c@ hold       \     emit the next char of "kMGT"
    then              \   End if
  loop                \ End loop
  0 #s                \ Emit all the remaining digits
  #>                  \ Finish conversion; push addr/len of the result string
;                     \ End function

```

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


title: Compute a complex power

text:
# Question
Title: Compute a complex power
# The Rundown

Given any input **x** and **y**, perform a complex operation, and print a corresponding result.

# How your program should work

1. Given an input **x** and **y** in the form **z = x+yi**, find **zi-z**
2. If the absolute real value of **zi-z** is larger than the absolute imaginary part, print the real part; vice versa for the other way around. If both values are equal, print one of the values.

# Example

```
x: 2
y: 0

```

Therefore:

```
z = 2
z^(i-z) ~= 0.192309 + 0.159740i

```

Since the real part has a larger absolute value than the imaginary part, the program returns

```
0.192309

```

### More examples

```
z = 1+i >> 0.5
z = i >> 1
z = 0.5 >> 1.08787
z = -2+8i >> 2.22964E7
z = -10i >> 3.13112E7

```

# Answer
# Jelly, ~~8~~ 11 bytes

Thanks Johnathan Allan for updating the answer with the rules change.

```
ı_*@µĊ,ḞAÞṪ

```

Try it online!

```
ı_*@        z^(i-z)
    µ       new monadic link
     Ċ,Ḟ    pair real and imaginary parts
        AÞṪ sort by absolute value and take last value

```
> 7 votes

# Answer
# Python 2, 45 bytes

```
def f(z):z=z**(1j-z);print max(z.real,z.imag)

```

**Try it online** \- *all test cases*

Programming languages often use `j` instead of `i`. That is the case in Python. See this SO question for more information on why.
> 6 votes

# Answer
## Mathematica, 21 22 bytes

*Edit: Thanks to JungHwan Min for saving 3 btyes*

```
Max@ReIm[#^(I-#)]&

```

Pure function which expects a complex number as an argument. If an exact number is passed, then an exact number will be returned (e.g. `1/2` gives `Sqrt[2] Cos[Log[2]]`). The problem spec was edited after I posted my solution to specify that the absolute value should be used. The best I can come up with for that is `MaximalBy[ReIm[#^(I-#)],Abs][[1]]&` or `Last@MaximalBy[Abs]@ReIm[#^(I-#)]&`, both `34` bytes.
> 5 votes

# Answer
# MATL, 10 bytes

```
Jy-^&ZjhX>

```

Try it online! Or verify all test cases.

### Explanation

Consider input `-2+8i` as an example.

```
J     % Push i (imaginary unit)
      % STACK: i
y     % Implicit input. Duplicate from below
      % STACK: -2+8i, i, -2+8i
-     % Subtract
      % STACK: -2+8i, 2-7i
^     % Power
      % STACK: 3168271.58+22296434.47i
&Zj   % Real and imaginary parts
      % STACK: 3168271.58, 22296434.47
h     % Concatenate
      % STACK: [3168271.58 22296434.47]
X>    % Maximum. Implicitly display
      % STACK: 22296434.47

```
> 3 votes

# Answer
# Octave, 29 bytes

```
@(z)max(real(z^(i-z)./[1 i]))

```

This defines an anonymous function. It works in MATLAB too.

Try it online!

### Explanation

Element-wise dividing (`./`) the number `z^(i-z)` by the array `[1 i]` and taking the real part gives an array with the real and imaginary parts of `z^(i-z)`.
> 3 votes

# Answer
# TI-BASIC, ~~40~~, ~~32~~, ~~31~~ 29 bytes

*Saved a byte thanks to @Conor O'Brien*

```
Z^(i-Z→A                   #Perform operation, store as A, 8 bytes
:real(A)>imag(A            #Test if real part is greater than imaginary, 9 bytes
:Ansreal(A)+imag(Anot(Ans  #Determine output and print, 12 bytes

```

Takes input as a complex number on the `Z` variable.

TI-BASIC uses its own encoding, you can find it here.
> 2 votes

# Answer
# Pyth, 16 Bytes

```
=b^Q-Q.j;eS,ebsb

```
> 1 votes

# Answer
# C (GCC), ~~93~~ 79 + 4 (`-lm`) = ~~97~~ 83 bytes

*Saved 14 bytes thanks to @ceilingcat!*

```
float f(_Complex z){z=cpow(z,csqrt(-1)-z);return cimag(z)>creal(z)?cimag(z):z;}

```

Including the header `complex.h` is longer than that ¯\\\_(ツ)\_/¯

Try it online!
> 1 votes

# Answer
# Ruby, ~~25~~ 35 bytes

**EDIT**: Fixed to comply with new absolute value rule.

```
->z{(z**(1i-z)).rect.max_by(&:abs)}

```

Try it online!

This creates an anonymous function.
> 1 votes

# Answer
# Perl 6, 24 bytes

```
{($_**(i-$_)).reals.max}

```

`$_` is the possibly complex argument; `$_ ** (i - $_)` is the expression to be computed; `.reals` is a `Complex` method that returns a list of the real and imaginary parts; and finally `.max` returns the larger of the two.
> 1 votes

# Answer
# TI-Basic, ~~19~~ 16 bytes

```
Ans^(i-Ans
max(real(Ans),imag(Ans

```

`real(` and `imag(` are two-byte tokens.

Run with `5+3i:prgmNAME` (`5+3i` being the argmuent, `NAME` being the program name.)
> 1 votes

# Answer
# APL (Dyalog Unicode), 18 bytes

18 bytes (https://github.com/abrudz/SBCS/)
28 bytes (UTF-8)

⍵ is a complex number ajb = a+bi

```
{⌈/9 11∘.○⍵*0j1-⍵}

```

Try it online!
> 1 votes

# Answer
## R, 38 bytes

```
pryr::f({z=z^(1i-z);max(Re(z),Im(z))})

```

Anonymous function. Takes a (possibly) complex number `z`, takes it to the specified power, and then returns the `max` of the `Re`al and `Im`aginary parts.
> 0 votes

# Answer
# Axiom, 60 bytes

```
f(z:Complex Float):Float==(y:=z^(%i-z);max(real(y),imag(y)))

```

test code and results; i follow as the other the precedent version of the question...

```
(28) -> [[k,f(k)] for k in [1+%i,%i,1,-2+8*%i,-10*%i]]
   (28)
   [[1.0 + %i,0.5], [%i,1.0], [1.0,1.0],
    [- 2.0 + 8.0 %i,22296434.4737098688 53],
    [- 10.0 %i,31311245.9804955291 66]]

```
> 0 votes

# Answer
# C# - 189 Bytes

```
double f(double x, double y){double r,t,m,c;r=Math.Sqrt(x*x+y*y);t=Math.Atan2(y,x);m=Math.Pow(r,-x)*Math.Exp(y*t-t);c=Math.Cos((1-y)*Math.Log(r)-t*x);return m*(2*c*c<1?Math.Sqrt(1-c*c):c);}

```

Readable:

```
double f(double x, double y){
double r, t, m, c;
r = Math.Sqrt(x * x + y * y);
t = Math.Atan2(y, x);
m = Math.Pow(r, -x) * Math.Exp(y * t - t);
c = Math.Cos((1 - y) * Math.Log(r) - t * x);
return m * (2 * c * c < 1 ? Math.Sqrt(1 - c * c) : c); }

```

Explanation: Decided not to use any Complex libraries.

$$ \begin{align} z & = x + iy \\ & = r e^{it} \\ z^{i-z} & = (re^{it})^{(-x +i(1-y))} \\ & = r^{-x} r^{i(1-y)} e^{-xit} e^{t(y-1)} \\ & = r^{-x} e^{t(y-1)} e^{i((1-y)\ln(r)-xt)} \text{ (as }r^i = e^{i\ln(r)}\text{)} \end{align} $$

Let this be equal to \\$me^{ia}\\$ where

$$m = r^{-x} e^{t(y-1)}$$ $$a = (1-y)\ln(r)-xt$$

Then \\$\Re(z^{i-z})=m \cos a\\$ and \\$\Im(z^{i-z})=m \sin a\\$

The maximum absolute value can be determined by the \\$\cos a\\$ and \\$\sin a\\$ terms, with these being equal at \\$\frac{1}{\sqrt{2}}\\$ (hence the test \\$2c^2 \< 1\\$).

As mentioned, raising to a complex exponent is dependent on choosing a particular branch cut ( e.g. \\$z = 1\\$ could be \\$e^{i\pi}\\$ or \\$e^{3i\pi}\\$ \- raising this to \\$i\\$ gives a real part of \\$e^{-\pi}\\$ or \\$e^{-3\pi}\\$ respectively), however, I have just used the convention of \\$t \in \[0,2\pi)\\$ as per the question.
> 0 votes

---
Tags: code-golf, math, complex-numbers
---


title: Reconstruct the ASCII art from a string

text:
# Question
Title: Reconstruct the ASCII art from a string
I have a bunch of ASCII art that I have recovered from a failed hard drive. Unfortunately, all of the newlines were stripped out, and I don't know the resolution of the original artwork. I do know that each one was originally rectangular, but to make matters worse, all the white space at the beginning and end was stripped out too!

I *do* at least know what one small piece of each one looks like. Can you help me recover the artwork based on the input stream of bytes and the piece of ASCII art I remember?

## Example

I remember this one:

```
__(((55^$$%^/\__%%//\/_666332@12

```

Had this diamond in it:

```
/\
\/

```

The original artwork in this case was 8 characters wide:

```
__(((55^
$$%^/\__
%%//\/_6
66332@12

```

Then there's this one, which had a bigger diamond in it.

```
/\/\/\/\/\:;/  \00F\/\/\  /E%epopox\/e

```

The diamond looked like this:

```
 /\
/  \
\  /
 \/

```

The original artwork contained that diamond, but the white space surrounding the diamond was not white space in the original artwork. I’ve only added in the white space to the left to get the indentation right.

More generally, in each row, any space to the left of the first non-white-space character is indentation padding, and any white space to the right necessarily represents actual white space.

Note that this is also one of those pieces that has had its white space trimmed off. Here's the original, 11 characters wide, with white space restored:

```
   /\/\/\/\
/\:;/  \00F
\/\/\  /E%e
popox\/e

```

Remember, the amount of white space removed is unknown. That means I can’t even figure out the possibilities for line length by finding the divisors of the input’s character count.

## Input

A string of characters (the artwork, sans newlines, trimmed of white space at the beginning and end), and a two-dimensional string of characters (the piece to look for)

Essentially, the string of characters can be generated from the original artwork thus: `artwork.Replace("\n", "").Trim(" ")`

## Output

The original artwork with newlines inserted where necessary, and with trimmed white space re-added to the beginning of the first line and the end of the last line. If there is more than one possible solution, you may return one arbitrarily (or all of them if you really want to).

## Test Cases

```
Input:
__(((55^$$%^/\__%%//\/_666332@12
/\
\/

Output:
__(((55^
$$%^/\__
%%//\/_6
66332@12

-----------
Input:
 _-/\-_-_vv:;/  \00F\\||\  /E%epopox\/e0
 /\
/  \
\  /
 \/

Output:
   _-/\-_-_
vv:;/  \00F
\\||\  /E%e
popox\/e0

--------
Input:
__               (  )               ||                ||            ___|""|__.._     /____________\    \____________/~~~.
(  )
 ||
 ||
 ""

Output:
     __
    (  )
     ||
     ||
 ___|""|__.._
/____________\
\____________/~~~.

--------
Input:
..XX...XX.......X..X..X  X.....X..X...X  X.....XX......XX...
 XX
X  X
X  X
 XX

Output:
..XX...XX.......
X..X..X  X.....X
..X...X  X.....X
X......XX...

```

Notably, in this last case, the following is *not* valid output:

```
..XX...XX......
.X..X..X  X....
.X..X...X  X...
..XX......XX...

```

Credit to jrei @ asciiart.eu for the joystick

## Rules

* This is code golf, so shortest answer in bytes wins.
* Default I/O rules apply

# Answer
> 4 votes
# Perl 5, 192 bytes

To be golfed more

```
($_,@F)=@F;$l=max map length,@F;map{$_.=" "x($l-y///c);s/(^ +| +$)|\W/$1=~y, ,.,r||"\\$&"/gme}@F;for$i(0..y///c){$"=".{$i}";$i+=$l,$_=" "x($i-"@-").$_,map{printf"%-$i\s
",$_}/.{1,$i}/g if/@F/}

```

Try it online!

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


title: A Skittish Program

text:
# Question
Title: A Skittish Program
# Objective

You are to write a program that receives an integer `n` as input (from the command line), and embeds itself (the program) `n` directories down the directory tree. Example with `n=5`:

The folder names may be whatever you wish. The only requirements are that the depth is correct, and that the program can then be ran again from its new spot in the directory tree, and that the new source file retains the same filename.

## Bonuses:

* **Score * 0.9** If the directories all have a different name (must be true at least to depth 1 000 000)
* **Score * 0.5** If you do not **directly or indirectly** read or move the source file, or access the source code of the program

# Answer
# Bash, 30\*0.9\*0.5 = 13.5

```
mkdir -p `seq -s/ $1`;ln $0 $_

```

Takes depth as the first argument. Creates a hard link to itself into the following directory structure:

```
1/2/3/4/5/.../n

```

The script may then be run from the new location, even if `rm` is run on the old script.

**Explanation:**

`seq -s/ $1` outputs the numbers from 1 to `$1` (the first argument), separated by a forward slash.

`mkdir -p `seq -s` $1` creates the directory specified by `seq`, with `-p` creating all intermediate directories.

`ln $0 $_` create a hard link to the current running script in the newly created directory.

**Old (30 * 0.9 = 27):**

```
mkdir -p `seq -s/ $1`;cp $0 $_

```

**Example run (with ln):**

```
$ ls -lGR
.:
total 1
-rwx------+ 1 ducks 41 Jan  5 15:00 test.sh

$ ./test.sh 4

$ ls -lgR
.:
total 1
drwxr-xr-x+ 1 ducks  0 Jan  5 15:01 1
-rwx------+ 2 ducks 41 Jan  5 15:00 test.sh

./1:
total 0
drwxr-xr-x+ 1 ducks 0 Jan  5 15:01 2

./1/2:
total 0
drwxr-xr-x+ 1 ducks 0 Jan  5 15:01 3

./1/2/3:
total 0
drwxr-xr-x+ 1 ducks 0 Jan  5 15:01 4

./1/2/3/4:
total 1
-rwx------+ 2 ducks 41 Jan  5 15:00 test.sh

$ rm ./test.sh

$ ls -lg
total 0
drwxr-xr-x+ 1 ducks 0 Jan  5 15:01 1

$ ls -lg 1/2/3/4
total 1
-rwx------+ 1 ducks 41 Jan  5 15:00 test.sh

```

Thanks to @DigitalTrauma for suggestion to replace `$(..)` with ``..``

Thanks to @h.j.k. for suggestion to use `ln`.
> 36 votes

# Answer
# C, 225 * 0.9 * 0.5 = 101.25

My solution in C:

```
$ cat d.c
#define R(x)#x
#define T(x)R(x)
#define S(p)b[9];main(i,v)char**v;{for(i=atoi(v[1]);i--;sprintf(b,"%i",i),mkdir(b),chdir(b));fputs("#define R(x)#x\n#define T(x)R(x)\n#define S(p)"p"\nS(T(S(p)))",fopen("d.c","w"));}
S(T(S(p)))

```

Here in a somewhat more readable form:

```
#define R(x) #x
#define T(x) R(x)
#define S(p) char b[9];\
             main(int i,char**v) { \
                for(i=atoi(v[1]); i--; sprintf(b,"%i",i), \
                                       mkdir(b), \
                                       chdir(b)); \
                fputs("#define R(x) #x\n" \
                      "#define T(x) R(x)\n" \
                      "#define S(p) " p "\n" \
                      "S(T(S(p)))", \
                      fopen("d.c", "w")); \
             }
S(T(S(p)))

```

The check if it works:

```
$ gcc -o d d.c
# a lot of warning and notes from gcc ...
$ ./d 10
$ diff -s d.c 9/8/7/6/5/4/3/2/1/0/d.c
Files d.c and 9/8/7/6/5/4/3/2/1/0/d.c are identical

```

There most probably is a lot of golfing potential in the source code.
> 12 votes

# Answer
# Zsh, ~~63~~ ~~60~~ ~~58~~ 52 * 0.9 = ~~56.7~~ ~~54~~ ~~52.2~~ 46.8

```
s=$(<$0);for i in {1..$1};{mkdir $i;cd $i};echo $s>f

```

Example:

```
llama@llama:...Code/misc/foo$ zsh f 5
llama@llama:...Code/misc/foo$ ls -R
.:
d1  f

./d1:
d2

./d1/d2:
d3

./d1/d2/d3:
d4

./d1/d2/d3/d4:
d5

./d1/d2/d3/d4/d5:
f
llama@llama:...Code/misc/foo$ cat d1/d2/d3/d4/d5/f
s=$(cat $0);for i in {1..$1};do;mkdir d$i;cd d$i;done;echo $s>f
llama@llama:...Code/misc/foo$ cat f
s=$(cat $0);for i in {1..$1};do;mkdir d$i;cd d$i;done;echo $s>f
llama@llama:...Code/misc/foo$ diff f d1/d2/d3/d4/d5/f
llama@llama:...Code/misc/foo$

```
> 5 votes

# Answer
## Batch - 48 * 0.9 = 43.2

```
for /l %%a in (1,1,%1)do md %%a&cd %%a&move..\%0

```

This script simply creates a new directory, and moves the source file to it - `n` times.

```
H:\MyDocuments\uprof\top>embed.bat 5

     ...

H:\MyDocuments\uprof\top>tree /f
Folder PATH listing for volume DATA009_HOMES
Volume serial number is B88B-384C
H:.
└───1
    └───2
        └───3
            └───4
                └───5
                        embed.bat

```
> 5 votes

# Answer
# Rebol - 114 * 0.9 * 0.5 = 51.3

```
do b:[d: copy %./ repeat n do input[mkdir repend d[n"/"]]write join d s: system/options/script join"do b: "mold b]

```

Ungolfed:

```
do b: [
    d: copy %./
    repeat n do input [
        mkdir repend d [n "/"]
    ]
    write join d s: system/options/script join "do b: " mold b
]

```

### Original non-quine version - 90 * 0.9 = 81

```
d: %./ repeat n do input[mkdir repend d[n"/"]write join d s: system/options/script read s]

```

Ungolfed:

```
d: %./
repeat n do input [
    mkdir repend d [n "/"]
]
write join d s: system/options/script read s

```
> 3 votes

# Answer
# Bash 167\*0.5\*0.9 = 75.15

Borrowing heavily from @es1024's great answer, but this one is a true quine, so it qualifies for both bonuses.

```
b=\' c=\\ a='d=`seq -s/ $1`;mkdir -p $d;echo b=$c$b c=$c$c a=$b$a$b>>$d/$0;echo $a>>$d/$0'
d=`seq -s/ $1`;mkdir -p $d;echo b=$c$b c=$c$c a=$b$a$b>>$d/$0;echo $a>>$d/$0

```

Also, shell quine techniques from here.
> 2 votes

# Answer
# AutoIt3, 106 * 0,9 = 95,4 bytes

---

A bit long but I can't help with those long function/variable names:

```
$f = @WorkingDir
For $i = 1 To $CmdLine[1]
    $f &= "\" & $i
Next
DirCreate($f)
FileCopy(@ScriptFullPath, $f)

```

Simply call it with `<script/.exe name> <depth>` eg. `script.exe 5`.
It will work for any amount of directories; maybe even more than your file system can handle. :D

## How it works:

It's just a simple loop that adds the index to a string. Then the directory (and all parent directories, too) get created and the file copies itself to that directory.
> 1 votes

# Answer
# Node.js, ~~136~~ 133 * 0.9 * 0.5 = ~~61.2~~ 59.85

```
r=require,f=r('fs'),p=__dirname;while(i=process.argv[2]--)f.mkdirSync(p+='/'+i);f.linkSync(a=__filename,p+'/'+r('path').basename(a))

```

`fs.linkSync` maps to the POSIX call link, which creates a hard link. An invalid argument will cause the program to crash.
> 1 votes

# Answer
# J, 82 * 0.9 = 73.8

This is mostly a port of the top-voted answer.

```
exit (1!:1[1{A) 1!:2 <] (s,'/',>1{A)[fpathcreate s=:' /'charsub":1+i.".>{:A=:ARGV

```

Save as `skittish.ijs` or whatever you want, and call it from the command line using your version of `jconsole`. Mine is symlinked to `jc`:

```
$ jc skittish.ijs 20
$ ls 1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19/20/skittish.ijs
1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19/20/skittish.ijs

```
> 1 votes

# Answer
# Zsh, 55 * 0.9 * 0.5 = 24.75 bytes

I had my eyes on this challenge for a long time, but I wanted to complete it in Zsh without calling any external programs like `mkdir` and `ln` (otherwise, it would be identical to the bash solution). Turns out, Zsh can provide its own versions of those programs!

```
zmodload zsh/files
mkdir -p ${(j:/:):-{1..$1}}
ln $0 $_

```

Try it online!
> 0 votes

---
Tags: code-golf, file-system
---


title: Tips for golfing in brainfuck

text:
# Question
Title: Tips for golfing in brainfuck
What general tips do you have for golfing in brainfuck? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to brainfuck (e.g. "remove comments" is not an answer). Please post one tip per answer.

# Answer
Putting one tip per answer would be way too many answers.

* Learn to think in Brainfuck. It's very different than anything else. Read and write, and rewrite, and rewrite lots of brainfuck programs. The language doesn't give you much to work with, so it's important to use what it does give you flexibly and efficiently. Don't let any abstractions get between you and the language--get in there and grapple with it.
* Get very comfortable with nondestructive flow control. To get out of a decision loop, rather than zeroing the starting cell by copying it elsewhere and then copying it back after leaving the loop, it's often better to move the pointer to a pre-existing zero nearby. Yes, this means the pointer will be in different places depending on whether you went through the loop, but that also means those places probably have different arrangements of nearby zeros and nonzeros, which you can use to resynch the pointer location using another loop. This technique is fundamental to good Brainfuck programming, and various forms of it will constantly prove useful.
* That and the fact that every `>` or `<` costs mean that the details of memory layout are important. Try out as many variations of your layout as you have patience for. And remember, your memory layout does not have to be a rigid mapping of data to locations. It can morph over the course of execution.
* On a larger scale, consider and even try implementing a variety of different algorithms. Initially it will not be obvious exactly what algorithm will be best; it may not even be obvious what basic approach will be best, and it will probably be something different than what would be best in a normal language.
* If you're dealing with large or variable-sized data, see if there's any way you can possibly deal with it locally, without having to keep track of how big it is or your numerical location within it.
* The same data can be two different things. (Most often, a number or character and also a nonzero positional marker. But see random.b, where a bit counter doubles as the value of one cell of a cellular automaton.)
* The same code can do two different things, and it's a lot easier to make it do so in a language where code is as generic as `<+<`. Be alert to such possibilities. In fact, you may occasionally notice, even in what seems to be a well-written program, that there are small portions that could be deleted entirely, nothing added, and the thing would, by happenstance, still run flawlessly.
* In most languages, you use a compiler or interpreter frequently to check your program's behavior. The Brainfuck language demands greater conceptual control; if you need a compiler to tell you what your program does, you don't have a firm enough grasp of your program, and you probably need to stare at it some more--at least if you want to have a clear enough image of the conceptual halo of similar programs to be good at golf. With practice, you'll be producing a dozen versions of your program before you try running one, and by that point you'll be 95% sure that your shortest one will run correctly.
* Good luck! Very few people bother to write Brainfuck concisely, but I think that's the only way the language can possibly justify continuing attention--as a stunningly obscure art form.
> 34 votes

# Answer
A few tips here:

## Constants:

The Esolangs' constants page has an extremely useful list of the shortest ways to create specific values. I find myself consulting this page at least twice per program.

## The start of everything:

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

```

This sets up the tape in the format 3\*n^2, which looks like

3 6 12 24 48 96 192 128 0 0'

Why is this so important?

Let's go down the list:

* 3 and 6 are boring
* 12: Close to 10 (newline) or 13 (carriage return). Can also be used for the counter for 0-9
* 24: Close to 26, the number of letters in the alphabet
* 48: ASCII for `0`
* 96: Close to 97, ASCII for `a`
* 196 and 128: 196-128=64, close to 65, the ASCII for `A`.

From this one algorithm, we're at the start of practically every sequence in the ASCII range, along with a counter for each and a newline in easy reach.

A practical example:

**Printing all uppercase and lowercase letters and digits.**

With algorithm:

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

```

Without:

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

```

We spend most of the bytes just *initialising* the tape in the second example. Some of this it offset by the extra movements in the first example, but this method clearly has the advantage.

A couple of other interesting algorithms in the same vein:

3\*2^n+1:

```
+++[[<+>>++<-]+>]
Tape: 4 7 13 25 49 65 197 129 1 0'

```

This offsets the values by 1, which accomplishes a few things. It makes the 12 a carriage return, the 64 the actual start of the uppercase alphabet, and the 24 one closer to 26.

2^n:

```
+[[<+>>++<-]>]
Tape: 1 2 4 8 16 32 64 128

```

Because 64 is good for uppercase letters, 32 is the ASCII for space, and 128 can be used as the counter for 26 (130/5 = 26). This can save bytes in certain situations where digits and lowercase letters aren't needed.

## Choose the implementation that suits the question:

* Negative cells are almost *always* useful, and there's no reason to avoid them (unless it doesn't change your bytecount)
* Almost the exact same thing with wrapping cells, even more so because many constants use wrapping.
* Arbitrary cell sizes are useful for infinite math sequences, such as calculating the Fibonacci sequence infinitely (`+[[-<+>>+>+<<]>]`), or processing larger/negative numbers. The downside is that some common methods, such as `[-]` and `[->+<]` can't be relied upon, just in case the number is negative.
* EOF as 0, -1 or no change. 0 is usually preferable, as you can loop over an entire input without extra checks. -1 is useful when looping over array structures. I haven't yet found a use for no change :(.

## Keep track of what the frick is going on:

At all times you should have comments on where the pointer should be in relation to the data around it, and make sure that you know the range of possible values of each cell. This is *especially* important when you've split the pointer before a loop, because you'll want to join the two possibilities back together afterwards.

At any point, my code is littered with comments on every other line that look like this:

```
*0 *dat a_1 ?  0' !0 0*
 or
*0 *dat 0' ap1 0  !0 0*

```

Some extra advice is to assign symbols special meanings. In the above example, `'` is where the pointer is, `*` means repetition in that direction, `?` means a cell with unknown value, `!0` means a non-zero cell, `_` is a substitute for `-` and `p` is a substitute for `+`. `or` implies that the tape could look like either of representations, and needs to be handled as such.

Your symbol scheme doesn't necessarily have to be the same as mine (which has a few flaws), it just has to be consistent. This is also extremely useful when debugging, because you can run it up to that point and compare the actual tape to what you *should* have, which can point out potential flaws in your code.
> 14 votes

# Answer
My principal piece of advice would be **don't.**

OK, fine, you want something more useful than that. BF is already a very terse language, but what really kills you is arithmetic, which effectively needs to be done in unary. It's worth reading over the constants page in Esolang to pick out exactly how to write large numbers efficiently, and to exploit wrapping wherever possible.

Memory access is also very expensive. Since you're reading from a tape, you need to keep in mind where your head is moving at any given time. Unlike other languages where you can just write `a`, `b`, `c`, in bf you have to explicitly move the head some number of bytes left or right, so you must be mindful of where you store what. I'm pretty sure that organising your memory in the optimal way is NP-hard, so good luck with that one.
> 6 votes

# Answer
In this answer I'm going to refer to a specific cell on the tape many times. It doesn't matter which cell it is, but it's the same cell throughout the entire answer. For the purposes of this post, I'll call that cell "Todd".

When trying to set a cell to a constant value, it sometimes pays to not finish it immediately. For example, say you wanted Todd to contain 30. Later on in your code (which may modify Todd's value but never reads it) you come back to Todd. If Todd's value is 0, the program exits. Otherwise, Todd's value is printed forever.

According to the esolangs.org page of brainfuck constants (which could probably be the subject of a tip on its own!) the shortest way to get 30 is `>+[--[<]>>+<-]>+`. That leading `>` is only there to ensure that nothing to the left of the pointer is modified, but in this case we'll assume we don't care about that and drop it. Using that code, your code would look something like this:

```
+[--[<]>>+<-]>+(MISC. CODE)(GO TO TODD)[.]

```

You can think of the first chunk of code like this:

```
(SET TODD TO 30)(MISC. CODE)(GO TO TODD)[.]

```

But remember the last two characters in that chunk: `>+`. It's just as valid to think of it this way:

```
(SET TODD TO 29)(GO TO TODD)(ADD 1 TO TODD)(MISC. CODE)(GO TO TODD)[.]

```

Notice that you `(GO TO TODD)` twice! You could instead write your code this way:

```
(SET TODD TO 29)(MISC. CODE)(GO TO TODD)(ADD 1 TO TODD)[.]
+[--[<]>>+<-](MISC. CODE)(GO TO TODD)+[.]

```

Assuming that the number of bytes it takes to `(GO TO TODD)` is the same before, one less move == one less byte! Sometimes the fact that your starting position has changed does take that benefit away, but not always.
> 4 votes

# Answer
A tiny little tip for challenges without input. You can use `,` instead of `[-]`, if you need to clear the cell quickly, as most of the interpreters (including the TIO.run one) will set the cell contents to EOF representation being zero. This makes programs a tiny bit unportable, but who cares about it in code golf anyway?
> 2 votes

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


title: Greek Conversion Golf

text:
# Question
Title: Greek Conversion Golf
### Introduction

You must create a function to convert Arabic numerals into Greek numerals. The input will be an integer less than `1000` and more than `0`.

### Algorithm

1. Split number into digits (e.g. `123` -\> `1`, `2`, `3`)
2. Take each digit, and change to character found in table below, for letter symbol or letter name, (e.g. `123` -\> `1`, `2`, `3` -\> `ΡΚΓ` or `RhoKappaGamma`).

### Specifications

* No built-in number-system conversion
* Result must be capitalized as in example.
* Input will be in base 10.

### Test Cases

```
123 -> RhoKappaGamma or ΡΚΓ
8 -> Eta or Η
777 -> PsiOmicronZeta or ΨΟΖ
100 -> Rho or Ρ
606 -> ChiDiGamma or ΧϜ

```

### Table

```
Α = 1 = Alpha = 913 UTF-8
Β = 2 = Beta = 914 UTF-8
Γ = 3 = Gamma = 915 UTF-8
Δ = 4 = Delta = 916 UTF-8
Ε = 5 = Epsilon = 917 UTF-8
Ϝ = 6 = DiGamma = 988 UTF-8
Ζ = 7 = Zeta = 918 UTF-8
Η = 8 = Eta = 919 UTF-8
Θ = 9 = Theta = 920 UTF-8

Ι = 10 = Iota = 921 UTF-8
Κ = 20 = Kappa = 922 UTF-8
Λ = 30 = Lambda = 923 UTF-8
Μ = 40 = Mu = 924 UTF-8
Ν = 50 = Nu = 925 UTF-8
Ξ = 60 = Xi = 926 UTF-8
Ο = 70 = Omicron = 927 UTF-8
Π = 80 = Pi = 928 UTF-8
Ϙ = 90 = Koppa = 984 UTF-8

Ρ = 100 = Rho = 929 UTF-8
Σ = 200 = Sigma = 931 UTF-8
Τ = 300 = Tau = 932 UTF-8
Υ = 400 = Upsilon = 933 UTF-8
Φ = 500 = Phi = 934 UTF-8
Χ = 600 = Chi = 935 UTF-8
Ψ = 700 = Psi = 936 UTF-8
Ω = 800 = Omega = 937 UTF-8
Ϡ = 900 = SamPi = 992 UTF-8

```

# Answer
# Jelly, ~~42~~ 40 bytes

```
“#'nn(2jj33556;r”Or2/F+878Ọ
ṚĖ’ḅ9‘xṚQṚị¢

```

Try it online! or verify all test cases.
> 2 votes

# Answer
## Pyth, ~~49~~ ~~48~~ ~~46~~ 44 bytes

```
_s.b@+kNsYc3mC+913d-.iU25smXm17hT4Cd"KGO"17_

```

Try it here.

Still working on shortening the function to generate the alphabet... and yes, the generator is longer than hardcoding the alphabet by 4 characters, but not in bytes.

```
_s.b@+kNsYc3[...]_
                 _  get input (implicit) and reverse
            [...]   generate "ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ" (see below)
          c3        split into 3 equal chunks
  .b                map over each input digit (as Y) and chunk (as N)...
     +kN            prepend empty string to N (to support digits of 0)
    @   sY          get the Yth element of the empty-string-plus-digits array
 s                  concatenate all the digits
_                   reverse again to put digits back in the right order

```

Here's how the alphabet-generating function works. Let's take all the codepoints and subtract 913 (the smallest value):

```
0 1 2 3 4 75 5 6 7 8 9 10 11 12 13 14 15 71 16 18 19 20 21 22 23 24 79

```

Now let's pull out the ones that don't fit the pattern:

```
0 1 2 3 4    5 6 7 8 9 10 11 12 13 14 15    16 18 19 20 21 22 23 24
          75                             71                         79

```

Okay, so the strategy is forming: generate the range 0 to 24 (we'll deal with the missing 17 later), and then insert 75, 71, and 79 at the correct locations.

How can we insert the outliers? Pyth has an `.i`nterleave function that takes ex. `[1,2,3]` and `[4,5,6]` and results in `[1,4,2,5,3,6]`. We're going to have to add some placeholders, though, since obviously the outliers are far apart. Let's represent the placeholder with X:

```
0 1 2 3  4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24
X X X X 75 X X X X X  X  X  X  X  X 71  X  X  X  X  X  X  X 79

```

Right, so the bottom outlier array starts with four `X`s. Can we group the outliers to each be preceded by four `X`s and see what remains?

```
0 1 2 3  4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24
[four X]75 X X X X X  X [  four X  ]71  X  X  X [  four X  ]79

```

Now we make another key observation: since 79 comes at the *very end*, there can be *any* number of `X`s preceding it, and *any* number of `X`s following it as well! This is because interleaving `[1,2,3]` and `[4,5,6,7,8,9]` results in `[1,4,2,5,3,6,7,8,9]`—note that the extra elements in the second array end up at the end, and since they're going to be removed anyway, we can safely allow that.

That means we can normalize this such that every outlier is preceding by four `X`s and succeeded by 6:

```
0 1 2 3  4 5 6 7 8 9 10 11 12 13 14 15 16 18 19 20 21 22 23 24
[four X]75[   six X   ] [  four X  ]71[     six X      ] [four X]79[six X]

```

Great! Now we can simply take the array `[75, 71, 79]`, insert four placeholder values before each element and six after, and then interleave it with the range `0..24`.

But wait, what happened to `17`? Remember, the top line in all of these examples has been missing 17. We can simply remove the 17 after interleaving; but this leaves another delightfully evil possibility open. You guessed it—the placeholder value we've been referring to as `X` will be 17. This allows us to remove both the extraneous 17 and all the placeholder values in one fell swoop.

Finally! Here's the code used to implement this:

```
mC+913d-.iU25smXm17hT4Cd"KGO"17
              m         "KGO"    for each char in the string "KGO"...
                      Cd         take its ASCII value ("KGO" -> 75,71,79)
                m17hT            generate an 11-element array filled with 17
               X     4           replace the 5th element with the ASCII value ^^
             s                   concatenate all of these together
        .iU25                    interleave with range(25)
       -                     17  remove all the 17s
m     d                          for each value in the resulting array...
  +913                           add 913 (to get the real character value)
 C                               convert to character

```
> 11 votes

# Answer
# Julia, 138 bytes

```
f(x,d=digits(x))=reverse(join([d[i]>0?[["ΑΒΓΔΕϜΖΗΘ","ΙΚΛΜΝΞΟΠϘ","ΡΣΤΥΦΧΨΩϠ"][i]...][d[i]]:""for i=1:endof(d)]))

```

This is a function that accepts an integer and returns a string.

For each digit in the input in reversed order, we get the character corresponding to that digit from the appropriate string then combine the characters and reverse the result. For any digits that are 0, we simply use the empty string.
> 2 votes

# Answer
# JavaScript (ES6), ~~120~~ 115 bytes

```
n=>(s=n+"").replace(/./g,(d,i)=>d--?"ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ"[d+9*(s.length+~i)]:"")

```

Byte count is using UTF-8. It's 88 characters long. Input is a number.

## Test

```
var solution = n=>(s=n+"").replace(/./g,(d,i)=>d--?"ΑΒΓΔΕϜΖΗΘΙΚΛΜΝΞΟΠϘΡΣΤΥΦΧΨΩϠ"[d+9*(s.length+~i)]:"")
var testCases = [ 123, 8, 777, 100, 606, 700, 803 ];
document.write("<pre>"+testCases.map(c=>c+": "+solution(c)).join("\n"));
```
> 2 votes

# Answer
# Retina, 57 bytes

* 11 bytes saved thanks to @Martin Büttner.

Simple transliterate with appropriate character ranges and `0` deletion on each digit.

```
T`d`_ΡΣ-ΩϠ`.(?=..)
T`d`_Ι-ΠϘ`.\B
T`d`_Α-ΕϜΖ-Θ

```

Try it online. (First line added to allow all testcases to run together.)

---

Martin also suggested this one for the same score:

```
T`d`_J-R`.(?=..)
T`d`_L`.\B
T`dL`_Α-ΕϜΖ-ΠϘΡΣ-ΩϠ

```
> 2 votes

# Answer
# Python 3, 118 bytes

```
f=lambda n,i=3:i*"_"and f(n//10,i-1)+"   ΡΙΑΣΚΒΤΛΓΥΜΔΦΝΕΧΞϜΨΟΖΩΠΗϠϘΘ"[i-1::3][n%10].strip()

```
> 2 votes

# Answer
# Julia, 84 bytes

```
f(x,p=0)=x>0?f(x÷10,p+9)"$(x%10<1?"":"/0123z456789:;<=>v?ABCDEFG~"[p+x%10]+866)":""

```

Try it online!
> 2 votes

# Answer
## JavaScript (ES6), 83 characters, 110 bytes

```
n=>`${1e3+n}`.replace(/./g,(d,i)=>i--&&d--?"ΡΣΤΥΦΧΨΩϠΙΚΛΜΝΞΟΠϘΑΒΓΔΕϜΖΗΘ"[d+9*i]:"")

```
> 1 votes

# Answer
# Perl 6, 102 bytes

```
{[~] <ΡΣΤΥΦΧΨΩϠ ΙΚΛΜΝΞΟΠϘ ΑΒΓΔΕϜΖΗΘ>>>.&{('',|$^b.comb)[$_/100*10**$++%*]}}

```

Try it online!
> 1 votes

# Answer
# Ruby, 134 bytes

Basic lookup dealie using modulus. It probably can be optimized somewhere, but Ruby won't coerce strings into integers the way Javascript can, haha

```
->n{((0<d=n/100)?"ΡΣΤΥΦΧΨΩϠ"[d-1]:"")+((0<d=n%100/10)?"ΙΚΛΜΝΞΟΠϘ"[d-1]:"")+((0<n%=10)?"ΑΒΓΔΕϜΖΗΘ"[n-1]:"")}

```
> 0 votes

---
Tags: code-golf, number, natural-language
---


# Question
Title: Mirror, Mirror, on the wall. Who's the fairest of them all?
Well, you know it's Snow White, and the evil Queen is at it again. Will Snow White be saved? Will she fall asleep once again? Will the Prince find her?

# Challenge:

Given an arbitrary number (\>= 2) of possibly duplicated hexadecimal color values (ranging from #000000 to #FFFFFF) and paired strings, calculate the following:

* If #FF0800 (Candy apple red) appears in the input, return "Return to Sleeping Death"
* If #000000 appears in the input, return "Saved by Grumpy"
* If #A98AC7 or #111111 appears in the input, return "Saved by Happy"
* If #21E88E or #222222 appears in the input, return "Saved by Sleepy"
* If #32DCD5 or #333333 appears in the input, return "Saved by Bashful"
* If #43D11C or #444444 appears in the input, return "Saved by Sneezy"
* If #54C563 or #555555 appears in the input, return "Saved by Dopey"
* If #65B9AA or #666666 appears in the input, return "Saved by Doc"
* If #76ADF1 or #777777 appears in the input, return "Saved by the Seven Dwarfs"
* If #FFFAFA (Snow) appears in the input, return "Saved by Love's first kiss"
* If an F variant appears in the input, return "Press F to pay respects to Snow White"
    + An F variant is any number that contains at least one `F` in its hexadecimal form, and is otherwise all `0`s (e.g. #0FF0F0, #FFFFFF, #00000F, #F00F00)
* If **multiple** of the preceding occur, return the "fairest" answer. The "fairest" answer is calculated as follows:
    + For all N occurrences of special color values, choose the (N-1)/2-th (truncating division) occurrence. The associated special output is the "fairest" answer.

*"Appears in the input" here refers to only the hexadecimal color values, and not to the paired strings.*

* If none of the preceding occur, return the "fairest" answer. The "fairest" answer is calculated as follows:
    + Take the hexadecimal color value at the end of input values, write it down, and exclude that single color-string pair from consideration as the "fairest" answer
    + Show its binary form to the mirror, computing a reflection of only the last 24 (#FFFFFF is the mask) bits.
    + Choose the hexadecimal color with least Hamming distance from the reflection. If there are multiple (N) such colors, choose the middle ((N-1)/2-th, truncating division) instance of the color. The "fairest" answer is the associated string for the color.

# Inputs:

A sequence of hexadecimal color values and String values separated by a space. The input may also be read as two separate sequences of hexadecimal color values and String values, or a single sequence of 2-tuples (either `(hexValue, stringValue)` or `(stringValue, hexValue)` is permissible, as long as the ordering is consistent across all 2-tuples). Input order matters - for each index, the corresponding element in the supply of color values is "associated" with the corresponding element in the supply of String values, and duplicates can affect the "fairest" answer. The effect is something like `Function(List(HexColorValue),List(AssociatedStrings)) -> "fairest" answer`. Hexadecimal color values may be represented as either (your choice of) a String "#"+6 digits, or 6 digits alone, as long as the representation is consistent across all color values.

Here's an example input:

```
76ADF1 Return to Sleeping Death
2FE84E Return whence ye came!

```

Here's another example input:

```
2FE84E Return to Sender
4FFAFC Return of the Obra Dinn
2FE84E Return to the house immediately, young lady!
2FE84E Return to Sleeping Death
2FE84E Return of the Jedi

```

Here's the third example input:

```
2FE84E Return to Sender
4FFAFC Return of the Obra Dinn
2FE84E Return to the house immediately, young lady!
2FE84E Return to Sleeping Death
7217F8 Return of the King

```

Here's the final sample input:

```
F4A52F Eating hearts and livers
F4A52F Eating apples
F4A52F Eating porridge
F4A52F Eating candy houses
F4A52F A Modest Proposal

```

# Outputs:

The "fairest" answer as computed by the specified logic. For example, on the first sample input, the "fairest" answer would be **`Saved by the Seven Dwarfs`**, due to the special hex color `76ADF1` appearing within the input.

In the second sample, there are no special inputs. First, we take "2FE84E Return of the Jedi", which has value #2FE84E. In binary, this is:

```
001011111110100001001110

```

We take the reflection from the mirror, getting:

```
011100100001011111110100

```

We compare it against `2FE84E (001011111110100001001110)` and `4FFAFC (010011111111101011111100)`, which have Hamming distances of 18 and 12 from the reflection, respectively. Since #4FFAFC has the uniquely lowest Hamming distance from the reflection, the "fairest" answer is **`Return of the Obra Dinn`**.

In the third sample input, there are no special inputs. First, we take "7217F8 Return of the King", which has value #7217F8. In binary, this is:

```
011100100001011111111000

```

We take the reflection from the mirror, getting:

```
000111111110100001001110

```

We compare it against `2FE84E (001011111110100001001110)` and `4FFAFC (010011111111101011111100)`, which have Hamming distances of 2 and 8 from the reflection, respectively. All 3 instances of hexadecimal color value #2FE84E have minimum Hamming distance from the reflection, so we take the `(3-1)/2`=`1th` instance (0-indexed) of #2FE84E. Therefore, the "fairest" answer is **`Return to the house immediately, young lady!`**.

In the last sample input, there are no special inputs. First, we take "F4A52F A Modest Proposal", which has value #F4A52F. In binary, this is:

```
1111010011001100101111

```

We take the reflection from the mirror, getting:

```
1111010011001100101111

```

We compare it against `F4A52F (1111010011001100101111)`, which has Hamming distance 0 from the reflection. All instances of hexadecimal color value #F4A52F have minimum Hamming distance from the reflection. There are *FOUR* instances of #F4A52F, because we always exclude the last hexadecimal color instance from evaluation. Therefore, we take the `(4-1)/2=1th` instance (0-indexed) of #F4A52F, and the "fairest" answer is **`Eating apples`**. *If* you don't exclude the last value from consideration, you actually get the `(5-1)/2=2th` instance of #F4A52F (`Eating porridge`), which is wrong.

# Rules:

* No standard loopholes
* Input/output taken via standard input/output methods.
* The output must be exactly equal to the "fairest" answer

# Scoring:

This is code golf, so shortest program wins.

<sub>*Here's the sandbox link*</sub>

# Answer
# C# (Visual C# Interactive Compiler), 557 bytes

```
a=>b=>{var k=a.Select(l=>l==0xFF0800?"Return to Sleeping Death":$"{l:X}".All(x=>x>69|x<49)?"Press F to pay respects to Snow White":"Saved by "+"Grumpy,Happy,Sleepy,Bashful,Sneezy,Dopey,Doc,the Seven Dwarfs,Love's first kiss,	".Split(',')[l==0xFFFAFA?8:l==11111111?0:l%1118481<1?l/1118481:l%1111111<1?l/1111111:9]);int j=a.Last(),i=0,e=24;for(;e-->0;i|=j%2,j>>=1)i*=2;var m=k.Where(o=>o[9]!=9);var t=a.SkipLast(1).Select(o=>Convert.ToString(o^i,2).Sum(y=>y-48)).ToList();return(m.Any()?m:m=b.SkipLast(1).Where((x,y)=>t.Min()==t[y])).ToList()[~-m.Count()/2];}

```

Try it online!
> 3 votes

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

Takes input as a list of tuples `[color, string]`.

```
a=>(h=a=>a[a.length-1>>1])(a.flatMap(([c])=>(s=c-0xFFFAFA?"Grumpy/Happy/Sleepy/Bashful/Sneezy/Dopey/Doc/the Seven Dwarfs".split`/`[(d=c-11111111?c/1118481:1)%1?c/1111111:d]:"Love's first kiss")?"Saved by "+s:c-0xFF0800?(g=n=>n?n%16%15||g(n>>4):0)(C=c)?[]:"Press F to pay respects to Snow White":"Return to Sleeping Death"))||h(a.map(m=([c,s])=>[(d=g(c,i=24))>m?d:m=d,s],a.pop(g=n=>i--&&(n^C>>i)%2+g(n/2))).flatMap(([d,s])=>d-m?[]:s))

```

Try it online!
> 2 votes

---
Tags: code-golf, base-conversion, bitwise, text-processing
---