title: Snooker scoring

text:
# Question
Title: Snooker scoring
I was watching the world snooker championship and it got me wondering..

**Snooker scoring**

In the game of snooker there are certain rules that you must adhere too:

* When there are red balls on the table, during your turn you must first pot a red ball
* After potting each red ball, you must pot a colored (not red) ball (the potted colored ball is then replaced onto the table)
* After all the red balls are up (there are 15) you can first choose a colored ball and then you start with the lowest scoring ball and work your way up to the highest scoring ball (these are not replaced)
* Not potting at any point ends your turn.
* Points per ball
    + Red ball: 1 point
    + Yellow ball: 2 points
    + Green ball: 3 points
    + Brown ball: 4 points
    + Blue ball: 5 points
    + Pink ball: 6 points
    + Black ball: 7 points

**The question**

You start with a table with all the balls still on it - **15** red and **one** of each of the other coloured balls - and are given the score of a player in snooker after their first turn, what are the ways that they could have achieved this score?

Input will be a score going from 1 to 147. You can choose if it is an integer or a string. Output should be the different combinations of number of times you potted each ball.

Test cases:

```
Input: 4
Output:
1r 1g
2r 1y
Input: 25
Output:
4r 3b
5r 2b 1br 1y
5r 2b 2g
...
9r 8y

```

Rules:

