title: What associativity was it again

text:
# Question
Title: What associativity was it again
Non-associative operators (for example the subtraction-operator) often are either left- or right associative, such that one has to write less parentheses. Consider for example the following:

$$ a-b-c $$

Probably everybody read that as \\$(a-b)-c\\$, by default (usually) subtraction is left-associative.

Now let us consider some operation \\$\diamond: X \times X \to X\\$, the only thing we know about it is that it is not associative. In this case the following is ambiguous:

$$ a \diamond b \diamond c $$

It could either mean \\$(a \diamond b) \diamond c\\$ or it could mean \\$a \diamond (b \diamond c)\\$.

## Challenge

Given some possibly parenthesised expression that is ambiguous, your task is to parenthesise it such that there is no ambiguity. You can chooose freely whether the operator should be left- or right associative.

Since there is only one operation the operator is only implied, so for the above example you'll get `abc` as input. For left-associative you'll output `(ab)c` and for right-associative you'll output `a(bc)`.

## Input / Output

* Input will be a string of at least 3 characters
    + the string is guaranteed to be ambiguous (ie. there are missing parentheses)
    + you're guaranteed that no single character is isolated (ie. `(a)bc` or `a(bcd)e` is invalid input)
    + the string is guaranteed to only contain alphanumeric ASCII (ie. `[0-9]`, `[A-Z]` and `[a-z]`) and parentheses (you may choose `()`, `[]` or `{}`)
* Output will be a minimally1 parenthesized string that makes the string unambiguous
    + as with the input you may choose between `()`, `[]`, `{}` for the parentheses
    + output may **not** contain whitespace/new-lines, except for leading and trailing ones (finite amount)

## Test cases

These use `()` for parentheses, there is a section for each associativity you may choose (ie. left or right):

### Left associative

```
abc -> (ab)c
ab123z -> ((((ab)1)2)3)z
ab(cde)fo(0O) -> ((((ab)((cd)e))f)o)(0O)
(aBC)(dE) -> ((aB)C)(dE)
code(Golf) -> (((co)d)e)(((Go)l)f)
(code)Golf -> ((((((co)d)e)G)o)l)f

```

### Right associative

```
abc -> a(bc)
ab123z -> a(b(1(2(3z))))
ab(cde)fo(0O) -> a(b((c(de))(f(o(0O)))))
(aBC)(dE) -> (a(BC))(dE)
code(Golf) -> c(o(d(e(G(o(lf))))))
(code)Golf -> (c(o(de)))(G(o(lf)))

```

---

1: Meaning removing any pair of parentheses will make it ambiguous. For example `a(b(c))` or `(a(bc))` are both not minimally parenthesised as they can be written as `a(bc)` which is not ambiguous.

# Answer
> 3 votes
# Retina 0.8.2, 61 bytes

```
+1`(\(((\()|(?<-3>\))|[^()])+(?(3)$)\)|[^()]){2}(?=[^)])
($&)

```

Try it online! Link includes test cases. Explanation: I'd really like to use a recursive regex `(([^()]|\((?1)\)){2})(?=[^)])` here, but .NET only has balancing groups, so it's a bit verbose.

```
+1`

```

Repeatedly replace the first match each time. This ensures left-associativity.

