title: Generate Wordenticons

text:
# Question
Title: Generate Wordenticons
Identicons are visual depictions of hash values, often made from symmetrical arrangements of geometric shapes. Your default Stack Exchange avatar is an identicon. This challenge is about creating **"wordenticons"**, simple text-based versions of identicons that apply to strings of lowercase letters, i.e. words.

# Challenge

Write a program or function that takes in a string S and outputs its wordenticon. S is guaranteed to be nonempty and only contain lowercase English letter characters a-z. You may optionally assume S has a trailing newline.

The wordenticon of S will be a square grid of text with side lengths `2*length(S)` composed of spaces (), vertical bars, (`|`), and horizontal bars ().

To generate the wordenticon of S, form a square grid where every column corresponds to a letter of S (in normal left-to-right reading order) and every row corresponds to a letter of S (in normal top-to-bottom reading order).

For example, if S is `food` our initial grid looks like

```
 food
f....
o....
o....
d....

```

where `.` is just a placeholder.

For every empty point (every `.`) in the grid:

1. If the column letter comes before the row letter alphabetically, replace the `.` with `|`.
2. If the column letter comes after the row letter alphabetically, replace the `.` with .
3. If the column and row letters are the same, replace the `.` with  (space).

Here is the `food` example after each of these steps:

1. Adding `|`'s:

```
 food
f...|
o|..|
o|..|
d....

```
2. Adding 's:

```
 food
f.――|
o|..|
o|..|
d―――.

```
3. Adding 's:

```
 food
f ――|
o|  |
o|  |
d―――

```

To complete the wordenticon, remove the superfluous row and column containing the words

```
 ――|
|  |
|  |
―――

```

then mirror the entire thing horizontally

```
 ――||――
|  ||  |
|  ||  |
―――  ―――

```

and finally mirror it again vertically

```
 ――||――
|  ||  |
|  ||  |
―――  ―――
―――  ―――
|  ||  |
|  ||  |
 ――||――

```

resulting in the `2*length(S)` side length text grid that is the final wordenticon.

# Examples

Here are some additional wordenticon examples. Note that different words can have identical wordenticons and some wordenticons can be completely made of spaces (unfortunately markdown does not want to render those).

```
food

 ――||――
|  ||  |
|  ||  |
―――  ―――
―――  ―――
|  ||  |
|  ||  |
 ――||――

mood

 ――||――
|  ||  |
|  ||  |
―――  ―――
―――  ―――
|  ||  |
|  ||  |
 ――||――

foof

 ――  ――
|  ||  |
|  ||  |
 ――  ――
 ――  ――
|  ||  |
|  ||  |
 ――  ――

fool

 ――――――
|  ||  |
|  ||  |
|――  ――|
|――  ――|
|  ||  |
|  ||  |
 ――――――

a [2*2 grid of spaces]

to

 ||
―  ―
―  ―
 ||

it

 ――
|  |
|  |
 ――

tt [4*4 grid of spaces]

abc

 ――――
| ―― |
||  ||
||  ||
| ―― |
 ――――

and

 ――――
| || |
|―  ―|
|―  ―|
| || |
 ――――

but

 ――――
| || |
|―  ―|
|―  ―|
| || |
 ――――

you

 ||||
― ―― ―
―|  |―
―|  |―
― ―― ―
 ||||

bob

 ―  ―
| || |
 ―  ―
 ―  ―
| || |
 ―  ―

cat

 |――|
― ―― ―
||  ||
||  ||
― ―― ―
 |――|

cart

 |――――|
― ―――― ―
|| ―― ||
|||  |||
|||  |||
|| ―― ||
― ―――― ―
 |――――|

todo

 ||||||
― |  | ―
―― ―― ――
― |  | ―
― |  | ―
―― ―― ――
― |  | ―
 ||||||

mice

 ||||||
― |||| ―
―― ―― ――
――|  |――
――|  |――
―― ―― ――
― |||| ―
 ||||||

zyxw

 ||||||
― |||| ―
―― || ――
―――  ―――
―――  ―――
―― || ――
― |||| ―
 ||||||

banana

 |―|―||―|―|
― ― ―  ― ― ―
|| | || | ||
― ― ―  ― ― ―
|| | || | ||
― ― ―  ― ― ―
― ― ―  ― ― ―
|| | || | ||
― ― ―  ― ― ―
|| | || | ||
― ― ―  ― ― ―
 |―|―||―|―|

codegolf

 ――――――――――――――
| ||| |||| ||| |
|― ―――――――――― ―|
|―| ―――――――― |―|
|―|| ――||―― ||―|
| ||| |||| ||| |
|―|||― || ―|||―|
|―||―――  ―――||―|
|―||―――  ―――||―|
|―|||― || ―|||―|
| ||| |||| ||| |
|―|| ――||―― ||―|
|―| ―――――――― |―|
|― ―――――――――― ―|
| ||| |||| ||| |
 ――――――――――――――

programming

 ―||―||||||||||||―||―
| || |||||||||||| || |
―― |―||||||||||||―| ――
――― ―|――――  ――――|― ―――
| || |||||||||||| || |
――――― ―――――――――― ―――――
―――|―|  |―||―|  |―|―――
―――|―|  |―||―|  |―|―――
―――|―|―― ―||― ――|―|―――
―――|―|||| || ||||―|―――
――― ―|――――  ――――|― ―――
――― ―|――――  ――――|― ―――
―――|―|||| || ||||―|―――
―――|―|―― ―||― ――|―|―――
―――|―|  |―||―|  |―|―――
―――|―|  |―||―|  |―|―――
――――― ―――――――――― ―――――
| || |||||||||||| || |
――― ―|――――  ――――|― ―――
―― |―||||||||||||―| ――
| || |||||||||||| || |
 ―||―||||||||||||―||―

abcdefghijklm

 ――――――――――――――――――――――――
| ―――――――――――――――――――――― |
|| ―――――――――――――――――――― ||
||| ―――――――――――――――――― |||
|||| ―――――――――――――――― ||||
||||| ―――――――――――――― |||||
|||||| ―――――――――――― ||||||
||||||| ―――――――――― |||||||
|||||||| ―――――――― ||||||||
||||||||| ―――――― |||||||||
|||||||||| ―――― ||||||||||
||||||||||| ―― |||||||||||
||||||||||||  ||||||||||||
||||||||||||  ||||||||||||
||||||||||| ―― |||||||||||
|||||||||| ―――― ||||||||||
||||||||| ―――――― |||||||||
|||||||| ―――――――― ||||||||
||||||| ―――――――――― |||||||
|||||| ―――――――――――― ||||||
||||| ―――――――――――――― |||||
|||| ―――――――――――――――― ||||
||| ―――――――――――――――――― |||
|| ―――――――――――――――――――― ||
| ―――――――――――――――――――――― |
 ――――――――――――――――――――――――
```

# Scoring

This is , the shortest code in bytes wins. Tiebreaker goes to the earlier answer.

# Notes

* Any instance of horizontal bar () in your code may be counted as 1 byte instead of the 3 UTF-8 bytes it actually takes up. (Up to ten instances.)
* If desired you may use regular dashes (`-`) in place of horizontal bars ().
* Removing or adding trailing spaces in the lines of a wordenticon is not allowed (even if the shape remains unchanged). It should be an exact `2*length(S)` side length text square.
* The output wordenticon may optionally have a single trailing newline.

# Answer
> 21 votes
# MATL, ~~20~~ 15 bytes

```
'-| 'jtPht!-ZS)

```

Try it at **MATL Online**

**Explanation**

```
'-| '       % String literal defining the replacement characters
j           % Explicitly grab the input as a string
tP          % Duplicate and reverse the input string (row vector of chars)
h           % Horizontally concatenate the input and it's inverse
t!          % Duplicate and turn into a column vector
-           % Subtract the two vectors (converts to ASCII codes) and we automatically
            % broadcast to create a (2N x 2N) matrix where if the column is
            % later in the alphabet (higher ASCII) we get a positive number, if the
            % column was earlier (lower ASCII) we get a negative number, and if they are
            % the same letter (same ASCII) we get a 0.
ZS          % sign function which yields -1 for negative, 1 for positive, and 0 for 0;
)           % Use this to index (modulus) into the string literal '-| '. MATL uses 1-based
            % indexing so 0 yields ' ', -1 replaced by '|', and 1 replaced by '-'
            % Implicitly display the result

```

# Answer
> 18 votes
# Java, ~~329~~ ~~305~~ ~~264~~ ~~259~~ 192 bytes

Thanks to:

* @Bálint for suggesting to use ternary operators.
* @user902383 for suggesting to reverse the string myself
* @Frozn and @user902383 for suggesting to replace `StringBuilder` with `String`.

Golfed:

```
String g(String w){char[]a=w.toCharArray();String s="";for(int i=a.length-1;i>=0;s=s+a[i--]);w+=s;a=w.toCharArray();s="";for(char x:a){for(char y:a)s+=(x>y?'|':x<y?'-':' ');s+='\n';}return s;}

```

Ungolfed:

```
String g(String w) {
    char[] a = w.toCharArray();
    String s = "";
    for (int i = a.length - 1; i >= 0; s = s + a[i--]);
    w += s;
    a = w.toCharArray();
    s = "";// To keep the output pure (ie. without the input string as well)
    for (char x : a) {
        for (char y : a)
            s += (x > y ? '|' : x < y ? '-' : ' ');
        s += '\n';
    }
    return s;
}

```

Definitely a fun one. First attempt was a function that was `O(n)` but ended up getting replaced with this simpler form after I got too frustrated.

And, to test:

```
supercalifragilisticexpialidocious
 -|||||||||||||| -|||-||||||||||-  -||||||||||-|||- ||||||||||||||-
| |||||||||||||||||||-|||||||||| || ||||||||||-||||||||||||||||||| |
-- |-|||||-|||||--|||- |||||||||----||||||||| -|||--|||||-|||||-| --
--- -||----|-------| ---|--|-|--------|-|--|--- |-------|----||- ---
--|| ||||| |||||--|||-||||||||||----||||||||||-|||--||||| ||||| ||--
----- |----|------- ----|---- -------- ----|---- -------|----| -----
------ ---- ------------ ------------------ ------------ ---- ------
---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|---
---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
---|-||-- -|-------||---|--|-|--------|-|--|---||-------|- --||-|---
--|| ||||| |||||--|||-||||||||||----||||||||||-|||--||||| ||||| ||--
------ ---- ------------ ------------------ ------------ ---- ------
---|-||--|-| ------||---|--|-|--------|-|--|---||------ |-|--||-|---
---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|---
---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
 -|||||||||||||| -|||-||||||||||-  -||||||||||-|||- ||||||||||||||-
|-||||||||||||||| |||-||||||||||-||-||||||||||-||| |||||||||||||||-|
---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
----- |----|------- ----|---- -------- ----|---- -------|----| -----
--- -||----|-------| ---|--|-|--------|-|--|--- |-------|----||- ---
||||||||||||||||||||| |||||||||||||||||||||||| |||||||||||||||||||||
-- |-|||||-|||||--|||- |||||||||----||||||||| -|||--|||||-|||||-| --
---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
------ ---- ------------ ------------------ ------------ ---- ------
---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|---
---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
-----||----|-------|----|-- -|--------|- --|----|-------|----||-----
---|-|||||-|||||--|||--||||| || ---- || |||||--|||--|||||-|||||-|---
----- |----|------- ----|---- -------- ----|---- -------|----| -----
---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
---|-|||||-|||||--|||--||||| || ---- || |||||--|||--|||||-|||||-|---
| |||||||||||||||||||-|||||||||| || ||||||||||-||||||||||||||||||| |
 -|||||||||||||| -|||-||||||||||-  -||||||||||-|||- ||||||||||||||-
 -|||||||||||||| -|||-||||||||||-  -||||||||||-|||- ||||||||||||||-
| |||||||||||||||||||-|||||||||| || ||||||||||-||||||||||||||||||| |
---|-|||||-|||||--|||--||||| || ---- || |||||--|||--|||||-|||||-|---
---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
----- |----|------- ----|---- -------- ----|---- -------|----| -----
---|-|||||-|||||--|||--||||| || ---- || |||||--|||--|||||-|||||-|---
-----||----|-------|----|-- -|--------|- --|----|-------|----||-----
---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|---
------ ---- ------------ ------------------ ------------ ---- ------
---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
-- |-|||||-|||||--|||- |||||||||----||||||||| -|||--|||||-|||||-| --
||||||||||||||||||||| |||||||||||||||||||||||| |||||||||||||||||||||
--- -||----|-------| ---|--|-|--------|-|--|--- |-------|----||- ---
----- |----|------- ----|---- -------- ----|---- -------|----| -----
---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
|-||||||||||||||| |||-||||||||||-||-||||||||||-||| |||||||||||||||-|
 -|||||||||||||| -|||-||||||||||-  -||||||||||-|||- ||||||||||||||-
---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|---
---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
---|-||--|-| ------||---|--|-|--------|-|--|---||------ |-|--||-|---
------ ---- ------------ ------------------ ------------ ---- ------
--|| ||||| |||||--|||-||||||||||----||||||||||-|||--||||| ||||| ||--
---|-||-- -|-------||---|--|-|--------|-|--|---||-------|- --||-|---
---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|---
------ ---- ------------ ------------------ ------------ ---- ------
----- |----|------- ----|---- -------- ----|---- -------|----| -----
--|| ||||| |||||--|||-||||||||||----||||||||||-|||--||||| ||||| ||--
--- -||----|-------| ---|--|-|--------|-|--|--- |-------|----||- ---
-- |-|||||-|||||--|||- |||||||||----||||||||| -|||--|||||-|||||-| --
| |||||||||||||||||||-|||||||||| || ||||||||||-||||||||||||||||||| |
 -|||||||||||||| -|||-||||||||||-  -||||||||||-|||- ||||||||||||||-

```

# Answer
> 11 votes
## Haskell, 93 bytes

```
r=reverse
h x=unlines$(++)<*>r$zipWith(++)<*>map r$(<$>x).((("- |"!!).fromEnum).).compare<$>x

```

Usage example:

```
*Main> putStr $ h "food"
 --||--
|  ||  |
|  ||  |
---  ---
---  ---
|  ||  |
|  ||  |
 --||--

```

How it works (note: `(f <*> g) x` is defined as `f x (g x)`):

```
((("- |"!!).fromEnum).).compare       -- a function that finds the replacement char
                                      -- for two given chars
   (<$>x).(    )<$>x                  -- map this function for every char in the
                                      -- input over each char. Now we have the
                                      -- first quadrant as a list of strings
zipWith(++) <*> map r                 -- append to each line a reversed copy of itself
(++) <*> r                            -- append a reversed copy of the whole list
unlines                               -- turn into a single string

```

Alternative version: the "find replacement" function `((("- |"!!).fromEnum).).compare` can also be written as `a#b|a<b='-'|a>b='|'|1<2=' '` and called via `(#)` for the same byte count.

# Answer
> 8 votes
# Jelly, 16 bytes

```
Om©0_'®Ṡị“-| ”j⁷

```

Try it online!

### How it works

```
Om©0_'®Ṡị“-| ”j⁷  Main link. Argument: s (string)

O                 Ordinal; replace the characters of s with their code points.
 m 0              Concatenate the result with a reversed copy.
  ©               Copy the result to the register.
      ®           Yield the list in the register.
    _'            Perform spawned difference of the character codes.
       Ṡ          Apply the sign function.
        ị“-| ”    Index into that string (indices 1, -1, 0).
              j⁷  Join, separating by linefeeds.

```

# Answer
> 8 votes
## JavaScript (ES6), 94 bytes

```
s=>[...s,s].reverse().join``.replace(/./g,(c,_,t)=>t.replace(/./g,d=>d<c?`|`:d>c?`-`:` `)+`
`)

```

Using a dash because I usually run the SpiderMonkey JS shell on Windows and Unicode doesn't work if I do that.

# Answer
> 5 votes
# Pyth, ~~31~~ 30

```
js_BsM_BMclQsm@" |―"._-FCMd*QQ

```

Test Suite

Sadly can't drop the `Q`s because of the several bifurcates. Pretty basic algorithm so far, count treats the horizontal bar as 1 byte.

# Answer
> 5 votes
# Haskell, 66 bytes

```
u s|e<-s++reverse s=unlines[["- |"!!min(length[a..b])2|a<-e]|b<-e]

```

# Answer
> 4 votes
# JavaScript ES6, ~~138~~ ~~126~~ 123 bytes

```
s=>(a=(p=[...s]).map(l=>(b=p.map(i=>i<l?"|":i>l?"-":" ").join``)+[...b].reverse().join``)).concat([...a].reverse()).join`
`

```

most of the code is the reflecting / flipping

# Answer
> 4 votes
# J, ~~26~~ 20 bytes

6 bytes thanks to @Zgarb.

```
' |-'{~3*@-/~@u:[,|.

```

### Previous 26-byte answer

```
({&' |-')@*@-/~@(3&u:)@,|.

```

Uses the same algorithm as Dennis' answer.

Usage:

```
>> f =: ' |-'{~3*@-/~@u:[,|.
>> f 'food'
<<  --||--
   |  ||  |
   |  ||  |
   ---  ---
   ---  ---
   |  ||  |
   |  ||  |
    --||--

>> f 'supercalifragilisticexpialidocious'
<<  -|||||||||||||| -|||-||||||||||-  -||||||||||-|||- ||||||||||||||-
   | |||||||||||||||||||-|||||||||| || ||||||||||-||||||||||||||||||| |
   -- |-|||||-|||||--|||- |||||||||----||||||||| -|||--|||||-|||||-| --
   --- -||----|-------| ---|--|-|--------|-|--|--- |-------|----||- ---
   --|| ||||| |||||--|||-||||||||||----||||||||||-|||--||||| ||||| ||--
   ----- |----|------- ----|---- -------- ----|---- -------|----| -----
   ------ ---- ------------ ------------------ ------------ ---- ------
   ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|---
   ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
   ---|-||-- -|-------||---|--|-|--------|-|--|---||-------|- --||-|---
   --|| ||||| |||||--|||-||||||||||----||||||||||-|||--||||| ||||| ||--
   ------ ---- ------------ ------------------ ------------ ---- ------
   ---|-||--|-| ------||---|--|-|--------|-|--|---||------ |-|--||-|---
   ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
   ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|---
   ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
    -|||||||||||||| -|||-||||||||||-  -||||||||||-|||- ||||||||||||||-
   |-||||||||||||||| |||-||||||||||-||-||||||||||-||| |||||||||||||||-|
   ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
   ----- |----|------- ----|---- -------- ----|---- -------|----| -----
   --- -||----|-------| ---|--|-|--------|-|--|--- |-------|----||- ---
   ||||||||||||||||||||| |||||||||||||||||||||||| |||||||||||||||||||||
   -- |-|||||-|||||--|||- |||||||||----||||||||| -|||--|||||-|||||-| --
   ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
   ------ ---- ------------ ------------------ ------------ ---- ------
   ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|---
   ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
   -----||----|-------|----|-- -|--------|- --|----|-------|----||-----
   ---|-|||||-|||||--|||--||||| || ---- || |||||--|||--|||||-|||||-|---
   ----- |----|------- ----|---- -------- ----|---- -------|----| -----
   ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
   ---|-|||||-|||||--|||--||||| || ---- || |||||--|||--|||||-|||||-|---
   | |||||||||||||||||||-|||||||||| || ||||||||||-||||||||||||||||||| |
    -|||||||||||||| -|||-||||||||||-  -||||||||||-|||- ||||||||||||||-
    -|||||||||||||| -|||-||||||||||-  -||||||||||-|||- ||||||||||||||-
   | |||||||||||||||||||-|||||||||| || ||||||||||-||||||||||||||||||| |
   ---|-|||||-|||||--|||--||||| || ---- || |||||--|||--|||||-|||||-|---
   ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
   ----- |----|------- ----|---- -------- ----|---- -------|----| -----
   ---|-|||||-|||||--|||--||||| || ---- || |||||--|||--|||||-|||||-|---
   -----||----|-------|----|-- -|--------|- --|----|-------|----||-----
   ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
   ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|---
   ------ ---- ------------ ------------------ ------------ ---- ------
   ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
   -- |-|||||-|||||--|||- |||||||||----||||||||| -|||--|||||-|||||-| --
   ||||||||||||||||||||| |||||||||||||||||||||||| |||||||||||||||||||||
   --- -||----|-------| ---|--|-|--------|-|--|--- |-------|----||- ---
   ----- |----|------- ----|---- -------- ----|---- -------|----| -----
   ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
   |-||||||||||||||| |||-||||||||||-||-||||||||||-||| |||||||||||||||-|
    -|||||||||||||| -|||-||||||||||-  -||||||||||-|||- ||||||||||||||-
   ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
   ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|---
   ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
   ---|-||--|-| ------||---|--|-|--------|-|--|---||------ |-|--||-|---
   ------ ---- ------------ ------------------ ------------ ---- ------
   --|| ||||| |||||--|||-||||||||||----||||||||||-|||--||||| ||||| ||--
   ---|-||-- -|-------||---|--|-|--------|-|--|---||-------|- --||-|---
   ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|---
   ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|---
   ------ ---- ------------ ------------------ ------------ ---- ------
   ----- |----|------- ----|---- -------- ----|---- -------|----| -----
   --|| ||||| |||||--|||-||||||||||----||||||||||-|||--||||| ||||| ||--
   --- -||----|-------| ---|--|-|--------|-|--|--- |-------|----||- ---
   -- |-|||||-|||||--|||- |||||||||----||||||||| -|||--|||||-|||||-| --
   | |||||||||||||||||||-|||||||||| || ||||||||||-||||||||||||||||||| |
    -|||||||||||||| -|||-||||||||||-  -||||||||||-|||- ||||||||||||||-

```

(`>>` meaning input (STDIN), `<<` meaning output (STDOUT))

# Answer
> 3 votes
# Javascript ~~146~~ ~~142~~ ~~132~~ ~~130~~ 124 bytes

```
n=>(e=(a=[...n]).map(b=>(d=a.map(c=>c<b?"|":c>b?"-":" ")).concat([...d].reverse()).join``)).concat([...e].reverse()).join`
`

```

Test suite:

```
f=n=>{a=n.split``;e=a.map(b=>a.map(c=>c<b?"|":c>b?"-":" ")).map(d=>d.concat([...d].reverse()).join``);alert(e.concat([...e].reverse()).join`
`)}

f(prompt("Enter string!"));
```

Thanks for @HelkaHomba, for helping to remove at least 50 bytes, and to @Downgoat for 3 bytes!

# Answer
> 3 votes
# Mathematica, ~~124~~ ~~110~~ ~~104~~ 102 bytes

