title: Alarm Optimization

text:
# Question
Title: Alarm Optimization
# My Alarm Clock

I'm American, and so is my (digital) alarm clock. To set the alarm, it starts at the time it was previously. Hitting the hour button moves it up one hour, and hitting the minute button moves it up one minute. Hitting both buttons at the same time resets it to midnight (12:00 am), and counts as two button presses.

When the hours exceed their cap (12), it resets to 1 and toggles the AM/PM light. When the minutes exceed their cap (59), they reset to 0, without affecting the hours.

# The Task

Your task is, given a starting time and a target time, to output the optimal number of buttons presses needed to set my alarm to the target time.

You may take input in whatever format suits you best. The only data your program should need is hours and minutes, for both inputs. That means that you, for example, may take data as milliseconds since epoch, and extract the hours and minutes, but you may not encode *anything* into the year, month, second, etc. Note that while you may, for example, input using "military time" (or regular time for most of the world), but that doesn't change how my clock works.

# Examples

```
1:15 pm -> 2:30 am

```

You could push down both buttons to reset to 12:00 am, then increment to 2:30 am, which would be `2+2+30 = 34` button presses. You could also increment to 2:30 am, which would be `13+15 = 28` button presses. Therefore, your output is `28`.

```
3:58 am -> 4:02 am

```

You could reset and increment, which would be `2+4+2 = 8` button presses. You could also increment, which would be `1+4 = 5` button presses. Therefore, your output is `5`.

```
10:55 pm -> 1:00 am

```

You could reset and increment, which would be `2+1 = 3` button presses. You could also increment, which would be `3+5=8` button presses. Therefore, your output is `3`.

```
1:00 am -> 1:59 pm

```

You could reset and increment, but that would be three more presses than just incrementing. Therefore, your output is `12+59 =`  `71`.

# Test Cases

```
Current  Target   = Output
1:15pm   2:30am   = 28
3:58am   4:02am   = 5
10:55pm  1:00am   = 3
1:00am   1:59pm   = 71
12:00am  12:00am  = 0
6:51pm   12:00am  = 2
2:01pm   11:00pm  = 25
2:01pm   11:01pm  = 9
12:59am  12:01am  = 2
11:50am  12:00pm  = 11

```

# Answer
> 5 votes
# Husk, 16 bytes

```
§▼ṁ→(Σz%e24 60z-

```

Try it online!

Takes arguments as two lists \[hours,minutes\], for start and end time, in 24h format.

I'm quite happy about how much I was able to golf this one, I find interesting how arguments are managed in this composition of functions.

The function which calculates how many key presses we need if reset is not allowed is the following:

```
Σz%e24 60z-
         z-    elementwise subtract the two times
 z%e24 60      take the hours difference modulo 24 and the minutes difference modulo 60
Σ              sum the two resulting numbers

```

The interesting part is that since the rest of this solution can work only with a single list as argument, this one gets partially applied to the first argument of the whole program, "eating" it and leaving only the second argument visible both for itself and the rest of the program.

Next, we compute how many key presses we need if we reset the time to 0:00

```
ṁ→    take the sum of each element of the list increased by 1

```

As said before, this operates only on the second argument (the final time), and computes `hours+minutes+2`, just in a golfier way.

Finally, `§▼` is the part that passes the second argument to both functions, and returns the lesser of the two results.

# Answer
> 8 votes
# JavaScript (ES6), ~~73~~ ~~56~~ ~~54~~ ~~52~~ 50 bytes

Uses 24 hour format. Takes input as 4 integers representing the hours & minutes of each time.

```
(g,l,h,m)=>Math.min(2+h+m,(h-g+24)%24+(m-l+60)%60)

```

---

## Try it

Enter the times in 24-hour format, with the `:` separator.

```
o.innerText=(f=

(g,l,h,m)=>Math.min(2+h+m,(h-g+24)%24+(m-l+60)%60)

)(+(x=(i.value="01:00").split`:`)[0],+x[1],+(y=(j.value="13:59").split`:`)[0],+y[1]);oninput=_=>o.innerText=f(+(x=i.value.split`:`)[0],+x[1],+(y=j.value.split`:`)[0],+y[1])
```

```
label,input{font-family:sans-serif;font-size:14px;height:20px;line-height:20px;vertical-align:middle}input{margin:0 5px 0 0;width:100px;}
```

```
<label for=i>Current: </label><input id=i type=time><label for=j>Target: </label><input id=j type=time><pre id=o>
```

---

## Explanation

(To be updated shortly.)

```
(g,l,h,m)=>

```

Anonymous function taking the integers as arguments via parameters `g`, `l`, `h` & `m`, where `g` & `l` are, respectively, the hours & minutes of the current time and `h` & `m` are the hours & minutes of the target time.

```
2+h+m

```

First, we calculate how many button presses are needed if we just reset the clock, which is simply 2 (for the reset) plus the target hour and the target minute.

```
h-g+24*(h<g)

```