```
(           Either
 \(          Match outer `(`
 (           Either
  (\()        Capture a `(` into $3
 |           Or
  (?<-3>\))   A `)` if it matched an earlier `(`
 |           Or
  [^()]       Something else
 )+          Match as much of the above as possible
 (?(3)$)     But don't leave `(`s unmatched
 \)          Match outer `)`
|           Or
 [^()]       Match something else
){2}        Match the above twice
(?=[^)])    Followed by a non-`)`

```

Either, a `(` followed by a string containing balanced `()`s, followed by a `)`, or a non-`()`, twice, followed by a non-`)`. This represents an ambiguous match.

```
($&)

```

Wrap the match in disambiguating parentheses.

# Answer
> 1 votes
# JavaScript (ES6), 128 bytes

```
f=([a,...s],c=q=p="",$=")")=>s[1]?a<$?s.map(t=>c||(t<$?++p:t>$||p--||(c=f(q),q=""))?q+=t:0)&&q?a+c+$+a+f(q)+$:c:a+"("+f(s)+$:a+s

```

Recognizes `()` as parentheses, and outputs a right-associative expression. Test cases additionally include nested parentheses.

Try it online!

## Explanation

Recursively disambiguates sub-expressions within parentheses given in the input. To track nesting depth, it increments the variable `p` upon encountering a left paren (following the initial opening paren). A right paren decrements the counter, and if `p = 0` prior to decrementing, the function recurs on the accumulated sub-expression. A quick visual:

```
(ab(cd(ef)gh)ij)
0  1  2  1  0  = 0, so call function

```

When handling parentheses in inputs, i.e. the first character is a `(`, it partitions the input into the enclosed sub-expression and everything following the matching paren, e.g. `(cd)ef` splits into `cd`, which is fed back into the function, and `ef`, both of which are subsequently wrapped in parentheses. If an enclosed sub-expression has no trailing characters, the result of recurring on it isn't wrapped in parentheses. `(cd)ef` -\> `(cd)(ef)` but `(cd)` -\> `cd`

**Ungolfed:**

```
f = (
    [a, ...s],                                       // destructure string, e.g. "abc" => "a", ["b", "c"]
    c = q = p = "",
    $ = ")"
) =>
    s[1] ?                                           // if input length > 2 ...
        a < $                                        //     if first char is ( ...
            ? s.map(t =>
                c                                    //         stores disambiguated sub-expression
                || (                                 //         if sub-expression not yet found...
                        t < $                        //             if char is ( ...
                            ? ++p
                        : t > $
                            || p--                   //             if char is ) and p = 0, e.g. outer closing paren found...
                            || (c = f(q), q = "")    //                 reset q to accumulate characters following the closing paren
                )                                    //         this expression returns a truthy value if should append current char (i.e. if t is not the final closing paren)
                    ? q += t
                    : 0
            )
                && q
                    ? a + c + $ + a + f(q) + $       //         a = "(", guaranteed by the conditional check
                    : c
            : a + "(" + f(s) + $
    : a+s                                            // since s has length 1, appending it simply appends its first value

```

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


title: Is the bus load legal?

text:
# Question
Title: Is the bus load legal?
I was in the bus today, and noticed this sign:

```
      seated    standing    wheelchairs
max1    37         30            00
max2    36         26            01
max3    34         32            00

```

The number of seated passengers, standees, and wheelchairs all have to be no larger than some row in the table. (See chat for details.)

For the purposes of this challenge we will generalise this idea: Given a non-negative integer list of a strictly positive length N (number of passenger types) and a non-negative integer matrix of strictly positive dimensions (N columns and one row per configuration, or the transpose of this), return a list of indices/truthy-falsies/two-unique-values indicating which configurations limits are fulfilled.

E.g. with the above matrix:
`30,25,1``[1]` (0-indexed) `[2]` (1-indexed) or `[false,true,false]` (Boolean) or `["Abe","Bob","Abe"]` (two unique values) etc.

The following test cases use the above matrix and the 0/1 for false/true:
`[30,30,0]``[1,0,1]`
`[30,31,0]``[0,0,1]`
`[35,30,0]``[1,0,0]`
`[0,0,1]``[0,1,0]`
`[0,0,0]``[1,1,1]`
`[1,2,3]``[0,0,0]`

The following test cases use the following matrix:
`1 2 0 4`
`2 3 0 2`

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

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

```
∧.≤

```

Try it online!

# Answer
> 6 votes
## Haskell, ~~22~~ 20 bytes

```
map.(or.).zipWith(>)

```

Returns `False` if legal and `True` if not.

Try it online!

Flipping True/False as return values saves 2 bytes (thanks @user202729!). With `True` for legal it's `map.(and.).zipWith(<=)` (22 bytes). Try it online!

# Answer
> 4 votes
# Octave, 15 bytes

```
@(a,b)all(a>=b)

```

Try it online!

As per sundar's comment, omitting the transpose saves 2 bytes.

# Answer
> 3 votes
# Jelly, 3 bytes

```
<Ẹ€

```

Try it online!

`0` = True, `1` = False.

# Answer
> 3 votes
# Ohm v2, 3 bytes

```
>Σy

```

Try it online!

Algorithm: vectorized `>` (greater than), `Σ` sum each, `y` sign.

# Answer
> 3 votes
# MATL, 3 bytes

```
<~A

```

Try it online!

Takes the input matrix as a transpose of the format in the question (as allowed by OP), with one column per configuration. Outputs boolean 0 and 1 for false and true.

# Answer
> 3 votes
# , ~~32~~ ~~30~~ 26 bytes

```
function(x,y)!colSums(x<y)

```

Try it online!

Accepts the matrix in transposed form as `x`, test config as `y`. Returns a vector of booleans.

Initial -2 bytes thanks to mnel, and further -4 by JayCe.

# Answer
> 2 votes
# JavaScript (ES6), 38 bytes

Takes input as `(matrix)(vector)`. Returns a Boolean array.

```
m=>v=>m.map(r=>!r.some((t,x)=>v[x]>t))

```

Try it online!

# Answer
> 2 votes
# Japt, ~~6~~ 5 bytes

*-1 bytes from @Shaggy*

```
eÈ¨Vv

```

Try it online!

# Answer
> 2 votes
# Haskell, 30 bytes

```
map.((.).(==)<*>(zipWith min))

```

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, 57 bytes

```
\d+
$*
;(?=.*;(.*))
;$1¶
%(+`,1*(1*)(;.*),\1$
$2
(1*);\1$

```

Try it online! Link includes test cases, but the output is all run together. Explanation:

```
\d+
$*

```

Convert to unary.

```
;(?=.*;(.*))
;$1¶

```

Give each row of the matrix its own copy of the list.

```
%(

```

Operate separately on each row of the matrix.

```
+`,1*(1*)(;.*),\1$
$2

```

Repeatedly remove the last number of the row and list while the last number of the row is at least as big as that of the list.

```
(1*);\1$

```

There should then be one number left in the list and the number in the row should be at least as big as that.

# Answer
> 1 votes
# Python 2, 38 bytes

```
lambda m,l:[l==map(min,l,r)for r in m]

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 5 bytes

```
εs<›P

```

Try it online or verify all test cases.

**Explanation:**

Unfortunately 05AB1E v1 doesn't have a 1-char builtin for  or , so I decrease each value instead before using . 05AB1E v2 which is currently in development will have these builtins.

```
ε        # For-each row of the (implicitly input) matrix:
 s       #  Swap, so the (implicitly input) list is at the top of the stack
  <      #  Decrease every value in the input-list by 1
         #   i.e. [30,25,1] → [29,24,0]
   ›     #  Check for each value in the matrix-row if they're larger
         #  than the input-list value at the same index
         #   i.e. [37,30,0] and [29,24,0] → [1,1,0]
    P    #  Then take the product of these checks
         #   i.e. [1,1,0] → 0

```

# Answer
> 1 votes
# Stax, 8 bytes

```
â ╤┘µrφî

```

Run and debug it

Explanation:

```
mx\{:vm|A Full program, unpacked, implicit input
m         Map over rows of the matrix:
 x\         Zip with input array
   {  m     Map over result:
    :v        Check if non-increasing, i.e. matrix element greater than or equal to array element
       |A   All.
            Implicit output

```

# Answer
> 1 votes
# Brachylog, 14 bytes

```
zzᵐ{≥₁ᵐ∧1|∧0}ᵐ

```

Try it online!

# Answer
> 0 votes
# Wolfram Language (Mathematica), 18 bytes

```
Inner[Less,##,Or]&

```

Returns a list of two unique values: `True` means falsy, `False` means truthy.

Try it online!

---
Tags: code-golf, number, matrix, classification
---


# Question
Title: Evaluate Words Based on "Rules" (Skeptics.SE Crossover)
I came across this picture, which I initially questioned and thought about posting to Skeptics. Then I thought they'll only tell me if this one case is true, but wouldn't it be great to know how true any "rule" really is? Today you're going program a skeptic-bot

**Challenge**

Write a program or function which when given a dictionary of valid words and a rule determines if the rule is well applied

**Rules**

* The dictionary is "words.txt" taken from here. Your submission must theoretically be able to review all words in the file, but for testing you may use a shortened list
* "Rules" come in the form `x before y except <before/after> z`. Your submission may take that input in any reasonable form, some examples below
* Compliance is defined as: "There is an adjacent `x` and `y` in the word in the right order that are in the reverse order if before/after `z`"
* Non-compliance is defined as: "There is an adjacent `x` and `y` in the word in the incorrect order or they are not reverse if before/after `z`"
* Rules are evaluated case insensitive
* Output or return a truthy value if the number of compliant words in the dictionary is greater than the number of non-compliant words, otherwise output a falsey value. Submissions cannot end in errors.
* This is , so shortest submission in bytes wins

Example input:

```
["i","e","-","c"]  #list of values, "-" denotes "after"
[105,101,-99]    #list of values as ASCII numbers, "-99" denotes "after"
"ieac"           #string of values abbreviated

```

**Test Cases**

Below are sample cases as inputs, for clarity I list the matching words but this is not required

Example dictionary: `["caught", "lemon", "simplified", "queue", "qwerty", "believe", "fierce", "receive", "science", "foreign", "weird", "quit"]`

```
Input: "I before E except after C"
Compliant: simplified, believe, fierce, receive
Noncompliant: science, foreign, weird
Output: Truthy

Input: "Q before U except before E"
Compliant: quit
Noncompliant: queue
Output: Falsey

Input: "C before E except before E"
Compliant: fierce, receive, science
Noncompliant:
Output: Truthy

```

# Answer
> 7 votes
# Python3, 105 103 bytes

This is my first golf here so be kind =)

-2 bytes tanks to Chas Brown

```
lambda d,b,x,y,z:sum((x+y in i)-2*((z*b+x+y+z)[:3]in i)-(y+x in i)+2*((z*b+y+x+z)[:3]in i)for i in d)>0

```

Takes the dictionary `d` as any iterator of strings; a boolean 'b' (`True` being `after`); and the three letters `x,y,z` as Strings;

Try it online!

**Explanation:** might add later

# Answer
> 3 votes
# Java 8, 210 bytes

```
(D,a,b,c,f)->D.stream().filter(w->w.contains(a+b)&!w.contains(f?c+a+b:a+b+c)|w.contains(f?c+b+a:b+a+c)).count()>D.stream().filter(w->w.contains(b+a)&!w.contains(f?c+b+a:b+a+c)|w.contains(f?c+a+b:a+b+c)).count()

```

Takes the dictionary `D` as a `java.util.List<String>`; the three letters `a,b,c` as Strings; and whether it's after or before as a boolean `f` (truthy being 'after').

EDIT: Surprisingly enough using two `.matches` with regexes instead of the two times three `.contains` is longer. And creating variables for `f?c+a+b:a+b+c` and `f?c+b+a:b+a+c` is also 1 byte longer.

Try it online.

**Explanation:**

```
(D,a,b,c,f)->             // Method with List, 3 Strings, boolean parameters & boolean return
  D.stream()              //  Stream the given dictionary-List
   .filter(w->            //  Filter the words by:
     w.contains(a+b)      //   If the word contains `a+b`
      &!w.contains(f?     //   If the flag is true (after):
                   c+a+b  //    And the word does not contain `c+a+b`
                  :       //   Else (before):
                   a+b+c) //    And the word does not contain `a+b+c`
     |w.contains(f?       //   If the flag is true (after):
                  c+b+a   //    Or the word contains `c+b+a`
                 :        //   Else (before):
                  b+a+c)) //    Or the word contains `b+a+c`
   .count()               //  And get the amount of words left in the filtered result
  >                       //  And return whether this is larger than:
  D.stream()              //  Stream of the given dictionary again
   .filter(w->            //  Filtered by:
     w.contains(b+a)      //   If the word contains `b+a`
      &!w.contains(f?     //   If the flag is true (after):
                    c+b+a //    And the word does not contain `c+b+a`
                   :      //   Else (before):
                    b+a+c)//    And the word does not contain `b+a+c`
     |w.contains(f?       //   If the flag is true (after):
                  c+a+b   //    Or the word contains `c+a+b`
                 :        //   Else (before):
                  a+b+c)) //    Or the word contains `a+b+c`
   .count()               //  And get the amount of words left in the filtered result

```

# Answer
> 2 votes
# Python 2, ~~109~~ 107 bytes

```
lambda D,x,y,r,c:sum((((' '+w+' ')[w.find(p)+3*r]!=c)^(p==y+x))*2-1for p in(x+y,y+x)for w in D if p in w)>0

```

Try it online!

Takes Dictionary and rule input as `D,x,y,r,c` with `r=0` to mean 'before' and `r=1` to mean 'after'.

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


title: Decrypt the extended Wechsler format

text:
# Question
Title: Decrypt the extended Wechsler format
This challenge is based on a sandbox post by user48538. Since he is no longer active on this site, I took over this challenge.

---

apgsearch, the distributed soup search program for Conway's Game of Life and the search results database, Catagolue use **apgcodes** to classify and denote patterns. apgcodes themselves use the **extended Wechsler format**, an extension of a pattern notation developed by Allan Wechsler in 1992.

The following examples and the images are taken from LifeWiki.

1. A string of *n* characters in the set matching the regex `[0-9a-v]` denotes a strip of five rows, *n* columns wide. Each character denotes five cells in a vertical column corresponding to the bitstrings \[`00000`, `10000`, `01000`... `00010`, `10010`, `01010`, `11010`... `11111`\].

For instance, `27deee6` corresponds to a heavyweight spaceship:

$$ \begin{bmatrix} {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ 1 & 1 & {\color{Gray}0} & 1 & 1 & 1 & 1 \\ {\color{Gray}0} & 1 & 1 & 1 & 1 & 1 & 1 \\ {\color{Gray}0} & {\color{Gray}0} & 1 & 1 & 1 & 1 & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \end{bmatrix} $$

2. The character `z` separates contiguous five-row strips.

For example, `0ca178b96z69d1d96` corresponds to a 31-bit still life:

$$ \begin{bmatrix} {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & 1 & {\color{Gray}0} & 1 & {\color{Gray}0} & 1 & {\color{Gray}0} & 1 \\ {\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 \\ {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} & 1 & 1 & 1 & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & 1 & 1 & 1 & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} \\ 1 & {\color{Gray}0} & 1 & {\color{Gray}0} & 1 & {\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \end{bmatrix} $$

3. The characters `w` and `x` are used to abbreviate `00` and `000`, respectively.

So `w33z8kqrqk8zzzx33` corresponds to a trans-queen bee shuttle:

(10 blank rows omitted)

$$ \begin{bmatrix} {\color{Gray}0} & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & 1 & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & {\color{Gray}0} \\ 1 & {\color{Gray}0} & 1 & 1 & 1 & {\color{Gray}0} & 1 \\ {\color{Gray}0} & 1 & 1 & 1 & 1 & 1 & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \end{bmatrix} $$

4. Finally, the symbols matching the regex `y[0-9a-z]` correspond to runs of between 4 and 39 consecutive `0`s.

A good example is `31a08zy0123cko`, corresponding to a ship on quadpole:

$$ \begin{bmatrix} 1 & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ 1 & {\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & 1 & {\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & {\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & {\color{Gray}0} & 1 \\ {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & 1 \end{bmatrix} $$

## The Challenge

Write a program or a function to parse a string of the extended Wechsler format, defined above, and print (or return) the pattern corresponding to this string.

You may assume that the string is nonempty, and does not start or end with `z`.

You may use any reasonable output format, e.g., a string, a matrix, a 2d array. You may use any two values to represent `0` and `1`, given that you declare them in the answer.

You may omit the trailing zeroes lines in the output, or add extra trailing zeroes lines. You may also add/omit trailing zeroes on each line, as long as all lines have the same length in the output.

You may return the transpose of the array, if that is more convenient.

This is , so the shortest code wins.

## Test cases

```
153 => [[1, 1, 1], [0, 0, 1], [0, 1, 0], [0, 0, 0], [0, 0, 0]]
27deee6 => [[0, 1, 1, 0, 0, 0, 0], [1, 1, 0, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0]]
0ca178b96z69d1d96 => [[0, 0, 0, 1, 1, 0, 1, 1, 0], [0, 0, 1, 0, 1, 0, 1, 0, 1], [0, 1, 0, 0, 1, 0, 0, 0, 1], [0, 1, 1, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 0, 0, 1, 0, 0], [1, 0, 1, 0, 1, 0, 1, 0, 0], [0, 1, 1, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]]
w33z8kqrqk8zzzx33 => [[0, 0,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 bytes

```
ＵＢ0≔⁺⭆χιββＦＳ¿υ×0⁺⊟υ⌕βι≡ιz×⸿⁵y⊞υ⁴x×0³w¦00«Ｐ↓⮌⍘⌕βι²→

```

Try it online! Link is to verbose version of code. Uses `1` and `0`. Explanation:

```
ＵＢ0

```

Set the background, i.e. any unprinted cells of the rectangle enclosing the output, to `0`.

```
≔⁺⭆χιββ

```

Prefix the digits to the predefined lower case alphabet.

```
ＦＳ

```

Loop over the input string.

```
¿υ

```

If the predefined empty list is not empty...

```
×0⁺⊟υ⌕βι

```

... then print a number of `0`s given by the sum of the number popped from the list and the index of the current character in the digits and letters. See below for what that number always is.

```
≡ι

```

Switch over the current character.

```
z×⸿⁵

```

If it's a `z` then output 5 carriage returns, taking us to the next output strip.

```
y⊞υ⁴

```

If it's a `y`, then push `4` to the predefined empty list, causing `4+n` `0`s to be output next time.

```
x×0³

```

If it's an `x` then output 3 `0`s. (This is done via repetition to avoid the literal `0` touching the `x` or the following literal.)

```
w¦00

```

If it's a `w` then output 2 `0`s. (The `¦` is needed to separate the two string literals.)

```
«Ｐ↓⮌⍘⌕βι²→

```

Otherwise, index the current character in the digits and letters, convert to binary, and print the result downwards least significant bit first; then move the cursor right for the next column.

# Answer
> 6 votes
# JavaScript (ES8), 197 bytes

Takes input as a string. Returns an array of strings with '#' and spaces. The output may include extra (but consistent) trailing spaces on each line.

```
s=>[x='x',...s.replace(/w|x|y./g,s=>''.padEnd(s<x?2:s>x?P(s[1],36)+4:3),P=parseInt)].map(c=>[!++w,1,2,3,4].map(i=>c<x?o[y+i-5]+=' #'[P(c,36)>>i&1]:o=[...++y&&o,'']),w=y=o=[])&&o.map(r=>r.padEnd(w))

```

Try it online! (prettified output)

## How?

### Global variables

* The character `"x"` is used several times, so it's worth storing it into the variable **x**.
* The function `parseInt` is used twice, so it's worth storing it into the variable **P**.
* **y** is the row index, initialized to **0**.
* **w** keeps track of an upper bound of the width which is used to pad the final output.
* **o\[ \]** is the output array, initially empty.

### Pre-processing of repeated zeros

We first replace all patterns `"w"`, `"x"` and `"yX"` in the input string with the appropriate number of spaces. These spaces will later be interpreted as `"0"`.

```
s.replace(
  /w|x|y./g,
  s => ''.padEnd(
    // w --> 2
    s < x ? 2 :
    // yX --> value of X + 4
    s > x ? P(s[1], 36) + 4 :
    // x --> 3
    3
  )
)

```

### Decoding

We split the resulting string, prepend an initial `"x"` and iterate 5 times (with **i** = **0** to **4**) on each character **c**:

* If **c** is lower than `"x"`, we append the corresponding pattern to the next 5 rows.

```
o[y + i - 5] += ' #'[P(c, 36) >> i & 1]

```
* If **c** is greater than or equal to `"x"`, we allocate 5 new empty strings in **o\[ \]** and add **5** to **y**. This is triggered by the initial `"x"` that was added at the beginning of the string, or by any `"z"` in the original content.

```
o = [...++y && o, '']

```

### Padding

Finally, we pad each string in **o\[ \]** with spaces so that they all have **w** characters.

```
o.map(r => r.padEnd(w))

```

# Answer
> 6 votes
# 05AB1E, ~~148~~ ~~132~~ 98 bytes

I'm a highschool student and this was my first time for both golfing and using 05AB1E, so comments are appreciated!

```
„YY¾38×:'Yð:žLRDUsð«#εNĀiDнXsk4+s¦sú]'W¾2×:'X¾3×:J'Z¶:.Bð¾:vNUyvDykDNX‚Š32VY‹iY+b¦RX_i¶ì}‚ˆ]¯{€¦˜J

```

~~Try it online!~~

~~Try it online!~~

Try it online!

Takes input as uppercase and outputs the transposed matrix as multiple output lines of 1s and 0s. May add extra zeros.

If you want to test with lowercase strings, add `u` in the TIO header.

If you want pretty-printed output, add `'1'█:'0'.:` in the TIO footer.

# Explanation

(I'm calling "rows" and "columns" opposite of what you might expect because it generates the transposed matrix)

The basic algorithm is:

1. Replace "yy" with 38 0s
2. Split on "y" and and expand the 0-runs.
3. Replace "w" and "x"
4. Figure out the longest column (that is, the longest string between z's) and pad all the other columns so they are that length. (This is necessary because of how the algorithm below works)
5. Split on z
6. At this point, the input string is an array of columns where each column is a string of \[0-9A-V\], where each column is the same length.
7. The algorithm to get it into the output format is to
    1. Convert the characters to numbers by using indexOf in a lookup string
    2. Convert the characters to binary and then pad to length 5
    3. If it is the first column, add a linebreak before the binary number
    4. Add a prefix to the beginning of the binary string that stores the row and then the column of the character.
    5. Push the binary string with prefix to 05AB1E's "global array" register/variable
8. Sort the global array. The prefix string, which determines the sort order, will make sure everything ends up in the right order and the linebreaks are in the right places.
9. Remove the prefix string from each element of the global array
10. Join the array with "" and print it.

There are some other minor details you can see below in the expanded code. Everything after the tabs at the end of a line is a comment and can be ignored. (This comment scheme is not part of 05AB1E, by the way. I did it this way because it looked nice.) Lines that have comments starting with "@" are for debugging purposes and can be omitted without changing the final output.

```
„YY¾38×:                                        Replace "YY" with 38 0's. (y is the 34th character in the index, so need to add 34+4 = 38). ¾ is initialized to zero, which saves one byte from typing '038
'Yð:                                            Replace "Y" with " "
"Replaced input Stage1 = "?D,                   @DEBUG

žLR                                             Pushes [0-9A-Za-z]
DU                                              Set X to [0-9A-Za-z] and leave [0-9A-Za-z] on the stack.
s                                               Swap top two elements. Now the stack is [0-9A-Za-z],input

ð«                                              Append a space so the below splitter works even if there are no other spaces.
#                                               Split input on " ", which "Y" has been replaced with
ε                                               Map. This map replaces the y runs
    "Element = "?D,                             @DEBUG
    "N = "?N,                                   @DEBUG
    NĀi                                         If N != 0
        "Replacing!",                           @DEBUG
        Dн                                      Get the first letter
        X                                       Push X
        s                                       Swap
        k                                       X (which is [0-9A-Za-z]) .indexOf(firstLetter)
        "indexOf run token = "?D,               @DEBUG
        4+                                      Add 4 to the index, now becoming the number of zeros to add
        s                                       Swap. Now top is the string between runs
        ¦                                       Remove the first character
        s                                       Swap again. Now the top is the number of zeros to add.
        ú                                       Add that many spaces (will be replaced with zeros later) to the start of the element.
        "Element Replaced = "?D,                @DEBUG
]
'W¾2×:                                          Need to do this replacement after the Y replacement so stuff like YW gets parsed properly. Again, ¾ is zero.
'X¾3×:
J                                               Join with ""
"Replaced input Stage2 = "?D,                   @DEBUG
'Z¶:                                            Replace "Z" with "¶".
.B                                              "Squarify" command. Splits on \n and appends spaces to the end of each element so each is the same length. In this case, that is equivalent to adding zeros to the end of each column, which is what we want.
ð¾:                                             Replace spaces (which we used for padding above) with zeros.
"Replaced input Stage3 = "?D,                   @DEBUG
"0 Stack top = "?D,                             @SDEBUG
"0 Stack top-1 = "?sD,s                         @SDEBUG
v                                               pop and loop over top element, which is array of column code
    NU                                          Store the column number in X
    yv                                          Loop over each character in the column
        "1 Stack top = "?D,                     @SDEBUG
        "1 Stack top = "?D,                     @SDEBUG
        D                                       Duplicate top element (which is now [0-9A-Za-z])
        y                                       Push y (special loop variable)
        "Character = "?D,                       @DEBUG
        k                                       Push indexOf y in [0-9A-Za-z]
        "Index = "?D,                           @DEBUG
        "2.1 Stack top = "?D,                   @SDEBUG
        "2.1 Stack top-1 = "?sD,s               @SDEBUG
        D                                       Duplicate index.
        NX‚                                     Push [rowNumber,columnNumber]. This result is used for sorting.
        Š                                       Triple swap. The top of the stack is now sortPrefix, index, index
        32V                                     Set Y to 32
        Y‹i                                     index < 32. This uses up one copy of index
            Y+                                  Add 32 to the index
            b                                   Push the index in binary. This uses the second copy of index.
            ¦                                   Remove the first character, which will be a 1 because we added 32. The result is now a padded binary string of length 5
            "Binary = "?D,                      @SDEBUG
            R                                   Reverse the binary string. This gives the proper transposed output.
            X_i                                 This will only run if X (which is set to the column number) == 0. (Runs !X)
                ¶ì                              Stick a linebreak at the beginning of the binary string
            }
            "2.5 Stack top = "?D,               @SDEBUG
            "2.5 Stack top-1 = "?sD,s           @SDEBUG
            ‚                                   At this point the top of the stack is sortPrefix,binaryString. This will combine the two into a list.
            "Pushing '"?D?"'",                  @DEBUG
            ˆ                                   Push [[rowNumber,columnNumber],binaryString] to global array
            "2.6 Stack top = "?D,               @SDEBUG
            "2.6 Stack top-1 = "?sD,s           @SDEBUG
        ]                                       Close all blocks
¯                                               Push global array

{                                               Sort global array.
"Sorted Data = "?D,                             @DEBUG
€¦                                              Remove the sort prefix
˜                                               Flatten. Before doing this, the array is in the format [[<binary string>],[<binary string>],[<binary string>],...]
J                                               Join with ""
'1'█:'0'.:                                      @DEBUG pretty print

```

# Answer
> 5 votes
# APL (Dyalog Unicode), 87 80 77 67 63 bytes

thanks to H.PWiz for saving 7 bytes and ngn for another 13 17.

```
a←⎕D,⎕A⋄,⍉↓⊖(5/2)⊤↑35(≠⊆⊢)a⍳'Y.|W|X'⎕R{'0'/⍨30 36|a⍳2↑⍵.Match}⍞

```

Try it online!

NB: Takes the input as an upper case string.

With pretty printed output

# Explanation

`a←⎕D,⎕A` a is the string `'0123...89ABCD...XYZ'`
`'Y.|W|X'⎕R{'0'/⍨+/30 36|a⍳2↑⍵.Match}` replaces X W and Yx with the corresponding number of `'0'`s (explained more below) `35(≠⊆⊢)a⍳` converts the string into vector of indecies in `a` and splits on `35` (i.e.) `'Z'` creating a nested vector
converts the nested vector into a matrix padding ends with `0`s
`(5/2)⊤` converts each number into a binary vector resulting in a 3-dimensional matrix with binary vectors along the primary axis
reverses along the primary axis
reduces the rank of the matrix so it is 2-dimensional
`,⍉` reshapes the result to the appropriate output

```
'Y.|W|X'⎕R{'0'/⍨30 36|a⍳2↑⍵.Match}
'Y.|W|X'⎕R                         ⍝ Regular expression replace. mathing the string.
                        2↑⍵.Match  ⍝ Takes matching string (either 'X' 'W' or 'Y.') and pads with spaces to length 2
                      a⍳           ⍝ Returns the indecies of each charactor in a. on the spaces this is 36 (length of a)
                30 36|             ⍝ Takes the remainders of the indecies when divided by 30 and 36 respectively. Overall 'W' -> 'W ' -> 32 36 -> 2 0, 'Y2' -> 'Y2' -> 34 2 -> 4 2.
           '0'/⍨                   ⍝ Make vector of repeating '0's with length equal to the sum of the result. '0'/⍨4 2 ≡ '000000'

```

# Answer
> 3 votes
# Perl 6, ~~156~~ 142 bytes

*14 bytes saved thanks to Jo King. (Also fixed a little bug with parsing the `y` and added a prettifier.)*

*Fixed the buggy parsing of `y[wxy]`.*

```
{s:g/y(.)/000{0 x:36(~$0)}/;s:g/x/w0/;s:g/w/00/;s/$/z/;map {
.flatmap:{:32($_).fmt("%05b").flip.comb}},[Z] .split("z").map: (*~0 x.chars).comb}

```

Try it online!

The line break is there just to make the text fit on the screen. It is not a part of the program.

## How does it work

It is an anonymous function that takes a mutable string. (This makes using the function a little bit peculiar, because you can give it only variables, not literals.) After some work, it returns a list of lists containing 0's and 1's, with the same meaning as in the original post.

The input string comes in in the variable `$_`. We start by using a series of substitution statements on it in order to get rid of all of those shorthands for various numbers of zeroes. First, we need to sort out the `y`, because in the case of `yx` or `yw`, the `w` (or `x`) does not constitute a shorthand by itself. We search for `y(.)` (`y` and one character, which it remembers) and replace it by `000{"0"x:36(~$0)}`: the three zeroes are copied verbatim, then we convert the next character from base 36 to base 10 (`:36(~$0)`) and add that many more zeroes. Then, we replace the `w`'s using `s:g/w/00/`, and the `x`'s using `s:g/x/000/`. Finally, with `s/$/z/`, we add a `z` onto the end, adding a whole lot of empty lines to the bottom. (We'll see the reason later.)

The rest is just a big map statement. We're mapping over `.split("z").map: (*~0 x.chars).comb})`, which is the input string (without zero shorthands), splitted into lines at `z`, with each line being first padded with `0 x.chars` (tons of zeroes, namely as many as is the total length of the input string) on the right and then broken down into a list of individual characters (`.comb`). Finally, we transpose it with `[Z]` (reduce with zip). Zipping ends as soon as the shortest list is depleted, which results in all lines having the same length. (The number of useless trailing zeroes on the right is equal to the length of the shortest line. Also, this transposition trick fails for a "matrix" with only one row. That's why we forcibly added another row at the end before.)

Now, we just map over the rows (columns of the original matrix) and replace each character encountered with the corresponding 5 bits. That is done using `:32($_)` (base 32 to base 10) `.fmt("%05b")` (format as a bitstring of width 5, padded with zeroes) `.flip` (reverse the string, because the LSB is in the top row, not the bottom) `.comb` (break the string into a list of characters). We have used `.flatmap`, which flattens the resulting list (otherwise we would get a list of lists in each column). The transpose of the result is then implicitly returned.

(I feel a little bit bad because of abusing the possibility of trailing zeroes so hard. But it reduced the bytecount quite considerably :—).)

# Answer
> 3 votes
# Retina, 203 bytes

```
y(.)
#$1
{`#
0#
#0
000
)T`dl`_dl`#.
w
000
x
00
z
¶
%(`.+
$&¶$&¶$&¶$&¶$&
T`g-v`#`.+$
T`dl` `.+$
T`g-v`dl
T`89l`#`.+¶.+$
T`d` `.+¶.+$
T`89l`d
T`d`    #`.+¶.+¶.+$
T`4-7`d
T`d`  #`.+¶.+¶.+¶.+$
)T`d` # #
P`.+

```

Try it online! Link includes test cases. Alternative solution, also 203 bytes:

```
y(.)
#$1
{`#
0#
#0
000
)T`dl`_dl`#.
w
000
x
00
z
¶
%(`.+
$&¶$&
T`g-v`#`¶.+
T`dl` `¶.+
T`g-v`dl
^.+
$&¶$&
T`89l`#`¶.+
T`d` `¶.+
T`89l`d
^.+
$&¶$&
T`d`    #`¶.+
T`4-7`d
^.+
$&¶$&
T`d`  #`¶.+
)T`d` # #
P`.+

```

Try it online! Link includes test cases. Explanation:

```
y(.)
#$1

```

First handle the awkward case of the `y` command. Sadly the letter after this is allowed to be a `y` or even a `z`, so we have to be careful here. All the magic `y`s are first turned into `#`s.

```
{`#
0#
#0
000
)T`dl`_dl`#.

```

A loop then processes the `#`s. First, a `0` is prepended to the `#`. If this is a `#0` then that is changed to `000` which completes the operation, otherwise the character after the `#` is decremented and the loop repeats until all of the `#`s have been processed.

```
w
000
x
00

```

Fix up the `w`s and `x`s.

```
z
¶

```

Split on new lines. (`S`z` also works for the same byte count.)

```
%(`.+
$&¶$&¶$&¶$&¶$&
T`g-v`#`.+$
T`dl` `.+$
T`g-v`dl
T`89l`#`.+¶.+$
T`d` `.+¶.+$
T`89l`d
T`d`    #`.+¶.+¶.+$
T`4-7`d
T`d`  #`.+¶.+¶.+¶.+$
)T`d` # #

```

Make 5 copies of each line, then perform binary conversion by mapping letters with the appropriate bit to `#` and clearing that bit, while other letters become spaces. The bits are processed in the order 16, 8, 4, 2, and then the last translation handles clearing the `2` bit and converting the `1` bit at the same time. (The alternative version makes each copy individually which costs more bytes but these are saved because the bit handling is simplified.)

```
P`.+

```

Pad all the lines to the same length.

# Answer
> 2 votes
# Jelly, 66 bytes

<sup>Yowza!</sup>

```
ØBiⱮ+
Œuœṣ⁾YYj38Żṣ”YµḢç3;)Fṣ”Wj2ṣ”Xj3”0ẋ$¹OƑ?€Fṣ”Zµȯ”0ç31BḊ€UZ)Ẏz0

```

A monadic link which yields a transposed version as a list of lists (add `Z` to the end to transpose back).

**Try it online!** Or see the test-suite (with pretty printed output).

# Answer
> 1 votes
# Python 2, ~~249~~ 244 bytes

```
def f(s,Z='0'):
 while'y'in s:i=s.find('y');s=s[:i]+4*Z+Z*int(s[i+1],36)+s[i+2:]
 t=s.replace('w',2*Z).replace('x',3*Z).split('z');return map(''.join,zip(*[[(Z*5+bin(int(c,32))[2:])[:-6:-1]for c in r]+[Z*5]*(max(map(len,t))-len(r))for r in t]))

```

Try it online!

5 bytes saved by Jonathan Frech.

# Answer
> 1 votes
# JavaScript (ES8), 192 bytes

```
s=>[...s,"z"].map(c=>{h=parseInt(c,36);k="wxy".search(c)+1;y?k=h-y--:h-35?y=h>33:m=m.map(P,z+=5,i=k--);for(h=k?0:h;~k--;m[i]=h.toString(2)+P(m[i++]||""));},P=d=>d.padStart(z,0),m=[i=z=y=0])&&m

```

Returns the transpose... which is then reflected across the vertical axis; let me know if that invalidates this entry. Output is an array of strings containing `0`s and `1`s.

Try it online!

## Explanation

For each character `c`, `k+1` evaluates to the number of rows to modify. `k = "wxy".search(c) + 1;`, where the `search` method returns the index or `-1`. `k` is then decremented until it reaches `-1` by checking `~k--` for a truthy value.

If the current character is "y", set a flag so that the base-36 value of the next character - 1 becomes the value for `k`.

Upon encountering a "z", pad strings to the left, increment the pad amount by `5`, and reset the array index to `0`.

```
s =>
    [...s, "z"].map(c => {                  // append a "z" to ensure final output is properly padded
        h = parseInt(c, 36);
        k = "wxy".search(c) + 1;            // note that "y" -> 4 zeroes
        y                                   // if previous char is "y"...
            ? k = h - y--                   //      decrement y after subtracting y=1 since k is decremented to -1 and the previous y already pushed 4 zeroes
        : h - 35                            // else if current char is not "z"...
            ? y = h > 33                    //      set y if current char = "y"
        : m = m.map(P, z += 5, i = k--);    // else if current char is "z", pad
        for (
            h = k ? 0 : h;                  // if k is truthy, push zeroes
            ~k--;
            m[i] = h.toString(2)            // convert to boolean representation
                + P(m[i++] || "")           // prepend to row or to a newly padded row
        );
    },
        P = d => d.padStart(z, 0),
        m = [i = z = y = 0]                 // the logical OR 4 lines above replaces this value with ""
    ) &&
    m

```

# Answer
> 1 votes
# Haskell, 399 bytes

Install `split` package: `cabal install split`

```
import Data.Char
import Data.List.Split
import Data.List
p=map
r=replicate
a c|47<c&&c<58=c-48|96<c&&c<123=c-87
o=a.ord
m l n|l==0=[]|True=(mod n 2):m(l-1)(div n 2)
t a=p(\l->l++r((maximum$p length a)-length l)'0')a
y s|length s==0=""|h=='y'=(r(4+(o$s!!1))'0')++y(drop 2 s)|h=='w'="00"++y t|h=='x'="000"++y t|True=h:y t where h=head s;t=tail s
w=(p concat).transpose.(p$p$(m 5).o).t.(splitOn "z").y

```

---
Tags: code-golf, grid, parsing, game-of-life
---


title: Role-Playing Game Dice-Rolling

text:
# Question
Title: Role-Playing Game Dice-Rolling
## Background

When playing an RPG such as Dungeons & Dragons, Pathfinder, or Paranoia, players each need a set of dice You are hosting one such game this weekend, and some of the friends you invited have never played an RPG before. They don't want to commit to buying their own set of dice until they know they'll use them (if they want to keep playing). This is fine and dandy with you, but you're not going to let them use your lucky set of dice that you pre-rolled the ones out of...

## Goal

...so you are going to write a program or function that simulates the dice-rolling for them.

Dice are often described in the format: `<How many dice>d<Number of sides>` A common set of dice for RPG use includes: `1d4`, `1d6`, `1d8`, `2d10` (also used as `1d%` or `1d100`), `1d12`, and `1d20`.

Your code must accept a string of any number of the above dice specifiers separated by spaces or commas as input. It must then output the result of each individual die-roll separated by spaces, with parentheses around groups; then the sum of each grouping on the next line, separated by spaces; and finally, the total sum on a third line. Single-die groups don't have parentheses. Dice must always be in the same order as provided in the input.

The percent die, whether written as `1d%` or `1d100`, should be calculated as the concatenation of `2d10` (just 2 rolls, each from 0-9, but a final result of zero is instead counted as 100), but each occurrence will be displayed as if a single roll. `2d10` in the input will still be treated and displayed as 2 individual rolls. It can be easy to get confused by percent dice, here's a good explanation.

**Edit**: To clarify, the number of rolls may exceed 9.

## Examples

### Input:

```
1d4 3d6 2d8

```

### Possible Output:

```
3 (1 5 2) (8 4)
3 8 12
23

```

### Input:

```
1d20 1d% 2d10 1d100 5d12

```

### Possible Output:

```
16 100 (9 4) 42 (5 1 7 7 11)
16 100 13 42 31
204

```

## Rules

* Standard loopholes are disallowed.
* Printable ASCII in code, only.
* \- shortest code wins.
* -10 bytes if the rolls are actually random, rather than pseudo-random.

# Answer
> 3 votes
# Pyth, 48 bytes

```
-jdm?td(.*dhdJ.bmOSYNmm.xsk100cd\dcz))\,jdsMJssJ

```

Test Suite

Tricks / golfs in this code:

* Everything that's not a number will be treated as 100, not just `%`.
* To get the parentheses, I make the list into a tuple, then subtract out the commas.
* This is the first time I've used `.b`, the binary map, which was added 3 days ago.
* The code contains 6 different map functions.

# Answer
> 1 votes
# Pyth - 56 bytes

Nothing fancy, many nested maps. As OP said above in comments, we don't need to do the concatenating thing, just recognizing `%` is enough.

```
jdm?tld++\(j\ d\)j\ dKmmhOeGh=GsMcsXd\%]100\dczdjdJsMKsJ