```
a=Join[#,Reverse@#]&;#<>"
"&/@a@a@Table[{"|"," ","-"}[[c~Order~d+2]],{c,b=Characters@#},{d,b}]<>""&

```

Anonymous function. The Unicode character is U+F3C7 for `\[Transpose]`.

# Answer
> 3 votes
# C# ~~166~~ 143 bytes,

```
using System.Linq;s=>string.Join("\n",(s+=string.Concat(s.Reverse())).Select(x=>s.Aggregate("",(c, y)=>c+"- |"[Math.Sign(x.CompareTo(y))+1])));

```

### Explanation:

```
using System.Linq;

s=>                                     // Expression bodied member allows for implicit return
  string.Join("\n",                     // Join the generate lines into the final output
    (s+=string.Concat(s.Reverse()))     // Combine s and its reverse inline so aggregate has the whole line
        .Select(x=>                     // For each character in the line run the aggregate to generate its row
            s.Aggregate("",             // Empty string is required to cooerce the output type from char
                (c, y)=>                // c is the generated string so far, y is the next character
                        c+
                                        // Compare the two letters here (row to column)
                                        // Then take the sign of the result to collapse to -1, 0, or 1
                                        // Finally add 1 to line it up with the indexes of the constant string;
                        "- |"[Math.Sign(x.CompareTo(y))+1]
)));

```

Test:

```
Wordenticons

 ||||||||||||||||||||||
- -|||-|| |--| ||-|||- -
-| |||-||||--||||-||| |-
--- ----|------|---- ---
---| ---|------|--- |---
---|| -||- -- -||- ||---
-||||| |||||||||| |||||-
---||-- |------| --||---
-------- ------ --------
- -|||-|| |--| ||-|||- -
---|| -||- -- -||- ||---
-|||||-||||  ||||-|||||-
-|||||-||||  ||||-|||||-
---|| -||- -- -||- ||---
- -|||-|| |--| ||-|||- -
-------- ------ --------
---||-- |------| --||---
-||||| |||||||||| |||||-
---|| -||- -- -||- ||---
---| ---|------|--- |---
--- ----|------|---- ---
-| |||-||||--||||-||| |-
- -|||-|| |--| ||-|||- -
 ||||||||||||||||||||||

```

# Answer
> 3 votes
## Actually, 53 bytes

```
;l╗;∙`♂O♂ii-s3@%" |-"E`MW╜`d@`nkd@Σ'.o@WX'.@s;R+;♂R¥i

```

Once again, Actually's poor string-processing abilities are its kryptonite. It's still shorter than Java, so I have that going for me, which is nice.

Try it online!

Explanation:

The code can be separated into 3 distinct portions: the translation code, the processing code, and the mirroring code. For readability, I'm going to explain each section separately.

Translation code (starts with the input string, `s`, on the stack):

```
;l╗;∙`♂O♂ii-s3@%" |-"E`M
;l╗                       push len(s) to reg0 (needed for processing step; we'll call this n)
   ;∙                     cartesian product of s with itself
     `♂O♂ii-s3@%" |-"E`M  map:
      ♂O♂ii                 get a pair of ordinals for the characters
           -s               subtract, signum
             3@%            mod by 3 because element access with negative indices isn't working
                " |-"E      get corresponding string

```

Processing code (starts with a list of `n**2` characters, corresponding to the bottom-right corner):

```
W╜`d@`nkd@Σ'.o@WX
W╜`d@`nkd@Σ'.o@W   while loop (while top of stack is truthy):
 ╜`d@`n              remove n characters from the list
       kd@Σ'.o       concatenate those n characters, and append a period
                X  discard the empty list

```

Mirroring code (starts with a `n**2+n`-length string, with periods acting as newlines)

```
'.@s;R+;♂R¥i
'.@s          split on periods
    ;R+       add the reverse list (vertical mirror)
       ;♂R    make a copy of the list with each string reversed (horizontal mirror)
          ¥   concatenate each pair of strings in the two lists (zip-concat)
           i  flatten list
              (implicitly print each stack item, separated by newlines)

```

# Answer
> 3 votes
# \>\<\>, 109 bytes

```
i:0(?\:}
,[r]l\~l2,[r]rl2
1-:?!\$:}l1-[}
~]\  \
&r\l:?!;1-
?!\$:@@:@$:@@:@)}(}"- |"{?$@{?$o~~$}&1-:&
4.>~ao]2

```

Input is via STDIN. Try it online!

**Explaination:**

The input it read and mirrored on the first line. For input `abcd`, this leaves `dcbaabcd` on the stack. Each half is then mirrored to give `abcddcba` (line 2). Then, each element is duplicated and left on its own stack in turn (lines 3 and 4). After this process, the stack of stacks looks a little like this:

```
aabcddcba  <-- top of the stack of stacks
b
c
d
d
c
b
a          <-- bottom of the stack of stacks

```

For each stack in turn, the row value (the bottom of the stack) is compared to the column value (the top of the stack). The appropriate character is selected from `- |` and written to STDOUT. The column values are then rotated so that the next column is at the top of the stack (line 6).

Once all the columns have been considered, the row value is discarded, a newline printed, and the column values put onto the previous stack (line 7), for the output process to start again.

The `]` command, in addition to popping from the stack of stacks, empties the current stack if it is the only one left. The program's end condition is if the stack is empty, as all rows have been processed (line 5).

# Answer
> 2 votes
# J, ~~75~~ 70 bytes

5 bytes saved thanks to Dennis.

```
3 :'(],.|:@|.@|:)(],|.)''- |''{~]([:-.@*(,~@#$])-(,~@#$(##])@]))3 u:y'

```

I'll work on converting it into a tacit verb later.

# Answer
> 2 votes
## CJam, 20 bytes

```
l_W%+_ff{-g" |―"=}N*

```

Test it here.

Uses the obvious approach of computing an outer product and using difference and *sgn* to compute the character in each cell.

# Answer
> 2 votes
## C#, ~~169~~ 150 bytes

thanks FryAmTheEggman

```
void f(string s){s+=new string(s.Reverse().ToArray());foreach(char c in s){var t="";foreach(char k in s)t+=c==k?" ":c>k?"|":"-";Console.WriteLine(t);}

```

ungolfed:

```
    public static void f(string s)
    {
        s += new string(s.Reverse().ToArray());
        foreach (char c in s)
        {
            var t="";
            foreach (char k in s)
            t+=c==k?" ":c>k?"|":"-";

            Console.WriteLine(t);
        }

    }

```

more golfing advice appreciated

# Answer
> 2 votes
## Clojure, 171 bytes

```
(fn[w](let[f concat r reverse p(map #(f %(r %))(partition(count w)(for[x w y w :let[c(compare x y)]](if(neg? c)\-(if(pos? c)\|\ )))))](run! #(apply println %)(f p(r p)))))

```

ungolfed:

```
(fn [w]
  (let [n (count w)
        a (for [x w y w
                :let [c (compare x y)]]
            (if (neg? c)
              \-
              (if (pos? c)
                \|
                \ )))
        p (map #(concat % (reverse %))(partition n a))
        p (concat p (reverse p))]
    (run! #(apply println %) p))))

```

# Answer
> 2 votes
# Octave, 39 bytes

```
@(x)'| -'(sign([x,y=flip(x)]-[x y]')+2)

```

Creates an anonymous function that is able to be run using `ans('string')`.

**Demo**

**Explanation**