Next we calculate how many button presses are needed to reach the target hour. We do this by subtracting the current hour from target hour. However, if the current hour is less than the target, this will give us a negative number so we rectify that by adding 24 multiplied by checking if `h<g` (which returns a boolean but is implicitly cast to integer `1`, if true, or `0` if false by the mathematical operations.

```
+m-l+60*(m<l)

```

We use a similar formula to calculate the number of presses to get from the current minute to the target minute and add that to the hour presses.

```
Math.min()

```

Finally, we get the minimum of the 2 numbers to give us our result.

# Answer
> 7 votes
# Pyth, 29 bytes

This challenge obviously doesn't advantage golfing languages, that's why it's so long. On the other hand, this is improved by the fact that Pyth is Python-based, so we can abuse its negative modulus.

```
hS,+%-eQ@Q1 60%-@Q2hQ24+2s>Q2

```

**Test Suite.** Numbers in Pyth do not support leading zeros.

# Answer
> 5 votes
# Jelly, 19 bytes

```
_⁵%24µ+⁴_⁶%60µ«³+⁴¤

```

Try it online!

Input as 4 integers (end-hour, end-minute, start-hour, start-minute)

# Answer
> 3 votes
# C# (.NET Core), 56 bytes

```
(H,M,h,m)=>Math.Min(((h+24-H)%24)+((m+60-M)%60),(2+h+m))

```

Try it online!

Very similar to the Javascript answer. Bools in C# don't convert easily to numbers, so instead of `[diff]+24*(H<h)` I did `([diff]+24)%24` which effectively does the same thing.

# Answer
> 3 votes
# Haskell, 41 bytes

```
(a#b)c d=min(a+b+2)$mod(a-c)24+mod(b-d)60

```

Pretty straightforward. Takes input as four arguments using 24-hour time: end hour, end minute, start hour, start minute.

# Answer
> 2 votes
# Python 3, 43 bytes

```
lambda a,b,c,d:min((c-a)%24+(d-b)%60,2+c+d)

```

Try it online!

Input as 4 integers (start-hour, start-minute, end-hour, end-minute)

# Answer
> 2 votes
# Java 8, ~~54~~ 50 bytes

```
(h,m,H,M)->Math.min((H-h+24)%24+(M-m+60)%60,H+M+2)

```

Port of *@KamilDrakari*'s C# answer (after I golfed ~~2~~ 6 bytes).

**Explanation:**

Try it here.

```
(h,m,H,M)->       // Method with four integer parameter and integer return-type
  Math.min(       //  Return the lowest of the following two:
                  //   The hours:
   (H-h           //    Second hours - first hours inputs
       +24)       //    +24 so we won't have negative numbers
           %24    //    mod-24 to get the hours
   +              //   And add the minutes:
    (M-m          //    Second minutes - first minutes inputs
         +60)     //    +60 so we won't have negative numbers
             %60  //    mod-60 to get the minutes
    ,H+M          //  And compare it to the second hours + second minutes inputs
        +2)       //   +2 for the added +24 and +60 to get the positive modulo arguments

```

# Answer
> 1 votes
# Perl 5, 71 +2 (-ap) = 73 bytes

```
($w,$x,$y,$z)=@F;$_=($r=2+$y+$z)>($c=($y-$w+24)%24+($z-$x+60)%60)?$c:$r

```

Try it online!

Takes input in 24 hour format (military time), separated by spaces, start time first, end time second: *HH MM hh mm*

# Answer
> 1 votes
# Retina, 106 bytes

```
\d+
$*
 (1*):(1*)
 24$*1$1:60$*1$2#11$1$2
(1*):(1* )\1(1{24})?
$2
(1*) (1*):\1(1{60})?
$2
(1+)#(?!\1)

\G1

```

Try it online! Link includes test cases. Takes input as current and desired times in regular 24 hour time with a space separating the two times. Explanation:

```
\d+
$*

```

Convert to unary.

```
 (1*):(1*)
 24$*1$1:60$*1$2#11$1$2

```

This does two things; it adds 24 hours and 60 minutes to the desired hours and minutes, and it also adds 2 to the sum of the original desired hours and minutes, i.e. the the number of button presses to set using a reset.

```
(1*):(1* )\1(1{24})?
$2

```

Subtract the current hours from the desired hours, and subtract the 24 we added on if we can.

```
(1*) (1*):\1(1{60})?
$2

```

Similarly for the minutes. This also adds the two results together.

```
(1+)#(?!\1)

```

If the number of presses to set using the current time is more than the number of presses to set using a reset, delete it.

```
\G1

```

Convert the first remaining number back to decimal.

---
Tags: code-golf, date, path-finding
---


title: Square Root a Number my Way

text:
# Question
Title: Square Root a Number my Way
Now that we know how to Square a Number my Way, we need an inverse operation, a way to Square Root a Number my Way. To square a number my way, you simply stack it on top of itself a number of times equal to the number of digits it contains, and then take read off every number that is formed both vertically and horizontally, and then add them together. More information about squaring a number in this manner can be found here. To square root a number my way, you simply take the number that has the least decimal digits that squares (my way) to make the number you are square rooting. For example, since 12 can be formed by squaring 6, and there are no numbers with fewer decimal digits that can be squared to form 12, the square root of 12 is 6.

## Your Task:

Write a program or function that takes an integer and square roots it as outlined above.

## Input:

An integer or string

## Output:

A float or string square rooted as outlined above.

## Test Cases:

```
1263 -> 125
57   -> 12

```

## Scoring:

This is , lowest score in bytes wins!

# Answer
# Python 2, 101 bytes

Ports from my answer to square the numbers my way.

```
x,z=1,input()
while sum(float(i*len(z))for z in[[i for i in`x`if"/"<i]]for i in[x]+z)!=z:x+=1
print x

```

Try it online!
> 3 votes

# Answer
# Python 3, 112 bytes

```
f=lambda x,k=0:k if(lambda x:int(x)*len(x)+sum(map(int,map(''.join,zip(*[x]*len(x))))))(str(k))==x else f(x,k+1)

```

Try it online!
> 2 votes

# Answer
# Mathematica, 130 bytes

```
(For[i=1,(t=Length[s=#&@@RealDigits[#]//.{a___,0}:>{a}];If[IntegerPart@#==0,t++];t#+Tr[FromDigits@Table[#,t]&/@s])&[i]!=#,i++];i)&

```

other test cases

> 5994 -\> 999
> 79992 -\> 9999
> 999990 -\> 99999
> 1 votes

# Answer
# Pyth, 20 bytes

```
xms+RdsM*RF_lB@jkUT`

```

**Test Suite.**

As all the other answers, this assumes the input is a "perfect square (my way)". This also uses the fact that the square (my way) of an integer is always higher than or equal to itself. Also, this is a port of Erik's solution to that challenge. Porting my solution from that challenge would result in a longer submission.
> 1 votes

# Answer
# PHP, ~~92 90 89~~ 84+1 bytes

brute force (assuming that the input is a perfect square)
using my solution from Square a Number my Way:

```
while((0|$k/=10)||$s-$argn&&$k=++$n+$s=0)$s+=$n+str_repeat($k%10,strlen($n));echo$n;

```

Run as pipe with `-nR` or try it online.
> 1 votes

---
Tags: code-golf, number
---


title: Bifurcated text

text:
# Question
Title: Bifurcated text
Given a string of ASCII letters (upper and/or lower case), output the raw MathJax required to display that string bifurcating at each character, into superscripts and subscripts. For example, the inputs `cat` and `horse` would result in outputs which MathJax renders as the following, respectively:

Note that only one input is required to be taken - these two are listed side by side simply to save vertical space.

# Markup meaning

* `_` indicates a subscript.
* `^` indicates a superscript.
* Braces are required around superscripted or subscripted substrings that contain further superscripting or subscripting in order to prevent them all being at the same level.

# Test cases

Test cases are in the format `input : output`. The first test case shows the empty string as input should result in the empty string as output.

```
"" : ""
"a" : "a"
"me" : "m_e^e"
"cat" : "c_{a_t^t}^{a_t^t}"
"frog" : "f_{r_{o_g^g}^{o_g^g}}^{r_{o_g^g}^{o_g^g}}"
"horse" : "h_{o_{r_{s_e^e}^{s_e^e}}^{r_{s_e^e}^{s_e^e}}}^{o_{r_{s_e^e}^{s_e^e}}^{r_{s_e^e}^{s_e^e}}}"
"bifurcate" : "b_{i_{f_{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}^{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}}^{f_{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}^{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}}}^{i_{f_{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}^{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}}^{f_{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}^{u_{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}^{r_{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}^{c_{a_{t_e^e}^{t_e^e}}^{a_{t_e^e}^{t_e^e}}}}}}}"

```

You can see how these are rendered by pasting the output into mathurl.com.

# No redundant braces

MathJax will happily render markup that has redundant braces. For example, the following will all look identical when rendered: `a`, `{a}`, `{}{a}`, `{{{{a}}}}`.

However, valid output for this challenge has no redundant braces. Note in particular that single characters in the output are not surrounded by braces.

# Order

The order of subscript and superscript is unimportant. The following are equivalent and will be indistinguishable when rendered (and are all equally valid outputs):

```
c_{a_t^t}^{a_t^t}
c_{a^t_t}^{a_t^t}
c_{a_t^t}^{a^t_t}
c_{a^t_t}^{a^t_t}
c^{a_t^t}_{a_t^t}
c^{a^t_t}_{a_t^t}
c^{a_t^t}_{a^t_t}
c^{a^t_t}_{a^t_t}

```

# Scoring

For each language, the winner is the shortest code in bytes.

Too many notifications? Type `</sub>` to unsubscript

# Answer
> 10 votes
# Python, ~~95~~ ~~90~~ ~~86~~ ~~92~~ 82 bytes

*10 bytes saved thanks to @ConnerJohnston*

```
f=lambda s:s and s[0]+(s[1:]and'_{0}^{0}'.format(s[2:]and'{'+f(s[1:])+'}'or s[1]))

```

Try it online!

# Answer
> 7 votes
# Mathematica, ~~72~~ ~~84~~ ~~77~~ 76 bytes

```
a_±b__:={"{",a,"_",±b,"^",±b,"}"};±(a_:""):={"",a,""};""<>Most@Rest@±##&@@#&

```

Uses CP-1252 (Windows) encoding. Takes a list of characters as input.

## Explanation

```
a_±b__:=

```

Define the function `±`, with 2 or more arguments. Label the first argument `a`, and second and on `b`.

```
{"{",a,"_",±b,"^",±b,"}"}

```

Create a `List` equivalent to `"{a_±b^±b}"` (`±b` is evaluated again, recursively).

```
±(a_:""):= ...

```

Define the function `±`, with 1 or 0 arguments. Label the first argument`a`, if it exists, and assign `""` to `a` otherwise.

```
{"",a,""}

```

Create a `List` equivalent to `"a"`, padded with empty `String`s.

```
""<>Most@Rest@±##&@@#&

```

A pure function that applies `±` to the input, drops first and last element, and converts `List` to `String`.

# Answer
> 7 votes
## CJam (35 bytes)

```
MqW%{"^{ }_{ }"{AW$,)3e<#<},S/@*+}/

```

This is a full program. Online demo.

3 bytes work around a bug in the interpreter (see below).

### Dissection

```
M            e# Start building from the empty string
qW%{         e# For each character in the reversed input
  "^{ }_{ }" e#   Take a template
  {          e#   If the accumulator is of length n, remove all characters whose
    A        e#   codepoints are greater than pow(10,
    W$,)3e<  e#                                   min(n+1, 3))
    #<       e#   When the accumulator is the empty string, that's all of them.
  },         e#   When the accumulator is one character, that's {}
             e#   When the accumulator is any longer, it's none of them.
  S/@*       e#   Substitute the accumulator for the spaces.
  +          e#   Append to the new character.
}/

```

Note that the `min(n+1, 3)` is to work around a bug in the interpreter: there must be some pattern in the powers of 10 that `'}` is smaller than, but it's not obvious.

# Answer
> 7 votes
## JavaScript (ES6), ~~57~~ 55 bytes

```
f=([c,...s])=>s+s?c+`_${p=s[1]?`{${f(s)}}`:s}^`+p:c||''

```

~~Θ(len(s)) complexity!~~ According to @PeterTaylor, this is actually Θ(2^len(s)), which is still the best possible...

# Answer
> 6 votes
# Haskell, 71 bytes

```
f[x,y]=x:'_':y:'^':y:[]
f(x:y@(_:_))=x:"_{"++f y++"}^{"++f y++"}"
f x=x

```

Try it online!

If we just had to output valid code the following would work for 44 bytes:

```
f[a]=[a]
f(a:b)=a:"_{"++f b++"}^{"++f b++"}"

```

Try it online!

# Answer
> 5 votes
# SOGL V0.12, 21 bytes

```
±K;{╔+;lH?"{ŗ}”}1 ^Ο+

```

Try it Here!

Explanation:

```
±                      reverse the string
 K                     take off the first letter - will slowly convert to the output
  ;                    get the rest of the string ontop
   {                   iterate over the rest of the characters
    ╔+                   append "_" to it
      ;                  get the output string ontop
       lH?     }         if it's length - 1 [isn't 0]
          "{ŗ}”            push the string "{ŗ}" where ŗ is replaced by the output string
                1 ^Ο     wrap "^" around with the output string
                    +    prepend to it the current character + "_"

```

# Answer
> 5 votes
# Perl 5, 54 + 1 (-p) = 55 bytes

```
s/\{(.)\}/$1/g while s/([a-z])([a-z]+)/$1_{$2}^{$2}/ig

```

Try it online!

**How?**

The substitution in the while condition breaks occurrences of multiple letters in the first letter, followed by the rest in braces like this:

```
abc -> a_{bc}^{bc}

```

The while loop executes the substitution until no more multi-letter sequences remain. The substitution inside the loop removes braces from around single letters.

# Answer
> 4 votes
# Ruby, ~~76~~ ~~73~~ ~~72~~ ~~68~~ ~~67~~ 57 bytes

Use of lambda saving 4 bytes thanks to Tutleman

```
f=->s{(r=s[1..-1])[0]?s[0]+?_+[r[1]??{+f[r]+?}:r]*2*?^:s}

```

Try it online!

Ungolfed:

```
def f(s)
  r = s[1..-1]
  if r.size > 0
    if r.size > 1
      x = "{" + f(r) + "}"
    else
      x = r
    end
    return s[0] + "_" + [x, x].join("^")
  else
    return s
  end
end

```

# Answer
> 2 votes
# Python 2, 84 bytes

```
def b(s):q=s and(s[2:]and'{%s}'or'%s')%b(s[1:]);return s[1:]and s[0]+'^%s_'%q+q or s

```

Try it online!

# Answer
> 1 votes
# Pyth, 47 bytes

```
Ljk[hb|&ttbs[\_\{ytb"}^{"ytb\})&tbs[\_htb\^htb;

```

Try it online!

This is pretty much a straight port of @Uriel's Python answer. Going to golf it down in a bit.

# Answer
> 1 votes
# PHP, 121 bytes

```
function b($s){return $s[0].($s[1]?'_'.($s[2]?'{'.($b=b(substr($s,1))).'}^{'.$b.'}':"$s[1]^$s[1]"):'');}echo b($argv[1]);

```

The function itself is 104 bytes and shows a PHP Notice.

# Answer
> 1 votes
# Retina, 43 bytes

```
(.)(.)$
$1¶$2
+`(.)¶(.*)
¶{$1_$2^$2}
¶{|}$

```

Try it online! Link includes test cases. Explanation:

```
(.)(.)$
$1¶$2

```

Get the ball rolling by slicing off the last character. (But if it's the only character, them leave it alone.)

```
+`(.)¶(.*)
¶{$1_$2^$2}

```

Move the ¶ character back one step at a time, each time taking the previous result and making it a subscript and superscript of the next character.

```
¶{|}$

```

Remove the now redundant ¶ and the outer {}s.

# Answer
> 1 votes
# Java (OpenJDK 8), 121 bytes

```
s->{int l=s.length;String r=--l<0?"":""+s[l];for(;l-->0;)r="{"+s[l]+"_"+r+"^"+r+"}";return r.replaceAll("^\\{|\\}$","");}

```

Try it online!

# Answer
> 0 votes
# Javascript, 73 Bytes

```
s=>[...s].reduceRight((m,c)=>`${c}_{${m}}^{${m}}`).replace(/{(.)}/g,'$1')

```

## Explanation

```
s=>                                  // take the input string
    [...s]                           // split the string into an array
    .reduceRight(                    // reduce the array in reverse order
        (m,c)=>`${c}_{${m}}^{${m}}`  // storing the result of each iteration in the memo m
    )                                // and returning m at the end
    .replace(/{(.)}/g,'$1')          // replace redundant {}

```

Because there is no specified initial value of `m`, `reduceRight` takes the last element of `s` as the initial value, and begins iterating at index `s.length-2`.

```
const f=s=>[...s].reduceRight((m,c)=>`${c}_{${m}}^{${m}}`).replace(/{(.)}/g,'$1');

const input = document.querySelector('#input');
const output = document.querySelector('#output');
output.textContent = f(input.value);
input.addEventListener('keyup', e => output.textContent = f(input.value));
```

```
Enter text to bifurcate: <input type="text" id="input" value="cat" />
<br />
<span id="output"></span>
```

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


title: Polyglot the OEIS!

text:
# Question
Title: Polyglot the OEIS!
> **Note:** This challenge has been moved to Polyglot the (non constant) OEIS! to avoid closure.

## Introduction

We all know and love the *on-line encyclopedia of integer sequences* (OEIS). So what if we made an *off-line* version? Well, that would be kinda too easy, wouldn't it and how would you select a sequence with our standard interface!? No. We need an easier solution to this. A polyglot!

## Input

Your input will be a non-negative integer `n`.

## Output

Your output will either be

* The `n`-th entry of an OEIS sequence OR
* The first `n` entries of an OEIS sequence.

You may take the index to be 1-based or 0-based as you prefer.

## Uhm, so where is the Challenge?

You have to polyglot the above functionality. That is if you support languages A, B and C all must implement different OEIS sequences. The choice of sequence is not limited except that you need different ones for all languages.

That is, if you run the provided program in language A, then sequence X shall be generated, if you run the provided program in language B, then sequence Y shall be generated (with X!=Y) and if you run the provided program in language C, then sequence Z shall be generated (with X!=Z && Y!=Z).

## Who wins?

The answer with the most sequence/language pairs wins. First tie-breaker is code-size (in bytes) with lower being better. Second tie-breaker is submission time with earlier being better.

## Any final Words / Rules?

* You must declare which language will generate which sequence.
* Standard I/O rules apply.
* If different encodings are used between languages, both programs must use the same byte-sequence.
* Language (Python 2/3) revisions *do* count as different languages. Different implementations of a language (such as Browser JS vs Node.js) also count as different languages.
* Standard loopholes apply.

# Answer
> 39 votes
# 26 languages: C, C++, Cubically, rk, what, Bash, Morse, Ook!, str, Charcoal, Commercial, S.I.L.O.S, memescript, Forked, TRANSCRIPT, Braingolf, Fission, Arcyou, Beam, Beatnik, Cood, COW, Emoji, \>\<\>, Set, NTFJ

Over 1000 bytes \>.\< but I'm gonna go for the most languages.

Hit `Page Down` about 10 times if you don't want a description of all the languages.

```
#\
//ha kkkkkkkkkk ja ha kkkkkkkkkkd ja skd  I7Oq2_
#include<stdio.h>//$+77%6& ..... rk:start print: "11" rk:end  ?!!!!!!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!??!????!        Ook. Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. ⎚8» ##########################################
 /*
echo -n 3;exit
Hey, waiter!
I want 25 of this.
How much is it?
The bill, please.
foo now 9 dollars off!
foo has been selling out worldwide!
a = 10
printInt a
filler what the frick frack thumbtack diddily dack crack pack quarterback frick frack (p 22)
>F9+%&'L+:+:H
Ju is here.
>Ju, 32
>X Ju
 set ! 50
 set ! 56
oom MoO OOM  26➡ #####/
*/main(int a){getchar();printf("%d",sizeof(' '));}/* R"21"
 >2n7n; */

```

This outputs:

(Links are not all current, I'll eventually update them. I have verified each language.)

# C/C++

`sizeof(' ')` is 1 in C++ and 4 in C. Here's the C/C++ code:

```
#include <stdio.h>
main(){getchar();printf("%d",sizeof(' '));}

```
* `#include <stdio.h>` is needed for C++. (This is why I don't like it.)
* `getchar();` is there because we still technically need input.
* `printf("%d",sizeof(' ')` prints 4 in C and 1 in C++.

**Update** \- the `echo -n 3;exit` is ignored via `\` at the end of the comment on line 1.

# Cubically

Cubically ignores everything it doesn't care about as long as no functions get called.

```
$+7+7%6&
$          read int as input
 +7+7      double it (could be +77, I'll golf everything more if it comes to that)
     %6    print output
       &   exit (the `main()` would cause an infinite loop)

```

# rk

rk is horrible, but good for polyglotting. It ignores everything before `rk:start` and after `rk:end`:

```
rk:start print: "11" rk:end

```

Pretty simple. A010850 is a constant sequence. "Input is taken via command line arguments." :P

# what

The `what` interpreter reads three bytes at a time. Very stupid but useful.

```
?!!!??(x50)??!

```

Gets input (uselessly), goes to next memory cell, adds the ASCII value for 2 (50) to the current memory cell and outputs.

# Bash

```
# <comment>
echo -n 3; exit
<everything ignored because parser already exited>

```

Also takes input via "command line arguments". I love constant sequences.

# Morse

Morse Code is the oldest language used in this thread, I can guarantee. ;) This uses an interpreter I wrote last year for fun. It conveniently ignores everything it doesn't care about.

```
.....

```

Constant sequences probably weren't what the OP had in mind when creating the challenge...

# Ook!

Ook! is a Trivial Brainf\**k Substitution. The interpreter I found is really crappy, reads 11 characters at a time and checks if it's something it cares about. Pasting the code at the end of the first line magically lined it up properly, so the interpreter noticed the Ook! code.

```
Ook. Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook.

```

This is equivalent to Brainf\**k's `,>+(x48).`. Read a character, move to next memory cell, increment to 48 (ASCII code for `0`) and print.

# str

The str code wanted to be right at the top because something around `#include <stdio.h>` made it bug out. I had to rearrange the what and Ook! code, since I added something before both of them.

```
# // I7Oq

```

`#` is apparently a valid preprocessing token in C/C++. `//` comments it out. (That's a capital letter o, in case your screen tries to deceive you.)

* `I` \- read input
* `7` \- push 7
* `O` \- output
* `q` \- turn off STDOUT just in case

I think it's real clever how `I` is for input and `O` is for output. Nice language, Conor!

# Charcoal

Wow, I like this language, I'm gonna use it more sometime.

Luckily, there's a command to clear the output buffer, . So it just echoes everything up to the  on line 2, then clears that. The Charcoal code we care about looks like this:

```
⎚8»

```

8 prints 8. `»` exits with a parse error, which is allowed by default.

# Commercial

This one was a bit less nice because it wanted me to have its code on separate lines. I had to rearrange the C/C++ comments a bit.

For some reason, C emitted a warning and then didn't compile when I replaced the `//` with `/*`. So it's on its own line, making Bash annoyed but still prints the desired number.

```
foo now 9 dollars off!
foo has been selling out worldwide!

```
* `variable now x dollars off` creates a new variable `variable` with value `x`.
* `variable has been selling out worldwide!` prints the variable's value.

At least the interpreter is forgiving about *unrecognized* code...

Oh, I also updated all the TIO links. That was a pain so I'll probably only do so every 10 or when I quit working on this polyglot. Fun challenge, thanks!

# S.I.L.O.S

That had one of the clearest, most concise READMEs I've ever seen. Simple as this:

```
a = 10
printInt 10

```

Adding this code didn't even break anything!

# Memescript 1.0

Why does this language exist \>.\<

The interpreter was being lame so I had to add `filler` to get it to see `what the`.

```
filler what the frick frack thumbtack diddily dack crack pack quarterback frick frack

```
* `what the` \- start code
* `frick frack thumbtack` \- push 11
* `diddily dack crack pack` \- add 5
* `quarterback frick frack` \- output as integer

# Forked

Forked is my new 2d lang, it's only partially implemented. It's not in a triangle or a cube or anything interesting, it's just a fun simple esolang.

Unfortunately, having `# // I70q` on the first line had a mirror `/` in the way of the source code. I moved some things around so the mirrors look like this:

```
 \
//

```

The mirrors are pretty self-explanatory; the code enters from the top left and exits at the bottom left. Then it hits this code near the bottom:

```
>F9+%&

```

`>` directs the IP west. `F` pushes 15, `9` pushes 9. `+` adds them, `%` prints as integer, `&` exits.

Note: This may not work in future Forked versions, depending on how `#` will handle invalidity.

# TRANSCRIPT

This is a cool language. I don't really understand some of the syntax (specifically, `>`), but it's fun nevertheless. Also forgiving about syntax errors which is why I chose to use it.

Here's the code we care about:

```
Ju is here.
>Ju, 32
>X Ju

```
* `Ju is here.` defines an NPC (variable) named Ju. (Short for Julie, which was used in the example.)
* `>Ju, 32` puts 32 in Ju's memory (sets it to 32).
* `>X Ju` prints Ju. (Where did `X` come from?!?)

# Braingolf

Apparently, the code does some wacked out stuff to the stack but outputs 0 at EOF, so I found a place I could put the code without breaking anything else, found a sequence that ended in 0, and let it do its implicit output at the end.

```
2_

```

Pushes 2 and prints it. `0` is printed at the end, printing 20. More constant sequences, yay!

# Fission

For such a complicated language, this was pretty easy - just modified this:

```
R"21"

```

Prints 21. Surprisingly, putting this *anywhere* in the code worked just fine.

* `R` creates atom travelling right.
* `"21"` stores the string 21 in that atom.
* Implicit output at the end of the program, I guess.

# Arcyou

Another language forgiving about syntax errors. Here's the code we care about:

```
(p 22)

```

Arcyou is pretty much identical to LISP, but golfier. `p` is print, `22` is 22.

Also, it printed `None` due to the `main()`. I added `a` there, C++ complained, I made it `int a` and everything's running smoothly again.

# Beam

The hardest part about adding this language was finding the spec. Luckily, there's a mirror of esolangs.org! Thanks, totallyhuman!

Beam uses the same control flow as Forked but that's it. So I put its code after Forked's exit command.

```
'L+:+:H

```

`'` increments the store and `L` sets the beam to the store. `+` increments, `:` outputs as integer.

I tried `++:+:H` first, but the beam apparently is not initialized to 0. The store is, though.

# Beatnik

Beatnik is a language almost as awful as some I've written and am planning to write. It uses Scrabble word values. Here's its code:

```
ha kkkkkkkkkk ja ha kkkkkkkkkkd ja skd

```

Here is the Scrabble values for those:

```
5 50 9 5 52 9 17

```
* `5 50` \- push 50
* `9` \- print as ASCII
* `5 52` \- push 52
* `9` \- print as ASCII
* `17` \- exit

I used a comma and a bunch of Z's initially, which messed with str. Fixed by removing the useless comma and changing 5 z's to 10 k's.

# Cood

Cood cares about this (explanation on the right)

```
Hey, waiter!           (start program)
I want 25 of this.     (set memory to 25)
How much is it?        (print as int)
The bill, please.      (finish script)

```

# COW

Yay, a non-constant sequence! :D

```
oom MoO OOM
oom          read integer
    MoO      increment
        OOM  print as integer

```

# Emoji

```
26➡
..   push string
 26    "26"
    ➡  print top of stack

```

# \>\<\>

Another language I'm going to use more; I love how this wraps.

It initially hits `#`, which bounces the IP backwards, wraps around, hits `\`, which wraps vertically to the bottom, hits `>`, then it sees `2n7n;`.

```
2n7n;
2      push 2
 n     output
  7    push 7
   n   output
    ;  exit

```

# Set

I recall this being used in the . Luckily, ASCII-only's TIO interpreter doesn't care about syntax errors!\

```
set ! 50         (print 2)
set ! 56         (print 8)

```

# NTFJ

That's another one of your langs I've used, Conor.... this is possibly the strangest. All I do is push truthy values (`#`) and use `/` to push the number of items on the stack to the stack and `*` to print.

```
(line 3) ##########################################
(line 4) /*
(line 21) #####/
(line 22) *

```

I didn't really mess with the code in the middle. It probably does things to the stack, and this will probably be a pain down the road, but whatever, it works.

# Answer
> 28 votes
# 9 Languages, 217 bytes

```
2/3#^4 9

5
if 1:
  x="+++++++[>+++++++<-]>."#3
  R = input()
  try:
    print(int(eval(chr(49)+chr(47)+chr(40)+chr(49)+chr(47)+chr(50)+chr(41))*int(R)))
  except:
    print(7**int(R))
    R="6"#N;
    n=2
  R

```

Jelly outputs the first `n` elements of the sequence instead of the `n`-th element.

\>\<\> and Whitespace exit with an error after giving the correct output, which is allowed by default.

## How it works

**Jelly**

Jelly sees only the `R` at the bottom, which tells it to output `range(input)`.

**Python 2**

After removing unused lines, Python 2 sees:

```
if 1:                     # just do it, where it is the following:
  R = input()             # set input to R
  try:                    # try:
    print(int(eval(chr(49)+chr(47)+chr(40)+chr(49)+chr(47)+chr(50)+chr(41))*int(R))
  # print(int(1/(1/2))*int(R)). Floor division causes 1/(1/2) to be
  # 1/0, raising a division by 0 error, going into the except block
  except:
    print(7**int(R))      # print 7 to the power of R.

```

**Python 3**

```
if 1:                     # just do it, where it is the following:
  R = input()             # set input to R
  try:                    # try:
    print(int(eval(chr(49)+chr(47)+chr(40)+chr(49)+chr(47)+chr(50)+chr(41))*int(R))
  # print(int(1/(1/2))*int(R)). Float division causes 1/(1/2) to be
  # 1/0.5=2. This is multiplies by R and printed.
  except: # The except block is not called
    print(7**int(R))

```

**Brainfuck**

Brainfuck sees:

```
+++++++    Set counter cell to 7
[          While counter != 0
  >          Go to storage cell (default to 0)
  +++++++    Increase by 7
  <          Return to counter cell
  -          Decrement
]          EndWhile
>.         Print out chr value of storage cell => chr(49) = "1"

```

**///**

/// sees:

```
<Something including the top-left 2>
# replace the empty string with 2 and output

```

**Ohm**

Ohm sees:

```
<Something including the top 9>
# implicitly output 9.

```

**\>\<\>**

\>\<\> sees:

```
2/3#^4 9   -- the IP travels right (pushing 2) until it hits `/`
 f         -- it travels up (pushing f=15) until it hits `/`
           -- it travels right (pushing 3) until it hits `#`
           -- it travels left (pushing 3) until it hits `/`
           -- it travels down (pushing f=15) until it hits `/`
           -- it travels left (pushing 2 then 9 then 4) until it hits `^`
           -- it travels up. When it hits `n`, it prints the 4
           -- it then hits some characters ><> doesn't like,
           -- ending the program with an error.
    n

```

**Fission**

Fission sees:

```
R="6"#N;
R          - start an IP/atom going right
  "        - start string
   6       - 6
    "      - end string
      N    - add newline
       ;   - end program. (implicit) print

```

(it sees other lines, but those don't affect output) **Whitespace**

Some of this has likely been lost in copy-paste.

Whitespace sees the following, where N represents linefeed, S represents space, and T represents tab. All actual newlines should be ignored.

```
NSSN
SSSN  -- push 0
TN    -- print it
NTNSNSSNSSSSNSSNSSSSNSSNSSSSNSSSSNSSSSNSSN

```

# Answer
> 22 votes
# 9 Languages, ~~107~~ 98 bytes

Sub 100!

Python 2, Python 3, JavaScript, PHP, brainfuck, Retina, Gaia, \>\<\>, Ohm.

```
2 //1;""""0
;function a($n){return $n**(2+!"0");};
/*."""
print(input()*2)
1#/i$%o<
() #\7751cep*/

```

A005843 in Python 2

A020338 in Python 3

A000290 in JavaScript

A000578 in PHP (run with `-r`)

A000012 in brainfuck (IO by byte value)

A001477 in Retina

A000040 in Gaia

A000035 in \>\<\> (IO by byte value)

A000004 in Ohm

## Explanations

### Python 2 and 3

All the two Python versions see is the following:

```
print(input()*2)

```

The difference in their behaviour is that `input()` evals the line of input read in Python 2, but just returns the string in Python 3. So Python 2 prints **2n**, but Python 3 prints the string of **n** repeated twice.

### JavaScript and PHP

What these languages see is the following:

```
2
;function a($n){return $n**(2+!"0");};

```

Which defines a function `a` that computes the result. The difference in behaviour comes from `!"0"`.

In JavaScript, `"0"` is a truthy value. So `!"0"` becomes `false`, which gets cast to 0. Thus JavaScript computes `$n` to the power 2+0.

In PHP, the `"0"` is actually a falsy value, because (for whatever reason) it gets cast to the number `0` before being treated as a boolean. So `!"0"` is true. Thus PHP computes `$n` to the power 2+1.

### brainfuck

The `+` in the JS/PHP part increments the cell, then the `.` in the middle outputs it. Thus it outputs the byte value 1 for any input.

### Retina

Retina does a lot of regex substitutions on the input, using regexes that don't even remotely match any number that would be given as input (so no replacements are made). Then it prints the result of the replacements, which is just the input.

### Gaia

The only line executed by Gaia is:

```
() #\7751cep*/

(               Decrement the input
 ) #            Find the first (input-1) numbers such that (number+1) is true
    \           Delete that list of numbers
     7751c      Push the string "ṇ"
          e     Eval it (the command for "nth prime number")
           p    Print the result
            */  Some other stuff that doesn't matter

```

### \>\<\>

What's relevant to \>\<\> is

```
2 /

  /i$%o<

```

The fish starts at the top left, pushing `2`. It moves over to the `/`, mirroring and looping to the bottom of the code. It hits the other `/` and move right. It pushes input (`i`), swaps the top stack elements (`$`), computes input mod 2 (`%`), and outputs as a byte (`o`). Then it moves left and tries to output again, which causes the program to exit with an error since there's nothing left on the stack.

### Ohm

Ohm only executes the first line:

```
2 //1;""""0

```

Which is some random stuff and then `0`. Only the top stack element is printed implicitly.

# Answer
> 12 votes
# 5 languages - Braingolf, Pyth / GolfScript / Brain-Flak / Pyke / Brachylog, MATL, Retina / Jelly / Commentator and 05AB1E / 2sable / Oasis

```
Q

```

This has ~~two~~ three multi-language-sequence polyglots. In Braingolf, this computes the triangular numbers (A000217), Pyth and GolfScript and Pyke (and Brain-Flak) are 0-indexed and use the non-negative integers (A001477), MATL is 0-indexed and uses the positive integers (A000027), Retina, Commentator and Jelly always output `0` (A000004), regardless of the input and 05AB1E, Oasis and 2sable always output `1` (A000012).

---

# How?

In Braingolf, the nth triangular number is calculated using `Q` (1-indexed).

In Pyth and GolfScipt and Pyke (and Brain-Flak), the input just gets printed as it is.

In MATL, `Q` means increment by 1, hence it displays the number given as input plus 1.

In Retina, Commentator and Jelly, `Q` always prints `0`. Similarly, 05AB1E, Oasis and 2sable output `1`.

# Answer
> 8 votes
# 5 languages (05AB1E, CJam, Jelly, MATL, Retina), 8 bytes

```
rdK*p
%2

```

This produces:

The CJam program exits with an error after producing the correct result in STDOUT, which is allowed by default.

# Answer
> 6 votes
# 3 languages, QBIC, QBasic and Javascript

```
'';/*`
input a
?a*q
''*/f=()=>1;

```

## QBasic, all 0's; A000004

```
'';/*`          the ' makes this a comment for QBasic
input a         this asks for an input, stores it in a
?a*q            Multiplies a by q, which is not set in QBasic and therefore 0. ? prints this.
''*/f=()=>1;    And another comment

```

## QBIC, positive ints, A000027

```
'';/*`          The ' opens a code literal: This tells the QBIC interpreter that the next bit is pure QBasic.
                The following ' injects a comment in the output QBasic code, the ` at the end closes the code literal.
input a         this does the same as the QBasic bit
?a*q            Multiplies a by q, which is 1 in QBIC and just yields the input. ? prints this.
''*/f=()=>1;    And another comment

```

## Javascript, all 1's, A000012

```
'';/*`          ''; is mostly harmless. /* opens a multiline comment. ` is ignored
input a         commented
?a*q            and commented
''*/f=()=>1;    This closes the comment and defines function f() that always just returns 1

```

# Answer
> 4 votes
# 3 languages: Gaia, CJam, Retina, 7 bytes

```
1_0

@+

```

A005843 in Gaia, A010850 in CJam, and A000004 in Retina.

Try it Gaia!

Try it CJam!

Try it Retina!

### Explanations

**Gaia**

Gaia only executes the bottom line, which reads input (`@`) and adds it to itself.

**CJam**

```
1      Push 1
 _     Copy it
  0    Push 0
   @   Bring the bottom 1 to the top
    +  Add 1+0, making the stack `[1 1]`. Implicity push the stack flatten and joined.

```

**Retina**

Replaces instances of `1_0` in the input with nothing. Then counts and outputs the matches of the regex `@+` in the result. Since this won't ever appear, it outputs 0 for any *n*.

# Answer
> 3 votes
# 11 languages: C, C++, JavaScript (nodejs), Ruby, JavaScript (modern browser), Perl, dc, \>\<\>, brainfuck, JavaScript (spidermonkey), and Pyramid Scheme, 342 bytes

I wanted to see if I could break ~~9~~ 10. I decided to use mainly non-esoteric languages.

```
        //;<<E;#6nq>>>-[++>+[+<]>]>^\
/*   ;n7<>>                       / \:
#include <stdio.h>              //out\
//                              ^-----
//                              -
struct k {};int main(){printf("%i",1+sizeof(struct k));}
//;\
E
//;\
`echo`;  print($??3:5)
;//;#*/  console['log'](this['window']?4:this['print']?9:10)

```

Results I was able to verify (for input 4) on my machine:

```
Result in "C" (A000004):
> gcc normal.c -o normal && normal.exe 4
1
Result in "C++" (A000012):
> g++ normal.cpp -o normal && normal.exe 4
2
Result in "JavaScript" (A007395):
> node normal.js 4
10
Result in "Ruby" (A010701):
> ruby normal.rb 4
3
Result in "Perl" (A010716):
> perl -f normal.pl 4
5
Result in "dc" (A010722):
> echo 4 | dc -f normal.dc
6

```

Pyramid Scheme

# Answer
> 2 votes
# 2 languages: /// and \>\<\>

```
/9/0//8/0//7/0//6/0//5/0//4/0//3/0//2/0//1/0//00/0//
>1n;//

```

**///** outputs https://oeis.org/A000004 all 0's, and **\>\<\>** does https://oeis.org/A000012 all 1's

Try \>\<\> online!

Try /// online!

# Answer
> 2 votes
# 4 languages, Braingolf, 2col, arcplus, Lean Mean Bean Machine

```
 O
 2
+$
_/
1_
;
(p
4)
3

```

That's right! I've successfully created a polyglot of all of my own languages!

# Braingolf, A000012, the all 1s sequence.

Try it online!

Braingolf usually has implicit output of the top of the stack at program termination, but the semicolon prevents that. As a result, the only important code is this:

```
1_
;

```

`1_` pushes 1, then pops and prints the top of the stack, while `;` suppresses implicit output. There are no other braingolf print operators in the code, so nothing else is printed.

However it's a little more difficult than that, as polyglots tend to be. The `$` on line 3 is LMBM's "print value" operator, but is Braingolf's "silent" operator. This means that normally the `$` would "silence" the `_` in Braingolf, and cause it to silently pop the top of the stack. As a result we throw in an extra line:

```
_/

```

The slash is explained under LMBM, but the underscore is for Braingolf, it pops the top of the stack *before* we push the 1, consuming the silent operator in the process. This allows our `1_` to function as expected.

# 2col, A010701, the all 3s sequence.

Try it in 2collIDE!

2col is to blame for the peculiar layout of the code, as 2col requires every line to be no more than 2 characters in width. Some of these lines do some weird stuff in 2col, but ultimately as there is no valid 2col print operator in this code, the implicit output kicks in and outputs the return value of the last line.

```
3

```

This is the last line, an integer literal, which returns itself.

2col is also the cause of the `+` on line 3. This does nothing, but prevents 2col throwing a TypeError when trying to execute the `$` command.

# arcplus, A010709, the all 4s sequence.

Try it online! (code not included)

arcplus is inspired by arcyou, which is inspired by LISP. arcplus ignores everything not in parentheses. Here's the bit in parentheses:

```
(p
4)

```

This is a function call. Specifically the `p` function, which is shorthand for `print`. Any whitespace is valid separator between the function name and the argument, including a newline, so this is essentially `(print 4)`. I hope I don't need to explain what that does.

# Lean Mean Bean Machine, A007395, the all 2s sequence.

*No online interpreter available*

This one was surprisingly easy, despite being a rather awkward 2d language. Here's what matters for LMBM:

```
 O
 2
+$
_/
1_
;

```

`O` is a spawn point. A marble is spawned here with a spin of 1, and a value of 0. It hits the 2, setting its value to 2, then hits the `$`, printing its value. The `/` moves the marble one space to the left, and changes its spin to 0, *note that the underscore to the left of the slash is not executed, as "gravity" takes effect after the left shift before the marble has time to execute another symbol.* The marble then drops to 1, setting its value to 1, and finally hits the semicolon, silently killing the marble. LMBM terminates once all marbles are destroyed.

# Answer
> 2 votes
# 30 languageversions, 4 bytes

```
B3%0

```

This works with 30 different versions (cube sizes) of Cubically.

# I promise I'm not cheating!

However, I'd appreciate it if this answer didn't get accepted. There are other more impressive polyglots, including my other (previously winning) one.

> Language (Python 2/3) revisions do count as different languages. Different implementations of a language (such as Browser JS vs Node.js) also count as different languages.

This works in 30 different cube sizes a.k.a. versions of Cubically. I added support for multiple cube sizes last night and made changes live this morning. Each cube size is considered a different language version due to the fact that each cube size *completely* changes how math is done in the language.

I realized afterwards that this feature is very useful for polyglotting. As making the change was very difficult, useful for lots of things, and required hours of messing with dynamic memory in C, I clearly did not add it just for that reason.

# Explanation

`B3` turns the BACK face 90° clockwise three times. In Cubically 3x3x3, faces have nine cubelets (three per line), so this gets the cube to look like this:

```
   111
   000
   000
511222330444
511222330444
511222330444
   555
   555
   333

```

That's useful, because in Cubically 4x4x4, it looks like this:

```
    1111
    0000
    0000
    0000
5111222233304444
5111222233304444
5111222233304444
5111222233304444
    5555
    5555
    5555
    3333

```

# Run-down

```
Version   Sequence
2x2x2     A007395
3x3x3     A010701
4x4x4     A010709
5x5x5     A010716
6x6x6     A010722
7x7x7     A010727
8x8x8     A010731
9x9x9     A010734
10x10x10  A010692
...       ...
32x32x32  A010871

```

Looks like the constant sequences *finally* stopped at 32. Seems random but there you are.

# Answer
> 0 votes
# C89, C99, C++, Bash, Python

Look, ma, no esolangs!

```
#include<stdio.h>/*
"""
"; */int x=32//*
/4+//* */
4;/*
echo 3;exit
"""
#*/
#define print(y)main(){printf("%d",x-(int)sizeof(' '));}
print(2)

```

This prints:

# C89

Single-line comments did not exist in C89, so it sees this:

```
#include<stdio.h>

     int x=32/

4;

#define print(y)main(){printf("%d",x-(int)sizeof(' '));}

```

So `x` is 8, `sizeof(' ')` is 4, outputs 4.

# C99

Single-line comments *did* exist in C99, so it sees this:

```
#include <stdio.h>

     int x=32
/4+
4;

#define print(y)main(){printf("%d",x-(int)sizeof(' '));}

```

So `x` is set to 12, `sizeof(' ')` is 4, output is 8.

# C++

C++ sees the same thing as C99 but `sizeof(' ')` is 1. Outputs 11.

# Bash

Bash sees this:

```
"""
"; */int x=32//*
/4+//* */
4;/*
echo 3;exit

```

Okay, so those first four lines cause a lot of parsing errors. Other than that, prints 3.

# Python

Python sees this:

```
print(2)

```

Everything else is commented out one way or another. Prints 2.

---
Tags: code-challenge, sequence, polyglot, rosetta-stone
---


title: Prison Architect, ASCII version

text:
# Question
Title: Prison Architect, ASCII version
Here is a diagram of a prison using ASCII characters:

```
+------------------------------+
|                              |
|   X               X          |
|                              |
|                              D
D                              |
|                              |
|                              |
|        X           X   X     |
|                              |
+------------------------------+

```

Walls are made out of pipe characters `|`, dashes `-`, and pillars `+` for corners and intersections. There are also two doors marked with `D` (which will always be on the left and right walls). The prison is filled with scary people marked with `X`.

The goal is to build walls to satisfy the following:

1. Each person is in solitary confinement;
2. There is a corridor running between the two doors;
3. Each cell contains exactly one door, which is directly connected to the main corridor;
4. All space in the prison is used by the cells and the corridor;
5. Each cell contains a person (that is, there are no empty cells).

The corridor is a single path, doesn't branch off, and is always one character wide. Here's a solution for the prison above:

```
+---------+--------------------+
|         |                    |
|   X     |         X          |
|         |           +--------+
+------D--+-----D-----+        D
D                       +---D--+
+----D--------+---D-----+      |
|             |         |      |
|        X    |      X  |X     |
|             |         |      |
+-------------+---------+------+

```

You can assume that any input prison will always have a valid output. Here are some more input prisons, along with possible outputs:

```
+------------------------------+
|X X X X X X X X X X X X X X X |
|                              |
D                              D
|                              |
|              X               |
+------------------------------+

+-+-+-+-+-+-+-+-+-+-+-+-+-+-+--+
|X|X|X|X|X|X|X|X|X|X|X|X|X|X|X |
+D+D+D+D+D+D+D+D+D+D+D+D+D+D+D-+
D                              D
+----------------------D-------+
|              X               |
+------------------------------+

+-----------+
|X          |
|           |
|           |
|X         X|
|           |
|          X|
|           |
D           D
+-----------+

+-+-------+-+
|X|       D |
| D +---+ | |
+-+ |     | |
|X| | +---+X|
| | | |   +-+
| D | |    X|
+-+ | +-D---+
D   |       D
+---+-------+

+----------------+
|X    X    X    X|
|                |
D                |
|                |
|X    X    X     |
|                |
|                |
|                |
|     X    X     D
|                |
|                |
+----------------+

+---+---+----+---+
|X  | X |  X |  X|
+--D+--D+---D+--D+
D                |
+---+---+------+ |
|X  | X |  X   | |
+--D+--D+---D--+ |
|                |
| +-----+------+-+
| |   X |  X   | D
| +----D+---D--+ |
|                |
+----------------+

```

# Answer
> 15 votes
# Python 2, ~~2986~~ ~~2881~~ ~~2949~~ ~~2135~~ ~~2075~~ ~~2071~~ 1996 bytes

* Saved 105 bytes, implemented the program as a function to comply with standard rules. Implemented Wheat Wizard's tab and space suggestion.
* Added 68 bytes due to fixing a bug.
* Saved 814+51 bytes thanks to Halvard Hummel.
* Saved 9+4 bytes.
* Saved 4 bytes thanks to Erik the Outgolfer.
* Saved 71 bytes thanks to ppperry's suggestion.

```
exec r"""def Z(P):
 H,n,I,o,O,i,d,D,W=[type,range]+list(" dD#xX*");R=(1,0),(-1,0),(0,1),(0,-1)
 def F(j,k,l):P[j][k]=l
 def E(j,k,v,w):
	if G(j,k,v):F(k,j,w)
 def q(b,c,d):[[E(j+J,k+K,b,c)for J,K in M]&L if G(j,k,d)]
 def A(e,r,l,o,q):
	S,E,P[q][o],Q,X=P[q][o],e,0,[(o,q)],0
	for a,b in Q:
	 &R:
		x,y=a+j,b+k
		if(0<=x<w!=0<=y<h)<1:continue
		if e in((x,y),P[y][x]):X=1;e=x,y;break
		if I!=P[y][x]:continue
		F(y,x,P[b][a]+1);Q+=[(x,y)]
	 if X:break
	p,i=e,0
	while(o,q)!=p:
	 a,b=p;P[b][a],m=[r,l][l and i==1],0
	 &R:
		x,y=a+j,b+k
		if(0<=x<w!=0<=y<h)-1:continue
		if(H(P[y][x])==H(0))*(m==0 or P[y][x]<P[m[1]][m[0]]):m=x,y
	 p=m;i+=1
	P[q][o],P[e[1]][e[0]]=S,E;[F(k,j,I)&L if H(P[k][j])==H(0)]
 def B(N):
	[[E(j,k,"x*",I),0<j<w-1 and E(j,k,O,I)]&L]
	&L:
	 if G(j,k,D):[E(j+J,k+K,I,d)for J,K in M]
	 if G(j,k,O)and j==0:T=0,k
	if N:A(O,o,0,*T)
	U,V=M[-1];[[[F(k+K,j+J,I)for J,K in M if(P[k+K][j+J]!=i)*((0<=j+J+U<w!=0<=k+K+V<h and G(j+J+U,k+K+V,D))<1)],F(k,j,W),A(o,W,O,j,k),q(I,d,W),F(k,j,D)]&L if G(j,k,D)];q("xX*# @+-|",i,o)
 for j in"|+-":P=P.replace(j,i)
 P=list(map(list,P.split("\n")));h=len(P);w=len(P[0]);b,L,M,G="#+-|D",[(k,j)for k in n(w)for j in n(h)],[(k-1,j-1)for k in n(3)for j in n(3)if(j,k)!=(1,1)],lambda j,k,v:P[k][j]in v
 B(1);Y=lambda:0<j<w-1!=0<k<h-1and G(j,k,i);[[[F(k,j,o),F(k+g,j+N,i)]for N,g in((-1,-1),(-1,1),(1,-1),(1,1))if P[k][j+g]+P[k][j-g]==P[k+N][j+g]+P[k-N][j]==P[k+N][j]+i==o+i]&L if(j in(1,w-2)or k in(1,h-2))*Y()for N in n(w*h)];[F(k,j,I)&L if Y()];B(0)
 def c(x,y,b,l,d,f,Q):
	F(y,x,b)
	for J,K in M:Q+=[[],[(x+J,y+K)]][G(x+J,y+K,l)];E(x+J,y+K,d,f)
 &L:
	if G(j,k,D):Q=[(j,k)];[c(x,y,"@",W,d,I,Q)for x,y in Q if G(x,y,"X*")];[G(u,v,"X*")and[E(u+U,v+V,I,d)for U,V in M]or E(u,v,"@",I)for u,v in L];Q=Q[:1];[c(x,y,"$",I,"x*",i,Q)for x,y in Q];F(k,j,D)
 &L:E(j,k,"@$d",I);X=(k>0and G(j,k-1,b))+(k<h-1and G(j,k+1,b))-(j>0and G(j-1,k,b))-(j<w-1and G(j+1,k,b));E(j,k,i,{2:"+",X:"|",-X:"-"}[2])
 print"\n".join("".join(p)for p in P)""".replace("&","for j,k in ")

```

Try it online!

It was golfed down significantly; yet there may still be room for improvement. This piece of code, however, solves all test cases. Does not run very efficiently; for large prisons the architect may take their time to figure it out.
Uses a simple pathfinding algorithm to connect both doors and the prisoners to the corridor. Then it encapsulates all prisoners and their walls and pushes said walls in empty space until all of it is filled. As a final step, the ASCII art appearance is implemented.

Took me for sure several hours to write. I hope it also works on other prisons than the test cases. (You cannot test them all, can you?)

# Answer
> 4 votes
## C, ~~3732~~ 3642 bytes

I could definitely golf this a bit further, but it is a pretty nice start. I did not initially know that my approach had a name so shout out to @TehPers for giving me a name to research. I definitely enjoyed the challenge that this question offered. :)

-63 bytes from @Jonathan's suggestions. I also replaced `char` with `typedef char R` and replaced all character literals that are smaller than 100 with their ASCII values for a total of 90 bytes

A quick explanation of my code.

1. Convert char array to an ideal integer array (0 is space, 1 is wall, etc.)
2. Generate the Voronoi diagram using the people as the points
3. Use the intersections (a 5 surrounded by at least three other 5s) as pivot points for the path
4. Create the corridor using a directionally biased path finding algorithm (if it's going one way, favor paths that do not change direction). It also modifies the grid so that it favors traveling next to an already made corridor.
5. Regenerate diagram to place final walls. Ensures that all space is used.
6. Convert map back to a properly formatted ASCII representation and print.

To use this program, pass the map as either a string with newline characters or with each level seperated by a space as in the following example.

```
program-name.exe "+-----------+ |X          | |           | |           | |X         X| |           | |          X| |           | D           D +-----------+ "

+------+----+
|X     |    |
|    +D+-+  |
+----+   |  |
|X   | + D X|
|    | | +--+
|    | | | X|
+D---+ | +-D+
D      |    D
+------+----+

```

code

```
typedef int Q;typedef char R;typedef struct{Q x,y,v;}P;w,h,A,Y,Z,x,y,i,j,e,f,m,n,v;P*t,*u,*s;I(R*a,Q x,Q y,R c){a[x+y*w]=c;}G(Q*a,Q x,Q y){if(x>-1&&x<w&&y>-1&&y<h)return a[x+y*w];return-1;}J(Q*a,Q x,Q y,Q c){a[x+y*w]=c;}P*E(Q n,Q*a,Q*c){P*r=0;for(i=v=0;i<A;i++)if(a[i]==n)r=(P*)realloc(r,sizeof(P)*(v+1)),r[v].x=i%w,r[v].y=i/w,r[v].v=v,*c=++v;return r;}C(Q*a,Q x,Q y,Q b){return(G(a,x-1,y)==b)+(G(a,x+1,y)==b)+(G(a,x,y-1)==b)+(G(a,x,y+1)==b);}H(Q*a,Q b){P q[A],r[A];m=Y,n=0;for(i=0;i<Y;i++)q[i]=t[i];while(m){while(m){x=q[m-1].x,y=q[m-1].y,v=q[m-1].v;i=G(a,x,y);if(i!=b&&i!=1){for(f=-1;f<2;f++){for(e=-1;e<2;e++){i=G(a,x+e,y+f);if(i==0){J(a,x+e,y+f,v+8);r[n].x=x+e;r[n].y=y+f;r[n].v=v;n++;}else if(i>=8&&i!=v+8)J(a,x+e,y+f,b);}}}m--;}for(i=0;i<n;i++)q[i]=r[i];m=n;n=0;}}B(P p,Q*a,Q*b){for(i=m=n=0;i<A;i++)if(b[i]>-2)b[i]=-1;P q[A],r[A];q[0]=p,q[0].v=0,b[p.x+p.y*w]=0;while(m+1){while(m+1){x=q[m].x,y=q[m].y,v=q[m].v;for(f=-1;f<2;f++){for(e=-1;e<2;e++){if(e!=0&&f!=0||(x+e<0||x+e>=w||y+f<0||y+f>=h))continue;i=G(a,x+e,y+f);if(i!=7&&i!=1&&i!=0){j=3;if(i==4||i==5)j=1;if(x+e!=p.x&&y+f!=p.y)j++;Q*p=&b[x+e+(y+f)*w];if(*p!=-2&&(*p==-1||*p>v+j)){*p=v+j;if(i!=2)r[n].x=x+e,r[n].y=y+f,r[n].v=v+j,n++;}}}}m--;}for(i=0;i<n;i++){q[i]=r[i];}m=n-1,n=0;}}D(P S,P*T,Q n,P U,Q*a){Q m[A];Q x,y,v=0,c=0,d=1,d1=1;for(i=0;i<n;i++)T[i].v=0;for(i=0;i<A;i++)m[i]=-1;x=S.x,y=S.y;if(n==0){B(U,a,m);goto fin;}while(v<n){j=-1;for(i=0;i<n;i++)if(T[i].v==0)if(j==-1||abs(T[i].x-x)+abs(T[i].y-y)-(T[i].x==x)*!d*2-(T[i].y==y)*d*2<abs(T[j].x-x)+abs(T[j].y-y)-(T[j].x==x)*!d*2-(T[j].y==y)*d*2)j=i;T[j].v=1;B(T[j],a,m);fin:v++;c=m[x+y*w];while(c>0||c==-1){Q tx,ty;j=-1;for(f=-1;f<2;f++){for(e=-1;e<2;e++){if(e!=0&&f!=0)continue;if(x+e<0||x+e>=w||y+f<0||y+f>=h)continue;i=G(m,x+e,y+f);if(i>-1&&(i<c||c==-1)){if(j==-1||j>i||((e*d||f*!d)&&j==i)){j=i;tx=x+e,ty=y+f;d1=e!=0;}}}}J(m,x-1*!d1,y-1*d1,-2);J(m,x+1*!d1,y+1*d1,-2);d=d1;x=tx,y=ty,c=j;if(G(a,x,y)!=2)J(a,x,y,0);}for(f=0;f<h;f++)for(e=0;e<w;e++)if((i=G(a,e,f))>3&&i!=7)if(C(m,e,f,-2))J(a,e,f,5);if(v==n){B(U,a,m);goto fin;}}}main(Q c,R**v){R*a=v[1];w=strchr(a,'|')-a;h=(strchr(a+w,43)-a)/w+1;A=w*h;Q p[A];for(y=0;y<h;y++)for(x=0;x<w;x++){c=a[x+y*w];J(p,x,y,0);if(c==45||c=='|'||c==43)J(p,x,y,1);if(c==68)J(p,x,y,2);if(c==88)J(p,x,y,3);}t=E(3,p,&Y);u=E(2,p,&Z);H(p,5);for(c=0;c<Y;c++)for(y=-1;y<2;y++)for(x=-1;x<2;x++)if(G(p,t[c].x+x,t[c].y+y)>=4)J(p,x+t[c].x,y+t[c].y,7);for(y=1;y<h-1;y++)for(x=1;x<w-2;x++)if(G(p,x,y)==5)if(C(p,x,y,5)>2)J(p,x,y,4);s=E(4,p,&c);for(i=0;i<c;i++)s[i].v=0;for(y=1;y<h-1;y++)for(x=1;x<w-2;x++)if(G(p,x,y)>=8)if(C(p,x,y,5))J(p,x,y,4);i=u[0].x!=0;D(u[i],s,c,u[!i],p);for(y=0;y<h;y++){for(x=0;x<w;x++){i=0;if(G(p,x,y)>2){for(f=-1;f<2;f++)for(e=-1;e<2;e++)i+=G(p,x+e,y+f)==0;if(i>0)J(p,x,y,6);}}}free(s);for(i=0;i<A;i++)if(p[i]>=7||p[i]==4||p[i]==5)p[i]=0;for(y=0;y<h;y++){for(x=0;x<w-1;x++){if((x==0||x==w-2||y==0||y==h-1)&&G(p,x,y)!=2)J(p,x,y,1);}}H(p,1);P q[A],r[A];for(i=0;i<Y;i++){m=1,n=0;q[0]=t[i];while(m){while(m){x=q[m-1].x,y=q[m-1].y;for(f=-1;f<2;f++){for(e=-1;e<2;e++){if(e!=0&&f!=0)continue;c=G(p,x+e,y+f);if(c==6){if(G(p,x+e*2,y+f*2)==0){J(p,x+e,y+f,2);m=1,n=0;e=f=2;}}else if(c!=1&&c!=3&&c!=7){J(p,x+e,y+f,7);r[n].x=x+e;r[n].y=y+f;n++;}}}m--;}for(c=0;c<n;c++)q[c]=r[c];m=n;n=0;}}for(i=0;i<A;i++)if(p[i]==6)p[i]=1;R b[A];for(y=0;y<h;y++){for(x=0;x<w;x++){c=G(p,x,y);I(b,x,y,32);if(c==1){i=0;if(G(p,x,y-1)==1||G(p,x,y-1)==2)i|=1;if(G(p,x,y+1)==1||G(p,x,y+1)==2)i|=2;if(G(p,x-1,y)==1||G(p,x-1,y)==2)i|=4;if(G(p,x+1,y)==1||G(p,x+1,y)==2)i|=8;if(i==3)I(b,x,y,'|');else if(i==12)I(b,x,y,45);else I(b,x,y,43);}if(c==2)I(b,x,y,68);if(c==3)I(b,x,y,88);if(x==w-1)I(b,x,y,10);}}b[A-1]=0;puts(b);}

```

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


title: Smallest unseen, but no sharing digits!

text:
# Question
Title: Smallest unseen, but no sharing digits!
## Challenge

Here at PPCG, we sure do like our sequences, so here's ~~a fun~~ another one.

Let's define `a(n)` as being *the smallest non-negative integer `X` that is not equal to any `a(k)` (`0 < k < n`), and `a(n-1)` and `X` do not share any decimal digits. `a(0) = 0`*

Given an input `n > 0`, output such `a(n)`.

For example, for input `n = 13`, we have `a(13) = 20`, since `a(12) = 11` and `20` is the smallest non-negative integer we haven't seen yet that doesn't share any decimal digits with `11`.

## Sequence

Here are the first 20 terms to get you started. This is sequence A067581 on OEIS.

```
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 22, 11, 20, 13, 24, 15, 23, 14, 25

```

## Rules

* The input and output can be assumed to fit in your language's native integer type.
* The input and output can be given in any convenient format.
* You can choose to either 0-index, as I am here in my examples, or 1-index for your submission. Please state which you're doing.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# Python 2, 85 bytes

<sup>-1 byte thanks to Dead Possum </sup>

```
n=0,
exec"i=0\nwhile set(`i`)&set(`n[-1]`)or i in n:i+=1\nn+=i,;"*input()
print n[-1]

```

Try it online!
> 10 votes

# Answer
# Japt, 18 bytes

```
@A{!ZøA «As oX}a}g

```

Test it online! I've just added the `g` feature used here, but it's something I've been meaning to add for a long time (and this pushed me over the edge, because my non-`g` solution was around 35 bytes).

### Explanation

```
@   A{!ZøA «  As oX}a}g
XYZ{A{!ZøA &&!As oX}a}gU
                           Implicit: U = input integer
   {                 }gU   Starting with [0, 1], return the U'th item generated by
XYZ{                 }     this function: (X = previous item, Y = index, Z = full array)
    A{             }a        Return the smallest non-negative integer A where
      !ZøA &&                  Z does not contain A (A is not yet in the sequence), and
             !As oX            A.toString() does not contain any of the same chars as X.
                           Implicit: output result of last expression

```
> 7 votes

# Answer
# Pyth, 20 bytes

```
eu+Gf!|/GT@`eG`T0Q]0

```

Try it online! or Try the test suite.
> 5 votes

# Answer
## Haskell, 79 bytes

```
f 0=0
f x=[i|i<-[1..],all((/=i).f)[1..x-1],all(`notElem`show(f$x-1))$show i]!!0

```

The code is horribly inefficient. To calculate bigger values, i.e. \> 12, add `f x|x<11=x` between the two lines (implemented a `g` in the TIO link).

Try it online!
> 3 votes

# Answer
## Husk, 18 bytes

```
!¡₁;0
ḟȯ¬V€d→⁰d-⁰N

```

A 1-indexed solution. Try it online!

*Edit:* fixed bug for +1 byte.

## Explanation

Husk's built-in iteration function `¡` has many meanings. Here, I'm using "construct infinite list by repeatedly appending new elements computed from the existing ones". The second line is the helper function that computes a new element:

```
ḟȯ¬V€d→⁰d-⁰N  Takes a list of existing elements, e.g. x = [0,1,...,10]
           N  The positive integers
         -⁰   with elements of x removed:        [11,12,13,...
ḟȯ            Find an element n of this list that satisfies:
        d     Digits of n.
   V          Is any of them
    €         an element of
     d        the digits of
      →⁰      the last element of x?
  ¬           Negate.
              Returns 22.

```

The first line is the main function:

```
!¡₁;0  Takes an integer k.
 ¡     Iterate adding new elements to the list
   ;0  [0]
  ₁    using the helper function,
!      take k'th element of result.

```
> 1 votes

# Answer
## JavaScript (ES6), 82 bytes

0-indexed.

```
f=(n,x=[1,p=0])=>n--?f(x[(g=k=>x[k]||(k+'').match(`[${p}]`)?g(k+1):p=k)(0)]=n,x):p

```

### Demo

```
f=(n,x=[1,p=0])=>n--?f(x[(g=k=>x[k]||(k+'').match(`[${p}]`)?g(k+1):p=k)(0)]=n,x):p

for(n = 0; n < 50; n++) {
  console.log('a(' + n + ') = ' + f(n))
}
```
> 1 votes

# Answer
## Haskell, 78 bytes

```
n!k|r:_<-[j|j<-[1..],all(/=j)k,all(`notElem`show n)$show j]=n:r!(r:k)
(0![]!!)

```

It would be even more efficient if the second argument to `!` would not be the list of seen numbers but of unseen numbers. But I can't do that without using more bytes.

Try it online!
> 1 votes

# Answer
## Mathematica 115 Bytes

Still room to golf this down - and maybe use recursion (thus speeding it up).

```
(For[z={0};i=1,Length@z<#,
For[i=1,!FreeQ[z,i]||!DisjointQ@@IntegerDigits/@{l,i},i++];
z~AppendTo~i;l=Last@z;
];l)&

```

Original verbose code, with the same basic idea:

```
MakeSequenceA067581[n_]:=Module[{list={0}, innerCounter=1},

While[Length@list<n,
innerCounter=1;
(* inner loop *)While[Or[MemberQ[list,innerCounter],Intersection[IntegerDigits[Last@list],IntegerDigits[innerCounter]]!={}],innerCounter++];
AppendTo[list,innerCounter];
];
list
]

```
> 0 votes

---
Tags: code-golf, math, number, sequence, number-theory
---


title: Determining vertical slices

text:
# Question
Title: Determining vertical slices
Given an image, output the \[width in pixels of a full vertical section\]1 (if one exists). If no vertical section exists, output `0`.

Input may be provided as a local file or a nested array. If you choose to take input as a nested array, white pixels should be represented by a truthy value while non-white pixels should be represented by a falsey value.

1. the number of contiguous, all-white columns

---

You can assume that

* no image will be larger than 1000 square pixels
* there will be no more than one full vertical section per image

---

## Examples

Inputs:

Outputs:

```
50
57
0
0

```

Here are the first two examples, highlighted (in yellow) to show their sections:

# Answer
> 36 votes
# Jelly, 2 bytes

```
PS

```

Try it here!

If I encode an image like so:

```
0000111111111100000
0000000111111111000
0000000001111100000
0000000011111000000
0001111111111111100
0000001111110000000
0000000111111110000
0000111111111100000

```

Into a nested array like this:

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

```

Then `P` takes the element-wise product of all of the row vectors, and `S` sums all of the ones in the result, yielding the length of the vertical slice. (This works only because there’s guaranteed to be only one contiguous slice.) In our case, the answer is `3`.

# Answer
> 7 votes
# APL, 4 bytes

```
+/×⌿

```

`Try it here.`

This is my first APL answer!

Thanks to @jimmy23013 and @NBZ for saving bytes!

# Answer
> 6 votes
# Perl, ~~21~~ 22 bytes

## Fixed version

Includes +2 for `-lp` (`-l` can be omitted and would still be a valid solution, but it's ugly without the final newline)

Give sequences of 1's and 0's on 0 or more lines on STDIN. You can add spaces or commas or whatever between the digits if you want as long as the usage is.consistent on all lines.

```
$a|=~$_}{$_=$a=~y;\xce;

```

This works as shown, but replace `\xce` by the literal byte value to get the claimed score

If there are multiple vertical sections this returns the sum of all section widths. If you want the width of **a** vertical section use

```
$a|=~$_}{$a=~/\xce+/;$_="@+"-"@-"

```

## Old version

I originally misunderstood the challenge and implemented a program that gives true or false based on if a vertical line exists at all. Code and explanation here are for this old version

```
$a|=~$_}{$_|=~$a=~1

```

If only I could add 1=~ at the left for almost perfect symmetry... I suppose the closest would be

```
1=>$a|=~$_}{$_|=~$a=~1

```

## Explanation

```
$a|=~$_     The bitwise operators in perl (&, |, ^, ~) also work on strings by
            working on the sequence of byte values. The digits "0" and "1" happen
            to have the same ASCII value differing only in the last bit which is
            0 for "0" and 1 for "1". So I would really like to do an "&" here.
            Unfortunately "&" of two different length strings shortens the result
            to the shortest of the strings and my accumulator starts as an empty
            string. The "|" of two strings however extends to the longest string.
            So instead I will apply De Morgan's law and use "|" on the
            complemented byte string
}{          Standard perl golf trick. "-p code" transforms to (simplified)
            "while (<>) { code; print }". So if code is "code1 } { code2" this
            becomes "while (<>) { code1 } {code2; print }". So you can use code1
            for the loop operation, use code2 for the final calculation and get a
            free print by assigning to $_
$_|=~$a=~1  I would like to match the accumulator with the bit complement of "1",
            but $a=~~1 doesn't work because the 1 is not a string but a number.
            $a=~~"1" would work but is too long. Next up is complementing $a back
            and matching with 1, so $_=~$a=~1. That also doesn't work since the
            first =~ will be interpreted as a string match insteads of equals
            followed by complement. Easily solved by writing it as $_= ~a=~1. But
            if I am going to give up a byte I can at least have some fun with it.
            Using $_|= also makes the parse work and has the advantage that the
            failure case will give 0 instead of an empty string, which looks
            nicer. It also makes the code look very symmetric. I can also bring
            out the symmetry more by putting 1=> in front (which evaluates 1
            before the assignment and then immediately discards it)

```

# Answer
> 6 votes
# Bash + common utilities, 17

```
rs -Tc|grep -vc 0

```

If you're not using `grep` for , then you're doing it wrong ;-).

This uses the `rs` utility to do transposition. `rs` is bundled in OSX, but will need installing in most linux with something like `sudo apt-get install rs`.

Input columns are `TAB` separated, and rows are newline separated:

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

```

If you like, you can preprocess the example input images into this format with imagemagick and (GNU) sed. E.g:

```
$ for img in "AmXiR.jpg" "vb2Yt.jpg" "1V7QD.jpg" "MqcDJ.jpg" ; do
>     convert -depth 1 "$img" xpm:- | \
>     sed -nr '/pixels/{:l;n;/}/q;s/^"(.*)",?$/\1/;y/ ./01/;s/./&\t/g;p;bl}' | \
>     rs -Tc|grep -vc 0
> done
50
57
0
0
$

```

# Answer
> 4 votes
## JavaScript (ES6), ~~54~~ ~~45~~ 43 bytes

```
a=>a[s=0].map((_,i)=>s+=a.every(b=>b[i]))|s
a=>a[s=0].map((_,i)=>s+=!a.some(b=>b[i]))|s

```

Based on @Lynn's Jelly answer, though since golfed by using `every` or `some` instead of `reduce`. The first version encodes black = 0 while the second encodes black = 1.

Edit: Saved 2 further bytes thanks to @edc65.

# Answer
> 4 votes
# Python 2, 30 bytes

There is a surprisingly elegant solution using many of my favourite built-in functions chained together.

```
lambda c:sum(map(all,zip(*c)))

```

Using the test image from @Lynn:

```
>>> image = [[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]]
>>> func = lambda c:sum(map(all,zip(*c)))
>>> func(image)
3

```

# Answer
> 4 votes
# Pyth, 5

```
s*VFQ

```

Try it here

This uses Lynn's algorithm, but I decided to post it just to show how to golf vector operations in Pyth. The trick here is to chain the "sugar" syntax helpers `V` and `F` so that the fold is applied as a vector operation. The operator that is folded is of course multiplication, and then the result is summed to get the final answer.

# Answer
> 4 votes
# , ~~5~~ 6 bytes

Takes Boolean matrix as argument.

```
[:+/*/

```

This is my first J answer! (was wrong for 1½ years…)

`*/` columnwise product

`+/` sum

`[:` cap (serves as placeholder since `+/` should not take a left argument)

Try it online!

# Answer
> 3 votes
# CJam, 7 bytes

```
q~:.*:+

```

**Try it online!**

```
q~      e# read input and evaluate: push nested array
:.*     e# fold vectorized product over nested array: element-wise product of rows
:+      e# fold addition over array: compute its sum

```

# Answer
> 2 votes
## Mathematica 24

```
Length@Cases[Total@#,0]&

```

Takes an array in the following form:

```
{{1, 0, 0, 0, 1, 0},
{1, 0, 0, 1, 1, 1},
{1, 1, 0, 0, 0, 0},
{1, 1, 0, 0, 1, 1},
{1, 0, 0, 1, 1, 1}}

```

And in this case outputs:

```
1

```

# Answer
> 1 votes
# , 7 chars / 9 bytes

```
⨭МƟïⓜ⨴$

```

`Try it here (Firefox only).`

This is @Lynn's great algorithm, but I found it independently. (I thought there was a builtin for this somewhere, still looking :P)

# Explanation

`МƟï` transposes the input array, `ⓜ⨴$` turns each inner vector into its product, and  sums the resulting array.

# Answer
> 1 votes
# Japt, ~~6~~ 4 bytes

Takes input as an array of rows, with `1` being white and `0` being black.

```
y xe

```
* 2 bytes saved thanks to ETH.

Test it

---

## Explanation

```
y xe
          :Implicit input of array U.
y         :Transpose.
   e      :Map over each sub-array, checking if every element is truthy.
  x       :Reduce by summing, converting booleans to 1 or 0.
          :Implicit output of resulting integer.

```

---
Tags: code-golf, image-processing
---