```

Test Suite.

# Answer
> 1 votes
# Lua, 183 bytes

```
a=arg[1]:gsub("(%g+)d(%g+)",function(r,d)d=d=="%"and 100 or d n=tonumber(r)s=n>1 and"("or""for i=1,r do s=s..math.random(d)..(i<n and" "or"")end return s..(n>1 and")"or"")end)print(a)

```

# Answer
> 1 votes
# Pyth, 59 bytes

```
JmhMOMd.b*N]?YY100mvdcXz",d%"" ,0";-jdm?td(.*dhdJ\,jdsMJssJ

```

Test Suite

Unfortunately, neither isaacg's nor Maltysen's answer handles commas properly. When/if isaacg fixes it, I'm sure his will remain smaller.

# Answer
> 1 votes
# , 200 bytes

```
for(d in strsplit(scan(,""),"d")){d=gsub("%","100",d);u=d[1]>1;cat(if(u)"(",paste(i<-sample.int(d[2],d[1],T),collapse=" "),if(u)")"," ",sep="");F=c(F,sum(i))};cat("\n");cat(F[-1],"\n");cat(sum(F[-1]))

```

Try it online!

```
for(d in strsplit(scan(,""),"d")){
    d=gsub("%","100",d)                                # replace "%"
    u=d[1]>1                                           # whether to print parenthesis
    cat(if(u)"(",
        paste(i<-sample.int(d[2],d[1],T),collapse=" "),# dice rolls
            if(u)")",
            " ",
            sep="")
        F=c(F,sum(i))}
cat("\n")
cat(F[-1],"\n")                                        # sum of rolls of a certain type
cat(sum(F[-1]))                                        # sum of all dice rolls.

```

This can be shortened for sure... this is a naïve implementation with a for loop.

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


title: Symmetric Numbers

text:
# Question
Title: Symmetric Numbers
write a function to tell if a number is symmetric or not. for example:

input: 151 output: True

input: 142 output: False

and so on: 1111 True, 2390 False, 1226221 True

# Answer
> 0 votes
# Python 2, 23 bytes

```
lambda n:`n`==`n`[::-1]

```

Try it online!

---
Tags: code-golf, string, math, number, function
---


title: Find the optimal sliding door width

text:
# Question
Title: Find the optimal sliding door width
Sliding doors have varying prices based on the width of the doors. The different prices are as follows:

* 60 - 80 cm: ¤150
* 81 - 100 cm: ¤200
* 101 - 120 cm: ¤220

When buying a closet you would obviously want to minimize the cost, so your task is to find the width of the doors that minimizes the total cost based on the total width of the closet.

**Rules:**

* The total width will be taken as input
* All doors will have the same width
* Choose the smallest doors if two type of doors cost the same
* The widths are in centimeters, integers not decimals
    + Round up decimals
* The price shall be returned as an integer (no need for the currency sign)
* The input and output formats are optional, but the order of the output must be: `Number of doors, Width, Price`.
* Input will be in the range `[120 1000)`.

This is code golf. Shortest code in bytes win.

**Examples:**

```
Input: 156
Output: 2, 78, 300

Input: 331
Output: 3, 111, 660

Input: 420
Output: 4, 105, 880

```

# Answer
# 05AB1E, 47 bytes

Code:

```
D120/ó>DU=/ó>=D101›iX220*=q}D80›iX200*=q}X150*=