This solution combines the input string (`x`) and it's inverse (`flip(x)`) using `[x, flip(x)]`. The inverse is assigned to `y` to shorten the answer, `[x, y = flip(x)]`. We then create a column vector of the same thing by combining `x` and `y` and taking the transpose: `[x,y]'`. Then we take the difference which will automatically broadcast to create a 2D array of differences between any ASCII representations of letters in the strings. We use `sign` to make these either `-1`, `0`, or `1` and then add `2` to get valid 1-based index values. We then use these to index into the initial string `'| -'`.

# Answer
> 2 votes
## Julia, 70 bytes

This is my first attempt at code golf and I have not used Julia before, so tell me what you think:

```
f(s)=join([join([r>c?'|':r<c?'―':' 'for c=s])for r=s*=reverse(s)],"
")

```

Try it online!

Ungolfed:

```
function wordenticon(word::AbstractString)
    word*=reverse(word)
    join([
        join([
            if r>c
                '|'
            elseif r<c
                '―'
            else
                ' '
            end
            for c in word
        ])
        for r in word]
        ,"\n"
    )
end

```

I think it could probably be made shorter. This code stores the characters of the wordicon in a matrix:

```
f(s)=[r>c?'|':r<c?'―':' 'for r=s*=reverse(s),c=s]

```

Unfortunately, I couldn't manage to produce the desired output using the matrix.

# Answer
> 2 votes
# , 101 bytes

101 bytes since I'm using  (which I think looks better than `-`).

```
function(s)write(c("|"," ","―")[sign(outer(g<-c(r<-utf8ToInt(s),rev(r)),g,"-"))+2],"",2*nchar(s),,"")

```

Try it online!

I was surprised there wasn't an R answer before since we can exploit the symmetry and R's matrices to get a quite competitive answer, despite this being a `string` problem.

### Ungolfed Explanation:

```
function(s){
 r <- utf8ToInt(s)               # turn to vector of ints (charcodes)
 g <- c(r, rev(r))               # concatenate r and its reverse
 idx <- sign(outer(g,g,"-")) + 2 # compute all differences and their signs.
                                 # -1=>less than, 0=>equal, +1=>greater than
                                 # add 2 to make them 1-based indices into the vector
 write(c("|"," ","―")[idx],"",2*nchar(s),,"")
     # write the vector of characters to stdout "" with line width 2*nchar(s)
     # and no separator
}

```

# Answer
> 2 votes
# Vyxal `j`, 23 bytes

```
Ẋƛḣ>[\||ḣ=‛- $i];?Lẇvmm

```

Try it Online!

# Answer
> 1 votes
# Jolf, 42 bytes

Hardly golfed. I'm probably forgetting about a matrix builtin that Jolf has.

```
ΆΖR~mGiEd+γR~mGiEΨ."| -"hmA-~@ά~@HE_γSSZiζ

```

Try it here! This code uses an arrow function (`Ψ`) for the matrix map.

# Answer
> 1 votes
**Javascript, 303 Bytes**

```
function w(o){function r(o){var r=Array.prototype.slice.call(o).reverse();console.log(o.join("")+r.join(""))}var e,n,c,h=[],s=o.length;for(e=0;s>e;e++){for(h.push([]),n=0;s>n;n++)c=o.charCodeAt(n)-o.charCodeAt(e),0===c?h[e].push(" "):0>c?h[e].push("|"):h[e].push("-");r(h[e])}for(e=s-1;e>=0;e--)r(h[e])}

```

Ungolfed

```
function w(s) {
    var arr = [],
        l = s.length, r, c, x;
    for (r = 0; r < l; r++) {
        arr.push([]);
        for (c = 0; c < l; c++) {
            x = s.charCodeAt(c) - s.charCodeAt(r);
            if (0 === x) {
                arr[r].push(' ');
            } else if (x<0) {
                arr[r].push('|');
            } else {
                arr[r].push('-');
            }
        }
        out(arr[r]);
    }
    for (r = l - 1; r>=0; r--) {
        out(arr[r]);
    }
    function out(r){
        var rev = Array.prototype.slice.call(r).reverse();
        console.log(r.join('') + rev.join(''));
    }
}

```

No ecma 2015 fanciness here

# Answer
> 1 votes
# Python 3.5, ~~250~~ ~~223~~ 175 bytes:

```
def H(o):O=ord;G=len(o);p=[[' ―'[O(i)<O(g)],'|'][O(i)>O(g)]for i in o for g in o];u='\n'.join([''.join(p[i:G+i]+p[i:G+i][::-1])for i in range(0,len(p),G)]);print(u+'\n'+u[::-1])

```

Try It Online! (Ideone) (The last two test cases won't show up in the output since they are just blank lines. My program is processing them though, which is confirmed the fact that there are 10 cases input, but only 8 outputs appear.)

## Ungolfed followed by an Explanation:

```
def H(o):
    O=ord
    G=len(o)
    p=[[' ―'[O(i)<O(g)],'|'][O(i)>O(g)]for i in o for g in o]
    u='\n'.join([''.join(p[i:G+i]+p[i:G+i][::-1])for i in range(0,len(p),G)])
    print(u+'\n'+u[::-1])

```
1. `p=[[' ―'[O(i)<O(g)],'|'][O(i)>O(g)]for i in o for g in o]`

Create a list, `p`, where a `|` is added if the Unicode Point Value of the column letter is less than the row letter's value, a  is added if the Unicode Point Value of the column letter is more than the row letter's value, or a  if both values are equal.
2. `u='\n'.join([''.join(p[i:G+i]+p[i:G+i][::-1])for i in range(0,len(p),G)])`

Create a newline joined string, `u`, from list `p` by splitting it into joined string segments each consisting of input length number of characters both forwards and backwards, resulting in each one having the length of 2 times how ever many characters there are in the input. This is the top half of your wordenticon. So, in the case of your input being `food`, this would return:

```
 ――||――
|  ||  |
|  ||  |
―――  ―――

```
3. `print(u+'\n'+u[::-1])`

Finally, output `u` followed by a newline and then `u` reversed to vertically mirror the first half for the second half. This is your completed wordenticon, which for the test case `food` would finally be:

```
 ――||――
|  ||  |
|  ||  |
―――  ―――
―――  ―――
|  ||  |
|  ||  |
 ――||――

```

# Answer
> 1 votes
## Python 2, 126 bytes

```
def f(s):x=[''.join(" -|"[cmp(ord(a),ord(b))]for a in s)for b in s];y=[a+b[::-1]for a,b in zip(x,x)];print'\n'.join(y+y[::-1])

```

This is essentially a port of my Actually solution.

Try it online

Explanation:

```
x=[''.join(" -|"[cmp(ord(a),ord(b))]for a in s)for b in s] # get the correct character for each pair of characters in the Cartesian product of s with itself, and concatenate the characters in each line
y=[a+b[::-1]for a,b in zip(x,x)] # mirror each line horizontally
print'\n'.join(y+y[::-1]) # mirror vertically and print

```

# Answer
> 1 votes
# 05AB1E, ~~20~~ ~~22~~ ~~21~~ ~~19~~ 13 bytes

```
δ.S… |—sèJ»º∊

```

+2 bytes as bug-fix for single-char inputs (but later on -2 again by putting the fix at a different position in the code)
-7 bytes thanks to *@ovs*.

Takes the input as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
δ              # Apply double-vectorized on the (implicit) input-list:
 .S            #  Compare the characters (-1 if a<b; 0 if a==b; 1 if a>b)
   … |—        # Push string " |—"
       sè      # Index the -1,0,1 of the matrix into this string
         J     # Join each inner list together to a string
          »    # Join this list of strings by newlines
           º   # Mirror each line left to right
            ∊  # And mirror the entire block top to bottom
               # (and output the result implicitly)

```

# Answer
> 1 votes
# APL (Dyalog Extended), 24 bytes

```
⍪∘⊖⍨⍤,∘⌽⍨' |―'⊇⍨∘.(≠+<)⍨

```

Try it online!

Uses Extended for character comparison.

minus a lot of bytes from Adám.

uses `⎕IO←0` (0-indexing)

## Explanation(old)

```
{(⊢⍪⊖)(⊢,⌽)' |―'[∘.{1+⍺(≠+<)⍵}⍨⍵]} ⍵ → input.
                 ∘.           ⍨⍵   cartesian product of ⍵, with the following function:
                   {1+⍺(≠+<)⍵}     return 1 if equal, 2 if greater, 3 if lesser.
           ' |―'[               ]  index into the required characters
      (⊢,⌽)                        append the reverse of the pattern
 (⊢⍪⊖)                             append the y-axis reverse of the pattern

```

# Answer
> 1 votes
# Vyxal, 14 bytes

```
mC:ǒ-±` |-`İṠ⁋

```

Try it Online!

```
m              # Mirror
 C             # Get charcodes
  :ǒ-          # Outer product by subtraction
           İ   # Index
     ±         # Signs of those differences
      ` |-`    # Into " |-"
            Ṡ⁋ # Concatenate and join on newlines

```

# Answer
> 1 votes
# Perl 5 `-F`, 76 bytes

```
say@$_,reverse@$_ for(@;=map{//;[map{($",'-','|')[$_ cmp$']}@F]}@F),reverse@

```

Try it online!

# Answer
> 1 votes
# Uiua, ~~28~~ 20 bytes

```
∵(⊡:"| -")+1±⊞-.⊂:⇌.

```

Test pad (with explanation)

My older 28-byte solution had it mirroring at the end, but looking at some answers, I decided to mirror in the beginning.

# Answer
> 0 votes
# C (gcc), 202 bytes

```
f(c,i,j,s,t,a,v)char*c,*v;{v=malloc((a=strlen(c)*2)*a);for(j=0;t=c[j];j++)for(i=0;s=c[i];i++)v[j*a+i]=v[j*a+a+~i]=v[a*(a+~j)+i]=v[a*(a+~j)+a+~i]="- |"[(s<t)-(s>t)+1];for(;*v;v+=a)write(1,v,a),puts("");}

```

Try it online!

Works by looping through each character, then updating the resultant character (and the reflections thereof).

# Answer
> 0 votes
# Japt `-R`, 20 bytes

Everything I do to try to make this shorter only ends up making it longer!

```
¬£c_gXc)g|i-iSÃê1Ãê1

```

Try it

```
¬£c_gXc)g|i-iSÃê1Ãê1     :Implicit input of string U
¬                        :Split
 £                       :Map each X
  c                      :  Map the character codes of U
   _                     :  By passing them through the following function
    g                    :    Sign of difference with
     Xc                  :      character code of X
       )                 :    End sign
        g                :    0-based index into
         |i              :      "|" prepended with
           -i            :        "-" prepended with
             S           :          Space
              Ã          :  End inner map
               ê1        :  Mirror
                 Ã       :End outer map
                  ê1     :Mirror
                         :Implicit output joined with newlines

```

# Answer
> 0 votes
# Pip `-l`, ~~22~~ 21 "bytes"

```
QR(" |―"$CM Aa@GMC#a)

```

Try it here! Or, here's the 24-"byte" equivalent in Pip Classic: Try it online!

### Explanation

```
QR(" |―"$CM Aa@GMC#a)
                       a is first command-line argument (implicit)
                MC#a   Map this function to each [r,c] pair where 0 <= r,c < len(a):
             a@G         Get the chars in a at indices r and c
            A            ASCII value of each char
        $CM              Fold on numeric comparison (returns -1, 0, or 1)
  (" |―"            )  Use each number in the resulting nested list to index into " |―"
                       (0-based cyclic indexing: 0 -> " ", 1 -> "|", -1 -> "―")
QR                     Quad-reflect
                       Autoprint with each sublist on a separate line (-l flag)

```

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


title: A Programming Puzzle of Mode Golf

text:
# Question
Title: A Programming Puzzle of Mode Golf
Your task is to print the text `Good morning, Green orb!`, with every character repeated in place as many times as the most frequent byte in your source (the mode). A trailing newline is permitted and need not be repeated.

For example if your source was

```
print p

```

Since `p` appears twice and every other byte appears once you would need to print

```
GGoooodd  mmoorrnniinngg,,  GGrreeeenn  oorrbb!!

```

Answers will be scored by the product of their byte count and the number of times the output is repeated. For example the above code (if it worked) would score **7\*2 = 14**. The goal should be to minimize one's score.

Your code must contain at least 1 byte.

Use this program to verify that your code and output match

# Answer
> 19 votes
# Brain-Flak, ~~384 * 106~~ 366 * 100 = 36,600

```
(((((((()()()))))))(()({}{}{}(([(({}{})){}()]((((({}())){})){}{}()(({})<([{}](((({}()())))([{}]([{}]()((()()())(()()({}()([(({})){}()](((((({}))))({}({}{}{}){})(({}){}()))))<((((([]){}){}){}<>)<>)>[])))))))(((((()()())()){}{}){}){})<>(((({})<>)))>{}{})))))<(<>({})<>)>))(<>((({}))()){}{}<>)<>(((({}<>()))))({}{}{}<>)<>{((<>{}<><({}<>)>)<{({}[()]<(({}))>)}{}>)<>}<>{}

```

Try it online!

## Explanation

The first thing I do is push the string

```
!bro neerG ,gninrom dooG

```

to the stack using pretty standard brain-flak Kolmogorov-complexity tactics.

```
(((((((()()()))))))(()({}{}{}(([(({}{})){}()]((((({}())){})){}{}()(({})<([{}](((({}()())))([{}]([{}]()((()()())(()()({}()([(({})){}()](((((({}))))({}({}{}{}){})(({}){}()))))<((((([]){}){}){}<>)<>)>[])))))))(((((()()())()){}{}){}){})<>(((({})<>)))>{}{})))))<(<>({})<>)>))(<>((({}))()){}{}<>)<>({}<>())

```

Then we push a counter to the off stack to tell us how many times to duplicate each character. However I wasn't going to be able to determine what this counter was until I was done writing the program.

Next up we simultaneously reverse the string and duplicate each character in place the correct number of times. Specifically the counter + 1.

```
{((<>{}<><({}<>)>)<{({}[()]<(({}))>)}{}>)<>}<>{}

```

These two parts of the program have a mode of 99 open parentheses. However since we are most certainly going to need at least 1 parenthesis. Here is where I noticed that the last character we pushed `!` conveniently has character code 33 which means we can use it to create 99, the exact number we want using only one additional parenthesis. This is quite the coincidence but it works.

# Answer
> 17 votes
# Jelly, 13 bytes * 1 = 13

```
“¢Ȧ@XĊ'WÑṭḂ#»

```

Try it online!

# Answer
> 15 votes
# Haskell, 37 bytes × 3 = 111

*-20 thanks to H.PWiz. -25 thanks to nimi.*

```
"Good m\111rning, Green orb!"<*[2..4]

```

Try it online!

Haskell's operators FTW.

Self-reminder to never golf on mobile. I keep making dumb mistakes. I can push at least half the blame on mobile. :P

# Answer
> 15 votes
# brainfuck, 235 x 77 = 18,095 points

Edit: -2 bytes thanks to @Dennis

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

```

Try it online!

TIO test

Wait, this *isn’t* code bowling?? \s

With only 8 usable characters, brainfuck is one of the worst languages to do this question. I had to start with minimising which character would inevitably appear the most, typically either `+` or `-`. After writing the first iteration of the code, I found it horribly unbalanced in favour of `+`s. I rearranged parts of the code, such as generation of larger numbers, to use more `-`. Finally, I ended up at ~~an *equal* amount of the two characters at 77~~ one less `-` than `+`. It’s certainly possible to reduce this further, which I’ll have a go at tomorrow.

But hey, at least I beat the Brainflak answer

# Answer
> 10 votes
## Alice, 49 bytes * 2 = 98 ~~144~~

```
/:G!4o3r8"1=5',0Grey9Z<@
\"b0=dnm 2'i%g<7R6~e.;o/

```

Try it online!

### Explanation

```
/...@
\.../

```

This is the usual framework for linear programs that operate entirely in Ordinal mode. Unfolding the zigzag control flow, we get:

```
"G04d3m821i5g,7G6ee9;<:b!=onr "'=%'<0Rr~y.Zo@

```

The basic idea is to avoid characters which repeat more than twice with the help of a transliteration. The transliteration we're going to do is the following:

```
input: "G04d3m821i5g,7G6ee9;<:b!"
from:  "0123456789:;<"
to:    "onr "

```

The way transliteration works in Alice is that the `from` and `to` strings are first repeated to the LCM of their lengths, although in this case, all the matters is the length of the `from` string, so we get:

```
from:  "0123456789:;<"
to:    "onr onr onr o"

```

This way, we get four different characters to represent the `o`s, and three each for `n`, `r` and the space. We can generate the `from` string using range expansion as follows:

```
'<   Push "<".
0    Append a zero.
R    Reverse.
r    Range expansion.

```

The only issue now is that we'd need four `"` for both the `input` and the `to` string. To avoid that, we put them both into a single string and split it at a `=` used as a separator.

```
"G04d3m821i5g,7G6ee9;<:b!=onr "
     Push the string containing both parts.
'=%  Split around "=".

```

The rest is just:

```
~   Swap "from" and "to".
y   Transliterate.
.Z  Duplicate and interleave. This duplicates each character.
o   Print.
@   Terminate the program.

```

# Answer
> 7 votes
# C (gcc), ~~74×6=444~~crossed out 444 is still regular 444 ~~77×5=385~~ 81×4=324

```
f(q){char*a="Go\157d morning, G\162een o\162b!";for(q=0;q<96;)putchar(a[q++/4]);}

```

Try it online!

# Answer
> 6 votes
# Python 2, 62 × 3 = 186

```
lambda:`sum(zip(*['Good morning, Green \x6frb!']*3),())`[2::5]

```

Try it online!

# Answer
> 6 votes
# Vim, ~~42~~ 41 keystrokes × 3 = 123

```
iGod morning, Green orb!<Esc>2|qsyl2pl@sqX0@s

```

Explanation:

1. `iGod morning, Green orb!<Esc>`
Write the string `God morning, Green orb!` (one `o` missing).
2. `2|`
Jump to the first `o`.
3. `qsyl2pl@sq`
Create a recursive macro `s`. As a side effect, triple the current `o`.
4. `X0`
Remove one `o` and jump to the beginning.
5. `@s`
Run the macro `s`, which repeat each character twice.

# Answer
> 5 votes
# APL (Dyalog Unicode), 46 bytes × 2 = 92

(Contains unprintables)

```
2/⎕UCS(¯18+⍳24)+⎕UCS'X~r-yz|wqum1$Jtfemln]'

```

Try it online!

+Alot of bytes thanks to Dyalog's code page, thanks to @Adám for pointing that out.

# Answer
> 5 votes
# C (gcc), 68 × 3 = 204

```
0000000: 6a 3b 6d 61 69 6e 28 29 7b 77 68 69 6c 65 28 6a  j;main(){while(j
0000010: 3c 37 32 29 70 75 74 63 68 61 72 28 7e 22 b8 90  <72)putchar(~"..
0000020: 90 9b df 92 90 8d 91 96 91 98 d3 df b8 8d 9a 9a  ................
0000030: 91 df 5c 32 32 30 8d 9d de 22 5b 6a 2b 2b 2f 33  ..\220..."[j++/3
0000040: 5d 29 3b 7d                                      ]);}

```

*Thanks to @MDXF for saving 9 points and paving the way for 6 more!*

Try it online!

### Alternate version, printable ASCII, 69 × 3 = 207

```
j;main(k){while(j<72)putchar("Gnmg$hiuf`dl -I}ut|3{gt6"[k=j++/3]^k);}

```

Try it online!

# Answer
> 4 votes
# C, 78 × 4 = 312

```
*s=L" ÞÞÈ@ÚÞäÜÒÜÎX@äÊÊÜ@ÞäÄB";main(y){while(*++s)for(;y++%5;putchar(*s/2));}

```

Try it online!

## ~~356~~ ~~332~~

# Answer
> 3 votes
# Japt, 24 bytes * 2 = 48

```
`Good ¶rÍÁ,
GÎ9 b!`m²·¸

```

Contains an unprintable. Test it online!

The majority of the program is just a compressed string, which decompresses to

```
Good morning,
Green orb!

```

and  then `m`aps each character by repeating it `²`wice okay, that was a bit of a stretch. Space is the only character that appears 3 times in the compressed string; to save one instance we replace it with a newline, then use `·¸` to split on newlines and immediately join on spaces. While 2 bytes longer, it substantially reduces the score (from 66 to 48).

Now if only there were a short way to do it using no character twice...

# Answer
> 3 votes
# , ~~65 bytes * 5 = 325~~ ~~59 bytes * 5 = 295~~ 62 bytes * 4 = 248

```
cat(gsub('(.)',strrep('\\1',4),"Good Mo\x72ning, Green orb!"))

```

Try it online!

There are 4 `(or,')` characters.

# Answer
> 3 votes
# SNOBOL4 (CSNOBOL4), 97 bytes * 10 = 970

```
	S ='Good Morning, Green orb!'
y	S	LEN(1) . y rem . s	:f(p)
	x	=x DUPL(y,10)	:(y)
p	OUTPUT	=x
END

```

Try it online!

yeah........SNOBOL requires operators to be separated by whitespace, and there are whitespace requirements that are quite awkward. There are 9 `'\t'` and 10 `' '` in the code, so any improvements will require a fairly significant change in approach.

# Answer
> 3 votes
# Ruby, 52 bytes × 3 = 156

```
puts"Good morning, Green \x6frb!".gsub(/(.)/,'\1'*3)

```

Try it online!

# Answer
> 3 votes
# Perl 5, 59 × 2 = 118 points

```
$_="GSSdYmoVRing,YGVIen orb!";y<H-Z>[d-t ],s<.>[$&x2]eg;say

```

Try it online!

# Perl 5, 51 × 3 = 153 ~~156~~ points

```
s""GOOd morning, Green orb!";y'O'o';s/./$&x3/eg;say

```

Try it online!

# Perl 5, 43 × 4 = 172 points

```
say"Good morning, Green orb!"=~s/./$&x4/egr

```

Try it online!

Saved 2 bytes in each solution thanks to @Xcali (a few changes ago). For all optimizations look at the edits.

# Answer
> 2 votes
# Python 2, 62\*4 = 248

*Thanks to @ovs and @Giuseppe!*

```
lambda:"".join(c*4for(c)in"G\x6f\x6fd mor\x6eing, Green orb!")

```

Try it online!

# Python 2, 51\*6 = 306

```
print"".join(c*6for c in"Good morning, Green orb!")

```

Try it online!

# Python 2, 70\*5 = 350

```
lambda:"".join(c*5for(c)in"Gxxd mxrning, Green xrb!".replace('x','o'))

```

Try it online!

*Thanks to @Mr. Xcoder for saving a byte from both versions!*

# Answer
> 2 votes
# , 35 bytes * 2 = 70

```
IG²od morning, GreeN ORb!5h3~Óˆ/°°

```

Try it online!

Hexdump:

```
00000000: 4947 b26f 6420 6d6f 726e 696e 672c 2047  IG.od morning, G
00000010: 7265 654e 204f 5262 211b 3568 337e d388  reeN ORb!.5h3~..
00000020: 2fb0 b0                                  /..

```

# Answer
> 2 votes
# SOGL V0.12, 16 bytes * 1 = 16

```
7n]ēæ¬⁹≡qa╔αXE‘⁽

```

Try it Here!

Compression!

Though, if `Green` wasn't capitalized like that, this could be 3 bytes shorter :/

# Answer
> 2 votes
# Clean, 77 bytes * 3 = 231

```
import StdEnv
f=[[b,b..]%(0,2)\\a<-:"Qyyn*wy|xsxq6*Q|oox*\171|l+",b<-[a-'
']]

```

Try it online!

# Answer
> 2 votes
# Ohm v2, 20 bytes * 1 = 20

```
”1Gäåa¬Î|òÙγy[õ↕~LzN

```

Try it online!

Gotta love compression, although unfortunately it's not as good as SOGL's.

# Answer
> 2 votes
# CJam, 32 bytes × 2 = 64

```
"Gnmg$hiuf`dl -I}ut|3orb!"K,.^:_

```

Try it online!

Pushes a string, then XORs the first 20 character with `[0, 1, …, 19]`, then duplicates each character.

# Answer
> 2 votes
# PowerShell, ~~49\*5~~ 58 bytes * 4 = 232 pts

-13 pts thanks to ASCII-only

```
-join("Good m{0}rning, Green {0}rb!"-f'o'|% t*y|%{"$_"*4})

```

Try it online!

Uses formatting to go from 5 `o`s to 4 to chip out some numbers

# Answer
> 2 votes
# 05AB1E, Score: 22 (22 bytes * 1)

```
…‚¿•´,„ˆ¨èã).ªðý23£'!«

