title: Make the Stretchy Snakes Kiss

text:
# Question
Title: Make the Stretchy Snakes Kiss
A *stretchy snake* looks something like this:

```
<||=|||:)~

```

Each separate sequence of vertical bars (`|`) in a stretchy snake, known as a *stretchy portion*, is individually extendable to twice its width, and is drawn with alternating slashes (`/`,`\`) once extended.

The particular snake above has two such stretchy portions, giving it four possible poses:

```
<||=|||:)~

</\/\=|||:)~

<||=/\/\/\:)~

</\/\=/\/\/\:)~

```

The general form of a stretchy snake in its least stretched pose is defined by this regex:

```
<(\|+=)*\|+:\)~

```

Which can be stated in words as:

> `<`, followed by any number of sequences of `|`'s joined with `=` signs, followed by `:)~`.

So `<|:)~` and `<||:)~` and `<|=|:)~` and `<|=|=||=|||||=||:)~` are stretchy snakes, but `<=:)~` and `<=|:)~` and `<||=:)~` and `<|==||:)~` are not.

Stretchy snakes can also face left instead of right, e.g. `~(:|||=||>`. The forms are the same, just mirrored.

# Challenge

Write a program that takes in a single line string of two stretchy snakes facing each other, with some number of spaces in between. Both snakes will be in their least stretched pose (all vertical bars, no slashes). The string will start with the tail of the right-facing snake and end with the tail of the left-facing snake (you may optionally assume there's also a trailing newline).

For example, here's a possible input with five spaces between the snakes:

```
<|=||:)~.....~(:||||>

```

I'm using periods (`.`) instead of actual space characters for clarity.

Zero spaces between snakes is also valid input:

```
<|=||:)~~(:||||>

```

We say the snakes are *kissing* when their tongues are touching like this.

Your program needs to extend some combination of the stretchy portions of both of the snakes such that the snakes have the fewest number of spaces possible between them (without overlapping), **i.e. such that the snakes are as close to kissing as possible**.

Both the snakes' tails are fixed but their heads and bodies can move - right for the right-facing snake, left for the left-facing snake - according to what stretchy portions have been extended.

The output of your program is the single line string (plus optional trailing newline) that shows the snakes as close to kissing as possible, with alternating slashes drawn in place of vertical bars for stretchy portions that have been extended.

---

For example, the output for `<|=||:)~.....~(:||||>` (from above) would be:

```
</\=||:)~~(:/\/\/\/\>

```

This is the *only* solution here because with any other combination of the stretchy portions extended, the snakes would either overlap or be farther away from kissing.

---

If there are multiple solutions possible, the output may be any one of them.

For example, if the input were

```
<|=||:)~.....~(:|||=|>

```

the output could be

```
<|=/\/\:)~~(:/\/\/\=|>

```

or

```
</\=||:)~~(:/\/\/\=/\>

```

---

Remember that it won't always be possible to make the snakes kiss, but you still need to get them as close as possible.

For example, if the input were

```
<||=||||:)~...~(:||>

```

the output could be

```
</\/\=||||:)~.~(:||>

```

or

```
<||=||||:)~.~(:/\/\>

```

---

If the snakes are already kissing, the output will be the same as the input. e.g.

```
<|=||:)~~(:||||>

```

In general, the output will be the same as the input if the extension of any stretchy portion would make the snakes overlap. e.g.

```
<|||=|||:)~..~(:||||=|||||=||||||>

```

---

## Notes

* Takes input from stdin or the command line as usual, or write a function that takes a string. Print or return the output.
* You can use periods (`.`) in the input and output in place of spaces () if you prefer.
* It's only important that slashes alternate within the sequence of vertical bars they replaced. Their ordering in the snake at large or whether a forward or backward slash comes first doesn't matter.
* Stretchy portions cannot extend partway - it's exactly double or no extension at all.

## Scoring

This is code-golf. The shortest submission in bytes wins. Tiebreaker is earlier answer.

# Answer
> 9 votes
# CJam, ~~87~~ ~~71~~ ~~70~~ 68 bytes

```
l:L"|"f&Qa%_,Y\m*\f{.{_,"/\\"*?}L'|%.\s" /"1$fe=:-\a+}${0a>}=~S%\S**

```

Try it online in the CJam interpreter.

### How it works

```
l:L        e# Read a line from STDIN and save it in L.
"|"f&      e# Intersect each character with the string "|".
           e# This pushes either "|" or "".
Qa%        e# Split the resulting array at runs of "".
_,         e# Compute the length of the resulting array (A).
           e# This yield K, the number of stretchy parts.
Y\m*       e# Push the array of all vectores in {0,1}^K.
\f{        e# For each vector V in {0,1}^K, push V and A; then:
  .{       e#   For each C in V and the corresponding P in A:
    _,     e#     Compute the length of the stretchy part P.
    "/\\"* e#     Repeat "/\" that many times.
    ?      e#     If C, select P; else, select "/\"*length(P).
  }        e#   This modifies A.
  L'|%     e#   Split L at runs of vertical lines.
  .\s      e#   Interleave the chunks of L and the modified A. Sringify.
           e#   In each iteration, this constructs a different modification of L,
           e#   with some stretched out stretchy parts.
  " /"1$   e#   Push " /" and a copy of the modified L.
  fe=      e#   Calculate the number of spaces and slashes in the modifed L.
  :-       e#   Subtract the number of occurrences.
  \a+      e#   Construct the array [difference modified-L].
}          e#
$          e# Sort the array (by final number of spaces).
{0a>}=     e# Find the first element greater than [0].
           e# This skips over too far stretched snakes, where the number of
           e# slashes is less than the number of spaces.
~          e# Dump the difference (D) and modified L on the stack.
S%         e# Split L at runs of spaces.
\S*        e# Construct a string of D spaces.
*          e# Join the split L, delimiting by D spaces.

```

# Answer
> 20 votes
# Retina, ~~209~~ ~~107~~ ~~99~~ ~~97~~ 92 bytes

```
.(?=(.+)(?<=(?=<((\|+|(?<-5>\|(?=\1())?)+)[^|]+)+$(?(5)!)).+( )+\S+))\4
/ \
+` (.*~|~.*)
$1

```

For counting purposes, each line goes in a separate file, but you can run the code from a single file with the `-s` flag.

Bringing the best features of .NET regex and Retina together: balancing groups, arbitrary length lookbehinds and repeated regex substitution.

Essentially, the long regex encodes a valid solution and the regex engine's backtracker finds one of the optimal ones for me.

## Explanation

First, let's consider how we can find a valid solution (not necessarily producing the correct output) with a regex. We can use .NET's balancing groups to help us count the stretchy parts. Consider the following simpler regex:

```
\S+( )+.+(?<=(?(1)!)^([^|]+(\|+|(?<-1>\|)*))+>)

```

We can disect that.

```
\S+( )+.+

```

This matches the entire string, pushing one capture onto the group `1` stack for each space in the input. We will use that stack to ensure that the stretchy parts exactly fill the space captured into those groups.

Next is a lookbehind. The catch is that lookbehinds are matched from right to left in .NET (so that's how you should read them). This gives us the opportunity to traverse the string a second time, figuring out whether there's a subset of stretchy part that sums to the number of matched spaces. Going through the lookbehind from right-to-left:

```
>

```

This is just ensure that we're actually starting from the end of the string (the snake's tail).

```
(
  [^|]+
  (
    \|+
  |
    (?<-1>\|)+
  )
)+

```

For each stretchy part, this either just matches the entire part without doing anything (`\|+`), or it matches the entire part while popping captures off stack `1` (`(?<-1>\|)*`). Having this alternation ensures that we can only fully extend a stretchy part or leave it unchanged, and not get stuff like `|/\|`. Then we move on to the next stretchy part with `[^|]+`.

```
(?(1)!)^

```

Finally, we ensure that we've traverse the entire string (both snakes), and that stack `1` is completely empty. I.e. that we've found a subset of stretchy part that exactly sums to the number of spaces we've captured earlier.

The backtracker will go back and forth through the string trying all combinations of unchanged and extended parts until the subset sum problem is solved. If such a subset doesn't exist, the lookbehind will fail. This will cause the backtracker to go back to the `\S+( )+.+` part and try capturing one space less with `( )+` (which will just be cover by `.+` instead). Due to the greediness of `+` we therefore try filling as many spaces as possible.

You can check the validity of this approach with this slightly modified substitution:

```
\S+(( )+).+(?<=(?(2)!)^([^|]+(\|+|(?<-2>\|)*))+>)
=$1=

```

Which will give you a string `=spaces=` with exactly the number of spaces that can be filled with the given snakes.

I've had to add some more trickery to actually expand the correct `|`s. Basically, I want to replace all `|`s which were matched using the `(?<-1>\|)+` branch. The idea is to match an individual character, put the solver in a lookaround and set a flag if the match happens to be inside that branch. If that flag wasn't set we invalidate the match at the end to avoid replacement of other characters.

To do this, we use a bunch of nested lookarounds. Again, .NET's variable-length lookbehinds are matched from right to left, so if we nest lookaheads and lookbehinds, we can let the regex engine traverse the string several times. For golfing reasons, the solver is reversed in my actual solution (starting at the end, picking up the spaces from right to left, and then solving the subset sum from left to right), but otherwise the structure of the solver is exactly the same. Let's dissect the full regex:

```
.(?=(.+)...)

```

We match a single character, then capture the remainder of the string and move the cursor to the end of the string. We will use this group `1` later to check in the solver whether we're at the position of the match.

```
(?<=....+( )+\S+)

```

This is like the first part of the simple solver above, except that we pick up the spaces from right to left. The backtracking of the number of spaces works exactly the same as before, except that we're using group `5` now.

```
(?=<((\|+|(?<-5>\|(?=\1())?)+)[^|]+)+$(?(5)!))

```

This is the same as before, except we're going from left to right, and whenever we match a `|` in the expanding branch, we check if it's the one being matched right with

```
(?=\1())?

```

This is an optional lookahead. It tries to match group `1` again (which, here, is only possible if we're right after the character being matched), and if we do, we capture an empty string into group `4`, which indicates that we did find the current character in one of the expanded bits. If `\1` doesn't match, `4` won't capture anything, and the `?` ensures that the failing lookahead won't affect the solver at all.

Finally, after all the solving is done, we just check with `\4` whether this lookahead was used. If so, we want to replace the current character with `/\`.

One difficulty remains: removing the right amount of spaces. The shortest way to do this I've found so far is to insert a space along with the `/\` and then get rid of one space between the tongues for each of those marker spaces in a separate step:

```
+` (.*~|~.*)
$1

```

# Answer
> 6 votes
# Ruby ~~191 187 186 170~~ 162

```
->t{s=r=t.size
i=m=t[o=/ +/].size
(0...2**t.scan(y=/\|+/).size).map{|n|q=-1
x=t.gsub(y){|r|n[q+=1]<1?r:'\/'*r.size}
d=i+s-x.size
d<0||d<m&&r=x.gsub(o,' '*m=d)}
r}

```

This is a function that takes a string as a parameter and returns a string.

Online tests: http://ideone.com/uhdfXt

Here's the readable version:

```
# enumerates the possible states for any string containing snakes
COMBINATIONS =-> snake {
  expandable_fragments = snake.scan /(\|+)/

  (0...2**(expandable_fragments.size)).map{ |i|
    x=-1
    snake.gsub(/\|+/){|r| i[x+=1]>0 ? '\/'*r.size : r}
  }
}

# finds the configuration in which snakes are closest to each other
KISS=
-> input {
  result = input
  s = input.size
  initial_distance = min_distance = input[/ +/].size

  COMBINATIONS[input].map{|c|
    distance = initial_distance + s - c.size
    if distance > -1 && distance < min_distance
      min_distance = distance
      result = c.gsub(/ +/,' '*distance)
    end
  }

  result
}

```

In the golfed version, the main function is the equivalent of the `KISS` function above, and the `COMBINATIONS` function has been inlined.

# Answer
> 6 votes
# Python, 205 bytes

```
from itertools import*
f=lambda s:min([c.replace(".","",c.count("X"))for c in map("".join,product(*map({"|":"|X"}.get,s,s)))if{c.count("X")>c.count("."),"|X"in c,"X|"in c}=={0}],key=len).replace("X","/\\")

```

Having a single lambda looks neat and all, but I'm almost certain this is not the best way to go. But I'm posting this because it's all I've got so far that looks half decent.

This is a simple brute force over all possible replacements of `|` with `/\`, filtering out the invalid configurations. The only neat bit I guess is that we don't actually replace any `|` with `/\` directly - we first replace `|` with `X` and drop a `.` from the middle for every replacement, take the minimum length string over all valid strings, then replace the `X`s with `/\`.

I tried a few other approaches, including recursive ones, but they ended up pretty messy. I also learnt that `re.split` currently doesn't split on empty strings, which was unfortunate, because one of my ideas involved splitting on `\b` word boundaries.

# Answer
> 5 votes
# Mathematica, 381 bytes

```
StringReplace[MapAt[StringReplace[#,"|"->"/\\"]&,StringSplit[#<>"="<>#2,"="],#3]~StringRiffle~"=",")="->")~"<>If[#4>0,"."~StringRepeat~#4,""]<>"~"]&[#1,#3,Sequence@@Function[{l,s},{#,#2-Total@Extract[l,#]}&[Flatten[l~Position~#~Take~#2&@@@Tally@#&@@Select[Subsets@l,Total@#<=s&]~MaximalBy~Total,1],s]][StringLength/@StringCases[#1<>#3,"|"..],StringLength@#2]]&@@#~StringSplit~"~"&

```

Pure function taking the string as its argument. Expects `.` rather than  between the snakes.

I didn't think it would be this bad...Here's what I had before I smashed it together and infixed everything.

```
f[lhs_, rhs_,
  spaces_] := {StringLength /@ StringCases[lhs <> rhs, "|" ..],
  StringLength@spaces}

g[barLens_,
   spaceLen_] := {#, #2 - Total@Extract[barLens, #]} & @@ {Flatten[
     Take[Position[barLens, #], #2] & @@@
      Tally[First[
        MaximalBy[Select[Subsets[barLens], Total@# <= spaceLen &],
         Total]]], 1], spaceLen};

h[lhs_, rhs_, partspec_, newSpaceLen_] :=
 StringReplace[
  StringRiffle[
   MapAt[StringReplace[#, "|" -> "/\\"] &,
    StringSplit[lhs <> "=" <> rhs, "="], partspec], "="],
  ")=" -> ")~" <>
    If[newSpaceLen > 0, StringRepeat[".", newSpaceLen], ""] <> "~"]

 h[#1, #3, Sequence @@ g @@ f[#1, #3, #2]] & @@
     StringSplit[#, "~"] &

```

Here is an example run-through with explanation:

```
Input: "<|=||:)~.....~(:||||>"
@Call StringSplit[#, "~"] &, yielding  {"<|=||:)", ".....", "(:||||>"}
@@Apply h[#1, #3, Sequence @@ g @@ f[#1, #3, #2]] &, but first
Set arguments: h["<|=||:)", "(:||||>", Sequence @@ g @@ f["<|=||:)", "(:||||>", "....."]]
@Call f, yielding {{1, 2, 4}, 5} = {# of bars in each segment, # of spaces}
@@Apply g, let's trace from the interior:
Subsets[barLens] = all subsets of {1, 2, 4}
Select those subsets whose sum is less than # of spaces {{},{1},{2},{4},{1,2},{1,4}}
MaximalBy Total, yielding a list of all subsets whose sum is maximal {{1, 4}}
First of these subsets, can be any of them {1, 4}
Tally the subset, yielding frequencies of each {{1, 1}, {4, 1}}
@@@Apply Take[Position[barLens, #], #2] & at the first level, yielding
    {Take[Position[{1, 2, 4}, 1], 1], Take[Position[{1, 2, 4}, 4, 1]]}
    which takes the first 1 positions of 1 and the first 1 positions of 4, yielding
    {{{1}},{{3}}}
Flatten at the first level, yielding {{1}, {3}}
Create a list {{{1}, {3}}, 5}
@@Apply {#, #2 - Total@Extract[barLens, #]} &, inserting arguments:
    {{{1}, {3}}, 5 - Total@Extract[{1, 2, 4}, {{1}, {3}}]} = {{{1}, {3}}, 0}
    where the second element becomes the # of spaces left over.
Done with g, it returned {{{1}, {3}}, 0}
@@Apply Sequence, splicing the return of g into h, yielding the
@Call, h["<|=||:)", "(:||||>", {{1}, {3}}, 0]; let's start from the interior
StringSplit the concatenated "<|=||:)=(:||||>" with delimiter "=", {"<|","||:)","(:||||>"}
MapAt the part specification {{1}, {3}} and StringReplace at those indices any | with /\
    yielding {"</\","||:)","(:/\/\/\/\>"}
StringRiffle together, inserting back the delimiter "=", yielding "</\=||:)=(:/\/\/\/\>"
StringReplace ")=" with ")~", concat the new number of spaces, concat "~"
Yields "</\=||:)~~(:/\/\/\/\>", done.

```

# Answer
> 3 votes
### Prolog (ECLiPSe), 438 bytes

My other answers were solving the wrong problem (sorry for the noise). Here is another attempt in Prolog which actually respects all rules.

```
:-lib(fd).
a([],[]).
a([H|T],L):-append(H,X,L),a(T,X).
s(E,Z,X,Y,L):-length(E,L),a([[60],M,[58,41,126],T,[126,40,58],W,[62]],E),checklist(=(32),T),length(T,Z),b(M,X-[]),b(W,Y-[]).
b(I,[K:M|R]-E):-(I:K=[47,92|L]:s;I:K=[124|L]:n),M#=N+1,N#>=0,b(L,[K:N|R]-E).
b([61|L],[_:0|R]-E):-b(L,R-E).
b([],[_:0|E]-E).
d(_:N,Y:N):-Y=s;Y=n.
s(W,P):-string_list(W,E),s(E,_,X,Y,L),minimize((maplist(d,X,U),maplist(d,Y,V),s(K,Q,U,V,L)),Q),string_list(P,K).

```

### Tests

*(format: input, output, newline)*

```
<===:)~         ~(:>
<===:)~         ~(:>

<|||:)~         ~(:||||=|>
</\/\/\:)~ ~(:/\/\/\/\=/\>

<=|=:)~         ~(:||||=|>
<=/\=:)~   ~(:/\/\/\/\=/\>

<===|:)~         ~(:||=|>
<===/\:)~     ~(:/\/\=/\>

<|=|=|||=|:)~         ~(:=|>
</\=/\=/\/\/\=/\:)~  ~(:=/\>

<||||||:)~         ~(:=|>
</\/\/\/\/\/\:)~  ~(:=/\>

<||||||:)~         ~(:||>
</\/\/\/\/\/\:)~ ~(:/\/\>

<||=||||:)~ ~(:||>
<||=||||:)~ ~(:||>

<||=||||:)~   ~(:||>
</\/\=||||:)~ ~(:||>

<||=||||:)~    ~(:||>
</\/\=||||:)~~(:/\/\>

<||=||||:)~~(:||>
<||=||||:)~~(:||>

```

### Explanations

* The main predicate is `s/2`, which takes the input as a first argument and unfiy the result with the second argument (both strings). The input is converted to a list of character codes, `E`.
* Then, `s(E,Z,X,Y,L)` destructures the list into the following elements:

+ `Z` number of spaces between snakes
    + `X` and `Y`, abstract representation of the left and right bodies

    The format of a body is a list of `n:N` or `s:N` expressions, where `N` is a positive length; `n` means `normal` and `s` means `stretched`.
    + `L` total length of the list

**What is interesting about `s/5`** is that it goes *both ways*, i.e. we can **build** a snake if other arguments are instanciated:

```
    s(E,5,[n:3],[s:2,n:7,s:1],_),string_list(S,E).

... unifies `S` with `"<|||:)~     ~(:/\\/\\=|||||||=/\\>"` (backslashes are quoted). This is due to how `b/2` is written, which can parse the character list or generate it.

```
* We build modified left and right bodies where each part is either normal or stretched, while minimizing the space `Q` that separates the new snakes. The total length of the computed string is bounded so that the search terminates.

# Answer
> 1 votes
# Python 2.7.3 ~~427~~ ~~421~~ ~~400~~ 371 Bytes

```
import re,itertools as K
g,o,k='\|+',len,raw_input()
d=k.count(' ')
if d==0:exit(k)
p,x,y,s=re.sub,0,0,map(o,re.findall(g,k))
for e in [A for w in range(o(s)+1)for A in K.combinations(s,w)]:
 v=sum(e)
 if v==d or x<v<d:x,y=v,list(e)
print p(" +",' '*(d-x),p(g,lambda m:('/\\'*o(m.group(0))if y.remove(o(m.group(0)))or True else 1)if o(m.group(0))in y else m.group(0),k))

```

Non-golfed code here -

```
#!/usr/bin/env python
import sys
import re

def find_dist_combo(li, d):
    #Listing all combinations
    from itertools import combinations as c
    max_dist = -1
    max_dist_combo = []
    for p_len in xrange(1,len(li)+1):
        for e in c(li, p_len):
            e_sum = sum(e)
            cond1 = e_sum == d
            cond2 = max_dist < e_sum < d
            if cond1 or cond2:
                max_dist = e_sum
                max_dist_combo = list(e)
                if cond1:
                    return (max_dist, max_dist_combo)
    return (max_dist, max_dist_combo)

def snakes_foreplay(snakes):
    #find distance
    distance = snakes.count(" ")

    #already kissing
    if distance == 0:
        return snakes

    #find num_stretches
    stretch = map(len, re.findall("\|+", snakes))

    #find lowest combination of numbers
    (e_dist, res_stretch) = find_dist_combo(stretch, distance)

    def sub_callback(m):
        s = m.group(0)
        l = len(s)
        if l in res_stretch:
            res_stretch.remove(l)
            return '/\\'*l
        return s

    #Resultant substitution
    res_snakes = re.sub("\s+", " "*(distance - e_dist), re.sub("\|+", sub_callback, snakes))

    return res_snakes

if __name__ == "__main__":
    for s in [ip.strip() for ip in sys.stdin]:
        print snakes_foreplay(s)

```

Testing the golfed solution -

```
$ python stretchy_snakes.py
[In]  <=  <|=||:)~     ~(:||||>
[Out] =>  </\=||:)~~(:/\/\/\/\>

$ python stretchy_snakes.py
[In]  <=  <|=||:)~             ~(:||||>
[Out] =>  </\=/\/\:)~      ~(:/\/\/\/\>

$ python stretchy_snakes.py
[In]  <=  <|=||:)~     ~(:|||=|>
[Out] =>  </\=||:)~~(:/\/\/\=/\>

$ python stretchy_snakes.py
[In]  <=  <||=||||:)~   ~(:||>
[Out] =>  </\/\=||||:)~ ~(:||>

$ python stretchy_snakes.py
[In]  <=  <|=||:)~~(:||||>
[Out] =>  <|=||:)~~(:||||>

```

Surely this can be done better(I can't figure out how :)).
Let me know if I've missed anything obvious while golfing (It's my first codegolf, I may be doing something stupid :P)

# Answer
> 1 votes
# 05AB1E, 93 bytes

```
#õKDεγʒ'|å]©ε€gxøDgU`XGâ€˜]`âDε˜ODI„| Ãg>‹*}ZQÏε˜ε®˜NèDgyÊi„/\y∍]н©J'/¢Ið¢αð×ý'|¡õK®.ιJIðå≠iI

```

Way too long.. \>.\>

Try it online or verify all test cases or verify all possible results for all test cases.

**Explanation:**

```
#õK                   # Split the (implicit) input by one or multiple adjacent spaces
                      # (we now have both snakes as separated items
                      #  - if any spaces were in the input-string)
   D                  # Duplicate this list
    ε                 # Map both snakes to:
     γ                #  Split the snake into chunks of the same character-type
      ʒ'|å]          '#  And only leave the chunks of "|" characters
    ©                 #  Store this list in variable `r` (without popping)
     ε                #  Map the "|" chunks of both snakes again:
      €g              #  Get the length of each chunk of "|"
        xø            #  Pair each length with double itself
          DgU`XGâ€˜   #  Create all possible combinations for the current snake
     ]`â              # After the map: create all possible combinations for both snakes
        ε             # Map over each possible combination
         ˜O           #  Get the flattened sum
            I„| Ãg    #  Count the amount of "|" and spaces in the input
                  >‹  #  Check if it's smaller than or equal to this sum
                      #  (1 if truthy; 0 if falsey)
           D        * #  And multiply it by the sum
        }ZQ           # After the map, get the positions of the largest flattened sum,
                      # still below (or equal to) the amount of "|" and spaces combined
       D   Ï          # And only keep those combinations
ε                     # Then map over the remaining combinations
 ˜ε                   #  Flatten it, and map over each value `y`
   ®˜Nè               #   Get the `N`'th part of the snakes
                      #   (where `N` is the index of the map for the current combination)
       D              #   Duplicate this "|"-part
        gyÊi          #   If the length of this "|"-part is not equal to the map-value:
            „/\       #    Push the string "/\"
               y∍     #    Extended to a size equal to the map-value
                      #   (implicit else:
                      #    use the duplicated value)
]н                    # After the map: only leave the first (since we don't have
                      # to output all possibilities)
 ©                    # Store it in variable `r` (without popping)
  J'/¢               '# Count the amount of "/" in it
      Ið¢             # Count the amount of spaces in the input
         α            # Get the difference between those
          ð×ý         # And join the list of snakes by that many spaces
'|¡õK                '# Then split by one or multiple adjacent "|"
     ®.ι              # Interleave it with the modified parts of variable` r`
        J             # And join everything together to a single string
Iðå≠i                 # If the input didn't contain any spaces:
     I                #  Output the input instead
                      # (implicit else:
                      #  output the top of the stack before this if)

```

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


title: Folding Numbers

text:
# Question
Title: Folding Numbers
Given a number determine if it is a folding number.

A folding number is a number such that if you take it binary representation and "fold" it in half, That is take the result of XNOR multiplication of the first half of the number and the second half with it digits in reverse, you will get zero.

If the number has a odd number of digits in binary its middle digit must be 1 and is ignored when folding.

Since that might be a bit confusing I will give some examples:

### 178

The binary representation of 178 is

```
10110010

```

To fold this we first split it in half

```
1011 0010

```

We reverse the second half

```
1011
0100

```

And we XNOR the two halves:

```
0000

```

This is zero so this is a folding number.

### 1644

The binary representation of 1644 is

```
11001101100

```

To fold this we first split it in half

```
11001 1 01100

```

The middle bit is 1 so we throw it out.

```
11001 01100

```

We reverse the second half

```
11001
00110

```

And we XNOR the two halves:

```
00000

```

This is zero so this is a folding number.

### 4254

The binary representation of 4254 is

```
1000010011110

```

To fold this we first split it in half

```
100001 0 011110

```

The middle bit is 0 so this is not a folding number.

## Task

Your task is to take in a positive number and return a truthy if the number is folding and falsy if it is not. This is code golf so try to keep the byte count down.

## Test Cases

Here are the first 99 folding numbers:

```
[1, 2, 6, 10, 12, 22, 28, 38, 42, 52, 56, 78, 90, 108, 120, 142, 150, 170, 178, 204, 212, 232, 240, 286, 310, 346, 370, 412, 436, 472, 496, 542, 558, 598, 614, 666, 682, 722, 738, 796, 812, 852, 868, 920, 936, 976, 992, 1086, 1134, 1206, 1254, 1338, 1386, 1458, 1506, 1596, 1644, 1716, 1764, 1848, 1896, 1968, 2016, 2110, 2142, 2222, 2254, 2358, 2390, 2470, 2502, 2618, 2650, 2730, 2762, 2866, 2898, 2978, 3010, 3132, 3164, 3244, 3276, 3380, 3412, 3492, 3524, 3640, 3672, 3752, 3784, 3888, 3920, 4000, 4032, 4222, 4318, 4462, 4558]

```

# Answer
# Jelly, 9 bytes

```
Bœs2µḢ^UȦ

```

Try it online! or verify all test cases.

### How it works

```
Bœs2µḢ^UȦ  Main link. Argument: n

B          Binary; convert n to base 2.
 œs2       Evenly split 2; split the base 2 array into chunks of equal-ish length.
           For an odd amount of digits, the middle digit will form part of the
           first chunk.
    µ      Begin a new, monadic chain. Argument: [A, B] (first and second half)
     Ḣ     Head; remove and yield A.
       U   Upend; reverse the digits in [B].
      ^    Perform vectorized bitwise XOR of the results to both sides.
           If A is longer than B, the last digit will remain untouched.
           n is a folding number iff the result contains only 1's.
        Ȧ  Octave-style all; yield 1 iff the result does not contain a 0.

```
> 12 votes

# Answer
## Java 7, ~~152 145 142 138~~ 134 bytes

```
boolean f(Long a){byte[]b=a.toString(a,2).getBytes();int i=0,l=b.length,z=l%2<1?1:b[l/2]-48;for(;i<l/2;)z*=b[i]-b[l-++i];return z!=0;}

```

Loops over the string like it would for a palindrome, looking for zeroes. Keeps track by repeatedly multiplying, so all you have to do is check that it's not zero at the end.

Without scroll bars:

```
boolean f(Long a){
    byte[]b=a.toString(a,2).getBytes();
    int i=0,l=b.length,z=l%2<1?1:b[l/2]-48;
    for(;i<l/2;)
        z*=b[i]-b[l-++i];
    return z!=0;
}

```
> 9 votes

# Answer
# 05AB1E, ~~13~~ 12 bytes

### Code:

```
bS2ä`R0¸«s^P

```

Uses the **CP-1252** encoding. Try it online!

### Explanation:

First, we convert the number to binary using `b`. **1644** becomes **11001101100**. We split this into two pieces with . For example, **11001101100** would become:

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

```

If there is an uneven number of bits, the first part will receive the extra bit. We `R`everse the last string and append a zero using `0¸«`. The reason for this is to only give truthy results when the middle bit is a **1** (**1 XOR 0 = 1** and **0 XOR 0 = 0**). If there is no middle bit, 05AB1E will just ignore the last bit (the zero that was appended) :

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

```

The last thing we need to do is do an element-wise **XOR** and take the product of the result. If there is one element too many, the program will just leave the last element out (`[1, 0, 0] XOR [0, 1] = [1, 1]`) For example:

```
[1, 1, 0, 0, 1, 1]
[0, 0, 1, 1, 0, 0] XOR

```

Becomes:

```
[1, 1, 1, 1, 1, 1]

```

And the product of that is **1**, which is truthy.
> 9 votes

# Answer
## JavaScript (ES6), ~~61~~ ~~57~~ 52 bytes

Recursively computes:

```
(bit(N) XOR bit(0)) AND (bit(N-1) XOR bit(1)) AND (bit(N-2) XOR bit(2)) etc.

```

where `N` is the rank of the highest bit set in the input.

If the input has an odd number of bits, the middle bit is XOR'ed with *undefined* (the value returned by `pop()` on an empty array), which lets it unchanged. So, a `0` middle bit clears the output and a `1` middle bit doesn't alter the result of the other operations -- which is consistent with the challenge definition of a folding number.

```
f=(n,[a,...b]=n.toString(2))=>a?(a^b.pop())&f(n,b):1

// testing integers in [1 .. 99]
for(var i = 1; i < 100; i++) {
  f(i) && console.log(i);
}
```
> 9 votes

# Answer
## Python 2, 57 bytes

```
s=bin(input())[2:]
while''<s!='1':s[-1]==s[0]<_;s=s[1:-1]

```

Outputs via exit code: error for Falsey, and no error for Truthy.

Converts the input into binary. Checks whether the first and last character are unequal, keeps and repeating this after removing those characters.

The comparison `s[-1]==s[0]<_` gives an error if the first and last character are unequal by trying to evaluate the unassigned variable named `_`. If they are equal, the chain of inequalities is short-circuited instead. When we get to the middle element of `1`, the `while` loop is terminate to special-case it as OK.

I suspect a purely arithmetic approach will be shorter with a recursion like `f=lambda n,r=0:...f(n/2,2*r+~n%2)...` to chomp off binary digits from the end flipped and reversed, and detect when `n` and `r` are equal up to a center `1`. There are subtleties though with leading zeroes and the center.
> 9 votes

# Answer
# Python 2, ~~94 79 72~~ 67 bytes

```
F=lambda s:s in'1'or(s[0]!=s[-1])*F(s[1:-1])
lambda n:F(bin(n)[2:])

```

Saved 12 bytes thanks to @xnor

Defines an unnamed function on the second line.

Explanation (with some whitespace added):

```
F = lambda s:                                        # We define a function, F, which takes one argument, the string s, which returns the following:
             s in'1'                                 # Gives true if s is '' or s is '1', the first case is a base case and the second is for the middle bit case.
                     or(s[0] != s[-1])               # Or the first and last are different
                                      * F(s[1:-1])   # And check if s, without the first and last element is also foldable.
lambda n: F(bin(n)[:-2])                             # The main function, which calls F with the argument in binary form.

```

Try it here!
> 8 votes

# Answer
## Haskell, ~~89~~ ~~88~~ 86 bytes

```
f n|n<2=[n]|1>0=mod n 2:f(div n 2)
g n=elem(product$zipWith(+)(f n)$reverse$f n)[1,2]

```

Works by summing bitwise the bit representation with its reverse and taking the product. If it's 1 or 2, the number is a folding number (1 if there are even bits that fold, 2 if there are odd bits and a one in the middle).
> 6 votes

# Answer
# Python 2, ~~100~~ ~~99~~ ~~95~~ 94 Bytes

This feels a bit long, but I'll keep working at it :) Prints a `1` if the number can be folded, `0` otherwise.

```
a=bin(input())[2:]
b=len(a)
print(a[b/2]>=`b%2`)*all(c!=d for c,d in zip(a[:b/2],a[:~b/2:-1]))

```

Test it here!

*thanks to Wheat Wizard for the 1-byte save :)*

*thanks to Rod for the 5-byte save! :)*
> 5 votes

# Answer
# \>\<\>, 37+3 = 40 bytes

```
<,2-@:%2:v!?:
=2lrv?=1l<+={$r0?
0=n;>

```

Input is expected to be present on the stack at program start, so +3 bytes for the `-v` flag.

Try it online!
> 4 votes

# Answer
# Jelly, 13 bytes

```
Bœs2U0¦z0^/€Ạ

```

**TryItOnline**
Or matching terms up to 4558

### How?

```
Bœs2U0¦z0^/€Ạ - Main link: n
B             - binary
 œs2          - split into 2 slices (odd length will have first longer than second)
     0¦       - apply to index 0 (the right hand one)
    U         - reverse
       z0     - zip together with filler 0 (thus central 1 or 0 will pair with 0)
          /€  - reduce with for each
         ^    -     XOR
            Ạ - All truthy?

```
> 4 votes

# Answer
# Perl, 46 bytes

Includes +1 for `-p`

Run with the number on STDIN

```
folding.pl <<< 178

```

`folding.pl`:

```
#!/usr/bin/perl -p
$_=($_=sprintf"%b",$_)<s%.%!/\G1$/^$&^chop%eg

```

I consider it a perl bug that this even works. Internal `$_` should not be getting match position updates once it is modified. In this program the match position actually moves beyond the end of `$_`
> 4 votes

# Answer
# Brachylog, 16 bytes

```
ḃḍ{↔|h1&b↔}ᵗz₂≠ᵐ

```

It doesn't quite work online...

Takes input through the input variable and outputs through success or failure. It relies heavily on `z₂`, which has been in the language since April 30, but we forgot to ask to have it pulled on TIO so for the time being this only works on a local installation of the language. Either way it's probably an overly naive approach.

```
                    The input
ḃ                   's binary representation
 ḍ                  split in half
  {       }ᵗ        with its second half
   ↔|               either reversed, or
     h1             if it starts with 1
       &b           relieved of its first element
         ↔          and then reversed
              ≠     has no duplicate elements
            z  ᵐ    in any pair of elements zipped from the two halves
             ₂      which are equal in length.

```

# Brachylog (on TIO), 19 bytes

```
ḃḍ{↔|h1&b↔}ᵗlᵛ↖Lz≠ᵐ

```

Try it online!

`lᵛ↖Lz` is functionally equivalent to `z₂` (if you don't use the variable L anywhere else), but it's also three bytes longer.
> 4 votes

# Answer
# Python 2, ~~76 71~~ 69 bytes

-5 bytes thanks to @Dennis (`''` is present in `'1'`, so replace `in('','1')` with `in'1'`)
-2 bytes thanks to @xnor (use multiplication, `(...)*` in place of `and`)

```
f=lambda n:f(bin(n)[2:])if n<''else n in'1'or(n[0]!=n[-1])*f(n[1:-1])

```

**Ideone**

Recursive function, upon first call `n` is a number so it evaluates as less than the empty string, with `if n<''`, and the function is called again but with `n` cast to a binary string; the tail is either an empty string (even bit-length) or the middle bit, which returns true for empty or a `'1'`; on it's way down it tests the outer bits for inequality (equivalent to XOR) and recurses on the inner bits, `n[1:-1]`.
> 3 votes

# Answer
## Python 2, 63 bytes

```
s=bin(input())[2:]
while s[0]!=s[-1]:s=s[1:-1]or'1'
print'1'==s

```

Prints `True` or `False`. Takes the binary representation of `s` and repeatedly removed the first and last characters as long as they are unequal. Checks whether what remains is the empty string or a central `1`. This is done by converting `''` to `'1'` and checking if the result equals `'1'`, which also avoid an index error on the empty string.
> 3 votes

# Answer
## PowerShell v2+, 143 bytes

Two possible approaches, both the same byte count.

Method 1:

```
param($n)if($n-eq1){$n++}$o=1;0..(($b=($n=[convert]::ToString($n,2)).length-1)/2-!($b%2))|%{$o*=$n[$_]-ne$n[$b-$_]};$o*(+"$($n[$b/2])",1)[$b%2]

```

Takes input `$n`, if it's `-eq`ual to `1` (a special case for this algorithm), increment it. Set `$o`utput to be `1` (i.e., assume truthy), then loop from `0` to the midway point of the input number that has been `[convert]`ed to binary. Note the `-!($b%2)` to account for odd length binary numbers.

Each iteration, we compare the current digit `$n[$_]` with the digit the same length from the end `$n[$b-$_]`, and multiply the Boolean result into `$o` (essentially performing an `-and` on all of them). Once the loop is done, we need to potentially account for the middle binary digit, that's the pseudo-ternary at the end (array indexed via `$b%2`). That `1` or `0` is left on the pipeline, and output is implicit.

---

Method 2:

```
param($n)for($n=[convert]::ToString($n,2);$n.Length-gt2){if($n[0]-ne$n[-1]){$n=$n[1..($n.Length-2)]}else{0;exit}}($n-join'+'|iex)-eq1-or$n-eq10

```

Takes input and does the same process to `[convert]` the number to binary. Then we're in a `for` loop so long as the `.length` of the binary string is `-g`reater`t`han `2`. When we're in the loop, if the first `$n[0]` and last `$n[-1]` digits are `-n`ot`e`qual, slice those two digits off of `$n` and re-store it into `$n`. Otherwise, output `0` and `exit`. Once we're out of the loop, we either have (an array of `1`, `1,0`, `0,1`, `1,1`, or `0,0`), or the binary string for two `10`, or 3 `11`. So, we need to test those two possibilities. For the first, we `-join` `$n` together with `+` and evaluate the result and test that it's `1` (this is true for arrays `1`, `1,0`, and `0,1`, but is `$false` for arrays `0,0` and `1,1` or strings `10` or `11`). The other half of the `-or` is testing whether `$n` is `-eq`ual to `10` (i.e., input of `2`). That Boolean is left on the pipeline, and output is implicit.
> 3 votes

# Answer
# CJam, 13 bytes

```
ri2b_W%.+:*3&

```

Try it online! or generate a list of folding numbers up to a given number.

---

```
ri2b   e# convert input to binary
_W%.+  e# flip and sum (if folding all bits are 1 except middle)
:*     e# product is 0 or power of 2 (2 if middle folds)
3&     e# keep only 1 or 2, everything else becomes 0 (false)

```
> 3 votes

# Answer
# MATL, 16 bytes

```
tBn2/kW&\hBZ}P=~

```

Truthy is an array with all ones. Check truthy/falsy criteria here.

**Try it online!** Or **Verify the first 20 test cases**.

### Explanation

Let's use input `1644` as an example.

```
t     % Imolicitly take input. Duplicate
      %   STACK: 1644, 1644
Bn    % Number of digits of binary expansion
      %   STACK: 1644, 11
2/k   % Divide by 2 and round down
      %   STACK: 1644, 5
W     % 2 raised to that
      %   STACK: 1644, 32
&\    % Divmod
      %   STACK: 12, 51
h     % Concatenate horizontally
      %   STACK: [12 51]
B     % Binary expansion. Each numnber gives a row, left-padded with zeros if needed
      %   STACK: [0 0 1 1 0 0; 1 1 0 0 1 1]
Z}    % Split into rows
      %   STACK: [0 0 1 1 0 0], [1 1 0 0 1 1]
P     % Reverse
      %   STACK: [0 0 1 1 0 0], [1 1 0 0 1 1]
=~    % True for entries that have different elements
      %   STACK: [1 1 1 1 1 1]
      % Implicitly display

```
> 2 votes

# Answer
# PHP, 101 Bytes

```
for($r=1;$i<($l=strlen($b=decbin($argv[1])))>>1;)$r*=$b[$i]^1^$b[$l-++$i]^1;$r*=$l%2?$b[$i]:1;echo$r;

```

or with log

```
for($r=1,$s=log($n=$argv[1],2)^0;2*$i<$s;)$r*=($n>>$i)%2^($n>>$s-$i++)%2;$s%2?:$r*=($n>>$i)%2;echo$r;

```

108 Bytes with array

```
for($r=1,$a=str_split(decbin($argv[1]));$a;)$r*=array_pop($a)!=($a?array_shift($a):0);$r*=$a?$a[0]:1;echo$r;

```

True values \<10000

```
1,2,6,10,12,22,28,38,42,52,56,78,90,108,120,142,150,170,178,204,212,232,240,286,310,346,370,412,436,472,496,542,558,598,614,666,682,722,738,796,812,852,868,920,936,976,992,1086,1134,1206,1254,1338,1386,1458,1506,1596,1644,1716,1764,1848,1896,1968,2016,2110,2142,2222,2254,2358,2390,2470,2502,2618,2650,2730,2762,2866,2898,2978,3010,3132,3164,3244,3276,3380,3412,3492,3524,3640,3672,3752,3784,3888,3920,4000,4032,4222,4318,4462,4558,4726,4822,4966,5062,5242,5338,5482,5578,5746,5842,5986,6082,6268,6364,6508,6604,6772,6868,7012,7108,7288,7384,7528,7624,7792,7888,8032,8128,8318,8382,8542,8606,8814,8878,9038,9102,9334,9398,9558,9622,9830,9894

```
> 2 votes

# Answer
# C, ~~223~~ ~~201~~ ~~189~~ ~~194~~ 178 Bytes

```
i,j,m,l,r;f(n){for(m=j=1,i=n;i/=2;++j);for(l=r=i=0;i<j/2;i++)r|=n&m?1<<j/2-i-1:0,m*=2;i=(j&1&&n&m)?i+1:(j&1)?l=r:i;n>>=i;for(m=1;i<j;i++)l|=n&m,m*=2;return !(~(l^r)&(1<<j/2)-1);}

```

Brute force algorithm. Let's see how far it can be golfed.

Better test setup bugfixes...

```
 main()
 {
    int t, s, u, testSet[] =
    {
    1, 2, 6, 10, 12, 22, 28, 38, 42, 52, 56, 78, 90, 108, 120,
    142, 150, 170, 178, 204, 212, 232, 240, 286, 310, 346, 370,
    412, 436, 472, 496, 542, 558, 598, 614, 666, 682, 722, 738,
    796, 812, 852, 868, 920, 936, 976, 992, 1086, 1134, 1206,
    1254, 1338, 1386, 1458, 1506, 1596, 1644, 1716, 1764, 1848,
    1896, 1968, 2016, 2110, 2142, 2222, 2254, 2358, 2390, 2470,
    2502, 2618, 2650, 2730, 2762, 2866, 2898, 2978, 3010, 3132,
    3164, 3244, 3276, 3380, 3412, 3492, 3524, 3640, 3672, 3752,
    3784, 3888, 3920, 4000, 4032, 4222, 4318, 4462, 4558
    };

    for (u=s=0,t=1;t<=4558;t++)
    {
        if (f(t))
        {
          u++;
          if (testSet[s++]!=t)
              printf("BAD VALUE %d %d\n", testSet[s-1], t);
        }
    }

    printf("%d == %d Success\n", u,
           sizeof(testSet)/sizeof(testSet[0]));

}

```
> 2 votes

# Answer
# MATL, 13 bytes

```
BttP=<~5Ms2<*

```

Truthy is an array with all ones. Check truthy/falsy criteria here.

**Try it online!** Or **verify the first 20 test cases**.

### Explanation

Using input `1644` as an example:

```
B     % Implicit input. Convert to binary
      %   STACK: [1 1 0 0 1 1 0 1 1 0 0]
t     % Duplicate
      %   STACK: [1 1 0 0 1 1 0 1 1 0 0], [1 1 0 0 1 1 0 1 1 0 0]
tP=   % Element-wise compare each entry with that of the reversed array
      %   STACK: [1 1 0 0 1 1 0 1 1 0 0], [0 0 0 0 0 1 0 0 0 0 0]
<~    % True (1) if matching entries are equal or greater
      %   STACK: [1 1 1 1 1 1 1 1 1 1 1]
5M    % Push array of equality comparisons again
      %   STACK: [1 1 1 1 1 1 1 1 1 1 1], [0 0 0 0 0 1 0 0 0 0 0]
s     % Sum of array
      %   STACK: [1 1 1 1 1 1 1 1 1 1 1], 1
2<    % True (1) if less than 2
      %   STACK: [1 1 1 1 1 1 1 1 1 1 1], 1
*     % Multiply
      %   STACK: [1 1 1 1 1 1 1 1 1 1 1]
      % Implicitly display

```
> 2 votes

# Answer
# Julia, 66 bytes

```
c(s)=s==""||s=="1"||(s[1]!=s[end]&&c(s[2:end-1]))
f(x)=c(bin(x))

```

My first golf! works the same way as the Python solution of the same length, minor differences due to language (I did come up with it on my own, though...).

Explanation:

```
c(s) = s == "" || # Base case, we compared all the digits from
                  # both halves.
       s == "1" || # We compared everything but left a 1 in the middle
       (s[1] != s[end] &&  # First digit neq last digit (XNOR gives 0).
        c(s[2:end-1]))     # AND the XNOR condition is satisfied for the
                           # 2nd to 2nd to last digit substring.
f(x) = c(bin(x))  # Instead of a string f takes an integer now.

```
> 2 votes

# Answer
## Retina, ~~71~~ ~~70~~ 60 bytes

```
.+
$*
+`^(1*)\1(1?)\b
$1 $.2
+`^ (.)(.*) (?!\1).$
$2
^( 1)?$

```

I probably still have a lot to learn about Retina (e.g. recursive regex?). Explanation: Step 1 converts from decimal to unary. Step 2 converts from unary to pseudo-binary. Step 3 removes digits from both ends as long as they mismatch. Step four matches an optional final central 1 if necessary. Edit: Saved 1 byte thanks to @mbomb007. Saved 10 bytes by improving my unary to binary conversion.
> 1 votes

# Answer
# JavaScript, 71 bytes

```
(i,n=i.toString(2))=>/^(1*)2?\1$/.test(+n+ +n.split``.reverse().join``)

```

Defines an anonymous function.

This method may not be the shortest, but as far as I know, it is unique. It adds the number in binary to itself reversed, treating them as decimal, then checking if the result is valid using a regex.
> 1 votes

# Answer
# Retina, 92 bytes

Byte count assumes ISO 8859-1 encoding.

```
.+
$*
+`(1+)\1
${1}0
01
1
^((.)*?)1??((?<-2>.)*$.*)
$1¶$3
O$^`.(?=.*¶)

T`01`10`^.*
^(.*)¶\1

```

**Try it online**

Convert to unary. Convert that to binary. Cut the number in half and remove a middle `1` if there is. Reverse the first half. Switch its ones and zeros. Match if both halves are equal.
> 1 votes

# Answer
# Python 2, ~~61~~ 59 bytes

Saving two bytes for converting shifts to multiplications

```
m=n=input()
i=0
while m:i*=2;i+=m&1;m/=2
print(n+i+1)&(n+i)

```

Returns `0` for a folding number and anything else for non-folding. Uses the bit-twiddling approach.
> 1 votes

# Answer
# C, ~~65~~ 63 bytes

Two bytes for converting shifts to multiplications

```
i,m;
f(n){
 m=n;i=0;
 while(m)i*=2,i+=m&1,m/=2;
 return(n+i+1)&(n+i);
}

```

Whitespace is already excluded from bytecount, returns 0 for a folding number and anything else for non-folding. Uses the bit-twiddling approach.
> 0 votes

# Answer
# k, 77 bytes

```
{X:2 0N#X@&:|\X:0b\:x;c:#:'X;$[(~*X 1)|(=). c;~|/(=).(::;|:)@'(-&/ c)#'X;0b]}

```

by way of explanation, a translation to `q`

```
{X:2 0N#X where maxs X:0b vs x;
  c:count each X;
  $[(not first last X)or(=). c;
    not any(=).(::;reverse)@'(neg min c)#'X;0b]
  };

```
> 0 votes

---
Tags: code-golf, number, binary, bitwise, decision-problem
---


title: Extract Local Maxima

text:
# Question
Title: Extract Local Maxima
Given an array of positive integers, output an array of all the elements that are greater than or equal to the adjacent ones. Most elements will have two adjacent elements; the first and last element are special cases, as they only have one adjacent element.

You may assume that the array contains at least two elements.

Test cases:

```
Input               | Output
[4,2,6,12,4,5,4,3]  | [4,12,5]
[1,2]               | [2]
[1,2,3,2,1]         | [3]
[3,2,1,2,3]         | [3,3]
[4,4]               | [4,4]
[2,4,4,4,1]         | [4,4,4]
[2,3,3,4]           | [3,4]
[4,3,3,4]           | [4,4]

```

This is , shortest code wins!

# Answer
# Jelly,  ~~13 12~~  11 bytes

```
0;;0»3\f"⁸Ẏ

```

A monadic link taking a list of positive integers and returning the filtered list containing only those which are greater than or equal to all their neighbours.

**Try it online!**

---

Previous 12 byter:

```
0;INżI>0ḄNMị

```

Previous 13 byter:

```
0;;0ṡ3M€ċ€2Tị

```

---

### How?

```
0;;0»3\f"⁸Ẏ - Link: list of positive integers, A
0;          - a zero concatenated with A
  ;0        - concatenate a zero
     3\     - 3-wise reduce with:
    »       -   maximum (yields a list of the maximums in each overlapping window of 3)
         ⁸  - chain's left argument, A
        "   - zip with:
       f    -   filter keep (i.e. keep the maximal if it is [in] the [length 1 list
            -                     of the] respective original element)
          Ẏ - flatten by one level

```
> 5 votes

# Answer
# Python, 54 bytes

```
f=lambda l,*p:l and l[:p<=l[:1]>=l[1:2]]+f(l[1:],l[0])

```

Try it online!

I/O is with tuples rather than lists.

---

**Python, 57 bytes**

```
f=lambda l,p=0:l and l[:[p]<=l[:1]>=l[1:2]]+f(l[1:],l[0])

```

Try it online!

Alt 57:

```
f=lambda l,p=0:l and l[l<[max(p,*l[:2])]:1]+f(l[1:],l[0])

```
> 8 votes

# Answer
## Mathematica 22 Bytes

```
Pick[#,MaxDetect@#,1]&

```
> 7 votes

# Answer
## Haskell, ~~50~~ ~~49~~ 42 bytes

```
f l=[j|i:j:k:_<-scanr(:)[0]$0:l,k<=j,i<=j]

```

Try it online!

`scanr(:)[0]` makes a list of the tails of `(0:l)`, each with a final `0`, e.g. for `l = [4,3,3,4]`: `[[0,4,3,3,4,0],[4,3,3,4,0],[3,3,4,0],[3,4,0],[4,0],[0]]` which is pattern matched agains `i:j:k:_` to extract all lists with at least 3 elements which are named `i`, `j`, and `k`. Keep `j` if its \>= `i` and `j`.

Edit: Ørjan Johansen saved 7 bytes. Thanks!
> 6 votes

# Answer
# Dyalog APL, ~~31~~ ~~30~~ ~~28~~ ~~22~~ 21bytes

```
{⍵/⍨(⌈/=2⌷⊢)¨3,/∊0⍵0}

```

Try it online!

Explanation (I'm not good at explaining things):

```
0⍵0       - [0,input,0]   (it looks like a face!)
∊         - flatten
3,/       - split into overlapping sections of length 3.
(⌈/=2⌷⊢)¨ - Whether the middle element is the maximum (applied to every section)
⍵/⍨       - index

```
> 4 votes

# Answer
# Haskell, 40 bytes

```
p%(h:t)=[h|h>=p,[h+1]>t]++h%t
_%e=e
(0%)

```

Try it online!
> 4 votes

# Answer
## JavaScript (ES6), 40 bytes

```
a=>a.filter((e,i)=>!(e<a[i-1]|e<a[i+1]))

```
> 3 votes

# Answer
# Python 3, ~~84 75\*~~ 71 bytes

```
lambda l,k=[0]:[j for x,j in enumerate(l)if(k+l+k)[x+2]<=j>=(k+l+k)[x]]

```

Try it online!

---

*\*@LeakyNun saved 9 bytes using a clever operator trick.*
> 3 votes

# Answer
# Jelly, 15 bytes

```
2ị⁼Ṁ
0;;0ṡ3Ç€Tị

```

Try it online!
> 2 votes

# Answer
# 05AB1E, ~~15~~  ~~14~~  13 bytes

```
ü‹0¸«sĆÁü›+_Ï

```

Try it online!

**Explanation**

```
ü‹             # pairwise comparison for less than
  0¸«          # append 0
     s         # swap input to top of stack
      Ć        # enclose, append the head of the list
       Á       # rotate right
        ü›     # pairwise comparison for greater than
          +    # add the two boolean lists
           _   # logical negate
            Ï  # keep only elements of input that are true in the resulting list

```

**Previous 15 byte solution**

```
¬s¤)˜Œ3ùεZQ1è}Ï

```

Try it online!

**Explanation**

```
¬                # get head of input
 s¤              # get tail of input
   )˜            # wrap stack in flattened list
                 # produces the input list with the first and last element duplicated
     Œ3ù         # push sublists of length 3
        ε        # apply transformation on each triple
         ZQ      # ... check each element for equality to the max
          1è     # ... get the middle element
            }    # end transform
             Ï   # keep only elements of input that are true in the resulting list

```
> 2 votes

# Answer
# R, 44 bytes

```
pryr::f(x[(x>=c(0,x)&x>=x[-1])[1:sum(x|1)]])

```

which evaluates to the function:

```
function (x)
x[(x >= c(0, x) & x >= x[-1])[1:sum(x | 1)]]

```

Compares `x` to `c(0,x)`, so with `x` shifted one position to the right. Also compares `x` to `x[-1]`, so one position shifted to the left. These both are `TRUE` if there is a maximum there. `&` to take the AND of these booleans. Because of the wrapping nature of R's vectors when they are not the same length, we have to truncate the result at the length of `x`, which is found by taking `sum(x|1)`. We then plug in the boolean vector, taking only the true indices of `x` and return that.

Note, because these logical operations are done with unequal length vectors, R will complain. A lot. But the correct output will be there amidst the warnings:

```
> pryr::f(x[(x>=c(0,x)&x>=x[-1])[1:sum(x|1)]])(c(4,2,6,12,4,5,4,3))
[1]  4 12  5
Warning messages:
1: In x >= c(0, x) :
  longer object length is not a multiple of shorter object length
2: In x >= x[-1] :
  longer object length is not a multiple of shorter object length
3: In x >= c(0, x) & x >= x[-1] :
  longer object length is not a multiple of shorter object length

```
> 2 votes

# Answer
# , 42 bytes

```
function(x)x[c(d<-diff(x),0)<=0&c(0,d)>=0]

```

Try it online!

2 bytes shorter than JAD's solution. `diff` computes successive differences; then keep only the entries greater than both neighbours.
> 2 votes

# Answer
# Pyth, 20 bytes

```
-.b*YqYeSN.:++0Q03Q0

```

To be golfed...

Test suite.
> 1 votes

# Answer
# , 68 bytes

```
function(a)a[a==sapply(1:length(a),function(i)max(c(0,a,0)[i+0:2]))]

```

Try it online!
> 1 votes

# Answer
# PHP, 67 bytes

```
for(;$g=$argv[+$i];$l=$g)$g<$l|$g<$argv[++$i]?:$r[]=$g;print_r($r);

```

Try it online!
> 1 votes

# Answer
# Retina, 51 bytes

```
\d+
$*
^

M!`(?<=(^|1+) )(\1\d*)\b(?! 1\2)
^¶

%`1

```

**Try it online**
> 1 votes

# Answer
# q, 39 bytes

```
{x where x = -1 _ next 3 mmax x,last x}

```
> 1 votes

# Answer
# Stax, 10 bytes

```
úâH◄(☼bM•Å

```

Run and debug it

It produces output as newline separated values on standard output.

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

```
f       filter each value in input using the rest of the program; implicitly printing kept values
  x0|S  input pre- and post-pended with zero
  3B    split into batches of 3
  i@    get the i-th batch, where i is the iteration index
  |M=   is the current value equal to the max from the batch?

```

Run this one

**Updated:** Just found a 9-byte solution. Will update explanation later:

# Stax, 9 bytes

```
▀▓ûa¥╓╧↨⌐

```

Run and debug it
> 1 votes

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

```
map{$_>=$F[++$i]&$_>=$p&&say;$p=$_}@F

```

Try it online!
> 1 votes

---
Tags: code-golf, array
---


title: Self-displaying image

text:
# Question
Title: Self-displaying image
**Background**

There are self-extracting `.ZIP` files. Typically they have the extension `.EXE` (and by executing the file they will be extracted) but when renaming them to `.ZIP`, you can open the file with some ZIP extracting software.

(This is possible because `.EXE` files require a certain header but `.ZIP` files require a certain trailer so it is possible to build a file that both has an `.EXE` header and a `.ZIP` trailer.)

**Your task:**

Create a program that creates "self-displaying" image files:

* The program shall take some 64x64 image (at least 4 colors shall be supported) as input and some "combined" file as output
* The output file of the program shall be recognized as image file by common image viewers
* When opening the output file with the image viewer, the input image shall be displayed
* The output file shall also be recognized as executable file for any operating system or computer type

(If a file for an uncommon operating system or computer is produced, it would be nice if an open-source PC emulator exists. However, this is not required.)
* When executing the output file, the input image shall also be displayed
* It is probable that renaming the file (for example from `.PNG` to `.COM`) is necessary
* It is not required that the program and it's output file run on the same OS; the program may for example be a Windows program and output files that can be executed on a Commodore C64.

**Winning criterion**

* The program that produces the **smallest output file** wins
* If the size of the output file differs depending on the input image (for example because the program compresses the image), the the **largest possible** output file created by the program representing a 64x64 image with up to 4 colors counts

**By the way**

I had the idea for the following programming puzzle when reading this question on StackOverflow.

# Answer
> 5 votes
# 8086 MS-DOS .COM file / BMP, output file size = 2192 bytes

## Encoder

The encoder is written in C. It takes two arguments: Input file and output file. The input file is a 64x64 RAW RGB image (meaning it is simply 4096 RGB triplets). Number of colours is limited to 4, so that the palette can be as short as possible. It is very straight-forward in its doings; it merely builds a palette, packs pixels pairs into bytes and glues it together with pre-made headers and the decoder program.

```
#include <stdio.h>
#include <stdlib.h>

#define MAXPAL      4
#define IMAGESIZE   64 * 64

int main(int argc, char **argv)
{
    FILE *fin, *fout;
    unsigned char *imgdata = malloc(IMAGESIZE * 3), *outdata = calloc(IMAGESIZE / 2, 1);
    unsigned palette[MAXPAL] = {0};
    int pal_size = 0;

    if (!(fin = fopen(argv[1], "rb")))
    {
        fprintf(stderr, "Could not open \"%s\".\n", argv[1]);
        exit(1);
    }

    if (!(fout = fopen(argv[2], "wb")))
    {
        fprintf(stderr, "Could not open \"%s\".\n", argv[2]);
        exit(2);
    }

    fread(imgdata, 1, IMAGESIZE * 3, fin);

    for (int i = 0; i < IMAGESIZE; i++)
    {
        // BMP saves the palette in BGR order
        unsigned col = (imgdata[i * 3] << 16) | (imgdata[i * 3 + 1] << 8) | (imgdata[i * 3 + 2]), palindex;
        int is_in_pal = 0;

        for (int j = 0; j < pal_size; j++)
        {
            if (palette[j] == col)
            {
                palindex = j;
                is_in_pal = 1;
            }
        }

        if (!is_in_pal)
        {
            if (pal_size == MAXPAL)
            {
                fprintf(stderr, "Too many unique colours in input image.\n");
                exit(3);
            }

            palindex = pal_size;
            palette[pal_size++] = col;
        }

        // High nibble is left-most pixel of the pair
        outdata[i / 2] |= (palindex << !(i & 1) * 4);
    }

    char BITMAPFILEHEADER[14] = {
        0x42, 0x4D,                 // "BM" magic marker
        0x90, 0x08, 0x00, 0x00,     // FileSize
        0x00, 0x00,                 // Reserved1
        0x00, 0x00,                 // Reserved2
        0x90, 0x00, 0x00, 0x00      // ImageOffset
    };

    char BITMAPINFOHEADER[40] = {
        0x28, 0x00, 0x00, 0x00,     // StructSize
        0x40, 0x00, 0x00, 0x00,     // ImageWidth
        0x40, 0x00, 0x00, 0x00,     // ImageHeight
        0x01, 0x00,                 // Planes
        0x04, 0x00,                 // BitsPerPixel
        0x00, 0x00, 0x00, 0x00,     // CompressionType (0 = none)
        0x00, 0x00, 0x00, 0x00,     // RawImagDataSize (0 is fine for non-compressed,)
        0x00, 0x00, 0x00, 0x90,     // HorizontalRes
                                    //      db 0, 0, 0
                                    //      nop
        0xEB, 0x1A, 0x90, 0x90,     // VerticalRes
                                    //      jmp Decoder
                                    //      nop
                                    //      nop
        0x04, 0x00, 0x00, 0x00,     // NumPaletteColours
        0x00, 0x00, 0x00, 0x00,     // NumImportantColours (0 = all)
    };

    char DECODER[74] = {
        0xB8, 0x13, 0x00, 0xCD, 0x10, 0xBA, 0x00, 0xA0, 0x8E, 0xC2, 0xBA,
        0xC8, 0x03, 0x31, 0xC0, 0xEE, 0x42, 0xBE, 0x38, 0x01, 0xB1, 0x04,
        0xFD, 0x51, 0xB1, 0x03, 0xAC, 0xD0, 0xE8, 0xD0, 0xE8, 0xEE, 0xE2,
        0xF8, 0x83, 0xC6, 0x07, 0x59, 0xE2, 0xEF, 0xFC, 0xB9, 0x00, 0x08,
        0xBE, 0x90, 0x01, 0xBF, 0xC0, 0x4E, 0xAC, 0xD4, 0x10, 0x86, 0xC4,
        0xAB, 0xF7, 0xC7, 0x3F, 0x00, 0x75, 0x04, 0x81, 0xEF, 0x80, 0x01,
        0xE2, 0xEE, 0x31, 0xC0, 0xCD, 0x16, 0xCD, 0x20,
    };

    fwrite(BITMAPFILEHEADER, 1, 14, fout);
    fwrite(BITMAPINFOHEADER, 1, 40, fout);
    fwrite(palette, 4, 4, fout);
    fwrite(DECODER, 1, 74, fout);

    // BMPs are stored upside-down, because why not
    for (int i = 64; i--; )
        fwrite(outdata + i * 32, 1, 32, fout);

    fclose(fin);
    fclose(fout);
    return 0;
}

```

## Output file

The output file is a BMP file which can be renamed .COM and run in a DOS environment. Upon execution, it will change to video mode 13h and display the image.

A BMP file has a first header BITMAPFILEHEADER, which contains among other things the field ImageOffset, which denotes where in the file the image data begins. After this comes BITMAPINFOHEADER with various de-/encoding information, followed by a palette, if one is used. ImageOffset can have a value that points beyond the end of any headers, allowing us to make a gap for the decoder to reside in. Roughly:

```
BITMAPFILEHEADER
BITMAPINFOHEADER
PALETTE
<gap>
IMAGE DATA

```

Another problem is to enter the decoder. BITMAPFILEHEADER and BITMAPINFOHEADER can be tinkered with to make sure they are legal machine code (which does not produce a non-recoverable state), but the palette is trickier. We could of course have made the palette artificially longer, and put the machine code there, but I opted to instead use the fields biXPelsPerMeter and biYPelsPerMeter, the former to make the code aligned properly, and the latter to jump into the decoder. These fields will of course then have garbage in them, but any image viewer I have tested with displays the image fine. Printing it might produce peculiar results, though.

It is, as far as I know, standard-compliant.

One could make a shorter file if the `JMP` instruction was put in one of the reserved fields in BITMAPFILEHEADER. This would allow us to store the image height as -64 instead of 64, which in the magical wonderland of BMP files means that the image data is stored the right way up, which in turn would allow for a simplified decoder.

## Decoder

No particular tricks in the decoder. The palette is populated by the encoder, and shown here with dummy-values. It could be slightly shorter if it did not return to DOS upon a keypress, but it was not fun testing without that. If you feel you must, you can replace the last three instructions with `jmp $` to save a few bytes. (Don't forget to update the file headers if you do!)

BMP stores palettes as BGR (*not* RGB) triplets, padded with zeroes. This makes setting up the VGA palette more annoying than usual. The fact that BMPs are stored upside-down only adds to the flavour (and size).

Listed here in NASM style:

```
Palette:
    db 0, 0, 0, 0
    db 0, 0, 0, 0
    db 0, 0, 0, 0
    db 0, 0, 0, 0

Decoder:
    ; Set screen mode
    mov ax, 0x13
    int 0x10

    mov dx, 0xa000
    mov es, dx

    ; Prepare to set palette
    mov dx, 0x3c8
    xor ax, ax
    out dx, al

    inc dx
    mov si, Palette + 2
    mov cl, 4
    std
pal_loop:
    push cx
    mov cl, 3
pal_inner:
    lodsb
    shr al, 1
    shr al, 1
    out dx, al
    loop pal_inner

    add si, 7
    pop cx
    loop pal_loop
    cld

    ; Copy image data to video memory
    mov cx, 64 * 64 / 2
    mov si, ImageData
    mov di, 20160
img_loop:
    lodsb
    aam 16
    xchg al, ah
    stosw
    test di, 63
    jnz skip
    sub di, 384
skip:
    loop img_loop

    ; Eat a keypress
    xor ax, ax
    int 0x16

    ; Return to DOS
    int 0x20

ImageData:

```

---
Tags: code-challenge, graphical-output, metagolf, compiler
---


title: Manhattan Directions Code Golf

text:
# Question
Title: Manhattan Directions Code Golf
This code golf challenge is to show directions through numbers.

When the user enters a number, then that means a direction change as follows:

```
0 means stay still
1 means forward (initially from left to right and initially start with `:`)
2 means turn right
3 means turn left
4 means go backward

```

I will show you an example: `122123333114`

`1` means 1 step forward

```
:═>

```

`2` means 1 step to the right

```
   :═╗
     ‖
     V

```

`2` means 1 step to the right

```
    :═╗
      ‖
    <═╝

```

`1` means 1 step forward

```
    :═╗
      ‖
   <══╝

```

`2` means 1 step to the right

```
   ^:═╗
   ‖  ‖
   ╚══╝

```

`3` means 1 step to the left

```
 <═╗:═╗
   ‖  ‖
   ╚══╝

```

`3` means 1 step to the left

```
 ╔═╗:═╗
 ‖ ‖  ‖
 V ╚══╝

```

`3` means 1 step to the left

```
 ╔═╗:═╗
 ‖ ‖  ‖
 ╚═>══╝

```

`3` means 1 step to the left

```
 ╔═^:═╗
 ‖ ‖  ‖
 ╚═╝══╝

```

`1` means 1 step forward

```
   ^
 ╔═‖:═╗
 ‖ ‖  ‖
 ╚═╝══╝

```

`1` means 1 step forward

```
   ^
   ‖
 ╔═‖:═╗
 ‖ ‖  ‖
 ╚═╝══╝

```

`4` means 1 step backward

```
   ‖
 ╔═V:═╗
 ‖ ‖  ‖
 ╚═╝══╝

```

**These are the rules:**

* Start with `:` and the initial direction will be from left to right

If starting with `0`, then start with:

```
:

```

If starting with `1`, then start with:

```
:=>

```

If starting with `2` then start with:

```
:╗
 ‖
 V

```

If starting with `3`, then start with:

```
 ^
 ‖
:╝

```

If starting with `4`, then start with:

```
<=:

```
* Any other numbers or letters in the input will be ignored

`T6@1 92J;{4` will mean `124`

* If two arrows came on top of each other, the new arrow should overwrite the old one

An example of this:

```
 ╔═╗:═╗
 ‖ ‖  ‖
 V ╚══╝

```

`3` means 1 step to the left

```
 ╔═╗:═╗
 ‖ ‖  ‖
 ╚═>══╝

```
* Arrow head should be `>` for left to right direction
* Arrow head should be `<` for right to left direction
* Arrow head should be `V` for top to bottom direction
* Arrow head should be `^` for bottom to top direction

Do not forget the joint if you turn.

```
:╗
 ‖
 V

  :
<═╝

^
‖
╚:

╔═>
:

```

I hope I did not miss anything.
If you have any questions or if I missed anything, I will be editing this post.

# Answer
> 2 votes
# 05AB1E, ~~78~~ 73 bytes

```
4LÃ3ÝÐ<T**‡D₁Í«S4Ê>ćVs.¥Ì8%•2ß1Í'£Jθ•14вsxs¦©;+èŽb[+ç':š"^>V<"®;θèª®₂YèšΛ

```

Try it online!

Explanation:

```
# The canvas built-in takes 3 arguments: lengths, strings to draw, and angles.
# First, we map the input to a list of angles, coded as multiples of 45°:
# Forward = 0, right = 2, U-turn = 4, left = 6.
# Conveniently, 4 already means U-turn in the input format.
# Since each turn is implicitly followed by a step in the new direction,
# we actually want to map 2 to [2, 0] and 3 to [6, 0].
4L                    # range 1..4
  Ã                   # remove everything else from the input
   3Ý                 # range 1..3
     Ð                # triplicate
      <  *            # multiply one copy by the other -1
       T*             # multiply by 10
                      # stack is now [filtered input, [1, 2, 3], [0, 20, 60]]
          ‡           # transliterate: 1 => 0, 2 => 20, 3 => 60

# Now we compute the lengths. 05AB1E's canvas is a bit finnicky: to get the
# desired output, we need to use length 2 for each character, except right
# before U-turns and at the end, where we want length 1.
D                     # copy the list of angles
 ₁Í«                  # append 254
    S4Ê               # != 4 over each digit
       >              # increment each
        ćV            # remove the first element, save it in Y
          s           # swap so the list of angles is at the top again

# Cconvert relative angls to absolute angles.
# 05AB1E's 0 is up, but the default direction is right, so we start at 2.
.¥                    # undelta (eg [6, 0, 4] => [0, 6, 6, 10])
  Ì                   # add 2 to each
   8%                 # modulo 8

# Now, we find the character to print at each step using a lookup table.
# For each pair of directions, we compute the index = first / 2 + second * 2.
# This maps each pair to a unique integer in 0..15.
•2ß1Í'£Jθ•14в         # compressed list: [1,4,1,7,13,0,7,0,1,10,1,13,10,0,4,0]
s                     # swap
 x                    # * 2 without popping
  s                   # swap (yes we're doing that a lot...)
   ¦                  # remove the first element
    ©                 # save in variable `r` without popping
     ;                # / 2
      +               # sum
       è              # index into the lookup table
        Žb[+          # add 9552
            ç         # map codepoints to characters
':š                   # prepend a ":"
         ®;θ          # half of the last angle
   "^>V<"   è         # nth character of "^>V<"
             ª        # append

# If the first command is 4, the initial angle should be 6, otherwise 2.
®                    # push list of angles
 ₂Yè                 # Yth digit of 26 (we set Y earlier, remember)
    š                # prepend

# Finally, call the canvas built-in:
Λ

```

# Answer
> 3 votes
# Ruby, ~~302~~ ~~306~~ ~~322~~ 327 bytes

* +4 bytes to fix the edge case with the \\$-i\\$ direction (its angle is negative so we need to mod 4)
* +16 bytes for even more edge case fixes in the stepping algorithm...
* +5 bytes to fix the edge case where no inputs from 1-4 are present.

```
P=Math::PI/2
b=0i;f=d=p
c={b=>?:}
gsub(/[1-4]/){x=$&.to_i;d||=1
c[b+=d]="╗╝╚╔╗"[d.arg/P%4+x%2]if x[1]>0
d*=[0,1,1i,-1i,-1][x]
c[b+=d]="═║"[d.imag.abs]if x<4||!f
f=1}
c[b+=d]=">V<^"[d.arg/P]if d
q=c.keys.map &:rect
q=q.pop.zip *q
i,j=q[0].minmax
k,l=q[1].minmax
puts (k..l).map{|y|(i..j).map{|x|c[x+y*1i]||' '}*''}

```

Try it online!

### Explanation

We initiate the grid as a hash table where the keys are complex numbers (real is the X-axis, imaginary is the Y-axis, lower numbers are closer to the top-left corner). This is convenient because we can initialize the direction variable as \\$1\\$, multiply by \\$i\\$ to turn right, and multiply by \\$-i\\$ to turn left. Also, we can quickly determine which way we're facing by dividing the direction's angle by \\$\pi/2\\$ and use that in our lookup tables.

Our algorithm, then, is roughly as follows:

1. Get the next number from the input in the range 1-4.
2. If the number is 2-3, step once and add the correct corner piece.
3. Look up the corresponding direction change and multiply.
4. Step once and add the correct straight piece. (Don't need to step if we turn around.)
5. Repeat until done.
6. Step and add the arrow piece.
7. Print the grid.

**Code explanation (out of date, will fix later)**

```
P=Math::PI/2                            # Save PI/2
b=0i;d=1                                # Set initial coordinates and direction
c={b=>?:}                               # Create grid with starting `:`
gsub(/[1-4]/){x=$&.to_i                 # For each number 1-4
c[b+=d]="╗╝╚╔╗"[d.arg/P+x%2]if x[1]>0   # If 2-3 (second bit is a 1), step and write the corner piece
                                        # If turning left (3), +1 to the index
d*=[0,1,1i,-1i,-1][x]                   # Multiply direction to turn accordingly
c[b+=d]="═‖"[d.imag.abs]                # Step and write the straight piece
}                                       # (end the loop)
c[b]=">V<^"[d.arg/P]                    # Write the corresponding arrow piece
q=c.keys.map &:rect                     # Get the filled-in grid spaces as X,Y coordinates
i,*_,j=q.map(&:first).sort              # Find the min and max X coordinate
k,*_,l=q.map(&:last).sort               # Find the min and max Y coordinate
puts (k..l).map{|y|                     # For each Y coordinate in range
      (i..j).map{|x|                    # For each X coordinate in range
                    c[x+y*1i]||' '      # Get the character, or space if not present
                }*''                    # Join characters on that Y coordinate and print
        }

```

# Answer
> 2 votes
# 05AB1E, ~~129~~ ~~126~~ ~~120~~ 118 bytes

```
Žb_3Ý3*+ΣŽBÙNè}U4LÃ23SD1«‡©D4Å?Vε¾ˆ3%iŽb[D>‚¾èy≠i¼¼}ëy<iX¾è¼ëXÀ¾è.¼]¾ˆç':š®õQi`ë">V<^"¾èªDgÅ2¯¥2Q1Ý«-ćY+šsŽ9¦¯èYi¦6š}Λ

```

Sigh.. what a mess. Almost don't want to post it, but took too much time to not post it now. The challenge has quite a bit of edge cases I wasn't expecting when I started with it.. Can definitely be golfed (by a lot), though.

-3 bytes thanks to *@Grimy*.
-2 bytes by using  (unicode value 9553) instead of  (unicode value 8214). If this is not allowed, 2 bytes has to be added again.

Try it online. (No test suite for all test cases at once, because there is no way to reset the Canvas, so outputs would overlap..)

**Explanation:**

```
Žb_              # Push the compressed integer 9556
   3Ý            # Push the list [0,1,2,3]
     3*          # Multiplied by 3: [0,3,6,9]
       +         # Added to the integer: [9556,9559,9562,9565]
        Σ     }  # Sort it:
         ŽBÙNè   #  Based on the order in the compressed integer 3021
                 # (so it's now in the order [9559,9565,9562,9556] ("╗╝╚╔"))
               U # Then pop and store it in variable `X`
4L               # Push a list [1,2,3,4]
  Ã              # And only keep those digits from the (implicit) input-string
   23S           # Push [2,3]
      D1«        # Duplicate it, and append a 1 to each: [21,31]
         ‡       # Replace all "2" with "21" and all "3" with "31"
©                # Store the string in variable `r` (without popping) to use later on
D4Å?             # Check if it starts with a 4 (without popping by duplicating first)
    V            # Pop and store it in variable `Y` to use later on
ε                # Map over each digit:
 ¾ˆ              #  Add counter `c` to the global array
                 #  (counter `c` is 0 by default)
 3%i             #  If the current digit is a 1 or 4:
    Žb[          #   Push compressed integer 9552
       D>‚       #   Pair it with it's increment: [9552,9553] ("═║")
          ¾è     #   And index the counter `c` into it
    y≠i  }       #   If the current digit is NOT 1 (so it's a 4):
       ¼¼        #    Increase counter `c` twice to reverse the direction
 ëy<i            #  Else-if the current digit is a 2:
     X¾è         #   Index the counter `c` into the list of variable `X`
     ¼           #   And increase the counter `c` by 1
 ë               #  Else (the current digit is a 3):
  X              #   Push the list of variable `X`
   À             #   Rotated it once toward the left: [9565,9562,9556,9559] ("╝╚╔╗")
    ¾è           #   Index the counter `c` into it again
  .¼             #   And decrease counter `c` by 1
]                # Close all if-else statements and the map
 ¾ˆ              # And also add the current counter `c` to the global array after the map
   ç             # Now convert all integers to ASCII characters with these unicode values
    ':š         '# Prepend a ":" to this list
®õQi             # If the input we saved in variable `r` was empty:
    `            #  Push (and implicitly output) this single ":" as result
ë                # Else:
 ">V<^"¾è        #  Index the counter `c` in the string ">V<^"
         ª       #  And append it to the list
 Dg              #  Get the length of the list (without popping by duplicating first)
   Å2            #  Create a list with that many 2s
     ¯¥          #  Push the deltas/forward differences of the global array
       2Q        #  Check if a delta is equal to 2 (which means we reversed direction)
                 #  (1 if truthy; 0 if falsey)
         1Ý«     #  Append a trailing [0,1]
            -    #  Subtract them from the list of 2s
  Y              #  If the input started with a 4:
 ć +š            #   Increase the very first integer by 1 (from 1 to a 2)
 s               #  Swap this integer list for the lengths and string list on the stack
 Ž9¦             #  Push compressed integer 2460
    ¯è           #  Index each value of the global array into it
      Yi   }     #  If the input started with a 4:
        ¦6š      #   Replace the first integer with a 6
 Λ               # Use the Canvas builtin (which is output immediately implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Žb_` is `9556`; `ŽBÙ` is `3021`; `Žb[` is `9552`; and `Ž9¦` is `2460`.

As for a brief explanation of the Canvas builtin `Λ` and its three arguments:

**First argument: length(s):** the sizes of the lines we want to draw. Since we have to keep in mind overlapping, we use size `2` for every character, except if we reverse the direction and we want to overlap or for the final character (one of `>V<^`), for which we'll use size `1` instead.
**Second argument: string(s):** the characters we want to display. Which are the characters in this case, with the prepended `:`, and if the input wasn't empty/`0` the appended appended final character (one of `>V<^`).
**Third argument: direction(s):** the directions these character-lines of the given length should be drawn in. In general we have the directions `[0,7]` which map to these directions:

```
7   0   1
  ↖ ↑ ↗
6 ← X → 2
  ↙ ↓ ↘
5   4   3

```

Which is why we have the integer `2460` for the directions \\$\[→,↓,←,↑\]\\$ respectively.

See this 05AB1E tip of mine for a more detailed explanation about the Canvas builtin `Λ`.

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


title: Simulate a game of Craps

text:
# Question
Title: Simulate a game of Craps
Craps is a fairly simple dice game often played in casinos. Even if you aren't a gambler (which I'm not), it's still a fairly interesting game. Here's the rules:

At the start of a game of Craps there's what is called the *come-out* round. The player rolls two d6s (six-sided die) and the two die rolls are added. If the result is 7 or 11, the person automatically wins (this is known as a *natural*). If the result is 2, 3 or 12 the person automatically loses (this is known as *crapping out*). Otherwise, the result is set as the *point* for the point round.

After this, the *point* round begins. During the point round, the player must continuously roll 2 d6s until the person rolls a 7 or his/her point from the previous round. If the person rolls a 7, they lose. If they roll their point, they win.

# Challenge

Implement a simple program that simulates a game of craps. If the person rolls a natural or a crap-out during the come-out round, the program should output "Natural: " or "Crapping out: " followed by the die-roll and then exit. Otherwise, it should output "Point: " followed by the point. Then, during the point round, it should output every die-roll until a 7 or the point is reached. If the person wins, it should output `"Pass"`; if they lose it should output `"Don't Pass"`.

# Reference Implementation

Groovy, 277 bytes

```
def a={return Math.random()*6+1};int b=a()+a();(b<4||b==12)?{println"Crapping out: "+b}():{(b==7||b==11)?{println"Natural: "+b}():{println"Point: "+b;for(;;){int x=a()+a();println x;(x==7)?{println"Don't Pass";System.exit(0)}():{if(x==b){println"Pass";System.exit(0)}}()}}()}()

```

Try it online.

# Sample outputs

`Natural: 7`

`Crapping out: 3`

```
Point: 9
4
8
11
9
Pass

```

and

```
Point: 5
3
7
Don't Pass

```

This is , so shortest code wins.

(DISCLAIMER: This challenge is not intended to promote gambling in any way. Remember, the house always wins.)

# Answer
# Ruby 164

Pretty straightforward. Interesting features:

The crapping out cases are summarised as `r%12<4` and the remaining natural cases are summarised as `r%4==3`.

The initial string is stored in `c` and further rolls are taken only if this is later alphabetically than the single letter `?P` (which only occurs for `Point`.)

```
f=->{rand(6)+rand(6)+2}
s=0
r=f[]
print c=r%12<4?'Crapping out':r%4==3?'Natural':'Point',": #{r}
"
c>?P&&(until s==r||s==7
p s=f[]end
print s==7?"Don't ":"","Pass")

```
> 6 votes

# Answer
# Python 3, 190 bytes

```
from random import*
r=randrange
p=print
a=r(5)+r(5)+2
c=890145//3**a%3
p(['Point:','Crapping out:','Natural:'][c],a)
if c<1:
 while 7!=c!=a:c=r(5)+r(5)+2;p(c)
 p(['Pass',"Don't pass"][c==7])

```

This is based on Celeo's answer; I replaced some lengthy conditionals with a magic number that encodes a LUT for each number, reused a variable, and did a few other miscellaneous golfs. Still room to golf; it's probably possible to get under 170.

I didn't try to use Python 2, so I don't know if it would be shorter.
> 5 votes

# Answer
# Python 2, ~~226~~ 224 bytes

First pass and there's a lot of code there:

```
from random import*
r=randrange
a=r(5)+r(5)+2
if a in[7,11]:print'Natural:',a
elif a in[2,3,12]:print'Crapping out:',a
else:
 print'Point:',a
 b=0
 while b not in[7,a]:b=r(5)+r(5)+2;print b
 print'Pass'if b-7else"Don't pass"

```

Thanks to Mego for 2 bytes!
> 4 votes

# Answer
## C99, ~~366~~ ~~312~~ ~~293~~ 277 bytes

This is my first post here, so I'm going to guess that this can be improved by a lot.

```
#include<stdlib.h>
#include<time.h>
#define r rand()%6+1
#define p printf(
main(c,s){srand(time(0));s=r+r;int*a=s==7||s==11?"Natural:%d":2-s||3-s||12-s?0:"Crapping out:%d";if(a){p a,s);return 0;}p"Point:%d\n",c=s);do p"%d\n",s=r+r);while(7-s&&s-c);p(7-s)?"Pass":"Don't pass");}

```

### Expanded Version

```
#include<stdlib.h>
#include<time.h>
#define r rand()%6+1
#define p printf(
main(c,s){
    srand(time(0));
    s=r+r;
    int*a=s==7||s==11?"Natural:%d":2-s||3-s||12-s?0:"Crapping out:%d";
    if(a) {p a,s);return 0;}
    p"Point:%d\n",c=s);
    do p"%d\n",s=r+r);
    while(7-s&&s-c);
    p(7-s)?"Pass":"Don't pass");
}

```

As you can see, there's a good amount of redundancy here that can most likely be done away with.

Credits to @Mego for helping to make this smaller.
> 4 votes

# Answer
# PHP ~~230~~ ~~228~~ ~~218~~ ~~199~~ ~~192~~ 188 Bytes

186 bytes without the `<?`

```
<?$a=rand(1,6)+rand(1,6);$a%4==3?die("Natural: $a"):$a%12<4?die("Crapping out: $a"):print"Point: $a
";while(1){($b=rand(1,6)+rand(1,6))==7?die("Don't Pass"):$b==$a?die("Pass"):print"$b
";}

```

First attempt at code golf! Not sure if using `</br>` would be allowed though? As this would not work in a console (as a new line). Let me know if this is not allowed and will alter my code.

EDIT (16-8-16): After getting better at codegolf I noticed some possible improvements. This still works using the command line interface. Replaced `</br>` with an hard enter.
> 3 votes

# Answer
# Javascript 262

```
var r=(x=>Math.floor(Math.random()*6+1)),a=r()+r();if(a<4||a==12){alert("Crapping out: "+a)}else if(a==7||a==11){alert("Natural: "+a)}else{alert("Point: "+a);while(1){var b = r()+r();if(b==a){alert("pass");break}if(b==7){alert("dont't pass");break}alert(""+b)}}

```
> 2 votes

# Answer
# PowerShell, ~~181~~ ~~183~~ ~~179~~ ~~178~~ ~~167~~ 165 bytes

-10 bytes thanks to mazzy
-2 bytes thanks to Xcali

```
switch -r($z=&($x={(random 6)+(random 6)+2})){'7|11'{"Natural: $z"}'2|3'{"Crapping out: $z"}default{"Point: $z"
do{($m=&$x)}until($m-in7,$z)"Don't "*!($m-7)+'Pass'}}

```

Try it online!

Unrolled version:

```
#Switch using regex on $z which is...
#&($x={...}) first assigns $x to a scriptblock then calls it, saving the return to $z
switch -r($z=&($x={(random 6)+(random 6)+2})){
    '7|11' {"Natural: $z"}
    '2|3' {"Crapping out: $z"}
    default{
        "Point: $z"

        #Call the diceroll scriptblock until you Pass,
        #while pushing each roll to output
        do{($m=&$x)}
        until($m-in7,$z)
        "Don't "*!($m-7)+'Pass'
    }
}

```

There's a few less sticking points now that the list-building logic has been rebuilt into a switch. I think it's still a pretty alright approach. +2 bytes fixing a bug.
> 1 votes

# Answer
# Perl 5, 140 bytes

```
sub d{1+int rand 6}say$"=($p=&d+&d)%12<4?"Crapping out":$p%4-3?Point:Natural,": $p";if($"gt O){say$_=&d+&d until/7|$p/;say"Don't "x/7/,Pass}

```

Try it online!
> 1 votes

# Answer
# R, 197 bytes

```
 r=sum(sample(6,2,T));if(r%%12<4)cat("Crap Out",r)else if(r%%4==3)cat("Natural",r)else{cat("Point",r);while(T){cat("",q<-sum(sample(6,2,T)));if(q==7){cat(" Don't");break};if(q>r)break};cat(" Pass")}

```

Ungolfed

```
r=sum(sample(6,2,T))
if (r%%12<4)  {
    cat("Crap Out",r)
} else if (r%%4==3) {
    cat("Natural",r)
} else {
    cat("Point",r)
    while (T) {
        q = sum(sample(6,2,T))
        cat("",q)
        if (q==7) {
            cat(" Don't")
            break
        }
        if (q>r) break
    }
    cat(" Pass")
}

```
> 0 votes

# Answer
# Pyth, 108 bytes

```
p|K?}J+OS6OS6,7 11"Natural"?}J[2 3 12)"Crapping out"k"Point"+": "JI!KW!}Z,7JIq7=Z
+OS6OS6=K"Don't "))+K"Pass

```

Try it online!

First pass, can probably find a few savings.
> 0 votes

# Answer
# Runic Enchantments, 151 bytes

```
R}}6'RA6'RA2++{{B͍
00B:7=S:b={+?\"Natural: "@>
pping out: "@\:2=}:3=}:c={{++?/"Cra
{:}≠   ?\ 6?;$$k\/ak$00B:$:7≠?\
"Don't "R"Pass"a/\$:$" :tnioP"\

```

Try it online!

After fixing a bug regarding random numbers (it was re-seeding every time `'RA` was called, and the seed was system time, resulting in massive runs of repeated values) this works correctly.

### Explanation

Entry is on the second line, as the first line up until  is a function for rolling two dice and summing them.

Program flow, with some edge-wrapping and curled redirections unrolled for readability

```
   R}}6'RA6'RA2++{{B͍                      Roll 2, sum, return
   >00B:7=S:b={+?\                        Entry, make first roll, compare to 7 and 11.
                  "Natural: "@            If true, print "Natural: " and the value, else go down
                 \:2=}:3=}:c={{++?/       Compare to 2, 3, and 12.
"Crapping out: "@                         If true, print "Crapping out: " and the value, else go up
                     \$:$" :tnioP"\       Print "Point: " and value (IP is travelling RTL)
                     /ak$00B:$            Print newline, roll, print
:7≠?\                                     Compare to 7
    \"Don't "R"Pass"ak$$;                 If equal, print a newline and "Don't Pass"
     {:}≠   ?\                            Else compare to initial roll.
             R"Pass"ak$$;                 If equal, print a newline and "Pass"
              6?......ak$00B              Else return to roll loop by printing a newline
                                              and rolling again (. are skipped instructions)

```

There are only 4 NOP instructions (`{:}≠...?\.6?`) that would be very difficult to remove due to the space required on other lines (Namely the length of the `"Don't "` string).
> 0 votes

---
Tags: code-golf, game, random
---


title: Inverse function

text:
# Question
Title: Inverse function
Wouldn't it be neat if programming functions could be inverted, just like the mathematical function they implement?

Write a function (or program) that takes one input `x` in any form, that outputs `ln(x)`.
When the bytes of the program are reordered/reversed so that the first byte now is the last byte, it should take one input `x` in any form and output `e^x` instead.

* Your answer must have at least 3 correct significant figures.
* Approximations are fine, as long as they have at least 3 correct significant figures.
* Your code must be in the same programming language both forwards and backwards.

Let's say this program implements `ln(x)`:

```
abc你好

```

Then this program has to implement `e^x`:

```
\xBD\xA5\xE5\xA0\xBD\xE4cba

```

Gold star if you use a language without float support.

This is a weird form of code-golf, so the shortest program wins.

# Answer
## Haskell, 11 bytes

```
f=log
pxe=f

```

and in reverse order:

```
f=exp
gol=f

```

This works without the "comment" trick. Instead each version defines an additional, but unused function (`pxe`/ `gol`).
> 75 votes

# Answer
# APL, 3 bytes

```
*⊣⍟

```

This is a function train. Monadic `*` returns `e^x`, monadic  returns `ln(x)`.  is a dyadic function that returns its left argument. Thus, `*⊣⍟` is equivalent to just `*`, and the reverse `⍟⊣*` is equivalent to just .
> 42 votes

# Answer
## Jelly, ~~5~~ 4 bytes

Yay, my first Jelly answer. :) Input is via command-line argument.

Jelly has its own code page so each character is one byte.

```
eÆÆl

```

Try it online!

Reversed:

```
lÆÆe

```

Try it online!

### Explanation

The `Æ` on its own is an unrecognised token, so it acts the same as a linefeed. That means in either case the main link is only `Æl` or `Æe` which is the 2-character built-in for `exp()` or `ln()` and is by default performed on the first command-line argument.
> 22 votes

# Answer
## Javascript, 18 bytes

```
Math.log//pxe.htaM

```
> 9 votes

# Answer
## Seriously, 5 bytes

```
,_.e,

```

Input, ln, output, then exp on an empty stack (does nothing), and input (does nothing since input is exhausted). Try it online!

Reversed:

```
,e._,

```

Try it online!
> 7 votes

# Answer
# Mathematica, 19 bytes

```
1&#@pxE+0&0+Log@#&1

```

Reversed:

```
1&#@goL+0&0+Exp@#&1

```

This was interesting to golf! Mathematica has *no* line comments / implicit string endings, so I couldn't take the simple route. Instead, I used the fact that `0 + x == x`, `0 x == 0`, and that `1 x == x`, no matter what `x` is! Testing:

```
In[1]:= (1&#@pxE+0&0+Log@#&1)[x]

Out[1]= Log[x]

In[2]:= (1&#@goL+0&0+Exp@#&1)[x]

         x
Out[2]= E

```
> 6 votes

# Answer
# Julia, 7 bytes

```
log#pxe

```

This is an anonymous function. Assign it to a variable to call it. Evaluates to builtins `log` or `exp` plus a comment.
> 5 votes

# Answer
# Python2, 73 bytes

io: stdin/stdout

```
from math import*;print log(input())#))(tupni(pxe tnirp;*tropmi htam morf

```

inverse:

```
from math import*;print exp(input())#))(tupni(gol tnirp;*tropmi htam morf

```
> 4 votes

# Answer
## CJam, 11 bytes

```
rdmle#eemdr

```

Test it here.

Reversed:

```
rdmee#elmdr

```

Test it here.

Basically the same comment-trick as the OP's Python answer. `e#` starts a comment. `rd` reads the input and `ml` or `me` computes the logarithm or exponential.
> 3 votes

# Answer
# Brachylog, 3 bytes

```
*₁≡

```

Try it online!

Initially, I had hoped to use `~*`, but although `*~` computes `e^x` and successfully ignores the trailing tilde, `~*` fails for all integer inputs and hits a float overflow on most non-integer inputs.

Forwards:

```
       The output
  ≡    is
*₁     the natural logarithm of
       the input.

```

Backwards:

```
       The output is
  *    Euler's number to the power of
       the input
≡      passed through the identity predicate
 ₁     with an extraneous subscript.

```

This uses the identity predicate because, although trailing tildes are tolerated, leading subscripts are not. (If they were, the Brachylog answer would be `*₁` alone, which is just the normal builtin for natural log.)
> 3 votes

# Answer
# Vitsy, 5 bytes

This is a program that exits on an error.

```
EL^rE
E   E  Push java.lang.Math.E
 L     Push log_(top) (input) (ln(input))
  ^    Push (top)^(input)  (e^(input))
   r   Reverse the stack
```

This program exits on an error with ln(input) on the stack.

Try it online! (note that I have put `N` to have visible output)

Then it's inverse:

```
Er^LE
```

This program exits on an error with e^(input) on the stack.

Try it online!
> 2 votes

# Answer
# Fuzzy Octo Guacamole, 7 bytes

non-competing, FOG is newer than the challenge

```
EZO@pZE

```

This is the equivalent of a function in FOG. It assumes the input is on the stack. This can be assigned to a function by the code `"EZO@pZE""f"o`, where `f` is any single-char name you want to assign. Then use it like any other command. Example: `"EZO@pZE"'f'o^f`.

Explanation:

```
EZO@pZE
E       # Push E (2.718....)
 Z      # Reverse stack (it is now [e, input])
  O     # log(x, y) which is ln(input)
   @    # Exit. (implicit output) Nothing after this gets run.
    p   # x^y (power function)
     Z  # Reverse stack
      E # Push E.

```

Reversed:

```
EZp@OZE
E       # Push E (2.718....)
 Z      # Reverse stack (it is now [e, input])
  O     # x^y (power function)
   @    # Exit. (implicit output) Nothing after this gets run.
    p   # log(x, y) which is ln(input)
     Z  # Reverse stack
      E # Push E.

```
> 2 votes

# Answer
# Matl, 5 bytes

```
Yl%eZ

```

`Yl`: log `Ze`: exp `%`: comment
> 1 votes

# Answer
# Pyth, 12 bytes

Finds `ln(input())`

```
.lQ) " Q1n.^

```

Finds `e^input()`

```
^.n1Q " )Ql.

```

Spaces stop implicit printing of strings, each version calculates it then creates a string with the remaining characters.

`ln(x)` mode here

`e^x` mode here
> 1 votes

# Answer
# , 8 chars / 10 bytes

```
МŬï//ïŦМ

```

`Try it here (Firefox only).``Try reverse here (Firefox only).`

Just 2 builtins separated by a comment.
> 1 votes

# Answer
# Jolf, 9 bytes

Program 1: `exp` of input

```
amoj"jOma
a         print
 moj      e^j
    "jOma  the rest of the line is captured as a string; implicit printing is restricted.

```

Program 2: `ln` of input

```
amOj"joma
a         print
 mOj      ln(j)
    "joma  the rest of the line is captured as a string; implicit printing is restricted.

```

Bonus points for being a case-insensitive palindrome? Try it here!
> 1 votes

# Answer
# J, 8 bytes

The natural logarithm is `^.`, and exponential `^`. The problem is, `.` can only modify a valid verb, otherwise, a spelling error will occur. Thus, we can't use the left argument trick in the APL answer, becuase `^.[^` would cause an error when reversed, as `^[.^` creates an invalid verb. So, we must use comments; but `NB.` is so long :( Fortunately, they both end with `.`, so&ldots; there's that.

Logarithm:

```
^.NB.BN^

```

Exponential:

```
^NB.BN.^

```

You can enter them for yourself online!
> 1 votes

# Answer
# Runic Enchantments, 9 bytes

```
i'lA@Ae'i

```

Try it online!

An ungodly uninteresting program. `@` insures termination of the implied entry point at the left, everything after is unexecuted. I tried really hard to re-use the `'` or `A` instructions, but to no avail, even at larger program sizes. The required explicit entry point for multi-line programs essentially precludes it.
> 1 votes

# Answer
# Java 8, ~~198~~ ~~182~~ 30 bytes

```
d->Math.log(d)//)d(pxe.htaM<-d

```

Try it online.

and reversed:

```
d->Math.exp(d)//)d(gol.htaM<-d

```

Try it online.

Uses the comment trick (`//`) with built-ins for `Math.log` and `Math.exp`.
> 0 votes

---
Tags: code-golf, arithmetic, source-layout
---