```

Not the best submission, but at least something :)

Try it online!
> 2 votes

# Answer
# Perl, ~~190~~ ~~180~~ ~~154~~ ~~133~~ ~~128~~ 117 bytes

*includes +1 for `-p`*

```
use POSIX;$m=1E4;for$q(80,100,120){($m,@z)=($p,$n,ceil$_/$n)if$m>($p=(150,200,220)[$x++]*($n=ceil$_/$q))}$_="@z $m"

```

Commented:

```
use POSIX;                                  # for ceil()
$m = 1E4;                                   # init min price to 10k
for $q (80,100,120) {                       # iterate widths
    ($m,@z) = ($p,$n, ceil $_/$n)           # update min, output
    if $m > (                               #
       $p = (150,200,220)[$x++]             # grab price
          * ( $n = ceil $_/$q )             # times nr of doors needed
    )
}
$_="@z $m"

```

---

* Save 11 bytes by inlining and splitting hash to two arrays
* Save 5 bytes by using `-p` (thanks to @dev-null)
* Save 18 bytes by using POSIX::ceil and 3 more by using list syntax for hash (thanks to @msh210)
> 4 votes

# Answer
## JavaScript (ES6), 101 bytes

```
t=>[[80,150],[100,200],[120,220]].map(([w,p])=>[n=-~(~-t/w),-~(~-t/n),n*p]).sort((a,b)=>a[2]-b[2])[0]