```

Try it online.

**Explanation:**

NOTE 1: The *wrap stack into list* builtin `)` is used instead of the builtin *pair* , because the  is already part of the dictionary word `good`.
NOTE 2: The two commas in the code  and `,` may look the same, but are different unicode characters. The first one is usually used for the builtin *pair*, and the second for the builtin *print to STDOUT with trailing newline*. In this case they are used for the dictionary word `good`, and the expected comma in the output however.

```
…‚¿•´,        # 3-word dictionary string "good morning," (the comma counts as the third word)
„ˆ¨èã         # 2-word dictionary string "green orbit"
)             # Wrap everything on the stack into a list: ["good morning,","green orbit"]
 .ª           # Sentence capitalize all strings: ["Good morning,","Green orbit"]
   ðý         # Join by spaces: "Good morning, Green orbit"
     23£      # Only leave the first 23 characters: "Good morning, Green orb"
        '!«  '# Append a "!": "Good morning, Green orb!" (and output the result implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `…‚¿•´,` is `"good morning,"` and `„ˆ¨èã` is `"green orbit"`.

# Answer
> 2 votes
# PowerShell, 46 bytes * 4 = 184 points

```
"Good morning, Green orb!"-replace'.',('$0'*4)

```

Try it online!

# Answer
> 2 votes
# Vyxal, 19 bytes, score 38

```
‛ƛ⁋`øø, ×ŀ ⋎Ė!`"Ṅ2•

```

Try it Online!

```
‛ƛ⁋                 # Compressed string
   `øø, ×ŀ ⋎Ė!`     # Compressed string
               "Ṅ   # Pair and join by spaces
                 2• # Double each character

```

# Answer
> 1 votes
# JavaScript (ES6), 61 bytes * 3 = 183

```
_=>'Good morning, Gr\145en \x6f\x72b!'.replace(/./g,"$&$&$&")

```

```
f=
_=>'Good morning, Gr\145en \x6f\x72b!'.replace(/./g,"$&$&$&")
console.log(f())
```

# JavaScript (ES6), 51 bytes * 4 = 204