* You can choose whether you output the possibilities divided by a new line or a separator of some sort (/,;|\ or even others I'm missing)

This is codegolf, so the shortest code wins.

# Answer
> 6 votes
# Jelly,  ~~65~~  25 bytes

```
7Ḋṗ15Ė€F;ɗ€ƊÄċƇ⁸f€RŻ€IṢ€Q

```

A monadic Link that accepts an integer, "score", from \\$\[1,147\]\\$ and yields a list of lists - each being a potential selection of ball scores used in reaching the given score disregarding the order in which they were actually potted.

**Try it with only six reds** (`15` replaced with `6`; again, fifteen reds would take an age).

### How?

```
7Ḋṗ15Ė€F;ɗ€ƊÄċƇ⁸f€RŻ€IṢ€Q - Link integer, S
7                         - seven
 Ḋ                        - dequeue -> coloured ball scores, [2..7]
           Ɗ              - last three links as a monad - f([2..7]):
   15                     -   fifteen
  ṗ                       -   ([2..7]) Cartesian power (15) -> all length 15 words
                                using the coloured ball scores as letters
          €               -   for each (such Word):
         ɗ                -     last three links as a dyad - f(Word, [2..7])
                                              e.g. Word = [7,...,7]
     Ė€                   -       enumerate each          [[1,7],...,[1,7]]
       F                  -       flatten                 [1,7,...,1,7]
        ;                 -       concatenate ([2..7])    [1,7,...,1,7,2,3,4,5,6,7]
            Ä             - cumulative sums, i.e. convert each such legal way to
                              clear the table to a list of the running score
              Ƈ           - filter keep those for which this is truthy (non-zero):
               ⁸          -   chain's left argument (S)
             ċ            -   count - i.e. count of S in the running score
                  R       - range (input Score) -> [1..S]
                f€        - for each (running score list) filter keep ([1..S])
                   Ż€     - prefix each with a zero
                     I    - forward differences of each (back to ball scores)
                      Ṣ€  - sort each
                        Q - deduplicate

```

---

Original \\$66\\$ byte entry (\\$65\\$ really, since the trailing `G` is post-formatting):

```
L⁼30µÐfµ7Ḋ;\¤;€Ṣ€µ€;/
ċ1<⁴µÐfµ;Ç
7Ḋœċ⁴Ḷ¤;/L€;$€;@þ2B¤;/ḟ€0ÇS⁼¥Ðf⁸G

```

Well, it's too slow for TIO now!
...so here is a paste of the 2636 ways to make exactly **100** produced offline.
...and **here** is a version that will run there with just **SIX reds** (maximum break = 75)

Prints a grid of numbers each line being a space separated list of ball values (e.g. three red and two green would be on a line reading `1 1 1 3 3`).

---

For a value-grouped version that prints lines of counts along with the full names of the balls, at 102 bytes:

```
ŒrÑ€
Ṫ;ị“¡^³ṗ⁼¬wḌ⁼ø÷OẏK¦ẆP»Ḳ¤$K
L⁼30µÐfµ7Ḋ;\¤;€Ṣ€µ€;/
ċ1<⁴µÐfµ;Ç
7Ḋœċ⁴Ḷ¤;/L€;$€;@þ2B¤;/ḟ€0ÇS⁼¥Ðf⁸Ñ€K€Y

```

---

### How?

```
L⁼30µÐfµ7Ḋ;\¤;€Ṣ€µ€;/ - Link 1, create post-red-ball games: list of all pre-yellow-ball-games
    µÐf               - filter keep if:
L⁼30                  -   length equals 30 (games that get on to the yellow)
       µ         µ€   - for €ach sequence leading to the yellow:
            ¤         -   nilad followed by link(s) as a nilad:
        7Ḋ            -     7 dequeued  = [2,3,4,5,6,7]
          ;\          -     ;\ cumulative reduce with concatenation  = [[2],[2,3],[2,3,4],...]
             ;€       - concatenate the sequence with €ach of those
               Ṣ€     - sort each one
                   ;/ - reduce with concatenation (flatten by one)

ċ1<⁴µÐfµ;Ç - Link 2, filter bogus entries created and append post-yellow-ball games: list of pre-yellow-ball games (along with the bogus ones with 16 reds potted)
    µÐf    - filter keep if:
ċ1         -   count ones
   ⁴       -   literal 16
  <        -   less than?
       µ   - monadic chain separation
         Ç - call the last link (1) as a monad
        ;  - concatenate

7Ḋœċ⁴Ḷ¤;/L€;$€;@þ2B¤;/ḟ€0ÇS⁼¥Ðf⁸G - Main link: score
7Ḋ                                - 7 dequeued = [2,3,4,5,6,7]
      ¤                           - nilad followed by link(s) as a nilad:
     ⁴                            -   literal 16
    Ḷ                             -   lowered range = [0,1,2,...,15]
  œċ                              - combinations with replacement (every possible colour-ball selection that goes with the red pots)
       ;/                         - reduce with concatenation (flatten by one)
            $€                    - last two links as a monad for €ach:
         L€                       -   length of €ach (number of coloured balls potted)
           ;                      -   concatenate
                   ¤              - nilad followed by link(s) as a nilad:
                 2B               -   2 in binary = [1,0]
                þ                 - outer product with:
              ;@                  -   concatenation with reversed @rguments
                    ;/            - reduce with concatenation (flatten by one)
                      ḟ€0         - filter discard zeros from €ach
                         Ç        - call the last link (2) as a monad
                             Ðf   - filter keep:
                            ¥  ⁸  -   last two links as a dyad, with score on the right
                          S⁼      -     sum(ball values) is equal to score?
                                G - format as a grid
                                  - implicit print

```

# Answer
> 4 votes
## JavaScript (ES7), ~~188~~ ~~180~~ 178 bytes

Returns an array of arrays (sorted from red to black).

```
n=>[...Array(17**6)].map((_,x)=>[2,3,4,5,6,p=7].map(v=>(k=a[++j]=x%17|0,x/=17,t+=k,p+=!!(y=y&&k),s-=k*v),y=s=n,a=[j=t=0])&&(s==15|s>=t)&s<16&s<t+2&t<9+p&&(a[0]=s,a)).filter(a=>a)

```

### Commented

**Note**: This version doesn't include the last optimization on `p` (now initialized to 7) which makes the logic harder to understand.

```
n =>                              // given a target score n:
  [...Array(17**6)].map((_, x) => // for each x in [0 .. 17^6 - 1]:
    [2, 3, 4, 5, 6, 7].map(v =>   //   for each v in [2 .. 7] (yellow to black):
      ( k = a[++j] = x % 17 | 0,  //     k = a[j] = number of colored balls of value v
        x /= 17,                  //     update x to extract the next value
        t += k,                   //     update t = total number of colored balls
        p += !!(                  //     update p = number of consecutive colors that were
          y = y && k              //     potted at least once, using y = flag that is zeroed
        ),                        //     as soon as a color is not potted at all
        s -= k * v ),             //     subtract k * v from the current score s
      y = s = n,                  //     initialize y and s
      a = [j = t = p = 0]         //     initialize a, j (pointer in a), t and p
    )                             //   at this point, s is the alleged number of red balls
    &&                            //   this combination is valid if we have:
      (s == 15 | s >= t) &        //     - 15 red balls or more red balls than colored ones
      s < 16 &                    //     - no more than 15 red balls
      s < t + 2 &                 //     - at most one more red ball than colored ones
      t < 16 + p                  //     - no more than 15 + p colored balls
    &&                            //   if valid:
      (a[0] = s, a)               //     update the combination with red balls and return it
  ).filter(a => a)                // end of outer map(): filter out invalid entries

```

### Example output

Below is the output for n = 140:

```
//  R   Y  G  Br Bl P  Bk
[ [ 15, 1, 1, 1, 1, 8, 9  ],
  [ 15, 1, 1, 1, 2, 6, 10 ],
  [ 15, 1, 1, 1, 3, 4, 11 ],
  [ 15, 1, 1, 2, 1, 5, 11 ],
  [ 15, 1, 1, 1, 4, 2, 12 ],
  [ 15, 1, 1, 2, 2, 3, 12 ],
  [ 15, 1, 2, 1, 1, 4, 12 ],
  [ 15, 1, 1, 2, 3, 1, 13 ],
  [ 15, 1, 1, 3, 1, 2, 13 ],
  [ 15, 1, 2, 1, 2, 2, 13 ],
  [ 15, 2, 1, 1, 1, 3, 13 ],
  [ 15, 1, 2, 2, 1, 1, 14 ],
  [ 15, 2, 1, 1, 2, 1, 14 ],
  [ 15, 1, 1, 1, 1, 1, 15 ] ]

```

### Demo

This is too slow for a snippet. You can **try it here** instead. (You may get one or two *unresponsive script* alerts, but it should eventually complete.)

---
Tags: code-golf
---


title: Is it simple or is it hard?

text:
# Question
Title: Is it simple or is it hard?
For your hard thing to do, you must make a thing for a computer to do that finds out if some words are explained in a simple way. Something is explained in a simple way if it only uses the ten hundred most used words. If not, it is explained in a hard way. This can be a full computer thing or part of a computer thing. (full program or function)

There is a thing for a computer to read that has all of the ten hundred words in it with a space between each word. The name of the thing for the computer to read is called 'most used.txt'. You can take this thing from this computer place.

The person who uses the computer thing will enter some words. (This can be from STDIN, function arguments or command line arguments) The computer must say something like a true if the words are simple and something like a not true if it is hard. (truthy-falsy) The person who makes the shortest thing for the computer to do is the best. The things that every person knows are bad are bad. (standard loopholes apply)

---

More stuff to know about how the computer thing works:

* It doesn't matter if the words are BIG or little.
* The pictures that make what the word meaning easier to know (punctuation) don't matter. So if the person who uses the computer thing says "dont" it isn't a different word than the word "don't". Numbers and other pictures also don't matter. So if the person says "HE$$ll9o" the computer should read it like "hello"
* The little lines between words (dashes) work the same way as spaces. So the word "up-goer-five" is the same as the words "up goer five".

---

More stuff to know about making words like this:

https://xkcd.com/1133/

http://splasho.com/upgoer5/#

# Answer
> 6 votes
# CJam, 41 bytes

```
q"file:///most used.txt"g]{el_euS--S%}/-!

```

This makes the rather unclean assumption that `most used.txt` is in the root directory, since CJam cannot handle relative paths.

Alternatively, we have the following web-based solutions (78 and 29 bytes):

```
q"https://docs.google.com/uc?id=0B2sM8IORrbL3RVpJWTZNUy1rOFU"g]{el_euS--S%}/-!

```

```
q"j.mp/-o_O"g]{el_euS--S%}/-!

```

The "proper" way of doing this in CJam would be reading both inputs from STDIN (input on the first line, dictionary on the second), which is possible in 18 bytes:

```
qN%{el_euS--S%}/-!

```

You can try the last version in the CJam interpreter. (permalink tested in Chrome)

### Examples

```
$ cjam <(echo 'q"file:///most used.txt"g]{el_euS--S%}/-!') <<< 'ten hundred'; echo
1
$ cjam <(echo 'q"file:///most used.txt"g]{el_euS--S%}/-!') <<< 'thousand'; echo
0

```

# Answer
> 8 votes
# R, 106 bytes

Is not sure if is understand challenge because is has hard time reading.

```
function(s){u=toupper;all(strsplit(gsub("[^A-Z -']","",u(s)),"[ -]")[[1]]%in%u(scan("most used.txt","")))}

```

This creates an unnamed part of a computer thing that accepts a string and returns something like a true or like a not true.

Ungolfed + explanation:

```
partOfAComputerThing <- function(s) {
    # Remove everything but letters, spaces, dashes, and single quotes
    s <- gsub("[^A-Z -']", "", toupper(s))

    # Split s into a vector on spaces/dashes
    v <- strsplit(s, "[ -]")[[1]]

    # Read the file of words (assumed to reside in the current directory)
    m <- scan("most used.txt", "")

    # Determine if all words in the input are in the file
    all(v %in% toupper(m))
}

```

Thanks to Dennis for inspiration thing.

# Answer
> 3 votes
# Python 3, 148 bytes

```
import re
print(all(i in open("most used.txt").read().lower().split(' ')for i in re.sub("[^a-z ']+","",input().replace("-"," ").lower()).split(" ")))

```

Outputs `True` and `False`

## Examples

```
Input:  Don't
Output: True

Input:  The poison air he's breathing has a dirty smell of dying
Output: False

Input:  Who let the dogs out?
Output: False

```

# Answer
> 2 votes
# Pyth, 35 bytes

```
!-Fm@LGcrXd\-bZ),zs'"most used.txt

```

Tests, where the above is the file `common.pyth`

```
$ pyth common.pyth <<< 'I can write this way too-hell99#0O.'
True
$ pyth common.pyth <<< 'But I get confused easily.'
False

```

Explanation:

```
!-Fm@LGcrXd\-bZ),zs'"most used.txt
   m            ,zs'"most used.txt    Map over input and input file:
         Xd\-b                        Replace hyphens with newlines.
        r     Z                       Cast to lower case.
       c       )                      Split on whitespace.
    @LG                               Remove non-alphabetic characters.
 -F                                   Setwise difference - remove anything in
                                      the text file from the input.
!                                     Logical negation.

```

# Answer
> 0 votes
# APL (Dyalog), 69 bytes

Assumes that the file is in the current directory.

```
s←819⌶' '(1↓¨,⊂⍨⊣=,)'[- ]' '\W'⎕R' ' ''
∧/(s⍞)∊s⊃⎕NGET'most used.txt'

```

Try it online!

The first line defines a normalising and splitting-into-list-of-strings helper function, *s*:

`s←`*s* is
`819⌶` the lowercased
`' '(` result of the following function, with a space as left argument…
`1↓¨` drop one from each of
`,` the concatenation of the arguments
`⊂⍨` cut before each element where
the left argument
`=` is equal to
`,` the concatenation of the arguments
`)` applied to
`'[- ]' '\W'⎕R' ' ''` the PCRE replacements dash/space→space, non-word-char→nothing

`∧/(``)` is it all-true that
`s` the normalised and split
text input
are members of
`s` the normalised and split
first element of
`⎕NGET'most used.txt'` the (content, encoding, newline-style) of the file

# Answer
> 0 votes
# JavaScript (ES7), 161 bytes

```
s=>fetch("most used.txt").then(t=>t.text()).then(d=>alert(s.split(/[ -]/g).every(l=>d.split` `.map(w=>w.replace(/[\.']/,"")).includes(l.replace(/[^a-z]/g,"")))))

```

Anyone got a copy of the file online that I can use to create a working Snippet?

# Answer
> 0 votes
# PHP, 101 bytes

```
foreach(preg_split("#[^\w']+#",$argn)as$w)preg_match("#\b$w\b#i",end(file("most used.txt")))?:die(1);

```

takes input from STDIN, assumes single line dictionary
exits with `1` (error) for falsy, `0` (ok) for truthy. Run with `-R`.

Split input by non-word characters, loop through resulting array (words):
If word is in the dictionary, continue; else `exit(1)`.
implicit `exit(0)`.

or, simply put:

one word after another: If word is in the most used words, continue; else return 1. return 0.

and: I could save two points if the most used words had a space each in front and at the end.

# Answer
> -1 votes
# Java, 248 bytes

With the Phrase passed as an argument.

```
void g(String s) throws Exception{String c=new java.util.Scanner(new java.io.File("most used.txt")).useDelimiter("\\Z").next(),x="false";for(String l:s.split(" "))if(c.contains(l.toLowerCase().replaceAll("![a-z]","")))x="true";System.out.print(x);}

```

input/output:

```
g("was he")         --> "true"
g("was h!e")         --> "true"
g("delicious cake") --> "false"

```

Spaced and tabbed out:

```
void g(String s) throws Exception{
    String c=new java.util.Scanner(new java.io.File("most used.txt")).useDelimiter("\\Z").next()
      ,x="false";
    for(String l:s.split(" "))
      if(c.contains(l.toLowerCase().replaceAll("![a-z]","")))
          x="true";
    System.out.print(x);
}

```

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


title: Numbers for Letters

text:
# Question
Title: Numbers for Letters
There exists a very simple cipher that replaces a letter with it's position in the alphabet. For example, `abc` would become `1 2 3` in this cipher.

This challenge is an alternative take on this cipher.

---

# The Challenge

Create a program that takes an input of ASCII characters, and outputs a space-separated string of:

* integers `-26` through `26`
* letters `a` through `j`

The output should come through STDOUT or your language's closest alternative.

---

# Specifications

* Capital letters should be negated. A capital `D` for example would be `-4`, while a lowercase `d` would be `4`.
* Digits should be changed to their alpha counterparts. `1` being `a`, and so on. Any zeroes in the input will be `j`.
* All non-alphanumeric characters (except spaces) should be ignored.
* Spaces are `0`.
* Adjacent spaces in the output should be reduced to a single space.

```
Input: You + Me
Correct Output: -25 15 21 0 -13 5
Incorrect Output: -25 15 21 0 0 0 -13 5

```
* A single trailing space or newline is allowed.

---

# Examples

```
Input: programming puzzles
Output: 16 18 15 7 18 1 13 13 9 14 7 0 16 21 26 26 12 5 19

Input: Code Golf
Output: -3 15 4 5 0 -7 15 12 6

Input: Programming Puzzles & Code Golf
Output: -16 18 15 7 18 1 13 13 9 14 7 0 -16 21 26 26 12 5 19 0 -3 15 4 5 0 -7 15 12 6

Input: C0d3 G0lf
Output: -3 j 4 c 0 -7 j 12 6

Input: abc_ABC
Output: 1 2 3 -1 -2 -3

```

---

# Scoreboard

For your score to appear on the board, it should be in this format:

```
# Language, Bytes

```

Strikethroughs shouldn't cause a problem.

```
function getURL(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:getURL(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),useData(answers)}})}function getOwnerName(e){return e.owner.display_name}function useData(e){var s=[];e.forEach(function(e){var a=e.body.replace(/<s>.*<\/s>/,"").replace(/<strike>.*<\/strike>/,"");console.log(a),VALID_HEAD.test(a)&&s.push({user:getOwnerName(e),language:a.match(VALID_HEAD)[1],score:+a.match(VALID_HEAD)[2],link:e.share_link})}),s.sort(function(e,s){var a=e.score,r=s.score;return a-r}),s.forEach(function(e,s){var a=$("#score-template").html();a=a.replace("{{RANK}}",s+1+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SCORE}}",e.score),a=$(a),$("#scores").append(a)})}var QUESTION_ID=58107,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],answer_ids,answers_hash,answer_page=1;getAnswers();var VALID_HEAD=/<h\d>([^\n,]*)[, ]*(\d+).*<\/h\d>/;
```

```
body{text-align:left!important}table thead{font-weight:700}table td{padding:10px 0 0 10px}#scores-cont{padding:10px;width:600px}#scores tr td:first-of-type{padding-left:0}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="scores-cont"><h2>Scores</h2><table class="score-table"><thead> <tr><td></td><td>User</td><td>Language</td><td>Score</td></tr></thead> <tbody id="scores"></tbody></table></div><table style="display: none"> <tbody id="score-template"><tr><td>{{RANK}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SCORE}}</td></tr></tbody></table>
```

# Answer
# CJam, ~~58~~ ~~57~~ ~~54~~ ~~51~~ ~~50~~ 49 bytes

*Just* when I wrote up the explanation, I noticed that one of the alternative 50 byte versions can be shortened by a byte...

```
q_el_eu&S-A,s--S%S*{i_32md\2*5-*48md@)A%'a+\?}%S*

```

Test it here.

50 byte solutions:

```
q_el_eu&S-A,s--S%S*{_A,s&\i_)A%'a+\32md\2*5-*?}%S*
q_el_eu&S-A,s--S%'`*{i32md:D;(_(2*(D*D3+A%'a+?}%S*
q_el_eu&S-A,s--S%'`*{i32md\(_@_@(2*(*\3+A%'a+?}%S*
q_el_eu&S-A,s--S%'`*{i32md\(_(2*(g@*_z3+A%'a+?}%S*

```

## Explanation

```
q         e# Read input.
_el_eu&   e# Intersect a lower-case version with an upper-case version to remove
          e# all letters.
S-        e# Remove spaces from that string.
A,s-      e# Remove digit characters from that string. It now contains all the
          e# the characters from the input we should ignore.
-         e# Remove these characters from the input.
S%S*      e# Split on runs of spaces and join by spaces, collapsing multiple into one.
{         e# Map this block onto each character...
  i_      e#   Convert to character code and make a copy.
  32md    e#   Get divmod 32. Note that digits have character codes 32 + something,
          e#   the upper case letters have character codes 64 + n (where n is the
          e#   absolute value we want), while lower case letters have codes 96 + n.
          e#   So the div gives 2 or 3 to distinguish capitalisation (and 1 for digits)
          e#   and the mod gives the correct absolute value for letters.
          e#   As it happens, the mod also gives 0 for spaces.
  \2*5-   e#   Pull up the div, duplicate, subtract 5. Turns 2 into -1 and 3 into 1.
          e#   It also turns 1 (digits) into -3.
  *       e#   Multiply the mod by this sign.
          e#   We now have the correct result for everything but digits. Note that
          e#   the absolute value for digits is more than 26, and for everything
          e#   else it's less than 27.
  48md    e#   Get divmod 48. This gives div 0 and mod n for all correct results n.
          e#   For digits it gives div -1 and we don't care about the mod. We'll
          e#   use the div as a truthy/falsy value to select the right result.
  @)A%    e#   Pull up the other copy of the character code, increment
          e#   (range 49..58), take modulo 10.
          e#   This gives 9 for 0 and n-1 for any other digit n.
  'a+     e#   Add to the character a.
  \?      e#   Select the correct result based on the div 48.
}%
S*        e# Join the resulting values by spaces.

```

This must be the first time, that CJam's modulo behaviour for negative values was useful for me.
> 10 votes

# Answer
# JavaScript (ES6), ~~110~~ ~~107~~ ~~133~~ 120 bytes

Take that, old me!

```
a=>[...a.replace(/[\W_]*?( ?)[\W_]*/g,'$1')].map(x=>(c=x.charCodeAt())<40?0:c<60?'jabcdefghi'[x]:c<91?64-c:c-96).join` `

```

There's potentially a lot more room for golfing, ~~especially in the regexes~~ nope, got that one down pretty well. Ungolfed version:

```
function f(a) {
  // Replaces each run of bad chars and spaces with
  // a space if it contained one, nothing otherwise:
  a = a.replace(/[\W_]*?( ?)[\W_]*/g, '$1');

  var b = a.split('');
  b = b.map(function(x) {
    var c = x.charCodeAt();
    if (c == 32)     // space
      return 0;
    else if (c < 60) // numbers
      return 'jabcdefghi'.charAt(x);
    else if (c < 91)
      return 64 - c; // uppercase
    else
      return c - 96; // lowercase
  });
  b = b.join(' ');
  return b;
}

```

Suggestions welcome!
> 6 votes

# Answer
# Pyth, ~~50~~ 49 bytes

```
jdm?>d26C+70ddm-xZd26:-z-z=Zs[_rG1dGjk.<UT1)" +"d

```

Try it out here.

Edit: restructured string sanitisation to ensure underscores are handled correctly. It even saved a byte too, yay!

This program creates a lookup string, which is used to sanitise the input. This is then mapped to the corresponding index in that string. Finally, any index greater than 26 is converted to the correct ASCII character.

```
                                                     Implicit: z=input(), d=' ', ,
                                                       k='', G=[a-z]
                              _rG1                   Reversed, capitalised alphabet
                                  d                  Single space
                                   G                 Lower case alphabet
                                    jk.<UT1          '1234567890'
                            s[             )         Concatenate the 4 previous statements
                          =Z                         Store in Z
                        -z                           Setwise difference of input and above
                                                       (to get all illegal characters)
                      -z                             Setwise difference of input and illegal chars
                     :                      " +"d    Regex replace to lose multiple spaces
              m                                      Map the above over d:
                xZd                                    Get index of d in Z
               -   26                                  Subtract 26
  m                                                  Map the above over d:
   ?>d26                                               If d > 26
        C+70d                                            Convert (d+70) to ASCII
             d                                         Otherwise, select d
jd                                                   Join on spaces and print

```

Previous version, which made use of `\W` regex, at 50 bytes:

```
jdm?>d26C+70ddm-xs[_rG1\ Gjk.<UT1)d26::z"\W"d" +"d

```
> 4 votes

# Answer
# Julia, ~~145~~ 136 bytes

```
r=replace;print(join([47<x<58?x+58-10(x>48):x==32?0:cmp(x,96)*(lowercase(x)-96)for x=r(r(readline(),r"[^a-z0-9 ]"i,""),r" +"," ")]," "))

```

Ungolfed:

```
# Read a string from STDIN
input = readline()

# Remove non-alphanumeric characters and replace duplicated spaces
r = replace(replace(input, r"[^a-z0-9 ]"i, ""), r" +", " ")

# Construct an array using comprehension over the replaced input string
A = [47 < x < 58 ? x + 58 - 10(x > 48) : x == 32 ? 0 : cmp(x, 96) * (lowercase(x) - 96) for x = r]

# Join the array elements with spaces
j = join(A, " ")

# Print to STDOUT
print(j)

```

To get the digits as letters we add 58 to the ASCII value and subtract 10 if the current character isn't 0. That ensures that 0 maps to `j` and the other digits map to `a`-`i`.

Negating uppercase letters is done using `cmp`. This will return -1 for uppercase letters and 1 for lowercase.

Try it online
> 3 votes

# Answer
# Perl 5, ~~120~~ ~~116~~ ~~113~~ 105 Bytes

First cleans up the unwanted characters & extra spaces.
Then climbs down the ascii table for each character.

```
$_=pop;s/[^\w ]|_//g;s/ +/ /g;map{$n=ord;say$".($n>96?$n-96:$n>64?64-$n:$n>48?chr$n+48:$n>47?j:0)}split//

```

### Test

```
$ perl -M5.01 numbers4letters.pl "zZaA _ 190"
 26 -26 1 -1 0 a i j
$ perl -M5.01 numbers4letters.pl "PrOgr4mm1n9 Puz2l3s & C0d3_G0lf!"
-16 18 -15 7 18 d 13 13 a 14 i 0 -16 21 26 b 12 c 19 0 -3 j 4 c -7 j 12 6

```
> 2 votes

# Answer
# JavaScript (ES6), 108 ~~122 124~~

**Edit** Using the regexp from @Max's comment
**Edit2** 14 bytes saved thanks ETHProductions

EcmaScript 6 just for the arrow functions, so it should work in Firefox and latest Chrome.

Test running the snippet below

```
F=
t=>t[R='replace'](/[^\w ]|_/g,'')[R](/ +|./g,c=>((v=parseInt(c,36))>9?c>'Z'?v-9:9-v:'jabcdefghi'[v]||0)+' ')

// Less golfed
U=t=>
  t.replace(/[^\w ]|_/g,'') // remove invalid characters
  .replace(/ +/g,' ') // collapse spaces
  .replace(/./g, c => ( // valid character replacing
    v = parseInt(c,36), // '0'..'9'-> 0..9, 'a'..'z' -> 10..25, ' ' -> NaN
    (
      v > 9
      ? c > 'Z' ? v-9 : 9-v // manage upper vs lower
      : 'jabcdefghi'[v] || 0 // digits, NaN as an index gives undefined, substituted with 0
    ) + ' ' // separator space
  ))

// TEST
out=x=>O.textContent=x+'\n'+O.textContent;

function go() { out(I.value + ' --> ' + F(I.value) +'\n')}

// test cases, a trailing blank added to the expected output as ...
// "A single trailing space or newline is allowed."

;[
  ['A$b','-1 2 ']
, ['123___abc', 'a b c 1 2 3 ']
, ['You + Me','-25 15 21 0 -13 5 ']
, ['programming puzzles', '16 18 15 7 18 1 13 13 9 14 7 0 16 21 26 26 12 5 19 ']
, ['Code Golf', '-3 15 4 5 0 -7 15 12 6 ']
, ['Programming Puzzles & Code Golf', '-16 18 15 7 18 1 13 13 9 14 7 0 -16 21 26 26 12 5 19 0 -3 15 4 5 0 -7 15 12 6 ']
, ['C0d3 G0lf', '-3 j 4 c 0 -7 j 12 6 ']
].forEach(t=>{
  k=t[1],r=F(t[0]),
  out('Test '+(k==r?'OK':'Fail')+'\nInput:  '+t[0]+'\nResult: '+r+'\nCheck:  '+k+'\n')
})
```

```
Custom test: <input id=I><button onclick='go()'>-></button>
<pre id=O></pre>
```
> 2 votes

# Answer
# C, ~~142~~ ~~138~~ 135

```
c,d;main(s){while(c=getchar()+1)d=c|32,c=d-98<26u?s=(d-97)*(c/32*2-5),0:c-48<11u?s='a'+c%10,4:c==33&&s?s=0,0:3,printf("%d \0%c "+c,s);}

```

Ungolfed a bit:

```
int c,d;
int main(int s)                     // s initially non-zero, meaning spaces are allowed
{
    while(c=getchar()+1)            // getchar until EOF (-1) encountered
    {
        d=c|32;                     // d becomes lowercase c (both incremented by 1)
        if (d-98<26u)               // check for letter
        {
            s=(d-97)*(c/32*2-5);    // print this number and allow subsequent spaces
            c=0;                    // format string will be "%d "
        }
        else if (c-48<11u)          // check for digit
        {
            s='a'+c%10;             // print this letter and allow subsequent spaces
            c=4;                    // format string will be "%c "
        }
        else if (c==33&&s)          // else if space and allowed to output spaces
        {
            s=0;                    // print 0 and disallow subsequent spaces
            c=0;                    // format string will be "%c "
        }
        else
        {
            c=3;                    // format string will be "", prints nothing
        }
        printf("%d \0%c "+c,s);     // final c is treated as index into string literal
    }
}

```

Passes the given tests in GCC 4.9.3 & Clang 3.5.2.
> 2 votes

# Answer
# \>\<\> (fish), ~~219~~ 209 bytes

```
>i:84*=?v:86*1-)?!^:f4*2-(?v:88*)?!v:a9*1+(?v:c8*)?!^:ca*3+  (?v~
>4*(?vov>~86*$:@=?v86*00.  >:86*=?v77*1-+00.>88*-::-$-00.01-*8c<
 >.! ! ! 00~v?( 0:\00. >.!00+6*aa~<>~    92*2!.<2*29<
^7:;?=0:<r0~<
*o73.>n>84

```

Try it out here

This is my first code golf answer! Finally been able to use the language I wanted to use for a code golf challenge, and this seemed like the perfect one given that characters are automatically converted to decimals.

I expected my result to be way shorter, but apparently not. Though, I haven't golfed this one too much. There are a few places the code could be cleaner/make more sense, but won't save any bytes since they're in places where whitespace is needed anyway. There might be a way to save some bytes on the last bit on the second line, making it go the opposite direction and mashing up with the 00 already there, I'll have to play with it more later

Basically, this checks to see whether the current char is a space, number, uppercase letter, or lowercase letter, by checking if it's in range of the highest/lowest values of that group. If it isn't any of those, it gets discarded. If it is in one of those, it gets converted to a number if it's a letter, and a letter if it's a number (or rather, a number from 97-106 which are the values for letters a-j). Then it checks if the top value is less than 28, in which case it's a number and outputs a number, otherwise it's a letter and outputs the letter that number represents, outputs a space, then loops until the stack is empty.
> 2 votes

# Answer
# Python 2, ~~191~~ ~~179~~ ~~177~~ ~~173~~ ~~172~~ ~~168~~ 160 bytes

```
import re
print" ".join([[[chr(x+48),"j"][x<49],[`[x-96,-x+64][x<96]`,"0"][x<65]][x>57or x<33]for x in map(ord,re.sub(" +"," ",re.sub("[^\w ]|_","",input())))])

```

# Test

```
"programming puzzles"
16 18 15 7 18 1 13 13 9 14 7 0 16 21 26 26 12 5 19

"Code Golf"
-3 15 4 5 0 -7 15 12 6

"Programming Puzzles & Code Golf"
-16 18 15 7 18 1 13 13 9 14 7 0 -16 21 26 26 12 5 19 0 -3 15 4 5 0 -7 15 12 6

"C0d3 G0lf"
-3 j 4 c 0 -7 j 12 6

"You + Me"
-25 15 21 0 -13 5

```
> 1 votes

# Answer
# Pyth, 57 bytes

```
:jdm@s[r_26Zr1 27Zc<GT1"")xs[_rG1G\ jkr1TZ)dz"0[0 ]+""0 "

```

Live demo and test cases.
> 1 votes

# Answer
# CJam, 52 bytes

```
'{,97>:L_eu+A,s(++S+l{1$&},S%S*\26,:)_Wf*+LA<+0+erS*

```

Try it online

The key part with the solution is that it uses the CJam `er` (transliteration) operator. As arguments to the operator, it needs the list of all characters, and a list of the corresponding values.

As a pre-processing step on the input, it removes characters that are not part of the translation table (special characters), and reduces repeated spaces to a single space.

Explanation:

```
'{,97>  Build list of all lower case letters.
:L      Save it in variable L for later reuse.
_eu+    Add list of upper case letters.
A,s     Build digits "0123456789".
(+      Pop off first digit and append it at the end, to get "1234567890".
+       Add digits to list of characters.
S+      Add a space. List of characters that have values is now complete.
l       Get input.
{1$&},  Filter out all input characters that are not in list.
S%      Split input at spaces.
S*      And re-assemble it with spaces. This reduces multiple spaces to one space.
\       Swap input and character list.
26,     Start building list of values. Start with [0 ... 25].
:)      Use "smilie operator" to increment all values, to get [1 ... 26].
        These are the values for the lower case letters.
_Wf*    Copy the list and negate the values to get [-1 ... -26] for upper case.
+       Concatenate the two lists.
L       Retrieve the list of lower case letters we saved away earlier.
A<      Keep the first 10, which are the values for the digits.
+       Concatenate to list of values.
0+      Add 0 to list, as value for space.
er      Transliterate input string to corresponding values.
S*      Join with spaces for output.

```
> 1 votes

# Answer
# PHP, 116 bytes

```
while($c=ord(preg_replace(["#[^\w ]|_#","# +#"],["","@"],$argn))[$i++])echo$c<96?jabcdefghi[$c-48]?:64-$c:$c-96," ";

```

takes input from STDIN; run with `-nR`.

**breakdown**

```
while($c=ord(preg_replace(["#[^\w ]|_#","# +#"],["","@"],$argn) # sanitize input
    [$i++]))echo            # loop through string and print ...
    $c<96                       # if not lowercase:
        ?jabcdefghi[$c-48]          # digit -> letter
        ?:                          # if that turned out falsy (=empty):
        64-$c                       # uppercase (or former spaces) -> negative (or 0)
    :$c-96                      # else -> positive
," ";                           # append space

```

You can replace the `@` with a backtick to handle spaces in the lowercase part.
~~With `jabcdefghi0` for the digits, you could also use `:`.~~
> 1 votes

# Answer
# Hassium, 1156 Bytes

```
func main() {s = input();c="";for(x=0;x<s.length;x++){c=s[Convert.toNumber(Convert.toString(x))].toString();if (c.toLower()!=c)print(r(c.toLower())*-1);else if(r(c)=="")continue;else print(r(c));print(" ");}}func r(c) {if(c=="a")return 1;else if(c=="b")return 2;else if(c=="c")return 3;else if(c=="d")return 4;else if(c=="e")return 5;else if(c=="f")return 6;else if(c=="g")return 7;else if(c=="h")return 8;else if(c=="i")return 9;else if(c=="j")return 10;else if(c=="k")return 11;else if(c=="l")return 12;else if(c=="m")return 13;else if(c=="n")return 14;else if(c=="o")return 15;else if(c=="p")return 16;else if(c=="q")return 17;else if(c=="r")return 18;else if(c=="s")return 19;else if(c=="t")return 20;else if(c=="u")return 21;else if(c=="v")return 22;else if(c=="w")return 23;else if(c=="x")return 24;else if(c=="y")return 25;else if(c=="z")return 26;else if(c==" ")return 0;else if(c=="1")return "a";else if(c=="2")return "b";else if(c=="3")return "c";else if(c=="4")return "d";else if(c=="5")return "e";else if(c=="6")return "f";else if(c=="7")return "g";else if(c=="8")return "h";else if(c=="9")return "i";else if(c=="0")return "j";else return"";}

```

Very long answer
> 0 votes

# Answer
# Java 7, ~~257~~ 254 bytes

```
class M{public static void main(String[]a){String r="",x;for(int c:a[0].getBytes()){x=(c>96&c<123?c-96:c>64&c<91?"-"+(c-64):c>48&c<58?(char)(c+48):c==48?"j":c<33?0:"")+"";r+=!x.isEmpty()&&!(r.endsWith("0 ")&x.equals("0"))?x+" ":"";}System.out.print(r);}}

```

Try it here.

**Explanation:**

```
class M{                               // Class
  public static void main(String[]a){  //  Required main-method
    String r="",                       //   Result-String
      x;                               //   Temp String
    for(int c:a[0].getBytes()){        //   Loop over the characters of the input-String
      x=(                              //    Set the temp String to:
        c>96&c<123?                    //     If it's a lowercase letter:
          c-96                         //      Set `x` to the 1-indexed alphabetic index
        :c>64&c<91?                    //     Else-if it's a uppercase letter:
          "-"+(c-64)                   //      Set `x` to the 1-indexed alphabetic index as negative
        :c>48&c<58?                    //     Else-if it's a digit 1-9:
          (char)(c+48)                 //      Set `x` to the 1-indexed alphabetic character
        :c==48?                        //     Else if it's a zero:
          "j"                          //      Set `x` to "j"
        :c<33?                         //     Else if it's a space:
          0                            //      Set `x` to "0"
        :                              //     Else:
          ""                           //      Set `x` to an empty String
       )+"";                           //     Required `+""` because `(char)` and `0` aren't Strings
      r+=                              //    Append the result-String with:
        !x.isEmpty()                   //     If `x` has a value
        &&!(r.endsWith("0 ")&x.equals("0"))?
                                       //     and it's not "0" with the previous value also being a zero
          x+" "                        //      Append the value of `x`, plus a space
        :                              //     Else:
          "";                          //      Append nothing
    }                                  //   End of loop
    System.out.print(r);               //   Print the result to STDOUT
  }                                    //  End of main-method
}                                      // End of class

```

**Example input & output:**

```
Input:
Programming Puzzles & C0d3 G0lf

Output:
-16 18 15 7 18 1 13 13 9 14 7 0 -16 21 26 26 12 5 19 0 -3 j 4 c 0 -7 j 12 6

```
> 0 votes

# Answer
# Jelly, 32 bytes, language postdates challenge

```
⁶ØB;µ³fi@€
Øaḣ⁵ṙ9
26RµN;;0¢;ị@ÑK

```

Try it online!

## Explanation

**Helper function `1Ŀ`** (translates each alphanumeric/space in the input into a number)

```
⁶ØB;µ³fi@€
⁶           space
 ØB;        append all digits, uppercase and lowercase letters (in that order)
    µ       set as the new default for missing arguments
     ³      first command-line argument
      f     delete all characters not in {space + alphanumerics}
       i@€  take index of each element within {space + alphanumerics}

```

**Helper function**  (returns the constant string `“jabcdefghi”`)

```
Øaḣ⁵ṙ9
Øa      lowercase alphabet
  ḣ⁵    take first 10 elements
    ṙ9  rotate 9 elements to the left

```

**Main program**

```
26RµN;;0¢;ị@ÑK
26R             Range from 1 to 26
   µ            set as default for missing arguments
    N           Minus {each element of the range from 1 to 26}
     ;          with {the range from 1 to 26} appended
      ;0        with a 0 appended
        ¢;      with the result of 2£ prepended
          ị@    index into this using
            Ñ   the result of 1Ŀ
             K  separate by spaces

```
> 0 votes

# Answer
# Retina, ~~74~~ 70 bytes

Note the leading space on line 3, the trailing space on line 6, and the empty second line.

```
[^\w ]|_

 +
~
.
$+
[A-Z]
-$+
T`L`l
[j-s]
a$+
[t-z]
b$+
T`~ld`dd0-6jl

```

Try it Online!
> 0 votes

---
Tags: code-golf, number, printable-ascii
---


title: Hexagonal Triangles!

text:
# Question
Title: Hexagonal Triangles!
Your task: make a hexagonal triangle with side length `n`, where `n` is a positive whole number or 0.

First, let me define a hexagon:

```
 / \
|   |
 \ /

```

(Amazing ASCII art, right?)

Hexagons can be linked together by sharing sides:

```
 / \ / \
|   |   |
 \ / \ /

   / \
  |   |
 / \ /
|   |
 \ /

```

A hexagonal triangle is the following:

```
   / \
  |   |
 / \ / \
|   |   |
 \ / \ /

```

That hexagonal triangle has a side length of 2-- 2 hexagons are required to make one side. A hexagonal triangle with side-length 1 is just a single hexagon, and a hexagon with side-length 0 is empty.

More formally, a hexagonal triangle is a triangle made of hexagons linked by their sides. The top hexagon links to the two below it on its bottom two sides. The triangle in the bottom left links to the one to its right and top-right, and the one in the bottom right links to the ones on its left and upper left. There are hexagons *in between* the corner ones, connected by their opposite sides, and their number is `n-2`. The triangles are **not** filled.

More examples:

```
Side length 3:
     / \
    |   |
   / \ / \
  |   |   |
 / \ / \ / \
|   |   |   |
 \ / \ / \ /

Side length 4:
       / \
      |   |
     / \ / \
    |   |   |
   / \ / \ / \
  |   |   |   |
 / \ / \ / \ / \
|   |   |   |   |
 \ / \ / \ / \ /
(This triangle isn't really filled, the borders make it look like there is a hexagon in the middle, but there is not.)

Side length 5:
         / \
        |   |
       / \ / \
      |   |   |
     / \ / \ / \
    |   |   |   |
   / \ /     \ / \
  |   |       |   |
 / \ / \ / \ / \ / \
|   |   |   |   |   |
 \ / \ / \ / \ / \ /

Side length 6:
           / \
          |   |
         / \ / \
        |   |   |
       / \ / \ / \
      |   |   |   |
     / \ /     \ / \
    |   |       |   |
   / \ /         \ / \
  |   |           |   |
 / \ / \ / \ / \ / \ / \
|   |   |   |   |   |   |
 \ / \ / \ / \ / \ / \ /

```

# Answer
# Charcoal, ~~62~~ ~~43~~ 39 bytes

```
ＮβＦ³«Ｆ⁻β‹ι²« / \¶|   |¶ \ /Ｍ×²ι↑¿⁻¹ιＭ⁶←

```

Try it online! Edit: Saved some bytes thanks to @ASCII-only (not sure exactly how many as I also saved another ~~6~~ 10 bytes but then needed to spend 4 bytes on a bugfix). Now using nested loops, which is what this should have been all along.
> 11 votes

# Answer
# Python 2, ~~184~~ ~~177~~ ~~174~~ 164 bytes

```
n=input();p='|   |';e=' \\ /'
for i in range(n):k=' '*(4*i-5);w='  '*~(i-n);print w+[' / \\'*-~i+'\n'+w+p[:4]*i+p,' /'+e+k[3:]+e+' \\\n'+w+p+k+p][2<i<n-1]
print e*n

```

Try it Online!

*-7 bytes thanks to Ørjan Johansen*
> 7 votes

# Answer
## JavaScript (ES6), 243 bytes

```
f=n=>(n=n*2-2,a=[...Array(n+3)].map(_=>Array(n*2+5).fill` `),g=(y,x)=>(a[y+1][x]=a[y+1][x+4]=`|`,a[y][x+1]=a[y+2][x+3]=`/`,a[y][x+3]=a[y+2][x+1]=`\\`),[...Array(n+!n)].map((_,i)=>i%2||(g(n,i*2),g(i,i=n-i),g(i,n+i))),a.map(a=>a.join``).join`
`)
```

```
<input type=number oninput=o.textContent=f(this.value)><pre id=o>
```
> 6 votes

# Answer
## JavaScript (ES6), ~~133~~ ~~129~~ ~~128~~ 126 bytes

Builds the output character by character with two *for* loops.

```
n=>{for(s='',y=n*2,n*=4;~y--;s+=`
`)for(x=n;~x--;)s+=' \\ /|'[x>y-2&x<n-y&(k=x+y&3,x>n-y-6|x<y+4|y<2)?y&1?k:k+1&4:0];return s}

```

### How it works

In the outer loop, ***y*** iterates from ***n\*2-1*** to ***-1***. In the inner loop, ***x*** iterates from ***n\*4-1*** to ***-1***. We set ***k = (x+y) & 3***, which is the underlying pattern that is used to generate the hexagons.

Below is the resulting grid for ***n = 4***:

```
     15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0 -1
   +---------------------------------------------------
 7 |  2  1  0  3  2  1  0  3  2  1  0  3  2  1  0  3  2
 6 |  1  0  3  2  1  0  3  2  1  0  3  2  1  0  3  2  1
 5 |  0  3  2  1  0  3  2  1  0  3  2  1  0  3  2  1  0
 4 |  3  2  1  0  3  2  1  0  3  2  1  0  3  2  1  0  3
 3 |  2  1  0  3  2  1  0  3  2  1  0  3  2  1  0  3  2
 2 |  1  0  3  2  1  0  3  2  1  0  3  2  1  0  3  2  1
 1 |  0  3  2  1  0  3  2  1  0  3  2  1  0  3  2  1  0
 0 |  3  2  1  0  3  2  1  0  3  2  1  0  3  2  1  0  3
-1 |  2  1  0  3  2  1  0  3  2  1  0  3  2  1  0  3  2

```

On even rows, a cell is filled with a pipe character when ***k = 3***, and a space otherwise. The pipe is the 5th character in our reference string `" \ /|"`, so the correct index is given by ***(k+1) & 4***.

On odd rows, each cell is filled directly with the corresponding character in the reference string:

* ***k = 0*** → space
* ***k = 1*** → "\\"
* ***k = 2*** → space
* ***k = 3*** → "/"

Below is our updated example (spaces replaced with dots):

```
     15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0 -1
   +---------------------------------------------------
 7 |  .  \  .  /  .  \  .  /  .  \  .  /  .  \  .  /  .
 6 |  .  .  |  .  .  .  |  .  .  .  |  .  .  .  |  .  .
 5 |  .  /  .  \  .  /  .  \  .  /  .  \  .  /  .  \  .
 4 |  |  .  .  .  |  .  .  .  |  .  .  .  |  .  .  .  |
 3 |  .  \  .  /  .  \  .  /  .  \  .  /  .  \  .  /  .
 2 |  .  .  |  .  .  .  |  .  .  .  |  .  .  .  |  .  .
 1 |  .  /  .  \  .  /  .  \  .  /  .  \  .  /  .  \  .
 0 |  |  .  .  .  |  .  .  .  |  .  .  .  |  .  .  .  |
-1 |  .  \  .  /  .  \  .  /  .  \  .  /  .  \  .  /  .

```

In the following formulas, we define ***N = n\*4*** for readability (although the same variable is used in the code).

The triangle shape is obtained by testing:

* ***x \> y - 2*** → removes the right corner
* AND ***x \< N - y*** → removes the left corner

And the inner part is removed by testing:

* ***x \> N - y - 6*** → keeps only the left edge
* OR ***x \< y + 4*** → keeps only the right edge
* OR ***y \< 2*** → keeps only the bottom edge

### Demo

```
let f =

n=>{for(s='',y=n*2,n*=4;~y--;s+=`
`)for(x=n;~x--;)s+=' \\ /|'[x>y-2&x<n-y&(k=x+y&3,x>n-y-6|x<y+4|y<2)?y&1?k:k+1&4:0];return s}

console.log(f(3))
console.log(f(4))
console.log(f(5))
console.log(f(6))
console.log(f(7))
```
> 4 votes

# Answer
# Jelly,  ~~62~~  61 bytes

### *Currently containing six sixes.*

```
_‘<×⁸>6
Rµ‘⁾| ẋ⁾/\ẋ⁸¤ż;/K€µ⁶ðMṀ_6r6ẋð¦"Jç¥
ḤḶUẋ@€⁶;"Çµ-ịṙ6ṭ⁸Y

```

**Try it online!**

### How?

```
_‘<×⁸>6 - Link 1, should we eat the praline? row number, triangle size
_       - row number minus triangle size
 ‘      - plus one
  <     - less than triangle size? (1 if one of the last rows else 0)
   ×⁸   - multiply by row number   (row number or 0)
     >6 - greater than 6?          (row number if between row 6 and last two rows)

Rµ‘⁾| ẋ⁾/\ẋ⁸¤ż;/K€µ⁶ðMṀ_6r6ẋð¦"Jç¥ - Link 2, build a solid triangle: triangle size
                                              (except the very bottom row)
R                                  - range: [1,2,...,size]
 µ                                 - monadic chain separation, call that r
  ‘                                - increment: [2,3,...,size+1]
   ⁾| <space                       - literal "| "
      ẋ                            - repeat: ["| | ","| | | ",...]
            ¤                      - nilad followed by link(s) as a nilad:
       ⁾/\                         -   literal "/\"
           ⁸                       -   link's left argument, r
          ẋ                        -   repeat (vectorises): ["/\","/\/\",...]
             ż                     - zip the two repeated lists together: [["/\","| | "],["/\/\","| | | "],...]
              ;/                   - reduce by concatenation: ["/\","| | ","/\/\","| | | ",...]
                K€                 - join with spaces for €ach: ["/ \","|   |  ","/ \ / \","|   |   |  ",...]
                  µ                - monadic chain separation call that s
                                 ¥ - last two links a a dyad:
                               J   -   range(length(s))
                                ç  -   call the last (1) link as a dyad (left = result of J, right = size)
                              "    - zip with: (call those d)
                    ð       ð¦     -   apply to indexes:
                   ⁶               -   a literal space character
                     M             -     indexes of maximal elements in an element of s (a row)
                      Ṁ            -     maximum (this is the rightmost non-space index, MṀ working like length ignoring trailing spaces)
                       _6          -     subtract 6  (6 indexes back from the right)
                         r6        -     range from there to 6, i.e [l-6,l-7,...,6]
                           ẋ       -     repeat d times (1 or 0), thus applying to the middle rows but not the bottom and top ones.

ḤḶUẋ@€⁶;"Çµ-ịṙ6ṭ⁸Y - Main link: triangle size
Ḥ                  - double(size)
 Ḷ                 - unlength: [0,1,2,...,double(size)-1]
  U                - upend: [double(size)-1,...,2,1,0]
      ⁶            - literal space character
   ẋ@€             - repeat for €ach with reversed arguments ["  ...  ",...,"  "," ",""]
         Ç         - call the last link (2) as a monad(size)
       ;"          - zip with concatenation (zips the leading spaces with the solid triangle body)
          µ        - monadic chain separation, call that t
           -ị      - index -1 (last but one row of t)
             ṙ6    - rotate left by 6 (any number congruent to 2 mod 4 would do)
               ṭ⁸  - tack to t (add this new row on)
                 Y - join all the rows by new lines
                   - implicit print

```
> 3 votes

# Answer
# Pyth, 82 bytes

```
jb+Rt_.rd"/\\"_.e<s[dd*dkb*dyQ)hyQ*,"|   |""/ \\ /"tQ*Q" / \\"+*Q"|   "\|*Q" \\ /"

```

Try it online!
> 1 votes

# Answer
## Mathematica, 155 bytes

```
""<>Table[If[i+j<d||i-j>d+1||i+j>d+5&&i-j<d-3&&j<d-1," ",Switch[Mod[i+d+{j,-j},4],{1,3},"/",{3,1},"\\",{1,1},"|",_," "]],{j,(d=2#)+1},{i,4#+1}]~Riffle~"\n"&

```

with `\n` replaced with a newline.

More readable:

```
"" <> Table[
    If[i+j < d || i-j > d+1 ||
      i+j > d+5 && i-j < d-3 && j < d-1, " ",
     Switch[Mod[i+d+{j,-j}, 4], {1, 3}, "/", {3, 1},
      "\\", {1, 1}, "|", _, " "]], {j, (d=2#)+1}, {i, 4#+1}]~
   Riffle~"\n" &

```

Creates an array of characters, indexed by *i* from 1 to 4 *n* \+ 1 horizontally and *j* from 1 to 2 *n* \+ 1 vertically. First, `Switch[Mod[i+d+{j,-j},4],{1,3},"/",{3,1},"\\",{1,1},"|",_," "]` fills in a hexagonal grid:

```
 \ / \ / \ / \ /
  |   |   |   |
 / \ / \ / \ / \
|   |   |   |   |
 \ / \ / \ / \ /
  |   |   |   |
 / \ / \ / \ / \
|   |   |   |   |
 \ / \ / \ / \ /

```

then `If[i+j<d||i-j>d+1||i+j>d+5&&i-j<d-3&&j<d-1," ",...]` replaces this with `" "` outside the unfilled triangle.
> 1 votes

---
Tags: code-golf, ascii-art, geometry, hexagonal-grid
---


# Question
Title: Find the number of subgroups of a finite group
## Definitions

You can skip this part if you already know the definitions of **groups**, **finite groups**, and **subgroups**.

### Groups

In abstract algebra, a *group* is a tuple **(G, ∗)**, where **G** is a set and  is a function **G × G → G** such that the following holds:

* Closure: for all **x, y** in **G**, **x ∗ y** is also in **G** (implied by the fact that  is a function **G × G → G**).
* Associativity: for all **x, y, z** in **G**, **(x ∗ y) ∗ z = x ∗ (y ∗ z)**.
* Identity: there exists an element **e** in **G** such that for all **x** in **G**, **x ∗ e = x = e ∗ x**.
* Inverse: for each **x** in **G**, there exists an element **y** in **G** such that **x ∗ y = e = y ∗ x**, where **e** is the identity element mentioned in the previous bullet point.

### Finite groups

A *finite group* is a group **(G, ∗)** where **G** is finite, i.e. has finitely many elements.

### Subgroups

A *subgroup* **(H, ∗)** of a group **(G, ∗)** is such that **H** is a subset of **G** (not necessarily proper subset) and **(H, ∗)** is also a group (i.e. satisfies the 4 criteria above).

### Examples

Consider the *dihedral group **D3*** **(G, ∗)** where **G = {1, A, B, C, D, E}** and  is defined below (a table like this is called a *Cayley table*):

```
∗ | 1   A   B   C   D   E
--+----------------------
1 | 1   A   B   C   D   E
A | A   B   1   D   E   C
B | B   1   A   E   C   D
C | C   E   D   1   B   A
D | D   C   E   A   1   B
E | E   D   C   B   A   1

```

In this group, the identity is **1**. Also, **A** and **B** are inverses of each other, while **1**, **C**, **D**, and **E** are the inverses of themselves respectively (the inverse of **1** is **1**, the inverse of **C** is **C**, the inverse of **D** is **D**, and the inverse of **E** is **E**).

Now, we can verify that **(H, ∗)** where **H = {1, A, B}** is a subgroup of **(G, ∗)**. For the closure, refer to the table below:

```
∗ | 1   A   B
--+----------
1 | 1   A   B
A | A   B   1
B | B   1   A

```

where all possible pairs of elements in **H** under  give a member in **H**.

The associativity does not require checking, since elements of **H** are elements of **G**.

The identity is **1**. This must be the same with the group identity. Also, the identity in a group must be unique. (Can you prove this?)

For the inverse, check that the inverse of **A** is **B**, which is a member of **H**. The inverse of **B** is **A**, which is also a member of **H**. The inverse of **1** is still itself, which does not require checking.

---

## Task

### Description

Given a finite group **(G, ∗)**, find the number of its subgroups.

### Input

For a group **(G, ∗)**, you will receive a 2D array of size **n × n**, where **n** is the number of elements in **G**. Assume that index `0` is the identity element. The 2D array will represent the multiplication table. For example, for the group above, you will receive the following 2D array:

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

```

For example, you can see that **3 ∗ 1 = 5** because `a[3][1] = 5`, where `a` is the 2D array above.

Notes:

* You can used 1-indexed 2D array.
* The row and the column for the identity can be omitted.
* **You may use other formats as you see fit, but it must be consistent.** (i.e. you may want the last index to be identity instead, etc.)

### Output

A positive number representing the number of subgroups in the group.

For example, for the group above, **(H, ∗)** is a subgroup of **(G, ∗)** whenever **H =**

* **{1}**
* **{1, A, B}**
* **{1, C}**
* **{1, D}**
* **{1, E}**
* **{1, A, B, C, D, E}**

Therefore, there are **6** subgroups, and your output for this example should be `6`.

---

## Hints

You can read the articles that I linked to. Those articles contain theorems about groups and subgroups that might be useful to you.

---

## Scoring

This is . Answer with lowest byte-count wins.

# Answer
> 8 votes
## Mathematica, 62 48 bytes

```
Count[Subsets@First@#,x_/;Union@@#[[x,x]]==x]-1&

```

Pure function expecting a 1-indexed 2D array. `Count`s the number of `Subsets` of the `First` row of the input array that are closed under the group operation. Since this will include the empty set, we subtract `1`. Note that a nonempty subset of a finite group that is closed under the group operation is in fact a subgroup, (and vice versa, by definition).

Strictly speaking I don't check that the subset `x` is closed under the group operation, I restrict the multiplication table to the subset `x` and check that it contains precisely the elements of `x`. Clearly this implies that `x` is closed with respect to the group operation. Conversely, any subgroup `x` will contain `1` and thus `x` will be a subset of the elements appearing in the restricted multiplication table, and since `x` is closed under the group operation, it must equal `x`.

# Answer
> 4 votes
# Haskell, 79 bytes

Basically a port of ngenisis's Mathematica method. (Except I'm using 0-indexed arrays.)

`c` takes a list of lists of `Int`s and returns an integer.

```
c g=sum[1|l<-foldr(\r->([id,(r!!0:)]<*>))[[]]g,and[g!!x!!y`elem`l|x<-l,y<-l]]-1

```

Try it online!

It is assumed that the `Int`s are numbered the same as the rows (outer lists) and columns showing their multiplication. Thus, since 0 is the identity, the first column is the same as the indices of the rows. This allows using the entries of the first column to construct the subsets.

# How it works

* `c` is the main function.
* `g` is the group array as a list of lists.
* `l` is a subset of the elements. The list of subsets is constructed as follows:
    + `foldr(\r->([id,(r!!0:)]<*>))[[]]g` folds a function over the rows of `g`.
    + `r` is a row of `g`, whose first (0th) element is extracted as an element that may be included (`(r!!0:)`) or not (`id`).
    + `<*>` combines the choices for this row with the following ones.
* `and[g!!x!!y`elem`l|x<-l,y<-l]` tests for each pair of elements in `l` whether their multiple is in `l`.
* `sum[1|...]-1` counts the subsets that pass the test, except for one, the empty subset.

# Answer
> 3 votes
# Python 2, ~~297~~ 215 bytes

```
from itertools import*
T=input()
G=T[0]
print sum(all(T[y][x]in g for x,y in product(g,g))*all(any(T[y][x]==G[0]==T[x][y]for y in g)for x in g)*(G[0]in g)for g in chain(*[combinations(G,n)for n in range(len(G)+1)]))

```

**Try it online**

This program works for the example group without `==T[x][y]`, but I'm still pretty sure it's necessary.

Edit: Now assumes that the identity element of **G** is always the first.

---

**Ungolfed:**

```
from itertools import*
T=input()
G=T[0]
def f(x,y):return T[y][x]                                           # function
def C(g):return all(f(x,y)in g for x,y in product(g,g))             # closure
def E(g):return[all(f(x,y)==y for y in g)for x in g]                # identity

a=E(G)
e=any(a)
e=G[a.index(1)]if e else-1                                          # e in G

def I(G):return all(any(f(x,y)==e==f(y,x)for y in G)for x in G)     # inverse

#print e
#print C(G),any(E(G)),I(G)

#for g in chain(*[combinations(G,n)for n in range(len(G)+1)]):      # print all subgroups
#   if C(g)and I(g)and e in g:print g

print sum(C(g)*I(g)*(e in g)for g in chain(*[combinations(G,n)for n in range(len(G)+1)]))

```

Ungolfed TIO

Negative group elements can be supported at no cost by changing `-1` to `''`.

# Answer
> 3 votes
# Jelly, ~~17~~ 16 bytes

1 byte thanks to ETHproductions (`LR → J`)

```
ị³Z⁸ịFḟ
JŒPÇÐḟL’

JŒPÇÐḟL’  main link. one argument (2D array)
J         [1,2,3,...,length of argument]
 ŒP       power set of ^
    Ðḟ    throw away elements that pass the test...
   Ç      in the helper link
      L   length (number of elements that do not pass)
       ’  decrement (the empty set is still closed under
          multiplication, but it is not a subgroup, as
          the identity element does not exist.)

ị³Z⁸ịFḟ   helper link. one argument (1D indexing array)
ị³        elements at required indices of program input (2D array)
  Z       transpose
   ⁸ị     elements at required indices of ^
     F    flatten
      ḟ   remove elements of ^ that are in the argument given
          if the set is closed under multiplication, this will
          result in an empty set, which is considered falsey.

```

Try it online! (1-indexed)

---
Tags: code-golf, math, abstract-algebra
---


title: Turn me 22.5 with a rose

text:
# Question
Title: Turn me 22.5 with a rose
Given a string that is one of the directions on a 16-point compass rose

output the two directions that are immediately adjacent to the input direction, in clockwise order.

Specifically, you need to handle these (and only these) input/output pairs:

```
Input  Output
N      NNW NNE
NNE    N NE
NE     NNE ENE
ENE    NE E
E      ENE ESE
ESE    E SE
SE     ESE SSE
SSE    SE S
S      SSE SSW
SSW    S SW
SW     SSW WSW
WSW    SW W
W      WSW WNW
WNW    W NW
NW     WNW NNW
NNW    NW N

```

The output may be a string with some delimiter (not nothing) between the directions or a two-element list. The direction immediately counterclockwise to the input must appear first. You may use lowercase letters for the directions instead of uppercase but keep all input and output in one case or the other.

For example, for input `N` (or `n` if you're using lowercase) some valid outputs are:

```
NNW NNE
NNW-NNE
["NNW", "NNE"]
nnw-nne (if using lowercase)

```

Some invalid outputs are:

```
NNWNNE
NNE NNW
nnwNNE
NNw NNe

```

**The shortest code in bytes wins.**

# Answer
> 12 votes
# Jelly, ~~37~~ 34 bytes

```
“¢ ¬9£Hæz¥{çb¤S®!‘ṃ€“¡&¦»
¢iµ’,‘ị¢

```

Try it online!

Takes lowercase input.

*-2 thanks to Jonathan Allan.*
*-1 since it turns out this is valid as a function :)*

Thanks to Jonathan Allan (and Dennis), now you can remove the . Unfortunately, that would be non-competing here.

**Detailed algorithm explanation**:

We usually start explaining from the bottom (main) link, going down, but here I feel like it's more appropriate to explain from the top.

First, we simply load up the list `[1, 32, 7, 57, 2, 67, 17, 92, 3, 94, 19, 119, 4, 109, 9, 34]`. This looks like random numbers huh? Well, this is actually a list of base-5-compressed numbers, so we base-5-decompress it. Now it looks like `[[1], [1, 1, 2], [1, 2], [2, 1, 2], [2], [2, 3, 2], [3, 2], [3, 3, 2], [3], [3, 3, 4], [3, 4], [4, 3, 4], [4], [4, 1, 4], [1, 4], [1, 1, 4]]`. Still random-looking stuff, but this is actually an `NESW`-mapped list of the sixteen coordinates, so we're not far away from completing the list (Jelly is 1-indexed). Doing the final mapping, we get `[['N'], ['N', 'N', 'E'], ['N', 'E'], ['E', 'N', 'E'], ['E'], ['E', 'S', 'E'], ['S', 'E'], ['S', 'S', 'E'], ['S'], ['S', 'S', 'W'], ['S', 'W'], ['W', 'S', 'W'], ['W'], ['W', 'N', 'W'], ['N', 'W'], ['N', 'N', 'W']]`, which is the complete list we want (Jelly strings are in the form `[char1, char2, char3, ...]`.)

Since we've now built the coordinate list, we work with it. The main link comes into play. First, we load up the list we've built, and then take the index that the input (as command-line argument) coordinate resides in. Then, we pair its predecessor and its successor into a list, and we use them as modular indices into the same list of coordinates to take the coordinate to the left and right of the input respectively. You'd now think we're finally done, but there's in fact one more thing, the separator. This is valid as a function, since 1) You can call it using `<integer>Ŀ` 2) You're allowed to define other functions as well (like importing modules). Now, we are done. As a full program, this doesn't have a separator, but that's OK, since it works as a function.

**Link-by-link code explanation**:

```
¢iµ’,‘ị¢K Main link. Arguments: z = cmd0
¢         Run the helper link niladically (i.e. load the coordinate list).
 i        Find the index of z in the list.
  µ       Start a new monadic chain. Arguments: z = list_index.
   ’      Decrement z.
     ‘    Increment z.
    ,     Pair x and y into [x, y].
       ¢  Run the helper link niladically.
      ị   Take the elements of y at the indices in x.

“¢ ¬9£Hæz¥{çb¤S®!‘ṃ€“¡&¦» Helper link. Arguments: [1, 32, 7, 57, 2, 67, 17, 92, 3, 94, 19, 119, 4, 109, 9, 34]
“¢ ¬9£Hæz¥{çb¤S®!‘        Generate the integer list (the argument).
                    “¡&¦» Literal "newsy".
                  ṃ€      Base-length(y)-decompress every integer in x, then index into y.

```

# Answer
> 11 votes
# Mathematica, ~~118~~ 112 bytes

*Thanks to Martin Ender for saving 6 bytes!*

```
r=StringSplit@"N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW N NNE";<|Array[r[[#]]->r[[#+{-1,1}]]&,16,2]|>

```

Unnamed function (an association, really) that takes a string as input and returns an ordered pair of strings. Basically just hardcodes the answer.

# Answer
> 8 votes
# Python 2, ~~116~~ ~~115~~ 103 bytes

*-12 bytes thanks to Neil*

```
d='N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW'.split()
n=d.index(input())
print d[n-1],d[n-15]

```

Try it Online!

# Answer
> 8 votes
# JavaScript ES6, ~~106~~ 102 bytes

```
p=>[(a=`N|NNE|NE|ENE|E|ESE|SE|SSE|S|SSW|SW|WSW|W|WNW|NW|NNW`.split`|`)[i=a.indexOf(p)-1&15],a[i+2&15]]

```

### Try it online!

```
const f = p=>[(a=`N|NNE|NE|ENE|E|ESE|SE|SSE|S|SSW|SW|WSW|W|WNW|NW|NNW`.split`|`)[i=a.indexOf(p)-1&15],a[i+2&15]]

console.log(f('N'))
console.log(f('NNE'))
console.log(f('ENE'))
console.log(f('E'))
console.log(f('ESE'))
console.log(f('SE'))
console.log(f('SSE'))
console.log(f('S'))
console.log(f('SSW'))
console.log(f('SW'))
console.log(f('WSW'))
console.log(f('W'))
console.log(f('WNW'))
console.log(f('NW'))
console.log(f('NNW'))
```

# Answer
> 7 votes
# Javascript - ~~234~~ ~~154~~ ~~156~~ ~~152~~ ~~120~~ ~~106~~ 102 bytes

Only my second time doing code golf!!

Latest Revision:

Thank you to @fəˈnɛtɪk for this neat variable trick!

```
s=>[(a=`NNW N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW`.split` `)[n=a.indexOf(s)-1&15],a[n+2&15]]

```

Before That: Okay so latest revision: Input is a string and output is a string which is in the rules, so I made it into a function, and with reductions I have gone even smaller (also function is anonymous, which now means mine has somehow meshed into the other js answer oops! He (powelles) had it first!!):

```
(s,a=`NNW N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW`.split` `,n=a.indexOf(s))=>[a[n-1&15],a[n+1&15]]

```

Can be used by:

```
f=(s,a=`NNW N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW`.split` `,n=a.indexOf(s))=>[a[n-1&15],a[n+1&15]]
alert(f(prompt()))

```

Remade (not function) with Output - 120:

```
a="NNW N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW".split(' ');n=a.indexOf(prompt());alert(a[n-1&15]+' '+a[n+1&15]);

```
* Note that I made an error originally, having it equal a.length instead of a.length-1 for the first index. Thanks @Neil for pointing out that it didn't work for NNW.
* Note 2: Thank you to @Neil and @ETHProductions for helping me shorten the code!

Originial:

```
a="NNWN  NNENE ENEE  ESESE SSES  SSWSW WSWW  WNWNW ";l=prompt("","");n=l.length<3?l.length<2?l+'  ':l+' ':l;f=a.indexOf(n);i=f-3;j=f+3;i=i<0?a.length+--i:i;j=j+3>=a.length?j-a.length:j;alert(a.substring(i,i+3)+' '+a.substring(j,j+3));

```

# Answer
> 7 votes
# 05AB1E, ~~44~~ 43 bytes (Thanks to Adnan)

```
"ESNW4"•2ßU^]>Þ‡¾“¾&é{½‡•5BSè4¡©skD<®ès>®è)

```

Try it online!

```
"ESNW4"•2ßU^]>Þ‡¾“¾&é{½‡•5BSè # Push N4NNE4NE4ENE4E4ESE4SE4SSE4S4SSW4SW4WSW4W4WNW4NW4NNW
4¡©            # Split on 4's and store.
   sk          # Index of input in direction array.
     D<®è      # Element before index of input.
         s>®è  # Element after index of input.
             ) # Wrap two element to array.

```

Exmaple output:

```
N => [NNW,NNE]

```

---

Version that pushes `N0NNE0NE0ENE0E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW` instead:

```
•17¿$Mn]6VAÆ—Dªd—•5B4LJ"NSWE"‡0¡©skD<®ès>®è)

```

Is also 44-bytes, there was 0 reason for my refactor and there is 0 reason for splitting on the 4's.

---

# Answer
> 3 votes
# Jelly,  ~~40~~ 38 bytes

```
“NSWE”“dḍ.ƈ€ḶƘfƥ’ṃṁ
“¢)`)’ḃ3RÇṙi¥µṖṪ,Ḣ

```

**Try it online!** (added the footer to show the output is a list of two items) ...or see all cases.

(I'm not quite sure why `1323DRẋ4` in place of `“¢)`)’ḃ3R` doesn't work at the moment.)

### How?

```
“NSWE”“dḍ.ƈ€ḶƘfƥ’ṃṁ - Link 1, rose list helper: shape array
“NSWE”              - "NSWE"
      “dḍ.ƈ€ḶƘfƥ’   - base 250 number: 1554210846733274963415
                 ṃ  - base decompress: "NNNENEENEEESESESSESSSWSWWSWWWNWNWNNW"
                  ṁ - mould like shape array

“¢)`)’ḃ3RÇṙi¥µṖṪ,Ḣ - Main link: direction string
“¢)`)’             - base 250 number: 33899292
      ḃ3           - to base 3: [1,3,2,3,1,3,2,3,1,3,2,3,1,3,2,3]
        R          - range (vectorises) [[1],[1,2,3],[1,2],[1,2,3],[1],[1,2,3],[1,2],[1,2,3],[1],[1,2,3],[1,2],[1,2,3],[1],[1,2,3],[1,2],[1,2,3]]
         Ç         - call the last link (1) as a monad: ["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"]
            ¥      - last two links as a dyad
          ṙ        -     rotate the list by:
           i       -         index of the direction string in the list
             µ     - monadic chain separation (call the rotated list x)
              Ṗ    - pop (x[:-1]) (removes the direction string)
               Ṫ   - tail that (i.e. x[-2])
                 Ḣ - head x (i.e. x[0])
                ,  - pair

```

# Answer
> 3 votes
## Batch, 196 bytes

```
@set s=N
@if %1==N echo NNW
@for %%r in (NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW)do @call:c %1 %%r
@if %1==NNW echo N
@exit/b
:c
@if %1==%2 echo %s%
@if %1==%s% echo %2
@set s=%2

```

Loops through each pair of compass points, printing one when the other matches. For example, for a parameter of `ENE`, when the loop reaches `ENE`, the variable `s` contains `NE` which is printed, then when the loop advances to `E`, the variable `s` contains `ENE` and so `E` is printed. One pair then needs to be special-cased to avoid the compass points from being printed in the wrong order.

# Answer
> 3 votes
# Haskell, ~~100~~ 99 bytes

```
s=words"N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW"++s
(a:b:c:r)#x|x==b=(a,c)|1<3=r#x
(s#)

```

Try it online! Calling `(s#) "N"` returns `("NNW","NNE")`.

`s` is an infinite repetition of the list of directions, thus we don't have to add an extra `N` and `NNE` like some of the other answers to correctly handle the edges of the list.

Thanks to @nimi for saving one byte!

# Answer
> 2 votes
# SOGL, 33 bytes

```
≠┐πΜ]ρ½d⁹V¹-┐*╔╤¹Ψæ;¶‘θ,W:AHwOaIw

```

The first part `≠┐πΜ]ρ½d⁹V¹-┐*╔╤¹Ψæ;¶‘` is a compressed string that is

```
N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW

```

compressed with a custom dictionary with  `ENSW`

The rest of the program:

```
...‘θ,W:AHwOaIw  example input: NNW
...‘             push the compressed string        ["N NNE NE ... NNW"]
    θ            split on spaces                   [["N","NNE",...,"NNW"]]
     ,W          get the index of input            [["N","NNE",...,"NNW"], 16]
       :A        save the index on variable A      [["N","NNE",...,"NNW"], 16]
         H       decrease [the index]              [["N","NNE",...,"NNW"], 15]
          wO     output that'th item of the array  [["N","NNE",...,"NNW"]]
            a    load variable A                   [["N","NNE",...,"NNW"], 16]
             I   increase [the index]              [["N","NNE",...,"NNW"], 17]
              w  get that item in the array        [["N","NNE",...,"NNW"], "N"]

```

# Answer
> 2 votes
# PHP, 122 bytes

```
preg_match("/([^ ]+ )$argv[1] ([^ ]+)/",'N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW N NNE',$m);
echo $m[1].$m[2];

```

# Answer
> 1 votes
# PHP, 115 Bytes

```
for($r=explode(_,($w=N_NNE_NE_ENE_E_ESE_SE_SSE_).strtr($w,SWNE,NESW).$w);$r[++$i]!=$argn;);echo$r[$i-1]._.$r[$i+1];

```

-2 Bytes using the deprecated function `split` instead of `explode`

## PHP, 128 Bytes

```
for($i=2;$i--;print$i?end($e)._:$e[2])$e=explode(_,strstr(($w=N_NNE_NE_ENE_E_ESE_SE_SSE_).strtr($w,SWNE,NESW).$w,_.$argn._,$i));

```

## PHP, 134 Bytes

```
echo($r=explode(_,N_NNE_NE_ENE_E_ESE_SE_SSE_S_SSW_SW_WSW_W_WNW_NW_NNW))[($k=array_search($argn,$r))-1<0?15:$k-1]._.$r[$k+1>15?0:$k+1];

```

# Answer
> 1 votes
# Ruby - 94 Bytes

A riff on Blue Okiris's answer, just to take advantage of some nice Ruby shorthand (the `%w[]` syntax and `p` specifically):

```
->(s,d=%w[N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW],n=d.index(s)){p d[n-1],d[n-15]}

```

# Answer
> 1 votes
# Japt, 66 52 bytes

*Saved 14 bytes thanks to @ETHproductions*

```
V=`ã@JaÀTeaÀÄsÁÁss°s°ws°°wn°n°nnw`qa [J1]£VgX+VaU

```

Try it online!

### Explanation:

```
V=(`...`qa) [J1]£Vg(X+VaU)
V=(       )                // Set V to:
   `...`                   //   "nanneaneaeneaeaeseaseasseasasswaswawswawawnwanwannw" (de-)compressed
        qa                 //    Split on "a", creating [n...nnw]
            [J1]           // [-1,1]
                £          // Iterate through ^, X becomes the iterative item
                 Vg(     ) //   V.Item at index:
                    X+VaU  //     X + V.indexOf(input)

```

# Answer
> 1 votes
# PHP, 110 109 bytes

Saved 1 byte thanks to Jörg Hülsermann.

```
echo@preg_filter("/.*?(\w+) $argn( \w+).*/",'$1$2',($s='N NNE NE ENE E ESE SE SSE ').strtr($s,NESW,SWNE).$s);

```

# Answer
> 1 votes
# CJam, 41

```
"NeSWN"2ew{_1<\_La*\$f+~}%:eu_ra#(m<2%2<p

```

Try it online

# Answer
> 0 votes
# **Python 3 - ~~112~~ 107 bytes**

I based this off of my Javascript answer:

Remade:

```
lambda i,s="N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW".split():[s[s.index(i)-1],s[s.index(i)-15]]

```

Use as say

```
f = lambda i,s="N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW".split():[s[s.index(i)-1],s[s.index(i)-15]]
print(f(input()));

```

Original:

```
lambda i,s="N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW".split():[s[s.index(i)-1&15],s[s.index(i)+1&15]]

```

# Answer
> 0 votes
# MATL, 43 bytes

```
';evl(Z?&fWElf`gvhM'F' NESW'ZaYbtjY=fFTEq+)

```

Try it online!

### Explanation

```
';evl(Z?&fWElf`gvhM' % Push this string
F                    % Push false
' NESW'              % Push this string
Za                   % Base conversion. This decompresses the first string from alphabet
                     % given by all printable ASCII except single quote to the alphabet
                     % ' NESW'. The result is the following string, which is pushed:
                     % 'N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW'
Yb                   % Split at spaces. Gives a cell array of strings
t                    % Duplicate
j                    % Input string
Y=                   % String comparison. Gives an array containing true at the index
                     % of the matching string
f                    % Find: index of the entry that equals true
FTEq                 % Push [-1 1] (obtained as [false true], times 2, minus 1)
+                    % Add, element-wise
)                    % Index modularly into the cell array of strings
                     % Implicitly display. Each cell is displayed on a different line

```

# Answer
> 0 votes
## c, ~~222~~ ~~216~~ 211 bytes

```
main(c,v)char**v;{char r[]="NXNNEXNEXENEXEXESEXSEXSSEXSXSSWXSWXWSWXWXWNWXNWXNNWX",*p=r,*s=r,*a[16],i=0,n;for(;*p++;)*p==88?*p=0,n=strcmp(a[i++]=s,v[1])?n:i-1,s=++p:0;printf("%s %s\n",a[n?n-1:15],a[n<15?n+1:0]);}

```

Try it online

# Answer
> 0 votes
# Javascript (ES6), 189 bytes

```
d="N.NNW NNE.NNE.N NE.NE.NNE ENE.ENE.NE E.E.ENE ESE.ESE.E SE.SE.ESE SSE.SSE.SE S.S.SSE SSW.SSW.S SW.SW.SSW WSW.WSW.SW W.W.WSW WNW.WNW.W NW.NW.WNW NNW.NNW.NW N".split`.`,f=>d[d.indexOf(f)+1]

```

Just takes the input, looks it up, and returns it.

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

Expects a string in uppercase such as `"ENE"`. Returns a comma separated string such as `"NE,E"`.

```
s=>/\D+,\D+/.exec('NNW0N0NNE0NE0ENE0E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW0N'.split(0+s+0))[0]

```

### How it works

The expression `0+s+0` is coerced to a string when `split()` is called. For instance, if the input is `"ENE"`, the string will be split on `"0ENE0"`:

```
"NNW0N0NNE0NE0ENE0E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW0N"
             ^^^^^

```

This leads to the following array:

```
[ "NNW0N0NNE0NE", "E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW0N" ]

```

Again, this array is coerced to a string when `exec()` is called. So, the regular expression is actually applied on:

```
"NNW0N0NNE0NE,E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW0N"

```

We look for consecutive non-numeric characters (`\D+`) followed by a comma, followed by consecutive non-numeric characters. This returns the array `[ "NE,E" ]`. We could arguably stop there and return just that. But the challenge is asking for either a delimited string or a two-element array. So, we extract the string with `[0]`.

### Demo

```
let f =

s=>/\D+,\D+/.exec('NNW0N0NNE0NE0ENE0E0ESE0SE0SSE0S0SSW0SW0WSW0W0WNW0NW0NNW0N'.split(0+s+0))[0]

;
["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"]
.map(
  s => console.log(s, '=>', f(s))
)
```

# Answer
> 0 votes
# Pyth, 39 bytes:

```
.rL]z_Bms@L"ESWN"jCd5"\"❤m❤w❤^❤\❤C❤9❤ ❤

```

where  represents unprintable letters.

Try it online!

Hexdump:

```
0000000: 2e 72 4c 5d 51 5f 42 6d 73 40 4c 22 45 53 57 4e .rL]Q_Bms@L"ESWN
0000010: 22 6a 43 64 35 22 5c 22 09 6d 04 77 13 5e 03 5c "jCd5"\".m.w.^.\
0000020: 11 43 02 39 07 20 01                            .C.9. .

```

---
Tags: code-golf, string, kolmogorov-complexity
---


title: Count occurences of a set in a list

text:
# Question
Title: Count occurences of a set in a list
Given a non-empty set of strings and a list of strings, find out how many times the set occurs in the list, i.e. how many times you could create the set with items from the list. Every element from the list can only be used once.

> Hint: a set is an unordered list of unique items.

Default input/output rules apply.

No external libraries allowed. Compiler/Interpreter standard libs are okay. This is code golf, so shortest solution counts.

---

Test cases:

```
["apple", "banana"], ["apple", "pear", "apple", "banana", "banana"] => 2

["apple", "banana"], ["apple", "pear", "apple", "banana", "apple"] => 1

["apple", "banana", "pear"], ["apple", "banana", "kiwi", "apple"] => 0

["coconut"], [] => 0

```

---

**EDIT:** removed a sentence stating that the input params are defined in local scope. This contradicts the default IO rules linked above.

# Answer
> 12 votes
# Python, 30 bytes

```
lambda s,l:min(map(l.count,s))

```

Try it online!

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

```
ċ@€Ṃ

```

Try it online!

The first argument of the program is the set, and the second argument is the list.

**Explanation**

```
ċ@€Ṃ
ċ@   -- Create a link which finds the number of occurrences of
          its left argument in its right argument (the list)
  €  -- Map this link over each element in the first argument
          of the program (the set)
   Ṃ -- Minimum value of this.

```

*-1 byte thanks to @ETHproductions*

*-1 byte again thanks to @ETHproductions*

# Answer
> 6 votes
# Jelly, 4 bytes

```
⁼þSṂ

```

**Try it online!**

### How?

```
⁼þSṂ - Main link: list theSet, list theList
 þ   - outer product using the dyadic operation:
⁼    -     is equal? (non-vectorising)
  S  - sum (vectorises) (yields the number of times each element of theSet appears in theList)
   Ṃ - minimum (can only make the minimum as a multiple)

```

# Answer
> 6 votes
## JavaScript (ES6), 56 bytes

```
f=(n,h)=>Math.min(...n.map(c=>h.filter($=>$==c).length))

```

Try it online

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

```
(s,l)=>l.map(e=>m[s.indexOf(e)]++,m=s.map(e=>0))&&Math.min(...m)

```

Assumes both `s` and `l` are arrays of objects. Uses JavaScript strict equality for comparisons, so for instance `[] === []` is false.

# Answer
> 4 votes
## Haskell, ~~37~~ 34 bytes

Thanks to @Laikoni for shaving off three bytes.

```
s#l=minimum[sum[1|y<-l,y==x]|x<-s]

```

Call with `(set::[a]) # (list::[a])` where `a` is any type deriving `Eq`.

# Answer
> 3 votes
# CJam, 11 bytes

```
q~f{\e=}:e<

```

Try it online!

**Explanation**

```
q~           e# Read and eval the input
  f{\e=}     e# Map each item in the set to the number of times it appears in the list
        :e<  e# Find the minimum of the resulting list

```

# Answer
> 3 votes
# Mathematica, 24 bytes

```
Min[#/.Rule@@@Tally@#2]&

```

Pure function taking two lists as arguments in the suggested order and returning a nonnegative integer. `Tally` counts how many occurrences of every symbol occur in the input list, and `#/.Rule@@@` converts each element of the input set into the corresponding number of occurrences.

# Answer
> 3 votes
# T-SQL, 62 ~~59~~ bytes

Previous version didn't work for sets with no matches

```
select top 1(select count(*)from l where l=s)from s order by 1

```

With s and l as tables and columns named the same as the table

```
select top 1         -- return only the first result
    (select count(*) -- count of rows
     from l          -- from table l
     where l=s)      -- for each l equal
from s               -- to each from s
order by 1           -- sort by count ascending

```

# Answer
> 3 votes
## Swift, 39 bytes

```
s.map{w in l.filter{$0==w}.count}.min()

```

explanation:

`s.map{}` goes through each word in s and will produce an array of counts

`w in` names the mapped word for use in the next filter

`l.filter{}` aplies a filter to the l array

`$0==w` is the filter condition matching word w

`.count` gives the number of elements of l that met the condition

`.min()` returns the lowest count in the mapped result

# Answer
> 3 votes
# APL (Dyalog), 9 bytes

```
⌊/+/⎕∘.≡⎕

```

Try it online!

get evaluated input (list of strings)

`⎕∘.≡` get evaluated input (non-empty set of strings) and create equivalency table

`+/` add across

`⌊/` minimum across

# Answer
> 2 votes
# C++, ~~203~~ 201 bytes

*Thanks to @Quentin for saving two bytes!*

```
#import<vector>
#import<string>
using T=std::vector<std::string>;
int f(T S,T L){for(int j,b,i=0;;++i)for(auto s:S){for(b=j=0;j<L.size();++j)if(L[j]==s){b=1;L.erase(begin(L)+j);break;}if(!b)return i;}}

```

Try it online!

# Answer
> 2 votes
# Perl 6,  ~~37~~  18 bytes

## 37

```
{+(($_=@^a⊍@^b)≽@a)&&.values.min}

```

Try it

Expanded:

```
{
  +( # turn into a 0 if False

    (
      $_ =        # store into $_ the result of
        @^a ⊍ @^b # use the baggy multiplication operator
    ) ≽ @a        # is that the baggy superset of the set
  )

  &&          # if that is True

  .values.min # get the minimum value from the Bag in $_
}

```

See Sets, Bags, and Mixes for more information.

---

## 18

```
{@^b.Bag{@^a}.min}

```

Try it

Explanation:

`@^b.Bag` create a Bag from the values
`{@^a}` key into that Bag (returns a list of counts)
`.min` get the minimum value of the resulting list

---

# Answer
> 2 votes
# Axiom, 42 bytes

```
f(a,b)==reduce(min,[count(x,b)for x in a])

```

test code and results

```
(28) -> f(["1","2"], ["1", "2", "1", "1", "7"])
   (28)  1
                                                    Type: PositiveInteger
(29) -> f(["apple","banana"],["apple","pear","apple","banana","banana"])
   (29)  2
                                                    Type: PositiveInteger
(30) -> f(["apple","banana"],["apple","pear","apple","banana","apple"])
   (30)  1
                                                    Type: PositiveInteger
(31) -> f(["apple","banana","pear"],["apple","banana","kiwi","apple"])
   (31)  0

```

# Answer
> 1 votes
# PHP, 74 Bytes

```
<?foreach($_GET[0]as$v)$t[]=array_count_values($_GET[1])[$v];echo+min($t);

```

Testcases

# PHP, 108 Bytes

```
<?[$x,$y]=$_GET;echo($a=array_intersect)($x,$y)==$x?min(($a._key)(array_count_values($y),array_flip($x))):0;

```

Testcases

# Answer
> 1 votes
# C#, 36 bytes

```
f=(n,h)=>n.Min(c=>h.Count(x=>x==c));

```

`n` and `h` are `string[]` and the output is an `int`.

Try it online!

This answer is inspire by @ovs and @Alberto Rivera's logic. Thank you!

# Answer
> 1 votes
# Java, 135 bytes

```
int f(List<String> s,List<String> l){int n=0,i=0;while(i<s.size()){if(!l.remove(s.get(i++)))break;if(i==s.size()){n++;i=0;}};return n;}

```

This is my first code golf challenge and answer, so not sure about the format. Does it need to be a full compiling program? Do I need to define the parameters? Suggestions appreciated.

**EDIT**: wrapped code in a function. Thanks @Steadybox

# Answer
> 1 votes
# Pyth, 5 bytes

```
hS/LF

```

Takes the list first and the set second. Test suite.

Explanation:

```
    F  Expand the input into l and s (not literally,
                  since those are function names in Pyth, but...)
   L   for d in s:
  /        Count instances of d in l
   L   Package all the results as a list
 S     Sort the results smallest-first
h      grab the smallest element

```

# Answer
> 1 votes
# 05AB1E, 7 bytes

```
v²y¢})W

```

Try it online!

```
v   }   # For each item in the first list...
 ²y¢    # Count the occurances in the second list.
     )W # Take the minimum occurrence count, return.

```

# Answer
> 1 votes
# Java, 114 Bytes

```
<T>int a(Set<T>b,List<T>c){int m=2e32;b.stream().map(i->{int j=java.util.Collections.frequency(c,i);m=j<m?j:m;});return m;}

```

Tio coming soon

**Explanation**

* creates local variable m.
* maps the set to a stream.
* for each element, if the number of occurances of the element in the list is less than m, m is set to that value.
* returns m, which is the number of complete versions of the set

# Answer
> 0 votes
## R, ~~61~~ ~~57~~ 44 bytes

```
print(min(sapply(s,function(x)sum(l%in%x))))

```

~~Anonymous function.~~ Apparently you don't have to define a function for this challenge. *Saved 13 bytes thanks to count.*

Explanation:

`sum(l%in%x))` returns the number of times a string in `s` is found in `l`.

`lapply(s,function(x))` applies that to each string in `s` separately and returns a list of sums.

`min()` returns the smallest from that list.

# Answer
> 0 votes
**R 54 Bytes**

```
f<-function(s,l) min(table(factor(l[l%in%s],levels=s)))

```

Explanation: creating a table of the counts of only the values in the list that also appear in the sublist.

I then turn the variable into a factor in order to generate zeros if a value that appears in the sublist does not appear in the list. Finally, I take the minimum of the counts.

# Answer
> 0 votes
# JavaScript (ES6), 59 bytes

```
a=>b=>a.reduce((x,y)=>(l=b.filter(s=>s==y).length)>x?x:l)|0

```

---

## Try it

```
f=

a=>b=>a.reduce((x,y)=>(l=b.filter(s=>s==y).length)>x?x:l)|0

console.log(f(["apple","banana"])(["apple","pear","apple","banana","banana"]))
console.log(f(["apple","banana"])(["apple", "pear", "apple", "banana", "apple"]))
console.log(f(["apple","banana","pear"])(["apple","banana","kiwi","apple"]))
console.log(f(["coconut"])([]))
```

---
Tags: code-golf, set-partitions
---


title: Brainflak Multiplication Metagolf

text:
# Question
Title: Brainflak Multiplication Metagolf
> *This question is the first of several Brain-flak Birthday challenges designed to celebrate Brain-Flak's first Birthday! You can find more information about Brain-Flak's Birthday here*

Last summer we had the Brain-flak Integer Metagolf, and the answers it generated have been very useful to the Brain-Flak community since. The main thing that makes the Integer Metagolf so efficient is a technique called Multiplication hardcoding.

In Brain-Flak runtime multiplication is extremely expensive. The shortest known multiplication snippet is:

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

```

*Discovered by Megatom*

However there is a very simple way to create compile time multiplication. For example the following code will multiply by 5:

```
 (({})({})({})({}){})

```

Try it online!

This works because consecutive expressions are added together. Each `({})` does nothing to the stack (`{}` pops and `(..)` pushes it right back) and evaluates to whatever is on top of the stack. All these expressions together sum up to five times whatever was on the top of the stack.

For any `n` the following string expression will make a snippet that will multiply the top of the stack by `n`:

```
"("+"({})"*(n-1)+"{})"

```

This works by making `n` expressions that all evaluate to the top of the stack. The first `n-1` don't actually change anything and the last one removes the top of the stack before the push.

For composite numbers you can chain multiple smaller expressions together to save bytes. For example you can multiply by 25 by multiplying by 5 twice:

```
(({})({})({})({}){})(({})({})({})({}){})

```

This is pretty simple, and for some numbers it works pretty well however there are better ways to do this. For example one method I came up with uses the binary representation of the number. (Here is a python implementation) This new method is much more effective than the simple string expression shown earlier, but its not the end, there are all sorts of interesting ways to hardcode multiplication and probably a ton that no one has yet discovered.

So I think it is time to see how good we can get.

## Brief Overview of Brain-Flak

Here is a description of everything you will need to know about Brain-Flak for this challenge.

Brain-Flak has "nilads" and "monads". Nilads are parentheses that have nothing inside of them. Each nilad does a thing and returns a value. For this challenge the two nilads we are concerned with are `{}` and `<>`. `{}` pops the top of the active stack and returns its value. `<>` switches the active stack and the in active stack, so that the active stack becomes inactive and the inactive stack becomes active, it returns zero.

Monads are parentheses with stuff inside them. They take a single argument, the sum of everything inside them, sometimes perform an action, and then return a value. The three of these we are concerned with are `(...)`, `<...>` and `[...]`. The most important monad for this challenge `(...)` takes the value of the inside and pushes it to the active stack. It then returns the argument. `<...>` and `[...]` are both "inert" monads, that is they do not perform any action but rather modify the value they are passed. `<...>` always returns zero regardless of the argument passed. Meanwhile `[...]` always returns the argument times `-1`.

---

### Sample programs with explanation

If you have never programmed in Brain-Flak it might be a good idea to look at some example programs using the operations described

```
({}{})

```

This adds the top two numbers on the stack. Each `{}` pops a value off of the stack and `(...)` pushes their sum back.

```
({}[{}])

```

Similarly this subtracts the second item on the stack from the first. Like before each `{}` pops a value but the `[..]` around the second one causes it to be added. Once again the `(...)` pushes the sum.

```
({}<{}>)

```

This removes the second value on the stack keeping the top value intact. It works just like the last two except the second value is silenced by the `<...>` so the push only pushes the first value back.

```
(({}))

```

This makes a second copy of the value on the top of the stack. It does this by popping the top of the stack with `{}` getting its value, the first `(..)` then pushes it back evaluating to its value. The second `(...)` takes the value returned by the first and pushes that to the stack as well. creating a second copy.

## Task

Given an integer `n` create a stack-clean Brain-Flak snippet that multiplies the top of the current stack by `n`.

You are permitted to use the following Brain-Flak operations

```
(...) -> Push Monad, Pushes the result of its contents
<...> -> Zero Monad, Returns zero
[...] -> Negative Monad, Returns the opposite of its contents result
{}    -> Pop nilad, Pops the TOS and returns its value
<>    -> Switch nilad, Switches the active and inactive stack

```

The other operations are banned for the purpose of the challenge.

## Scoring

Your score will be the cumulative lengths of all the programs from `n=2` to `n=10000`. Be sure to include a link to the output of your program for verification.

# Answer
> 2 votes
# Ruby, 669856

```
$answers = Hash.new{|hash,n|
  valid = []
  2.upto(n**0.5){|i|
    valid.push("("+hash[n/i]+")"+"({})"*(i-2)+"{}") if n%i == 0
  }
  valid.push("({})"+hash[n-1])
  (hash[n] = valid.min_by{|s| s.length})
}
$answers[1] = "{}"

def full_answer n
  "("+$answers[n]+")"
end

```

This is a quick baseline answer. First 1000 min-programs found here. (I tried posting all of them, but that overloaded the max pastebin size.) I may add a code explanation later.

Examples:

```
360:    ((((((({})(({}){}){})({}){})({}){}){}){}){})
4608:   (((((((((((({})({}){})({}){}){}){}){}){}){}){}){}){}){})
9991:   (({})((({})(((((((({})((({})({}){}){}){}){}){}){}){}){}){}){})({}){}){})

```

---
Tags: metagolf, brain-flak
---


title: Cheapo Enigma machine (Robbers)

text:
# Question
Title: Cheapo Enigma machine (Robbers)
For cops' post, Cheapo Enigma machine (Cops)

A robber's submission consists of a program/function that accepts the output of a cop's code and returns the input for all the outputs provided by that cop's code. (In other words, you must write the inverse function)

You cannot use built-ins that have the sole purpose of hashing or encryption.

# Input/Output format

8 bits (0 or 1), or a base-10 integer in range 1-256, 0-255 or -128 to 127. Can use standard I/O or file I/O. Function can also return a value as output. Input and output must belong to the same range (as in, binary, 1-256, 0-255 or -128 to 127), which must also be the same range as that used by the cop.

# Scoring

Ratio of the cop's byte count to your byte count. Highest score wins.

You can submit a robber attempt against your own cop code for reference. (Of course this code isn't eligible for winning)

# Notification

Please edit the corresponding cop's answer to include your new byte count and the corresponding ratio.

# Answer
> 3 votes
## JavaScript by Christoph, 8/25

```
f=(y,x=0)=>y?f(y/2,x^y):x

```

(range 0-255)

Sadly, `f=(y,x)=>y?f(y/2,x^y):x` works for all values except `0`.

### Technical note

We use `y/2` rather than `y>>1` to save a byte. This is abusing the fact that any value of `y` will eventually be rounded to `0` because of arithmetic underflow.

# Answer
> 2 votes
## JavaScript by fəˈnɛtɪk, 13/19

```
x=>((514>>x%2)-x)/2

```

(range 1-256)

# Answer
> 2 votes
# C, by Dave, 64/~~95~~ ~~92~~ 85

```
b,i,e,t[256];r(x){for(;!b;++i,b=e==x)for(srand(i&&e);t[e=rand()%256]++;);return i-1;}

```

Try it here!

# C, shorter version, 64/~~89~~ 71

```
i,e,t[256];r(x){for(srand(1);t[e=rand()%256]++||++i,e!=x;);return i-1;}

```

This one is more implementation specific, but works on TIO. Same length as the PHP solution, I wasn't able to get it any shorter than this.

Try it here!

# Answer
> 1 votes
# Javascript by histocrat, 27 / 29

```
x=>x-65?x-126?x*127%258:131:6

```

Sadly two hard codings are needed in order to break it. Note that the orginal function doesn't map any value to *130* but maps a value to *256*.

# Answer
> 1 votes
# JavaScript by fəˈnɛtɪk, 13 / 12

```
x=>x*128%257

```

Another multiplicative inverse.

# Answer
> 1 votes
# JavaScript, 11/13

```
x=>a.sort().indexOf(x)
for(a=[],i=0;i<256;)a[i]=i++;

```

Try it online!

# Answer
> 1 votes
# Jelly, 22/3 = 7 1/3

```
⁹ḶDÞḊi

```

**Try it online!**

The cop submission by fəˈnɛtɪk was to return the **nth** (**0**-indexed) lexicographically sorted decimal number using the domain **\[0,255\]**.

I first literally reversed the operation described, `⁹ḶDÞi⁸‘` \- takes the lowered range of **256**, `⁹Ḷ`, and `Þ` instructs to sort it by a key function of conversion to a decimal list, `D`; then finds the index of, `i`, the input, , and subtracts **1**,  (Jelly lists are **1**-indexed).

Then I golfed it by dequeuing the sorted list with . When an item is not found `i` returns **0** as required for the removed first element (**0**), while everything else is found one index earlier, allowing the removal of the decrement, , which in turn gives `i` implicit input on its right from the left (only) input to the monadic link.

# Answer
> 1 votes
# Javascript by Magenta, 32 / 23

```
x=>x%16*16+(x/16+13)%16

```

Code basically switches the lower and the upper 4 bits and does a modulo addition on one part.

# Answer
> 1 votes
# PHP, Score 64/71

```
for(srand(0);$a<256;)$b[$c=rand()%256]++||$d[$c]=$a++;echo$d[$argn]|0;

```

Luckily PHP's `rand` just forwards to the **stdlib** like C. So this works as long as we're using the same stdlib. This means it works on *TIO* but not on e.g. *sandbox.onlinephpfunctions.com*. The current version of Dave's code just iterates over a pseudorandom sequence and returns the *nth unique value* so I guess there might be much shorter answers if a golfing languages also uses the stdlib.

Here's an implementation of Dave's code that does not dependent on the stdlib. That might also help.

# Answer
> 0 votes
# Octave, 16/18

```
@(x)mod(x*171,256)

```

Try it online!

# Answer
> 0 votes
# Jelly, 2/5

```
^H$7¡

```

Try it online to see the whole table.

# Answer
> 0 votes
# Jelly, 8/5

```
^H$7¡

```

Try it online to see the whole table.

# Answer
> 0 votes
# Jelly, 16/6

```
×171%⁹

```

Try it online to see the whole table.

# Answer
> 0 votes
# Jelly, 11/8

```
*205%257

```

Try it online to see the whole table.

In case robber submissions in a different languages are disallowed in the future, I call dibs on the following solution.

```
g=(x,y=0)=>x-++y**5%257?g(x,y):y

```

# Answer
> 0 votes
# Jelly, 37/11

```
O_77×191%⁹Ọ

```

Uses the same I/O format as the cop. Not sure if that is required.

Try it online to see the whole table.

### How it works

For input **n**, the cop answer computes **f(n) := ((((n + 5) % 256 × 2) % 256 + 2) % 256 × 9) % 256**. Since `%` is a linear operator, this is equivalent to **f(n) = (((n + 5) × 7 + 2) × 9) % 256**. Expanding the right term, we get **f(n) = (63n + 333) % 256 = (63n + 77) % 256**.

Reversing this is rather straightforward. To undo the addition, we simply have to subtract **77**. Also, since **191 × 63 % 256 = 12033 % 256 = 1**, it follows that **191** is **63**'s inverse modulo **256**, so multiplying by **191** undoes multiplying by **63**. This way, **g(n) = (n - 77) × 191 % 256** defines the inverse of **f**.

# Answer
> 0 votes
# Jelly, 35/7

```
⁹Ṗ+\%⁹i

```

Try it online to see the whole table.

# Answer
> 0 votes
# C (gcc) by Bijan, 32 / 30

```
g(x){x=x?g(--x)*205+51&255:0;}

```

Had a fun time golfing it, thanks ! `x=` allows to skip return with gcc and tcc (you might want to change your answer to include it). `g(--x)*205+51&255` is the inverse.

---
Tags: permutations, cops-and-robbers
---