```

`-~(~-a/b)` is the same as Math.ceil(a/b) in 31-bit integers.
> 4 votes

# Answer
## PowerShell, ~~137~~ 135 bytes

```
param($a)$j=9e9;60..120|%{if((($c=[math]::ceiling($a/$_))*($p=(220,(200,150)[$_-le80])[$_-le100]))-lt$j){$j=($k=$c)*$p;$i=$_}}
$k;$i;$j

```

Output is newline-separated.

We take input `$a`, set our cost `$j` to `9000000000` (a large number that's way more than we would ever need). Next, we loop from `60..120` with `|%{...}`. Each iteration we calculate the `$p` price of the current item with a pseudo-ternary statement, then calculate the `$c` ceiling of `$a/$_`. If the current total is smaller than the smallest total we've seen (`$j`), save all these variables: `$j` (the total), `$k` (the number of doors required), and `$i` (the door width), and continue the loop. Once the loop is finished, just output the best values.

Edit -- Saved two bytes by moving the `$c` and `$p` assignments into the `if` conditional
> 3 votes

# Answer
# Pyth, 65 bytes

```
ho+eNcehNTm[d*hd?>81ed150?<101ed220 200)f}eTr60 121m[d.EcQd)r2 17

```

Try it here!

### Explanation

First this generates a list of all possible door count/door width combinations and calculates the price for every of those combinations. Then we only have to order it by price and door width and take the first element of the resulting list.

~~Code explanation follows after I golfed this down~~ Please help me golf this, this is way too long.

```
ho+eNcehNTm[d*hd?>81ed150?<101ed220 200)f}eTr60 121m[d.EcQd)r2 17  # Q=input

                                                   m        r2 17  # map range(2,17) to
                                                    [d     )       # list with door count first
                                                      .EcQd        # and width second
                                        f                          # Filter map result with T
                                         }   r60 121               # in range(60,121)
                                          eT                       # door width
          m                                                        # map filter result with d
           [d                          )                           # to a list with door count and width first
             *hd                                                   # mult door count with
                ?>81ed150?<101ed220 200                            # price per door, simple lookup with ternaries
 o                                                                 # order map result with N
  +eNcehNT                                                         # order key=price+width/10