```
_=>'Good morning, Green orb!'.replace(/./g,'$&$&$&$&')

```

Answer suggested by @ETHproductions.

```
f=
_=>'Good morning, Green orb!'.replace(/./g,'$&$&$&$&')
console.log(f())
```

# JavaScript (ES6), 73 bytes * 4 = 292

```
_=>`G00d mo1ning, G244n orb!`.replace(/./g,_=>(('o'+!0)[_]||_).repeat(4))

```

```
f=
_=>`G00d mo1ning, G244n orb!`.replace(/./g,_=>(('o'+!0)[_]||_).repeat(4))
console.log(f())
```

# JavaScript (ES6), 58 bytes * 6 = 348

```
_=>'Good morning, Green orb!'.replace(/./g,_=>_.repeat(6))

```

```
f=
_=>'Good morning, Green orb!'.replace(/./g,_=>_.repeat(6))
console.log(f())
```

# Answer
> 1 votes
# Jelly, 31 bytes × 2 = 62 points

```
“2ðƈZ(Øṡdȷ¿Ɱ’ṃ“God mrnig,eb!”x2

```

Try it online!

**Explanation**

```
“2ðƈZ(Øṡdȷ¿Ɱ’ṃ“God mrnig,eb!”x2
“2ðƈZ(Øṡdȷ¿Ɱ’                     Base 250 number
              “God mrnig,eb!”     Unique characters of "Good morning..."
             ṃ                    Convert the base 250 number in base 13 then index into the string "God mr..."
                             x2   Repeat each character twice because “ occurs twice in the source (and now 2)

```

# Answer
> 1 votes
# Retina, 36×4=144

```

Good morning, Green orb!
.
$&$&$&$&

```

Try it online! There are three newlines and four `o`s, so there's nothing more to be done.

# Answer
> 1 votes
# Pushy, 36 * 2 = 72

```
`GXVWOP^4W_[afdc\hiB`N$29+L-''.

```

**Try it online!**

The main principle of this answer is that each character `n` is stored as `n + index - 29` in order to avoid the repetition in the original string. This mapping created the string in the backticks. The rest of the program simply decodes this and prints each character twice:

```
` ... `              \ Push the encoded string
       N             \ Remove printing delimiter
        $            \ While there are items left on stack:
         29+         \   Add 29 to top of stack
            L-       \   Subtract current length from top of stack
              ''.    \   Print twice, then pop

```

Bytes used twice: ``'W`

**Changelog**

* Golfed length from 41 to 38, by changing decoding method.
* Golfed length from 38 to 37 by subtracting 29 from each encoded character to prevent multibyte characters.
* Golfed length from 37 to 36 by using implicit 'end loop'

# Answer
> 1 votes
# Ruby, 55x4 = 220 points

```
"Good morning, Green orb!".split(//).each{|x|print x*4}

```

Im quite annoyed that using each\_char makes the count of r's 5..

# Answer
> 1 votes
# brainfuck, 414 * 163 = 67,482

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

```

Try it online!

I'm not very good at brainfuck so this is likely far from optimal, but it works.

## Explanation

The first part is

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

```

This writes the charcodes for

```
Good morning, Green orb!

```

to memory in order. It is certainly the place that could use the most optimization.

Then we have

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

```

Which goes and prints off each character as many times as we tell it. Since there are 163 pluses in the program we tell it to print each character 163 times.

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

```

# Answer
> 1 votes
# Standard ML (MLton), ~~84\*5=420~~ 83 bytes * 5 = 415

```
map(fn$ =>map(fn _=>print(str$))[0,2,3,4,5])(explode"Good mor\110ing, Green orb!");

```

Try it online!

---

### Alternative approach (same score)

```
String.map;it(fn c=>(print(it(fn _=>c)"vwxyz");c))"Good mor\110i\110g, Green orb!";

```

Try it online!

# Answer
> 1 votes
# Noether, 42 bytes * 4 = 168

```
"Good morning, Green orb!"~sL(si/4*Pi1+~i)

```

Outputs:

```
GGGGoooooooodddd    mmmmoooorrrrnnnniiiinnnngggg,,,,    GGGGrrrreeeeeeeennnn    oooorrrrbbbb!!!!

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 22 bytes * 2 = 44

```
”‚¿•´,ˆ¨ orb!”'m5ǝ2иζJ

```

Try it online!

---

If I am able to output title-cased:

# 05AB1E, 13 bytes

```
”‚¿•´,ˆ¨ Orb!

```

Try it online!

Please note, CP-1252  is not a comma, therefore there are no dupes.

# Answer
> 1 votes
# \>\<\>, 41 bytes x 7 = 287

```
|v"Good morning, Green orb!"
o\! !\:::|oo

```

Try it online!

As 'o' is used as the print character, this uses some mirrors to reuse them for printing.

# Answer
> 1 votes
# Perl 6, 3 * 54 bytes = 162

```
<<"G{q`o`x 2}d"morning,'Green'orb!>>~~say S:g{.}=$/x 3

```

Try it online!

I started off with the normal:

```
"Good morning, Green orb!"~~(S:g{.}=$/x 4).say

```

Which simply replaces each letter by 4 copies of itself and prints. The mode characters were the spaces and the `o`s, so I changed the string part to a word quote with interpolation:

```
<<Good morning,'Green'orb!>>~~say S:g{.}=$/x 4

```

This decreased the spaces down to 3. Next was the `o`, which I decided to double in the `oo` part of `Good`.

```
<<"G{q`o`x 2}d"morning,'Green'orb!>>~~say S:g{.}=$/x 4

```

This involved wrapping the `Good` in interpolating quotes of its own, then having to use a custom `q`uoting construct to do the o character, since the quote characters were taken.

# Answer
> 1 votes
# AWK, 57 bytes × 4 = 228

```
END{$0="Good morning, Green orb!";gsub(/./,"&&&&");print}

```

Try it online!

# Answer
> 0 votes
# K (oK), 35 bytes * 4 = 140

**Solution:**

```
`0:,/4#'"Good morning, Green orb!";

```

Try it online!

**Explanation:**

Nothing fancy here, the most common letter is `o` which occurs `4` times.

```
`0:,/4#'"Good morning, Green orb!"; / the solution
        "Good morning, Green orb!"  / the string to be displayed
     4#'                            / 4 take (#) each (') repeats each character 4 times
   ,/                               / flatten these lists
`0:                               ; / print to stdout (`0:) and swallow return value (;)

```

# Answer
> 0 votes
# Swift, 53\*3=159 bytes

```
{"Good morning, Green \u{6f}rb!".flatMap{[$0,$0,$0]}}

```

Try it online!

# Answer
> 0 votes
# Java 11, score: 455 (91 bytes * 5)

```
x->{for(var s:"G\157od mo\162ning, G\162een orb!".split(""))System.out.print(s.repeat(5));}

```

The `e`, `o`, `r`, and `t` are all four used 5 times.

Try it online.

**Explanation:**

```
x->{                     // Method with empty unused parameter and no return-type
  for(var s:"G\157od mo\162ning, G\162een orb!"
                         //  Push String "Good morning, Green orb!"
            .split(""))  //  And loop over its characters as Strings
    System.out.print(s   //   Print the current character
      .repeat(5));}      //   Repeated 5 times

```

# Answer
> 0 votes
# Pip, 42\*4 = 168

```
a:"Good morning, Green orb!"Fi,#a{L4O(ai)}

```

Try it online!

# Answer
> 0 votes
# Julia, 59 × 3 = 177

```
map(y->print(y^3),["Good morning, G\x72ee\x6E \x6Frb!"...])

```

Try it online!

# Answer
> 0 votes
# Excel, 60x4 = 240

```
=CONCAT(REPT(MID("Good morning, Green orb!",ROW(1:24),1),4))

```

# Answer
> 0 votes
# Zsh \+ sed, 61 × 2 = 122

```
sed<<.�"s$?.$?&&0g"|tr�{A-Z,AG\ d-z}
BOoDCmORniNg,CBREen orb!

```

Attempt This Online!

represents tabs.

Getting a good score without sed seems pretty hard.

# Answer
> 0 votes
# Uiua, 32 bytes×4 `o`s=128 points

```
&p♭⍉↯4"Good morning, Green orb!"

```

Test pad

On stdout:

```
GGGGoooooooodddd    mmmmoooorrrrnnnniiiinnnngggg,,,,    GGGGrrrreeeeeeeennnn    oooorrrrbbbb!!!!

```

---
Tags: code-challenge, kolmogorov-complexity, hello-world, self-referential
---


title: Please parse this aLL1en language

text:
# Question
Title: Please parse this aLL1en language
# Background

Due to some unfortunate accident during coding you are now teleported and stranded on an alien planet. You really hope that the locals will be helpful and point to the general direction of how to get home, but before trying to talk to them you want to decipher their language. Fortunately it looks like the aliens were expecting this, and are actually displaying the grammar of their language near the place you got teleported.

# Your task

Your job is to write an LL(1) parser, that can determine whether a specific string belongs to the specified grammar or not and also return the rules that were used during parsing. Your fingers are a bit strained because of the teleporting, so you want to code this parser in as less characters as possible.

Also it looks like for some weird reason there is free wifi there, but only wikipedia is available, so if you need help you can check how to parse an LL(1) grammar and how to create the parsing table for it.

# Input

The first line of the input is the string you need to parse. The following lines will all include the available rules of the grammar, where the first character is the left hand side of the rule, and the rest of the line is the right hand side of the rule.

Example input:

```
(a+a)
SF
S(S+F)
Fa

```

Which describes that you have to determine whether `( a + a )` is part of the following grammar or not:

```
S → F
S → ( S + F )
F → a