h                                                                  # first element is the best

```
> 2 votes

# Answer
# JavaScript (ES6) 96

```
n=>[80,100,120].map((d,i)=>[d=-~(~-n/d),-~(~-n/d),d*[150,200,220][i]]).sort((a,b)=>a[2]-b[2])[0]

```

As noted by @Neil, `=-~(~-n/d)` is equivalent to division with rounding up for integeres of 32 bit or less.
> 1 votes

# Answer
# , ~~135~~ 104 bytes

```
"!"=utf8ToInt;cbind(n<-16:1,w<-ceiling(scan()/n),p<-n*approx(!"<Qex",!"–ÈÜÜ",w,"c")$y)[order(p)[1],]

```

Try it online!

Saved 31 bytes by

* decompressing numbers
* using `utf8ToInt`
* using "!" to shorten function call
* using vectorized functions
* not defining total length
* using `cbind` directly rather than after defining variables

### How it works:

1. `approx` returns the price of a single door based on its length. It returns `NA` outside of the range `[60,120]`.
2. Based on the spec, the total numbers of doors can't be more than 16 (total length 1000). All number of doors from 16 to 1 are tested, and the triplet `(number of doors, door width, total price)` is returned.
3. The `order` function is used to locate the minimum price; the correct triplet is extracted based on that. In case of ties, `order` will return the entry that comes first, and since we looped from 16 to 1 the greatest numbers of doors (smallest door width) will be returned.
> 1 votes

---
Tags: code-golf, arithmetic
---


title: Longest Non-Repeating Substring

text:
# Question
Title: Longest Non-Repeating Substring
Given a string as input find the longest *contiguous* substring that does not have any character twice or more. If there are multiple such substrings you may output either. You may assume that the input is on the printable ASCII range if you wish.

## Scoring

Answers will first be ranked by the length of their own longest non-repeating substring, and then by their total length. Lower scores will be better for both criteria. Depending on the language this will probably feel like a challenge with a source restriction.

## Triviality

In some languages achieving a score of **1, x** (lenguage) or **2, x** (Brain-flak and other turing tarpits) is pretty easy, however there are other languages in which minimizing the longest non-repeating substring is a challenge. I had a lot of fun getting a score of 2 in Haskell, so I encourage you to seek out languages where this task is fun.

## Test cases

```
"Good morning, Green orb!" -> "ing, Gre"
"fffffffffff" -> "f"
"oiiiiioiiii" -> "io", "oi"
"1234567890"  -> "1234567890"
"11122324455" -> "324"

```

## Scoring submission

You can score your programs using the following snippet:

```
input.addEventListener("input", change);

// note: intentionally verbose :)
function isUnique(str) {
  var maxCount = 0;
  var counts = {};
  for(var i = 0; i < str.length; i++) {
    var c = str.charAt(i);
    counts[c] |= 0;
    counts[c]++;
    if(maxCount < counts[c]) {
      maxCount = counts[c];
    }
  }
  return maxCount <= 1;
}

function maximizeSubstring(str, pred, cost) {
  var mostExpensive = -1;
  // iterate over substrings
  function iterate(start, end) {
    var slice = str.slice(start, end);
    if(pred(slice)) {
      var profit = cost(slice);
      if(profit > mostExpensive) {
        mostExpensive = profit;
      }
    }
    end++;
    if(start >= str.length) {
      return;
    }
    else if(end > str.length) {
      start++;
      iterate(start, start);
    }
    else {
      iterate(start, end);
    }
  }
  iterate(0, 0);
  return mostExpensive;
}

function size(x) {
  return x.length;
}

function longestNonRepeatingSize(str) {
  return maximizeSubstring(str, isUnique, size);
}

function change() {
  var code = input.value;
  output.value = "Your score is: " + longestNonRepeatingSize(code);
}

change();
```

```
* {
  font-family: monospace;
}
```

```
Input code here:
<br>
<textarea id="input"></textarea>
<br>
<textarea id="output"></textarea>
```

# Answer
> 14 votes
# C, score 2,  ~~747~~   ~~720~~  662 bytes

```
L  [  1  <<  7  ]  ,  *  q  ,  *  r  ,  l  ,  d  ,  i  ,  c  ,  j  ,  s  ,  t  ,  k  =  1  <<  7  ;  h  (  )  {  q  =  s  +  i  +  j  ++  ;  *  q  %  k  &&  !  L  [  *  q  %  k  ]  ++  &&  h  (  ++  c  )  ;  }  g  (  )  {  q  =  s  +  i  ;  *  q  %  k  ?  z  (  k  )  ,  h  (  j  =  c  =  0  )  ,  c  >  d  &&  (  d  =  c  )  &&  (  l  =  i  )  ,  g  (  ++  i  )  :  0  ;  }  f  (  S  ,  T  )  {  s  =  S  ;  l  =  i  =  d  =  0  ;  g  (  t  =  T  )  ;  p  (  i  =  0  )  ;  }  p  (  )  {  q  =  s  +  l  +  i  ;  r  =  t  +  i  ;  i  ++  <  d  ?  p  (  *  r  =  *  q  )  :  (  *  r  =  0  )  ;  }  z  (  i  )  {  L  [  --  i  ]  =  0  ;  i  &&  z  (  i  )  ;  }

```

Works at least on 32-bit MinGW (with optimizations disabled). Doesn't use a single keyword.

Works apparently on TIO with gcc and clang, too: Try it online! (Thanks @Dennis!)

**Call with:**

```
int main()
{
    char str[1024];

    f("Good morning, Green orb!", str);
    puts(str);

    f("fffffffffff", str);
    puts(str);

    f("oiiiiioiiii", str);
    puts(str);

    f("1234567890", str);
    puts(str);

    f("L  [  1  <<  7  ]  ,  *  q  ,  *  r  ,  l  ,  d  ,  i  ,  c  ,  j  ,  s  ,  t  ,  k  =  1  <<  7  ;  h  (  )  {  q  =  s  +  i  +  j  ++  ;  *  q  %  k  &&  !  L  [  *  q  %  k  ]  ++  &&  h  (  ++  c  )  ;  }  g  (  )  {  q  =  s  +  i  ;  *  q  %  k  ?  z  (  k  )  ,  h  (  j  =  c  =  0  )  ,  c  >  d  &&  (  d  =  c  )  &&  (  l  =  i  )  ,  g  (  ++  i  )  :  0  ;  }  f  (  S  ,  T  )  {  s  =  S  ;  l  =  i  =  d  =  0  ;  g  (  t  =  T  )  ;  p  (  i  =  0  )  ;  }  p  (  )  {  q  =  s  +  l  +  i  ;  r  =  t  +  i  ;  i  ++  <  d  ?  p  (  *  r  =  *  q  )  :  (  *  r  =  0  )  ;  }  z  (  i  )  {  L  [  --  i  ]  =  0  ;  i  &&  z  (  i  )  ;  }");
    puts(str);
}

```

**Output:**

**The code with slightly more readable formatting:**

```
L[1<<7],
*q, *r, l, d, i, c, j, s, t, k=1<<7;

h()
{
    q = s+i+j++;
    *q%k && !L[*q%k]++ && h(++c);
}

g()
{
    q = s+i;
    *q%k ? z(k), h(j=c=0), c>d && (d=c) && (l=i), g(++i) : 0;
}

f(S, T)
{
    s = S;
    l = i = d = 0;
    g(t=T);
    p(i=0);
}

p()
{
    q = s+l+i;
    r = t+i;
    i++<d ? p(*r=*q) : (*r=0);
}

z(i)
{
    L[--i] = 0;
    i && z(i);
}

```

And this can be used to generate proper spacing to get to the formatting with score 2: Try it online!

---

# C, score 3, 309 bytes

```
i
,
j
,
l
,
c
,
d
;
f
(
\
c\
\
h\
\
a\
\
r
*
s
)
{
\
f\
\
o\
\
r
\
(
i
=
l
=
d
=
0
;
s
[
i
]
;
c
>
d
&&
(
d
=
c
)
&&
(
l
=
i
)
,
++
i
)
\
f\
\
o\
\
r
(
\
c\
\
h\
\
a\
\
r

L
[
\
1\
\
2\
\
8
\
]
=
{
j
=
c
=
0
}
;
s
[
i
+
j
]
&&
!
L
[
s
[
i
+
j
++
]
]
++
;
++
c
)
;
\
w\
\
r\
\
i\
\
t\
\
e
(
1
,
s
+
l
,
d
)
;
}

```

Try it online!

# Answer
> 11 votes
# Haskell, score 2, ~~492~~ ... ~~307~~ ~~224~~ ~~212~~ ~~209~~ 207 bytes

```
((yy:yyy))??ss|ss==yy  =  ""  |  yy==yy=yy:yyy??ss
ss??sss=ss
ss""=""

ss((ff:fff))  =  ff  :  ss  fff??ff
ff""=""

ff((xxx:xx))  =  ss((xxx:xx))##ff  xx
xx##xxx  |  ((((xx>>xx))<))  $  xxx>>xx=xxx|xx==xx=xx

```

Try it online!

Golfed literally hundreds of bytes thanks to W W and Ørjan Johansen!

### Explanation

The function `(??)` takes a character `c` and a string `s` and returns the longest prefix of `s` that does not contain `c`. Ungolfed and not optimized for score:

```
c ?? (y:s)
    | c==y = ""
    | True = y : c ?? s
c ?? s = s

```

The function `ss` uses `(??)` to find the longest prefix of unique chars of a given string:

```
ss (x:r) = x : (x ?? ss r)
ss "" = ""