```

Notes on the input:

* The grammar might contain empty (epsilon) rules, here the the right hand side is empty
* All terminals and non terminals occupy exactly one character
* Terminals are the following characters: `abcdefghijlkmnopqrstuvwxyz+-/*^%=()[]{}`
* Non Terminals are the following characters: `ABCDEFGHIJKLMNOPQRSTUVWXYZ`
* The starting non terminal is always `S`
* You can assume that the grammar in the input is always a proper LL(1) grammar
* A trailing newline may or may not be present, your choice.

# Output

The output should contain whether the string is part of the grammar or not, and if it is, it should also include the rules you had to use for parsing.

Example output for the input above:

```
true
S(S+F)
SF
Fa
Fa

```

Variations on the output is allowed as long as it returns all information required. For example the following output is considered accepted as well: `1 [2,1,3,3]` (`1` because the string is accepted, then `[2,1,3,3]` are the rules used as an array, where each element represents the index of the rule in the input starting from one)

# Scoring

You have to write either a complete program (reading from STDIN) or a function (reading from a string). The output can either be done to STDOUT, or returned from the function in an appropriate way (like a `Pair<bool,int[]>`).

Your point score is the byte count of the program, with the following penalties:

* Add 10 to the byte count and square it, in case you are using a built in LL(1) parser of your chosen language
* Add 100 to the byte count and square it, in case you are using a built in LL(2+), LR(1), LALR, SLR, or any other more advanced parser than LL(1)
* Although they might not be more advanced than an LL(1), use the previous penalty if you are using regular expression features which are not considered part of a regular grammar

(these penalties apply, since the teleporter messed up these built in functions a bit, and you have to magically fix them first)

# Note:

Normal regular expressions are allowed and don't count into the penalty, unless you use advanced regexp features which make your expression not a regular grammar anymore. Also using a built in LR(0) parser is okay (but probably not very helpful)

# Lowest points win.

If your language is not character based use the appropriate metric for your language and then apply the penalties on the resulting number. Standard loopholes apply, but solutions where the language was updated since the post was posted are allowed given you add the proper disclaimer to your post.

# Examples

In:

```
(a+a)
SF
S(S+F)
Fa

```

Out: `1 [2,1,3,3]`

In:

```
(aa)
SF
S(S+F)
Fa

```

Out: `0`

In:

```
a*(a+a)
STE
E+TE
E
TFU
U*FU
U
F(S)
Fa

```

Out: `1 [1,4,8,5,7,1,4,8,6,2,4,8,6,3,6,3]`

In:

```
aaabbb
SaA
AaAb
Ab

```

Out: `1 [1,2,2,3]`

In:

```
aabbb
SaA
AaAb
Ab

```

Out: `0`

In:

```
aaabb
SaA
AaAb
Ab

```

Out: `0`

# Answer
> 12 votes
# JavaScript (ES6), 177 bytes

177 looks like LL1 rotated 177°, so I stopped golfing.

```
s=>(f=(x,i)=>x<"A"||x>"Z"?v=s[i]==x&&[i+1,x]:s.split`
`.some((r,a,j)=>v=r[0]==x&&[j=i,a=[a],...r].slice(3).every(y=>f(y,j)&&a.push(([j]=v)[1]))&&[j,a]))("S",0)&&s[v[0]]==0&&v[1]

```

Try it online!

Outputs `false` if the string does not match, otherwise outputs a nested array of rule indices and terminals:

```
[2,"(",[1,[3,"a"]],"+",[3,"a"],")"]

```

## Ungolfed

```
str =>
  (applyRule = (ruleName, index) =>
    ruleName < "A" || ruleName > "Z"
      ? result = str[index] == ruleName && [index + 1, ruleName]
      : str.split("\n").some(
        (rule, appliedRules, jndex) => result =
          rule[0] == ruleName &&
          (
            jndex = index,
            appliedRules = [appliedRules],
            [...rule].slice(1).every(char =>
              applyRule(char, jndex)
              && appliedRules.push(([jndex] = result)[1])
            )
            && [jndex, appliedRules]
          )
      )
  )("S", 0)
  && str[result[0]] == 0 // "\n" == 0
  && result[1]

```

```
function main(input) {
  const [str, ...rules] = input.split("\n")

  const result = applyRule("S", 0)

  if(result && result[0] === str.length)
    return result[1]

  function applyRule(ruleName, index) {
    if (ruleName === ruleName.toLowerCase())
      return str[index] === ruleName ? [index + 1, ruleName] : null

    main: for (const [ruleIndex, rule] of rules.entries()) {
      if (!rule.startsWith(ruleName))
        continue
      let curIndex = index
      let appliedRules = [ruleIndex + 1]
      for (const char of rule.slice(1)) {
        let result = applyRule(char, curIndex)
        if (!result) continue main
        curIndex = result[0]
        appliedRules.push(result[1])
      }
      return [curIndex, appliedRules]
    }

    return null
  }
}

```

# Answer
> 0 votes
# Python3, 672 bytes

```
E=enumerate
def F(b,g):
 if not b[0].isupper():yield b[0]
 for a,*B in g:
  if b[0]==a:yield from F(B*(B!=[' '])+b[1:],g)
def T(a,g):
 q=[(a,b,[])for A,*b in g if A==a]
 for A,b,s in q:
  for i,j in enumerate(b):
   if j==a and b[i+1:]and not b[i+1].isupper():yield b[i+1]
   for J,*k in g:
    if j==J and j not in s:q+=[(J,b[:i]+k*(k!=[' '])+b[i+1:],s+[j])]
def f(g):
 l,*g=g
 D={i[0]:{}for i in g}
 for i,(a,*b)in E(g):
  K=[*F(b,g)]
  for j in K:D[a][j]=i
  if' 'in K:
   for j in{*T(a,g)}:D[a][j]=i
 q,R=['S'],[]
 l+=[' ']
 while q:
  a,b=q.pop(0),l.pop(0)
  if a!=b:
   if a not in D:return
   q=[t for t in g[D[a][b]][1:]if' '!=t]+q;l=[b]+l;R+=[D[a][b]+1]
 return R

```

Try it online!

---
Tags: code-golf, parsing, grammars
---


title: Sort by Largest Digit(s)

text:
# Question
Title: Sort by Largest Digit(s)
# Challenge:

Given a list of integer, sort descending by their single largest digit(s). The order for numbers with the same largest digit are then sorted by second largest digit, etc.
We ignore duplicated digits in numbers. And if all digits in a number are the same, the order of those numbers in the list can be in any way you'd like.

**Example:**

```
Input:            [123, 478, -904, 62778, 0, -73, 8491, 3120, 6458, -7738, 373]
Possible outputs: [8491, -904, 62778, 478, -7738, 6458, 373, -73, 3120, 123, 0]
                  [8491, -904, 62778, 478, -7738, 6458, -73, 373, 3120, 123, 0]

```

Why? Here are the relevant digits the numbers were sorted on:

```
Output:
[8491,  -904,  62778,   478,     -7738,   6458,  373,   -73,   3120,      123,     0  ]

Relevant digits they were sorted on:
[[9,8], [9,4], [8,7,6], [8,7,4], [8,7,3], [8,6], [7,3], [7,3], [3,2,1,0], [3,2,1], [0]]

```

## Challenge rules:

* We ignore duplicated digits, so `478` and `-7738` will be ordered as `478, -7738`, because the largest digits are `[8,7,4]` and `[8,7,3]`, and not `[8,7,4]` and `[8,7,7,3]`.
* If multiple numbers have the same digits, the order of those can be either way. So `373` and `-73` can be sorted as both `373, -73` or `-73, 373` (digits are `[7,3]` for both of these numbers).
* If a number contains no more digits to check, it will be placed at the back of the relevant numbers. So `123` and `3120` will be sorted as `3120, 123`, because the largest digits `[3,2,1]` are the same, but `0` comes before *`none`*.
* You can assume all numbers in the input are in the range `[-999999,999999]`.
* Just one of the possible outputs is enough as result, but you are allowed to output all possible outputs where sublists can be in any permutation if you want (although I doubt it would save bytes in any language).

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

```
Input:            [123, 478, -904, 62778, 0, -73, 8491, 3120, 6458, -7738, 373]
Possible outputs: [8491, -904, 62778, 478, -7738, 6458, 373, -73, 3120, 123, 0]
                  [8491, -904, 62778, 478, -7738, 6458, -73, 373, 3120, 123, 0]

Input:            [11, -312, 902, 23, 321, 2132, 34202, -34, -382]
Possible outputs: [902, -382, 34202, -34, -312, 321, 2132, 23, 11]
                  [902, -382, 34202, -34, 2132, -312, 321, 23, 11]
                  etc. The sublist [-312, 321, 2132] can be in any permutation

Input:            [9, 44, 2212, 4, 6, 6, 1, 2, 192, 21, 29384, 0]
Possible outputs: [29384, 192, 9, 6, 6, 4, 44, 2212, 21, 2, 1, 0]
                  [29384, 192, 9, 6, 6, 44, 4, 2212, 21, 2, 1, 0]
                  etc. The sublists [4, 44] and [2212, 21] can be in any permutation

Input:            [44, -88, 9, 233, -3, 14, 101, 77, 555, 67]
Output:           [9, -88, 67, 77, 555, 14, 44, 233, -3, 101]

```

# Answer
> 7 votes
# 05AB1E, 5 bytes

```
ΣêR}R

```

Try it online! or as a Test suite

**Explanation**

```
Σ  }    # sort input by
 ê      # its sorted unique characters
  R     # reversed (to sort descending)
    R   # reverse the result (to sort descending)

```

# Answer
> 7 votes
# Brachylog, 9 bytes

```
{ȧdṫo₁}ᵒ¹

```

Note: due to how ordering works in brachylog, it does not work on number correctly. This is fixed by casting the number to a string () at the cost of 1 byte.

Try it online!

# Answer
> 7 votes
# Perl 6, ~~36~~ ~~34~~ ~~33~~ 31 bytes

*-1 byte thanks to Jo King*
*-2 bytes thanks to Phil H*

```
*.sort:{sort 1,|set -<<m:g/\d/}

```

Try it online!

### Explanation

```
       {                      }  # Map each number, e.g. -373
                       m:g/\d/  # Extract digits: (3, 7, 3)
                    -<<  # Negate each digit: (-3, -7, -3)
                set  # Convert to set to remove duplicates
               |  # Pass as list of pairs: (-3 => True, -7 => True)
             1,  # Prepend 1 for "none": (1, -3 => True, -7 => True)
        sort  # Sort (compares 1 and pair by string value): (-7 => True, -3 => True, 1)
*.sort:  # Sort lexicographically

```

# Answer
> 7 votes
# , ~~97~~ 95 bytes

```
function(x)x[rev(order(sapply(Map(sort,Map(unique,strsplit(paste(x),"")),T),Reduce,f=paste0)))]

```

Try it online!

This challenge seems to have been pessimized for R. Explanation of the original version (start at 1. and work up):

```
f <- function(x) {
  x[                                                  # 8. Input vector in
    rev(                                              # 7. Reversed
        order(                                        # 6. Lexicographical order
              sapply(                                 # 5. Paste....
                     Map(sort,                        # 4. Sort each using...
                              Map(unique,             # 3. Deduplicate each
                                  strsplit(           # 2. Split each string into characters
                                           paste(x),  # 1. Coerce each number to string
                                           "")),
                         T),                          # 4. ...descending sort.
                     paste,collapse="")               # 5. ...back into strings
              )
        )
    ]
}

```

# Answer
> 6 votes
# Python 2, ~~60~~ ~~55~~ 54 bytes

-1 byte thanks to Jonas Ausevicius.

```
def f(l):l.sort(cmp,lambda n:sorted(set(`n`))[::-1],1)

```

Try it online!

---

## Ungolfed

```
def f(l):
  l.sort(        # Sort the list in place
    cmp = cmp,   # ... compare with the builtin function cmp
    key = k,     # ... on the function k
    reverse = 1  # ... in reverse
  )              # As the arguments are used in the right order, no names are necessary.

k = lambda n:sorted( # sort
  set(`n`)           # ... the set of digits
  )[::-1]            # reverse the result
                     # As '-' is smaller than the digits,
                     # it will be sorted to the back and ignored for sorting

```

Try it online!

# Answer
> 6 votes
# Python 2, ~~58~~ 60 bytes

`lambda a:sorted(a,key=lambda x:sorted(set(`x`))[::-1])[::-1]`

Try it online!

# Answer
> 6 votes
# Pyth, ~~7~~ 6 bytes

*-1 byte by @Sok*

```
_o_{S`

```

Pyth, which uses only printable ASCII, is at a bit of a disadvantage here. Optimally encoded this would be `6*log(95)/log(256) = 4.927` bytes, beating 05AB1E.

Explained:

```
 o              Sort the implicit input by lambda N:
  _               reversed
   {               uniquified
    S               sorted
     '               string representation [of N]
_               then reverse the result.

```

Try it here.

# Answer
> 5 votes
# Jelly, 8 bytes

```
ADṢUQµÞU

```

Try it online!

### How it works

```
ADṢUQµÞU  Main link (monad). Input: integer list
     µÞU  Sort by (reversed):
AD        Absolute value converted to decimal digits
  ṢUQ     Sort, reverse, take unique values

```

# Answer
> 5 votes
# Julia 1.0, ~~50~~ 47 bytes

```
x->sort(x,by=y->sort(∪([digits(-abs(y));1])))

```

Try it online!

-3 bytes by Ashlin Harris.

# Answer
> 4 votes
# MathGolf, ~~7~~ 6 bytes

```
áÉ░▀zx

```

Try it online! or as a test suite.

## Explanation

After looking at Emigna's 05AB1E solution, I found that I didn't need the absolute operator (and my previous answer was actually incorrect because of that operator). Now the main difference is that I convert to string and get unique characters instead of using the 1-byte operator in 05AB1E.

```
áÉ      Sort by the value generated from mapping each element using the next 3 instructions
  ░     Convert to string
   ▀    Get unique characters
    z   Sort reversed (last instruction of block)
     x  Reverse list (needed because I don't have a sort-reversed by mapping)

```

# Answer
> 4 votes
# C (gcc), ~~114~~ ~~111~~ 109 bytes

```
a;v(n){n=n<0?-n:n;for(a=0;n;n/=10)a|=1<<n%10;n=a;}c(int*a,int*b){a=v(*a)<v(*b);}f(a,n)int*a;{qsort(a,n,4,c);}

```

Try it online!

Explanation:

f() uses qsort() to sort provided array in place. Using comparison function c() to compare numbers which evaluates numbers using v(). v() calculates a higher number if bigger digits are present in parameter.

\[Edit 1\] Improved by 3 bytes. 2 byte credits to Kevin. Thanks

\[Edit 2\] 2 more bytes improved. Credits to gastropner. Thanks

# Answer
> 4 votes
# Japt, 12 bytes

```
ñ_a ì â ñnÃw

```

All test cases

Explanation:

```
ñ_        Ãw    :Sort Descending by:
  a             : Get the absolute value
    ì           : Get the digits
      â         : Remove duplicates
        ñn      : Sort the digits in descending order

```

# Answer
> 4 votes
# Haskell, 54 52 bytes

```
import Data.List
f=r.sortOn(r.sort.nub.show);r=reverse

```

Try it online!

# Answer
> 4 votes
# Stax, ~~6~~ 7 bytes

```
èó≥ü≤♥¥

```

Run and debug it

# Answer
> 4 votes
# APL (Dyalog Extended), 19 bytes

```
{⍵[⍒∪¨(∨'¯'~⍨⍕)¨⍵]}

```

Try it online!

Fixed at a cost of +2 bytes thanks to OP.

# Answer
> 3 votes
# JavaScript (SpiderMonkey), 68 bytes

Thanks for @Arnauld for reminding me again that SpiderMonkey uses stable sort, so -4 bytes for removing `||-1`.

```
A=>A.sort((x,y,F=n=>[...new Set(""+n)].sort().reverse())=>F(x)<F(y))

```

Try it online!

# JavaScript (Node.js), 72 bytes

```
A=>A.sort((x,y,F=n=>[...new Set(""+n)].sort().reverse())=>F(x)<F(y)||-1)

```

Try it online!

# Answer
> 3 votes
# , 17 bytes

```
{~[:\:~.@\:~@":@|

```

Try it online!

## Explanation:

```
                @|    - find the absolute value and
             @":      - convert to string and
         @\:~         - sort down and
       ~.             - keep only the unique symbols
    \:                - grade down the entire list of strings
  [:                  - function composition
{~                    - use the graded-down list to index into the input

```

# Answer
> 3 votes
# Java (JDK), 98 bytes

```
l->l.sort((a,b)->{int r=0,i=58;for(;r==0&i-->48;)r=(b.indexOf(i)>>9)-(a.indexOf(i)>>9);return r;})

```

Try it online!

## Explanation

```
l->                           // Consumer<List<String>>
 l.sort(                      //  Use the incorporated sort method which uses a...
  (a,b)->{                    //   Comparator of Strings
   int r=0,                   //    define r as the result, initiated to 0
       i=58;                  //           i as the codepoint to test for.
   for(;r==0&i-->48;)         //    for each digit codepoint from '9' to '0',
                              //     and while no difference was found.
    r=                        //     set r as the difference between
     (b.indexOf(i)>>9)-       //      was the digit found in b? then 0 else -1 using the bit-shift operator
     (a.indexOf(i)>>9);       //      and was the digit found in a? then 0 else -1.
   return r;                  //    return the comparison result.
  }
 )

```

**Note:**

I needed a way to map numbers to either `0/1` or `0/-1`.

`indexOf` has the nice property that it's consistently returning `-1` for characters not found. `-1` right-shifted by any number is always `-1`. Any positive number right-shifted by a big enough number will always produce `0`.

So here we are:

```
input        input.indexOf('9')      input.indexOf('9')>>9
"999"        0                       0
"111119"     5                       0
"123456"     -1                      -1

```

# Answer
> 3 votes
# Ruby, 55 bytes

```
->a{a.sort_by{|x|x.abs.digits.sort.reverse|[]}.reverse}

```

Try it online!

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), ~~75~~ 74 bytes

-1 thanks @ASCII-only

```
x=>x.OrderByDescending(y=>String.Concat((y+"").Distinct().OrderBy(z=>-z)))

```

Try it online!

In C#, strings are considered "enumerables" of characters. I use this to my advantage by first converting each number to a string. LINQ is then leveraged to get the unique characters (digits) sorted in reverse order. I convert each sorted character array back into a string and use that as the sort key to order the whole list.

# Answer
> 2 votes
# APL(NARS), 366 chars, 732 bytes

```
_gb←⍬

∇a _s w;t
t←_gb[a]⋄_gb[a]←_gb[w]⋄_gb[w]←t
∇

∇(_f _q)w;l;r;ls;i
(l r)←w⋄→0×⍳l≥r⋄l _s⌊2÷⍨l+r⋄ls←i←l⋄→3
  →3×⍳∼0<_gb[i]_f _gb[l]⋄ls+←1⋄ls _s i
  →2×⍳r≥i+←1
l _s ls⋄_f _q l(ls-1)⋄_f _q(ls+1)r
∇

∇r←(a qsort)w
r←¯1⋄→0×⍳1≠⍴⍴w⋄_gb←w⋄a _q 1(↑⍴w)⋄r←_gb
∇

f←{∪t[⍒t←⍎¨⍕∣⍵]}

∇r←a c b;x;y;i;m
x←f a⋄y←f b⋄r←i←0⋄m←(↑⍴x)⌊(↑⍴y)⋄→3
→0×⍳x[i]<y[i]⋄→3×⍳∼x[i]>y[i]⋄r←1⋄→0
→2×⍳m≥i+←1⋄r←(↑⍴x)>(↑⍴y)
∇

```

For the qsort operator, it is one traslation in APL of algo page 139 K&R Linguaggio C. I think in it there is using data as C with pointers... Test

```
 c qsort 123, 478, ¯904, 62778, 0, ¯73, 8491, 3120, 6458, ¯7738, 373
8491 ¯904 62778 478 ¯7738 6458 ¯73 373 3120 123 0
 c qsort 11, ¯312, 902, 23, 321, 2132, 34202, ¯34, ¯382
902 ¯382 34202 ¯34 321 ¯312 2132 23 11
 c qsort 9, 44, 2212, 4, 6, 6, 1, 2, 192, 21, 29384, 0
29384 192 9 6 6 4 44 2212 21 2 1 0
 c qsort 44, ¯88, 9, 233, ¯3, 14, 101, 77, 555, 67
9 ¯88 67 77 555 14 44 233 ¯3 101

```

# Answer
> 2 votes
# Powershell, 44 bytes

```
$args|sort{$_-split'(.)'-ne'-'|sort -u -d}-d

```

Test script:

```
$f = {

$args|sort{$_-split'(.)'-ne'-'|sort -u -d}-d

}

@(
    ,( (123, 478, -904, 62778, 0, -73, 8491, 3120, 6458, -7738, 373),
       (8491, -904, 62778, 478, -7738, 6458, 373, -73, 3120, 123, 0),
       (8491, -904, 62778, 478, -7738, 6458, -73, 373, 3120, 123, 0) )

    ,( (11, -312, 902, 23, 321, 2132, 34202, -34, -382),
       (902, -382, 34202, -34, -312, 321, 2132, 23, 11),
       (902, -382, 34202, -34, 2132, -312, 321, 23, 11) )

    ,( (9, 44, 2212, 4, 6, 6, 1, 2, 192, 21, 29384, 0),
       (29384, 192, 9, 6, 6, 4, 44, 2212, 21, 2, 1, 0),
       (29384, 192, 9, 6, 6, 44, 4, 2212, 21, 2, 1, 0),
       (29384, 192, 9, 6, 6, 44, 4, 21, 2212, 2, 1, 0) )

    ,( (44, -88, 9, 233, -3, 14, 101, 77, 555, 67),
       ,(9, -88, 67, 77, 555, 14, 44, 233, -3, 101) )
) | % {
    $a, $expected = $_
    $result = &$f @a
    $true-in($expected|%{"$result"-eq"$_"})
    "$result"
}

```

Output:

```
True
8491 -904 62778 478 -7738 6458 -73 373 3120 123 0
True
902 -382 34202 -34 2132 -312 321 23 11
True
29384 192 9 6 6 44 4 21 2212 2 1 0
True
9 -88 67 77 555 14 44 233 -3 101

```

# Answer
> 2 votes
# PHP, ~~87 86~~ 84 bytes

```
while(--$argc)$a[_.strrev(count_chars($n=$argv[++$i],3))]=$n;krsort($a);print_r($a);

```

Run with `-nr` or try it online.

Replace `++$i` with `$argc` (+1 byte) to suppress the Notice (and render `-n` obosolete).

**breakdown**

```
while(--$argc)  # loop through command line arguments
    $a[                             # key=
        _.                              # 3. prepend non-numeric char for non-numeric sort
        strrev(                         # 2. reverse =^= sort descending
        count_chars($n=$argv[++$i],3)   # 1. get characters used in argument
        )
    ]=$n;                           # value=argument
krsort($a);     # sort by key descending
print_r($a);    # print

```

`-` is "smaller" than the digits, so it has no affect on the sorting.

# Answer
> 2 votes
# Common Lisp, 88 bytes

```
(sort(read)'string> :key(lambda(x)(sort(remove-duplicates(format()"~d"(abs x)))'char>)))

```

Try it online!

Good old verbose Common Lisp!

Explanation:

```
(sort                   ; sort
 (read)                 ; what to sort: a list of numbers, read on input stream
 'string>               ; comparison predicate (remember: this is a typed language!)
 :key (lambda (x)       ; how to get an element to sort; get a number
       (sort (remove-duplicates  ; then sort the unique digits (characters)
               (format() "~d" (abs x))) ; from its string representation
             'char>)))  ; with the appropriate comparison operator for characters

```

# Answer
> 2 votes
# Husk, 7 bytes

```
↔Öö↔Oda

```

Try it online!

# Answer
> 2 votes
# Vyxal 3, 6 bytes

```
µᵛfG]Ṛ

```

Try it Online!

need two bytes to reverse the end result otherwise i might have a 4 byter lol

# Answer
> 1 votes
# Perl 5 `-nl`, 68 bytes

```
$a{eval"9876543210=~y/$_//dcr"}=$_}{say$a{$_}for reverse sort keys%a

```

Try it online!

---
Tags: code-golf, number, integer, sorting
---