```

`(##)` is a function which takes two strings and returns the longer one. The length comparison works by repeating the string `x` as often as `x` is long (`x>>y`) and as `y` is long (`y>>x`) and checking which of the resulting strings is lexicographically larger.

```
x ## y
  | (x>>x) < (y>>x) = y
  | True = x

```

Finally `ff` recurses over the input string, generates the longest prefix with `ss`, recursively determines the longest non-repeating substring of the tail of the string and returns the longer of the two with `(##)`:

```
ff "" = ""
ff (x:r) = ss(x:r) ## ff r

```

# Answer
> 5 votes
# Lua, score 3, 274 bytes

```
g='g'..'s'..'u'..'b'  _G  [  'l'..'o'..'a'..'d'  ](  g[g  ](  "s  =...f  o  r d = # s - 1 , 0 , - 1 d  o f  or r = 1 , # s - d d  o t = s :s  ub  (r  ,r  +d  )i  f n  ot t:  fi  nd  '(  .)  .*  %1  't  he  n p  ri  nt  (t  )r  et  ur  n en  d e  n  d e  nd  ","  ",""))(...)

```

Note: Lua 5.2 or Lua 5.3 is required

Usage:

```
$ lua lnrs.lua "Good morning, Green orb!"
ing, Gre
$ lua lnrs.lua "fffffffffff"
f
$ lua lnrs.lua "oiiiiioiiii"
oi
$ lua lnrs.lua "1234567890"
1234567890
$ lua lnrs.lua "11122324455"
324

```

Main idea: interleave everything with spaces, insert `" "` (two spaces) to split long identifiers

Ungolfed code:

```
g = "gsub"
_G["load"](
   g[g](      -- g[g] == string.gsub - a function for substitution of substrings
      "The source of actual program, but two-space sequences were inserted in some places",
      "  ",   -- we are replacing all two-space substrings
      ""      -- with an empty string
   )
)(...)

```

Actual program (after removing all pairs of spaces):

```
s = ...
for d = #s - 1, 0, -1 do
   for r = 1, #s - d do
      t = s:sub(r, r+d)
      if not t:find"(.).*%1" then
         print(t)
         return
      end
   end
end

```

BTW, the JS snippet for calculating the score fails on my code.

# Answer
> 4 votes
# Jelly, score 2, 14 bytes

```
Ẇµµff  Q  €  Ṫ

```

*Thanks to @JonathanAllan for score -1, +7 bytes and for noticing a bug.*

Try it online!

### How it works

```
Ẇµµff  Q  €  Ṫ  Main link. Argument: s (string)

Ẇ               Window; yield all substrings of s, sorted by length.
 µ              Begin a new chain. Argument: A (array of substrings)
  µ             Begin a new chain. Argument: A (array of substrings)
   f            Filter A by presence in itself. Does nothing.
       Q  €     Unique each; deduplicate all strings in A.
    f           Filter A by presence in the array of deduplicated substrings,
                keeping only substrings composed of unique characters.
             Ṫ  Tail; take the last (longest) kept substring.

```

# Answer
> 4 votes
# Retina 0.8.2, 37 bytes, score 9

```
.
$&$'¶
(.)(?<=\1.+).*

O#$^`
$.&
1G`

```

Try it online! The direct translation of this answer to Retina 1 saves a byte by using `N` instead of `O#`. However, if you naïvely golf the Retina 1 answer down to 28 bytes, its score actually rises to 10! Explanation:

```
.
$&$'¶

```

Generate all suffixes of the input.

```
(.)(?<=\1.+).*

```

For each suffix, take the prefix up to the first duplicated character.

```
O#$^`
$.&

```

Sort the remaining strings in reverse order of length (i.e. longest first).

```
1G`

```

Take the longest.

# Answer
> 4 votes
# Clean, score ~~7~~ 5, 276 bytes

```
@[ss:s]=rr(pp[][ss:s])((@s))
@s=s
ee x[rr:xx]|e x rr=True=ee x xx
ee x xx=f
f=e'e'' '
e::!  Char  !  Char  ->Bool
e  _ _=  code  {

eqC
}
pp p[r:rr]|ee r p=p=pp(a r p)rr
pp a _=a
a  x[ll:l]=[ll:a x  l]
a l ll=[l]
l[]rr=e'l''l'
l ff[]=f

l[r:rr][ss:ll]=l rr ll
rr x y|l x y=y=x

```

Try it online! Thanks to @Οurous for showing me that it is possible to call ABC machine code directly from within Clean. This allows to get rid of the previous bottle-neck `import` which set the minimal score to 7, but needs the keyword `code` which sets the minimal score to 5 for this approach.

An ungolfed and not score-optimized version of the above code can be found here: Try it online!

---

### Previous version with score 7, ~~158~~ ~~154~~ 130 bytes

```
import  StdEnv
@[xx:rr]=c(%[][xx:rr])(@rr)
@e=e
c s b|  length  s<  length  b=b=s
%s[xx:r]|  isMember xx s=s= %(s++[xx])r
%r _=r

```

Try it online!

With the `import` the score cannot go below 7. Without the import one would need to implement equality on strings or chars without any library functions which is ~~probably not~~ possible, as can be seen in the new version above.

# Answer
> 3 votes
# Python 3, score 4, 155 bytes

```
exec(('l=la''mbd''a f'',e=en''ume''rat''e:m''ax''([f[ j  :k]  for  j,i in e ( f)f''or  k,i in e ( f )if  len  ( { *''f[j'':k]''})==k-''j],''key''=le''n)'))

```

This defines a function `l`.

*Thanks to @xnor for pointing out that strings of length 3 don't raise the score, saving 32 bytes.*

Try it online!

# Answer
> 3 votes
# Brachylog, score 2, 19 bytes

```
s  ᶠ  l  ᵒ  ≠  ˢ  t

```

Try it online!

Just a boring old "space everything out" answer. At least I learnt that metapredicates can be spaced away from the predicates and still work (and the (parametric) subscripts and superscripts can't).

`s ᶠ` \- find all substrings of the given string

`l ᵒ` \- order them by their length (ascending by default)

`≠ ˢ` \- select those that have all distinct elements

`t` \- get the tail (last element) of that - the one with the biggest length

# Answer
> 2 votes
# Pyth, 11 bytes, score 4

-4 score thanks to Dennis

```
e lD {I# .:

```

---

```
elD{I#.:Q      Full program, inputs "string" from stdin and outputs to stdout
e              The last element of the list generated by taking
      .:Q      All substrings of the input
     #         Filtered for
   {I          Being invariant over deduplicate i.e. being "non-repeating"
 lD            and sorted by length

```

Try it online!

# Answer
> 2 votes
# Husk, score 2, 10 bytes

```
►IIËII≠IIQ

```

Try it online!

## Explanation

The program is equivalent to this:

```
►Ë≠Q  Implicit input.
   Q  List of substrings.
►     Find one that maximizes:
 Ë    all ordered pairs
  ≠   are inequal.

```

The built-in `Ë` evaluates  on all ordered pairs of its argument `x`, and returns `length(x)+1` if every result is truthy, otherwise `0`. When we maximize this, we find the longest string that has no repeated characters.

In the submission, I just insert the identity function `I` between each function, twice. Since  is the same as `Ë`, `I≠` is the same as  and so on, this does not change the semantics. The only danger is that a higher order function could decide to use one of the `I`s as its argument, but luckily that leads to a type error in our program, so it doesn't happen.

# Answer
> 2 votes
## Clojure, score 4

```
#(  let  [N  (fn  [[_ & r]] r) R  (fn  R [f v c]  (if  c (R f (f v (  nth  c 0))  ( N  c)) v)) C  (fn  C  (  [i]  (C (  seq  i) 0)) ( [i  n]  (if i (C ( N  i )  (  inc n)) n)))  J  (fn  [c  i]  (assoc c (C  c) i)) I  (fn  F [f i n R]  (if ( =  (C  R) n) R (F f (f  i) n ( J  R (f  i)))))] ( apply  str  (R ( fn  [a  b] ( if  (< (C  a)  (C  b)) b a )) "" (  for  [k  (I N % (C  % ) [])]  (R  ( fn [ t  c ] ( if ( or ( = t (  str t) ) ((  set t)c))(apply  str t) ( J  t c)))[]k)))))

```

Oh man this was painful! `N` implements `next`, `R` is `reduce`, `C` is `count`, `J` is `conj` (works only for vectors) and `I` is `iterate`. `apply str` is there twice because otherwise "aaaa" input wouldn't return a string but a vector `[\a]`. Luckily I got to use `apply` and `assoc`, I didn't know you could assoc one index beyond a vector's last element :o

# Answer
> 1 votes
# Jelly, score 5, 10 bytes

```
ẆµQQ⁼µÐfµṪ

```

Try it online!

# Answer
> 1 votes
# Python 3, score 4, 317 bytes

```
exec(('%s'  *58  %(  's=','in','pu','t(',');','pr','in','t(','so','rt','ed','((s','[i',':j',']f','or',' j',' i','n ','ra','ng','e(','1,','le','n(','s)','+1',')f','or',' i',' i','n ','ra','ng','e(','j)','if',' l','en','(s','et','(s','[i',':j',']))','==l','en','(s','[i',':j',']))',',k','ey','=l','en',')[','-1','])')))

```

Try it online!

Unexeced code:

```
s=input();print(sorted((s[i:j]for j in range(1,len(s)+1)for i in range(j)if len(set(s[i:j]))==len(s[i:j])),key=len)[-1])

```

`lambda a` contains `mbda`  which has score 5, and a function needs `return` which apparently can't be `exec`ed (so takes a score of at least 5 for `eturn`), so a full program was necessary. It's probably possible to golf down the unexeced code size quite a bit, but I can't see a quick clear improvement.

# Answer
> 1 votes
# Java 8, score ~~9 (384 B)~~ 7 (401 B)

```
S -> { int s = 0 , e = 0 , l = 0 , x = 0 , y = 0 , b [ ] = new int [ 256 ] ; for ( ; x <S.  length  & y <S.  length  & l <S.  length  - x ; x ++ ) { b [S[x]] = 1 ; for ( y ++ ; y <S.  length  && b [S[y]] < 1 ; b [S[y ++]] = 1 ) ; if ( l < y - x ) { s = x ; e = y ; l = y - x ; } for ( ; y <S.  length  && x < y & S[x] != S[y  ];)b [S[x ++]] = 0 ; }  String g=""; for( ; s<e ; g+= S[s++]);  return  g;}

```
* ~~Initial version. Will go down from here. Score is 9 due to `"ubstring "`, so `substring` will be the first part to replace.~~
* Score is now 7 due to `" length"`, which I probably won't be able to reduce further.. I doubt it is possible to drop the four uses of `length`. If it is possible, `" eturn"` (6) might lower the score by 1 as final improvement, but I guess this is it (except maybe a small reduce in byte-count..)

Try it online.

# Answer
> 1 votes
# Alice, 40 bytes

```
/ii..nn$$@@BBww..DD~~FF..!!nn$$KK??oo@@

```

(Trailing newline)

Try it online!

The instruction pointer moves diagonally in ordinal mode, so only every other character is executed.

```
i.n$@Bw.D~F.!n$K?o@

i     take input
.n$@  terminate if empty
B     push all nonempty substrings, with the longest on the top of the stack
w     push return address (start main loop)
.     make copy of current substring
D     deduplicate characters
~     swap: this places the original above the deduplicated copy
F     Push the original string if it is a substring of the deduplicated copy
      (which can only happen if they're equal); otherwise push empty string
.!    place a copy on the tape
n$K   if the empty string was pushed, return to start of loop
o     output
@     terminate

```

# Answer
> 1 votes
# Perl 6, score: ~~15 10~~ 8, length: ~~46 55~~ 62 bytes

```
{~m:ov/(.+)<!{$0.comb.repeated}>/.max(&chars)}

```

Test it

```
{~m:ov/(..*)<!{(($0)).comb.repeated}>{{}}/.max(&chars)}

```

Test it

```
{m:ov:i/(..*)<!{(($0)).comb.repeated}>{{}}/.max((&chars)).Str}

```

Test it

## Expanded:

```
{    # bare block lambda with implicit parameter ｢$_｣

    m                          # match (implicitly against ｢$_｣)
    :overlap                   # in every single way possible
    :ignorecase                # add a ｢:｣ to break up substring
    /

      (..*)                    # match at least one character

      <!{
        (($0)).comb.repeated  # backtrack if there were repeats
      }>

      {{}}                    # anon hash in code block (no-op)
    /

    .max((&chars))            # get the longest

    .Str                      # coerce to a Str (from a Match object)
}

```

# Answer
> 0 votes
# Haskell, score 7

*-4 thanks to Laikoni.*

```
import  Data.List
f s=snd $ maximum [ (0<$i ,i)|i<-  tails  =<<inits s, nub i==i]

```

Try it online!

# Answer
> 0 votes
# Kotlin, score: ~~11~~ ~~10~~ 9 bytes, length: ~~227~~ ~~246~~ 245 bytes

```
indices
  .flatMap { p -> indices . map { p to p + it } }
  .  filter { (r,i) -> i < length  }
  .map { ( s , a )->substring  (  s,  a  ) }
  .  filter { it  .  groupBy  { it } .  none { ( k , v )->v . size>1 } }
  .maxBy { it.length }

```

The longest is `ubstring`, which is 9 chars

It is called like this:

```
val c = "Good morning, Green orb!"

fun String.c(): String? = indices
    .flatMap { p -> indices . map { p to p + it } }
    .  filter { (r,i) -> i < length  }
    .map { ( s , a )->substring  (  s,  a  ) }
    .  filter { it  .  groupBy  { it } .  none { ( k , v )->v . size>1 } }
    .maxBy { it.length }

fun main(args: Array<String>) {
    val text = """indices
    .flatMap { p -> indices . map { p to p + it } }
    .  filter { (r,i) -> i < length  }
    .map { ( s , a )->substring  (  s,  a  ) }
    .  filter { it  .  groupBy  { it } .  none { ( k , v )->v . size>1 } }
    .maxBy { it.length }"""
    val message = text.c()!!
    println(message)
    println(text.length)
    println(message.length)
    println(c.c())
}

```

# Answer
> 0 votes
## Mathematica, score ~~11~~ 9

```
Length@Last@Select[Subsequences[Characters@#],#==DeleteDuplicates  @#&]&

```

Shaving a couple of bytes off of the longest nonrepeating string by obscuring the function's name:

```
Length@Last@Select[Subsequences[Characters  @#],#==(  ToExpression@
StringJoin@@FromCharacterCode@{{68},{101},{108},{101},{116},{101},{68},{117},
{112},{108},{105},{99},{97},{116},{101},{115}}))@#&]&

```

# Answer
> 0 votes
# Pyth, score 3 ( ~~18~~  14 bytes)

```
e  fq  T{T  .:

```

**Try it online!**

The longest non-repeating substrings is `.:`.

# Answer
> 0 votes
# 05AB1E, 22 bytes | Score: 2

```
Œ  ʒ  D  Ù  Q  }  é  ¤

```

*-1 score + 7 bytes thanks to HeebyJeeby*

Try it online!

---

# 05AB1E, 15 bytes | Score: 3

```
Œ ʒ D Ù Q } é ¤

```

Try it online!

---

# 05AB1E, 8 bytes | Score: 8

```
ŒʒDÙQ}é¤

```

Try it online!

---

05AB1E can actually do something rather cheap... adding whitespace into 05AB1E does nothing.

If there is a rule against this, I can also use `´` and like 7 other chars.

---
Tags: string, code-challenge, source-layout
---