title: Remove unnecessary parentheses

text:
# Question
Title: Remove unnecessary parentheses
You are given a string composed with the characters `0123456789+*()`. You can assume that string is always a valid mathematical expression.

Your task is to remove the unnecessary parentheses, assuming multiplication has higher priority than addition.

The parentheses should be removed only when they are not needed *structurally*:

* because of multiplication higher priority: `3+(4*5)` =\> `3+4*5`
* because of multiplication or addition associativity: `3*(4*5)` =\> `3*4*5`
* when they are redundant around an expression: `3*((4+5))` =\> `3*(4+5)`

Parentheses *should be kept* when they could be simplified because of specific number values:

* `1*(2+3)` should not be simplified to `1*2+3`
* `0*(1+0)` should not be simplified to `0*1+0`

Examples:

```
(4*12)+11         ==>    4*12+11
(1+2)*3           ==>    (1+2)*3
3*(4*5)           ==>    3*4*5
((((523))))       ==>    523
(1+1)             ==>    1+1
1*(2*(3+4)*5)*6   ==>    1*2*(3+4)*5*6
1*(2+3)           ==>    1*(2+3)
0*(1+0)           ==>    0*(1+0)

(((2+92+82)*46*70*(24*62)+(94+25))+6)    ==>    (2+92+82)*46*70*24*62+94+25+6

```

# Answer
> 16 votes
# Mathematica, ~~105~~ ~~97~~ 91 bytes

<sup>*-6 bytes thanks to Roman!*</sup>

```
a=StringReplace;ToString@ToExpression@a[#,{"*"->"**","+"->"~~"}]~a~{" ** "->"*","~~"->"+"}&

```

Replaces `+` and `*` with `~~` (`StringExpression`) and `**` (`NonCommutativeMultiply`) respectively, evaluates it, stringifies it, and replaces the operators back.

# Answer
> 7 votes
# JavaScript (ES6) 163 ~~178~~

**Edit** 15 bytes saved thx @IsmaelMiguel

```
a=>eval(`s=[]${_=';for(b=0;a!=b;a=b.replace(/'}\\(([^()]*)\\)(?=(.?))/,(x,y,z,p)=>~y.indexOf('+')?-s.push(b[p-1]=='*'|z=='*'?x:y):y))b=a;${_}-\\d+/,x=>s[~x]))b=a`)

```

*Less golfed*

```
a=>{
  for(s=[],b='';
      a!=b;
      a=b.replace(/\(([^()]*)\)(?=(.?))/,(x,y,z,p)=>y.indexOf('+')<0?y:-s.push(b[p-1]=='*'|z=='*'?x:y)))
    b=a;
  for(b=0;
      a!=b;
      a=b.replace(/-\d+/,x=>s[~x]))
    b=a;
  return a
}

```

**Test**

```
f=a=>eval(`s=[]${_=';for(b=0;a!=b;a=b.replace(/'}\\(([^()]*)\\)(?=(.?))/,(x,y,z,p)=>~y.indexOf('+')
?-s.push(b[p-1]=='*'|z=='*'?x:y)
:y))b=a;${_}-\\d+/,x=>s[~x]))b=a`)

console.log=x=>O.textContent+=x+'\n'

test=`(4*12)+11         ==>    4*12+11
(1+2)*3           ==>    (1+2)*3
3*(4*5)           ==>    3*4*5
((((523))))       ==>    523
(1+1)             ==>    1+1
1*(2*(3+4)*5)*6   ==>    1*2*(3+4)*5*6
1*(2+3)           ==>    1*(2+3)
0*(1+0)           ==>    0*(1+0)
(((2+92+82)*46*70*(24*62)+(94+25))+6)    ==>    (2+92+82)*46*70*24*62+94+25+6`

test.split`\n`.forEach(r=>{
  var t,k,x
  [t,,k]=r.match(/\S+/g)
  x=f(t)
  console.log((x==k?'OK ':'KO ')+t+' -> '+x+(x==k?'':' expected '+k))
})
```

```
<pre id=O></pre>
```

# Answer
> 5 votes
# Python3 + PEG implementation in Python, 271 bytes

```
import peg
e=lambda o,m=0:o.choice and str(o)or(m and o[1][1]and"("+e(o[1])+")"or e(o[1]))if hasattr(o,"choice")else o[1]and e(o[0],1)+"".join(str(x[0])+e(x[1],1)for x in o[1])or e(o[0])
print(e(peg.compile_grammar('e=f("+"f)*f=p("*"p)*p="("e")"/[0-9]+').parse(input())))

```

A while back I made a PEG implementation in Python. I guess I can use that here.

Parses the expression into a tree, and only keeps parenthesis if the child is addition, and the parent is multiplication.

# Answer
> 4 votes
# Perl, 132 bytes

129 bytes source + 3 for `-p` flag:

```
#!perl -p
0while s!\(([^\(\)]+)\)!$f{++$i}=$1,"_$i"!e;s!_$i!($v=$f{$i})=~/[+]/&&($l.$r)=~/[*]/?"($v)":$v!e
while($l,$i,$r)=/(.?)_(\d+)(.?)/

```

Using:

```
echo "1*(2*(3+4)*5)*6" | perl script.pl

```

# Answer
> 4 votes
# Ruby, ~~140~~ 130 bytes

127 bytes source + 3 for  `-p` flag:

```
t={}
r=?%
0while$_.gsub!(/\(([^()]+)\)/){t[r+=r]=$1;r}
0while$_.gsub!(/%+/){|m|(s=t[m])[?+]&&($'[0]==?*||$`[/\*$/])??(+s+?):s}

```

And ungolfed:

```
tokens = Hash.new
key = '%'

# convert tokens to token keys in the original string, innermost first
0 while $_.gsub!(/\(([^()]+)\)/) { # find the innermost parenthetical
  key += key # make a unique key for this token
  tokens[key] = $1
  key # replace the parenthetical with the token key in the original string
}

# uncomment to see what's going on here
# require 'pp'
# pp $_
# pp tokens

# convert token keys back to tokens, outermost first
0 while $_.gsub!(/%+/) {|key|
  str = tokens[key]
  if str['+'] and ($'[0]=='*' or $`[/\*$/]) # test if token needs parens
    '(' + str + ')'
  else
    str
  end
}
# -p flag implicity prints $_

```

# Answer
> 2 votes
# Retina, 155 bytes

```
{`\(((\d+|\((((\()|(?<-5>\))|[^()])*(?(5)^))\))(\*(\d+|\((((\()|(?<-10>\))|[^()])*(?(10)^))\)))*)\)
$1
(?<!\*)\((((\()|(?<-3>\))|[^()])*(?(3)^))\)(?!\*)
$1

```

Try it online!

Verify all testcases at once.

### Explanation

The main thing is this code:

```
(((\()|(?<-3>\))|[^()])*(?(3)^)

```

This regex can match any string in which the brackets are balanced, e.g. `1+(2+(3))+4` or `2+3`.

For the ease of explanation, let this regex be `B`.

Also, let us use `<` and `>` instead for the brackets, as well as `p` and `m` for `\+` and `\*`.

The code becomes:

```
{`<((\d+|<B>)(m(\d+|<B>))*)>
$1
(?<!m)<B>(?!m)
$1

```

The first two lines match for brackets which consist of only multiplication, e.g. `(1*2*3)` or even `(1*(2+3)*4)`. They are replaced by their content inside.

The last two lines match for brackets which are not preceded and which are not followed by multiplication. They are replaced by their content inside.

The initial `{`` means "replace until idempotent", meaning that the replacements are done until they either no longer match or they are replaced with themselves.

In this case, the replacements are done until they no longer match.

# Answer
> 2 votes
# Python 3, ~~274~~ ~~269~~ ~~359~~ ~~337~~ 336 bytes

This method basically removes every possible pair of parentheses and checks to see if it still evaluates the same.

```
from re import *
def f(x):
    *n,=sub('\D','',x);x=sub('\d','9',x);v,i,r,l=eval(x),0,lambda d,a,s:d.replace(s,"?",a).replace(s,"",1).replace("?",s),lambda:len(findall('\(',x))
    while i<l():
        j=0
        while j<l():
            h=r(r(x,i,"("),j,")")
            try:
                if eval(h)==v:i=j=-1;x=h;break
            except:0
            j+=1
        i+=1
    return sub('9','%s',x)%tuple(n)

```

**Test Harness**

```
print(f("(4*12)+11")=="4*12+11")
print(f("(1+2)*3") =="(1+2)*3")
print(f("3*(4*5)")=="3*4*5")
print(f("((((523))))")=="523")
print(f("(1+1)")=="1+1")
print(f("1*(2*(3+4)*5)*6")=="1*2*(3+4)*5*6")
print(f("(((2+92+82)*46*70*(24*62)+(94+25))+6)")=="(2+92+82)*46*70*24*62+94+25+6")
print(f("1*(2+3)")=="1*(2+3)")
print(f("0*(1+0)")=="0*(1+0)")

```

**Updates**

* **-1** \[16-10-04\] Removed extra space
* **-22** \[16-05-07\] Made use of the `re` lib
* **+90** \[16-05-07\] Updated to handle the new test cases
* **-5** \[16-05-07\] Removed parameter from the length (`l`) lambda

# Answer
> 1 votes
**PHP, 358 bytes**

```
function a($a){static$c=[];$d=count($c);while($g=strpos($a,')',$g)){$f=$a;$e=0;for($j=$g;$j;--$j){switch($a[$j]){case')':++$e;break;case'(':--$e;if(!$e)break 2;}}$f[$g++]=$f[$j]=' ';if(eval("return $f;")==eval("return $a;"))$c[str_replace(' ', '', $f)]=1;}if(count($c)>$d){foreach($c as$k=>$v){a($k);}}return$c;}$t=a($argv[1]);krsort($t);echo key($t);

```

Not an impressive length, that's what I get for taking a less than optimal approach (and using a less than optimal language).

Strips a pair of brackets out, then evals the resulting expression. If the result is the same as the original it adds it to a map of valid expressions and recurses until no new expressions can be found. Then prints the shortest valid expression.

Breaks when the result of the expression gets large and casts to double / exponent notation show up.

# Answer
> 1 votes
# Prolog (SWI), ~~122~~ 118 bytes

```
T+S:-term_string(T,S).
I/O:-X+I,X-Y,Y+O.
E-O:-E=A+(B+C),A+B+C-O;E=A*(B*C),A*B*C-O;E=..[P,A,B],A-X,B-Y,O=..[P,X,Y];E=O.

```

Try it online!

Defines a predicate `//2` which removes parentheses from its first argument's string value and outputs a string through its second argument. If input could be in Prolog terms, this would only be ~~81~~ 77 bytes defining `+/2` without having to deal with the verbose `term_string/2`, but a lot of unnecessary parentheses would simply not have existed to begin with that way so it would be pretty close to cheating, since all that `+/2` does is handle associativity.

I tried to use `=../2` for all of it, but it came out far longer, because a three-byte operator that works with lists isn't exactly terse:

# Prolog (SWI), 124 bytes

```
T+S:-term_string(T,S).
I/O:-X+I,X-Y,Y+O.
X-Y:-X=..[O,A,B],(B=..[O,C,D],E=..[O,A,C],F=..[O,E,D],F-Y;A-C,B-D,Y=..[O,C,D]);X=Y.

```

Try it online!

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


title: Reroute the Path

text:
# Question
Title: Reroute the Path
Given a grid of directions and a start and end position, determine the minimum number of substitutions in the direction grid that needs to be made to complete the path between the two points. The grid is doubly-cylindrical. This is clearer given an example.

## Example

Let's take the following grid as an example:

```
>>>>v
>>>><
<<<<<

```

Let's start at `(1, 1)` and end at `(1, 3)` (where the coordinates are `(x, y)` or `(col, row)`, with the top row and left column being `1`). Then, one possible solution is to replace the `(1, 1)` and `(1, 2)` with `v`, so that the final grid looks like this:

```
v>>>v
v>>><
<<<<<

```

Starting from `(1, 1)`, the path would lead us to `(1, 3)`. However, a shorter solution exists, which is to replace `(5, 2)` with `v`, so the final grid is this:

```
>>>>v
>>>>v
<<<<<

```

Starting from `(1, 1)`, a rather long path leads to `(1, 3)`.

Replacing anything in the top row with `^` works too (thanks @Spitemaster).

## Input

The input will consist of a rectangular grid of 4 possible values, as well as two coordinates. You can take the grid in any reasonable format; for example, character or integer matrix, string list, etc. You can also request the dimensions of the grid. You can take the coordinates in any reasonable format; for example, integer pair, complex number, etc. You can choose 0- or 1-indexing.

## Output

The output should be a single integer, the minimal number of grid replacements necessary to close the path from the start to the end.

## Rules and Specifications

* Standard Loopholes Apply
* the grid is doubly cylindrical, meaning that moving up from the top goes to the bottom, left from the left goes to the right, etc.

## Sample Cases

The sample cases are given as a character matrix and 1-indexed coordinates.

### Case 1

**Input**

```
>>>>v
>>>><
<<<<<
1 1
1 3

```

**Output**

```
1

```

**Explanation**

See example.

### Case 2

**Input**

```
<<<<<
v>v>v
>>>>>
1 1
5 3

```

**Output**

```
1

```

**Explanation**

You can either replace `(1, 1)` with `v` or `(2, 1)` with `v`. In the first case, starting from `(1, 1)`, the path goes straight down and then to the right to the destination. In the second case, the path loops off the left to the right, reaches `(2, 1)`, goes down, right, down, and then right until it hits the destination.

### Case 3

**Input**

```
^^^^^^
><<>>>
vvvvvv
2 2
5 2

```

**Output**

```
2

```

**Explanation**

The best change is to make the center row wrap around the left to the point; that is, make the first and last items in the center row `<`. Alternatively, make `2 2` and `3 2` both `>`.

This is a challenge, so the shortest code wins!

# Answer
> 5 votes
# JavaScript (ES6),  ~~140~~  135 bytes

Takes input as `(a, width, height, x1, y1)(x0, y0)` where `a[]` is a matrix of integers and all coordinates are 0-indexed.

Directions: \\$-2\\$ for *left*, \\$-1\\$ for *up*, \\$0\\$ for *right* and \\$1\\$ for *down*.

```
(a,w,h,X,Y)=>m=g=(x,y,n=0,r=a[y%=h],v=r[x%=w])=>x-X|y-Y?[-1,0,1,2].map(d=>r[v<2&&g(x+w+d%(r[x]=2),y+h+--d%2,n+(v!=d)),x]=v)|m:m=m<n?m:n

```

Try it online!

### How?

We use a breadth-first search to try all possible paths from \\$(x,y)\\$ to \\$(X,Y)\\$ without visiting twice the same cell.

We keep track of the number of times \\$n\\$ where the direction that was chosen did not match the direction stored in the input matrix.

We eventually return \\$m\\$, which is defined as the minimum value of \\$n\\$.

# Answer
> 3 votes
# Jelly, ~~73~~ 72 bytes

```
W,0+Ɱ⁴PṬ€×Ɱ3¤Ẏ¤,€ɗ/€Ẏ$‘ƭ€ịØ.,N;U$¤;ɗ/0ị+æ.Ɱ⁴‘Ṫịʋ¥Ɗ%⁴ṭƲ⁴P¤¡ŒHṪe¥/Ʋ€Ẹ¬Ɗ/¿Ṫ

```

Try it online!

Example using case 3 that requires two changes (also has a footer to translate the `><v^` into numbers).

A full program that expects the following arguments:

* Left: a list of two lists; first the flattened direction grid encoded as 1=right, 2=left, 3=down, 4=up, followed by a list of the end position and start position as zero-indexes \[row, column\]. For first example, `[1,1,1,1,3,1,1,1,1,4,2,2,2,2,2],[[2,0],[0,0]]`.
* Right: a list of the number of rows followed by columns. For first example `[3,5]`

Returns the number of changes required to get from start to end. Slow once this is more than one change. On TIO the third example case takes approx. 30 seconds to complete.

Full explanation below, but overview is:

1. Initialise a counter to zero.
2. Work out positions after each of \\$\mathit{row} × \mathit{column}\\$ moves.
3. Check if the end position is included:
    * If false, increment a counter and create \\$3 × \mathit{row} × \mathit{column}\\$ new versions of the grid, each with a single grid position changed to one of the three possible alternative moves. Then go back to step 2.
    * If true, terminate and output the counter

### Full explanation:

```
W,0 | Wrap input in a list, and then pair with 0 (thus initialising the counter)

                                           Ɗ/¿ | While the following is true for the first item of the input pair (i.e. the list of all grids to be tested, paired with the end and start grid positions):
                                       Ʋ€      | - For each member of the list:
          ɗ/                                   |   - Reduce using the following as a dyad (so left argument is flattened grid and right is end/start positions)
ị       ¤                                      |     - Index into the following as a nilad
 Ø.                                            |       - [0, 1]
   ,N                                          |       - Pair with negative [[0, 1], [0, -1]]
     ;U$                                       |       - Concatenate to upended version of this [[0, 1], [0, -1], [1, 0], [-1, 0]]
         ;                                     |     - Concatenate (to end/start positions)
                            Ʋ⁴P¤¡              |   - Repeat the following links the number of times indicated by the product of the grid dimensions:
                        Ɗ                      |     - Following as a monad:
            0ị                                 |       - Last item (current grid position)
              +        ¥                       |       - Add to the following as a dyad:
               æ.Ɱ⁴                            |         - Dot product of current position with each of grid dimensions
                   ‘                           |         - Increase by 1
                    Ṫ                          |         - Tail (which is current position in flattened grid)
                     ị                         |         - index into flattened grid
                         %⁴                    |        - Mod grid dimensions
                           ṭ                   |        - Tack onto end of current grid/position list
                                 ŒH            |   - Split into halves (first half will be flattened grid and desired end position, second half will be all positions reached after moving through grid)
                                     ¥/        |   - Following as a dyad, with the first half from above step as left argument and the second half as right
                                   Ṫ           |     - Tail (i.e. the desired end position)
                                    e          |     - Exists within (the list of all positions reached)
                                         Ẹ¬    | - Not true for any of the input grids

                    ƭ€ | For each of the pair (list of grids, counter), do one of the following:
                  $    | - For the list of grids, do the following as a monad:
              ɗ/€      |   - Do the following as a dyad, with the flattened grid as the left argument and end/start positions as the right:
+Ɱ                     |     - Add to the flattened grid list each of:
           ¤           |       - The following as a nilad
         ¤             |         - The following as a nilad:
  ⁴P                   |           - The product of the grid dimensions
    Ṭ€                 |           - Convert each (using an implicit range from 1 to the grid dimension product) to a boolean list with a 1 at the relevant position (i.e. [[1], [0, 1], [0, 0, 1]...])
      ×Ɱ3              |           - Multiply by each of 1..3
          Ẏ            |        - Flatten to a single list of lists
            ,€         |    - Pair each with the end/start positions
                 Ẏ     |   - Tighten to a single list of grids paired with end/start positions
                   ‘   | - For the counter increment it

Ṫ | Finally, take the tail (which is the final value of the counter)

```

---
Tags: code-golf, grid, graph-theory
---


title: Quine/Error Quine Polyglot

text:
# Question
Title: Quine/Error Quine Polyglot
Your task is simple: Write a program that can be run in two languages. It should be a normal quine (prints its own source code) in language 1, and should be an error quine (generates an error message identical to its own source code) in language 2.

This is , so the shortest valid submission (in bytes) wins.

Rules:

* The languages may be arbitrarily similar. Supersets/similar versions/similar dialects are not disallowed.
* The error quine rules are the same as those in Make an Error Quine!.

# Answer
> 3 votes
# Befunge-93 (FBBI) / C (tcc), 93 + 62 = 155 bytes

```
^"
>#001p#"<>:#,_@#1-8*3:-1*57+55-1*79*57:-1:*77**278\-1:*57$p:1: error: declaration expected

```

Try it online!: Befunge-93,

*Thanks to randomdude999 for noting that the filename requires matching quotes to work.*

Must be saved under the filename `^"\n>#001p#"<>:#,_@#1-8*3:-1*57+55-1*79*57:-1:*77**278\-1:*57$p`, where `\n` is a newline. Because of this, the TIO for C doesn't run exactly as intended. Tested to work on Lubuntu.

### Explanation (C):

The program fails to compile, and tcc happily outputs the name of the file as part of its error message. There are multiple compilation errors you can get, based on the beginning of the code. `^` at the start gives us a `declaration expected`, which is short and doesn't contain any problematic characters like `"`. On the other hand, the gcc and clang developers are very pessimistic and they chose to output multiple errors at once, which is not very nice, so we aren't using their compilers.

### Explanation (Befunge-93):

Befunge is convenient for quines in that its code can also be utilised as character data, thanks to the `"` command, which toggles string mode. At the beginning, we perform some useless stack operations, then issue a `p` (put command) which places a NUL character at (0, 1). Then we reflect the instruction pointer to the left and begin reading everything as a string. This has to be done to the left, because of the stack's LIFO nature. After wrapping around and reaching the `"` character again, the string ends. Note that the NUL character replaced the `$` character, creating a delimiter midway through the string. We then push 3 numbers onto the stack and jump over the NUL (because it unfortunately hangs the interpreter when run as an instruction). The static part of the error message has to be executed here. Most of its characters are no-ops, but the `p` command consumes three arguments (hence why we pushed 3 numbers, otherwise part of the string would be eaten here), and `:` & `1` characters push a total of 4 values to the stack, which we counteract with a `p` and a `$` (pop and discard) instruction. Then, some arithmetic is performed to push the ASCII codes for `^"\n>#001p#"` and finally a loop prints out all the values on the stack as characters until it finds a NUL character and terminates.

# Answer
> 0 votes
# Applesoft BASIC / Commodore LCD BASIC, 13 bytes

```
?SYNTAX ERROR

```

In the Apple \]\[ emulator, hit the `RESET` key to enter BASIC mode.
In the Commodore LCD emulator, hit `RightArrow``Enter` to get into the BASIC application.
In both of them, don't type `?SYNTAX ERROR` in all caps, because they automatically capitalize.

---
Tags: code-golf, quine, polyglot, error-message
---


title: Today in the YOLD

text:
# Question
Title: Today in the YOLD
The Discordian calendar is an alternative calendar used by Discordians.

1. The discordian year has 5 seasons, each lasting 73 days: Chaos, Discord, Confusion, Bureaucracy, and The Aftermath.
2. The discordian week has 5 days: Sweetmorn, Boomtime, Pungenday, Prickle-Prickle, and Setting Orange. Every year begins with Sweetmorn (and in Chaos).
3. Every **f**ourth year (which happe**n**s to align with Greg**o**rian leap yea**r**s), an extra **d**ay is inserted between Chaos 59 and Chaos 60 called *St. Tib's Day*. It is outside of the Discordian week, meaning the day after St. Tib's Day will be Setting Orange, the day before Prickle-Prickle.
4. The Gregorian and Discordian calendars line up; both start on the same day, which is called January 1st in the Gregorian calendar, and Chaos 1 in the Discordian one.
5. The first Year of Our Lady of Discord (YOLD 1) was 1166 BC in the Gregorian calendar, meaning this year (2017 AD) is YOLD 3183.
6. The Discordian calendar also has holidays, but they are not important for this challenge and you should not output them or anything about them.

Write a program or function that outputs or returns today's date (at the time of execution):

```
Today is Boomtime, the 16th day of Confusion in the YOLD 3183

```

The format is `"Today is $day_of_the_week, the $ordinal day of $season in the YOLD $year"`, where $day\_of\_the\_week is the capitalized (title-case) day of the week, $ordinal is the day of the season as an ordinal (1st, 2nd, 3rd, 4th, ...), $season is the capitalized (title-case) season, and $year is the year.

If your program or function is executed on St. Tib's Day, it should instead output or return `"Today is St. Tib's Day in the YOLD $year"`.

### Rules:

* Standard loopholes apply.
* If your language of choice has no way of getting the current date, it may also take the current Gregorian date in any reasonable format as input.
* This is , the shortest code (per language) wins.
* Trailing whitespace is okay.
* Capitalization matters.
* Calling `ddate` in any way is banned
* Your program should be guaranteed to work from 3067 to 3265 YOLD (1901 to 2099 AD), outside that range it can give incorrect values

## See also:

# Answer
> 5 votes
## Mathematica, ~~403~~ 401 bytes

Version to count number of bytes: (removed spaces and newlines - unfortunately this part is quite hard)

```
"Setting Orange"["Sweetmorn","Boomtime","Pungenday","Prickle-Prickle"][[#~Mod~5]]<>", the "<>SpokenString@p[[Mod[#,73,1]]]~StringExtract~2<>" day of "<>{"Chaos","Discord","Confusion","Bureaucracy","The Aftermath"}[[⌈#/73⌉]]&;
Row@{"Today is ",#2," in the YOLD ",1166+#}&[#,If[4∣#,If[#2>60,%[#2-1],If[#2<60,%@#2,"St.Tib's Day"]],%@#2]]&@@FromDigits/@DateString@"ISOOrdinalDate"~StringSplit~"-"

```

Version to read:

```
"Setting Orange"["Sweetmorn", "Boomtime", "Pungenday",
     "Prickle-Prickle"][[#~Mod~5]] <>
   ", the " <>
   SpokenString@p[[Mod[#, 73, 1]]]~StringExtract~2 <>
   " day of " <>
   {"Chaos", "Discord", "Confusion", "Bureaucracy",
     "The Aftermath"}[[Ceiling[#/73]]] &;
Row@{
      "Today is ",
      #2,
      " in the YOLD ",
      1166 + #
      } &[#,
   If[4 ∣ #,
    If[#2 > 60, %[#2 - 1],
     If[#2 < 60, %@#2, "St.Tib's Day"]
     ], %@#2
    ]] & @@ FromDigits /@ DateString@"ISOOrdinalDate"~StringSplit~"-"

```

The answer can be tested with arbitrary date by replacing `DateString@"ISOOrdinalDate"` by `DateString[{year,month,day},"ISOOrdinalDate"]` for `year`, `month` and `day` replaced by numbers.

# Answer
> 4 votes
## Python 2, 423 Bytes

Short version:

```
import time
y,d=time.gmtime()[0::7]
t="Today is "
o=" in the YOLD "+`y+1166`
if y%4<1 and d>59:
 if d==60:print"%sSt. Tib's Day%s%d"%(t,o);quit()
 d-=1
s,e=divmod(d-1,73)
print t+["Sweetmorn","Boomtime","Pungenday","Prickle-Prickle","Setting Orange"][(d-1)%5]+", the %d%s day of %s"%(e+1,'tsnrthtddh'[min(e*(e/10-1 and 1)%10,4)::5],["Chaos","Discord","Confusion","Bureaucracy","The Aftermath"][s]+o)

```

Longer, more readable form:

```
import time

# now = time.strptime("2017.06.11", "%Y.%m.%d")  # for testing
now = time.gmtime()
year, day_of_year = now[0::7]
leapyear = year % 4 < 1
today = "Today is "
yold = " in the YOLD " + `y+1166`

if leapyear and day_of_year>59:
    if day_of_year==60:
        print "%sSt. Tib's Day%s%d"% (today, yold)
        quit()  # dirty, but ... hey.
    day_of_year -= 1
season, day = divmod(day_of_year-1,73)

print today + \
    ["Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"][(day_of_year-1)%5] + \
    ", the %d%s day of %s" % (
        day+1,
        'tsnrthtddh'[min(day*(day/10-1 and 1)%10,4)::5],
        ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"][season] + yold
    )

```

**Update:** Fixed with help of the great @Neil and @EriktheOutgolfer. But @Jonathans answer is way shorter.

# Answer
> 2 votes
## JavaScript (ES6), ~~387~~ 380 bytes

```
f=(d=new Date(),a=d.getDate()-1,y=d.getFullYear()+1166)=>d.getMonth()?f(d,a+d.getDate(d.setDate(0))):`Today is ${y%4-2|a<59||59-a--?`Sweetmorn,Boomtime,Pungenday,Prickle-Prickle,Setting Orange`.split`,`[a%5]+`, the ${d=a%73+1}${[,`st`,`nd`,`rd`][d-10-(d%=10)&&d]||`th`} day of `+`Chaos,Discord,Confusion,Bureaucracy,The Aftermath`.split`,`[a/73|0]:`St. Tib's Day`} in the YOLD `+y

```

Takes an optional date parameter. Ungolfed:

```
function discordian(date) {
    var a = date.getDate();
    while (date.getMonth()) {
        date.setDate(0);
        a += date.getDate();
    }
    if (date.getYear() % 4 == 0) {
        if (a == 60) return "Today is St. Tib's day in the YOLD " + (date.getYear() + 1166);
        if (a > 60) a--;
    }
    var weekday = ['Setting Orange', 'Sweetmorn', 'Boomtime', 'Pungenday', 'Prickle-Prickle'][a % 5];
    var seasonday = (a - 1) % 73 + 1;
    var ordinal = seasonday % 10 == 1 && seasonday != 11 ? 'st' : seasonday % 10 == 2 && seasonday != '12' : 'nd' : seasonday % 10 == 3 && seasonday != '13' ? 'rd' : 'th';
    var season = ['Chaos', 'Discord', 'Confusion', 'Bureaucracy', 'The Aftermath'][Math.floor((a - 1) / 73)];
    return "Today is " + weekday + ", the " + seasonday + ordinal + " day of " + season + " in the YOLD " + (date.getYear() + 1166);
}

```

# Answer
> 2 votes
# Python 2, 346 bytes

<sub>*Note:* This is a golf (and fix) of jammon's answer \- I originally thought I'd submit a comment, but I changed quite a bit in the end (plus the day-suffixes have been fixed).</sub>

```
import time
y,d=time.gmtime()[::7]
t="Today is %s in the YOLD "+`y+1166`
r=y%4<1<59<d
d-=r+1
e=d%73
print t%[["Sweetmorn","Boomtime","Pungenday","Prickle-Prickle","Setting Orange"][d%5]+", the %d%s day of "%(e+1,'snrttddh'[min(e%10+3*(e/9==1),3)::4])+["Chaos","Discord","Confusion","Bureaucracy","The Aftermath"][d/73],"St. Tib's Day"][(r*d)==58]

```

**Try it online!** or see some hard-coded test dates.

# Answer
> 1 votes
# C#, 392 bytes

```
using System;s=>{var t=DateTime.Now;int d=t.DayOfYear,y=t.Year,m=d%73;return"Today is "+(DateTime.IsLeapYear(y)&d==60?"St. Tib's Day":"Sweetmorn|Boomtime|Pungenday|Prickle-Prickle|Setting Orange".Split('|')[d%5-1]+", the "+ m+(m<2|m==21|m>30?"st":m==2|m==22?"nd":m==3|m==23?"rd":"th")+" day of "+"Chaos|Discord|Confusion|Bureaucracy|The Aftermath".Split('|')[d/73])+" in the YOLD "+(y+1166);}

```

Full/Formatted version:

```
using System;

class P
{
    static void Main()
    {
        Func<string, string> f = s =>
        {
            var t = DateTime.Now;
            int d = t.DayOfYear, y = t.Year, m = d % 73;

            return "Today is " + (DateTime.IsLeapYear(y) & d == 60
                   ? "St. Tib's Day"
                   : "Sweetmorn|Boomtime|Pungenday|Prickle-Prickle|Setting Orange".Split('|')[d % 5 - 1] +
                     ", the " +
                     m +
                     (m < 2 | m == 21 | m > 30 ? "st" : m == 2 | m == 22 ? "nd" : m == 3 | m == 23 ? "rd" : "th") +
                     " day of " +
                     "Chaos|Discord|Confusion|Bureaucracy|The Aftermath".Split('|')[d / 73])
                   + " in the YOLD " + (y + 1166);
        };

        Console.WriteLine(f(null));

        Console.ReadLine();
    }
}

```

# Answer
> 1 votes
# Pyth, 295 bytes

```
J.d2A<J2Kt+s<+,31 28*2t*3,30 31tH@J2=Y&&!%G4<58K!qH3=N%K73%"Today is %s in the YOLD %d",@,++@c"SweetmornZBoomtimeZPungendayZPrickle-PrickleZSetting Orange"\Z%K5%", the %d%s day of ",+N1@c"stndrdth"2h.mb,3+%NT*3q1/N9@c." yNlSFk.»&ô?Z#u!%ô6'mçM«_ôvëû¹)+¬<"\Z/K73"St. Tib's Day"q*YK59+G1166

```

Note: contains binary, may not be safe to copy-paste from here. Copy-pasting from TIO should work.

Try it online!

You can test arbitrary dates by replacing `.d2` at the start with a 3-tuple of (year, month, day) like this: `(2020 2 29)`.

This one was a bit annoying since Pyth doesn't have any way to get "day of year" so I had to compute it myself.

---
Tags: code-golf, date
---


# Question
Title: Proving that a Russian cryptographic standard is too structured
The aim of this challenge is to find an *impossibly* short implementation of the following function `p`, in the langage of your choosing. Here is C code implementing it (see this TIO link that also prints its outputs) and a wikipedia page containing it.

```
unsigned char pi[] = {
    252,238,221,17,207,110,49,22,251,196,250,218,35,197,4,77,
    233,119,240,219,147,46,153,186,23,54,241,187,20,205,95,193,
    249,24,101,90,226,92,239,33,129,28,60,66,139,1,142,79,
    5,132,2,174,227,106,143,160,6,11,237,152,127,212,211,31,
    235,52,44,81,234,200,72,171,242,42,104,162,253,58,206,204,
    181,112,14,86,8,12,118,18,191,114,19,71,156,183,93,135,
    21,161,150,41,16,123,154,199,243,145,120,111,157,158,178,177,
    50,117,25,61,255,53,138,126,109,84,198,128,195,189,13,87,
    223,245,36,169,62,168,67,201,215,121,214,246,124,34,185,3,
    224,15,236,222,122,148,176,188,220,232,40,80,78,51,10,74,
    167,151,96,115,30,0,98,68,26,184,56,130,100,159,38,65,
    173,69,70,146,39,94,85,47,140,163,165,125,105,213,149,59,
    7,88,179,64,134,172,29,247,48,55,107,228,136,217,231,137,
    225,27,131,73,76,63,248,254,141,83,170,144,202,216,133,97,
    32,113,103,164,45,43,9,91,203,155,37,208,190,229,108,82,
    89,166,116,210,230,244,180,192,209,102,175,194,57,75,99,182,
};

unsigned char p(unsigned char x) {
     return pi[x];
}

```

## What is `p`

`p` is a component of two Russian cryptographic standards, namely the hash function Streebog and the block cipher Kuznyechik. In this article (and during ISO meetings), the designers of these algorithms claimed that they generated the array `pi` by picking random 8-bit permutations.

## "Impossible" implementations

There are \\$256! \approx 2^{1684}\\$ permutations on 8 bits. Hence, for a given random permutation, a program that implement it shall not be expected to need fewer than 1683 bits.

However, we have found multiple abnormally small implementations (which we list here), for example the following C program:

```
p(x){unsigned char*k="@`rFTDVbpPBvdtfR@\xacp?\xe2>4\xa6\xe9{z\xe3q5\xa7\xe8",l=0,b=17;while(--l&&x^1)x=2*x^x/128*285;return l%b?k[l%b]^k[b+l/b]^b:k[l/b]^188;}

```

which contains only 158 characters and thus fits in 1264 bits. Click here to see that it works.

We talk about an "impossibly" short implementation because, if the permutation was the output of a random process (as claimed by its designers), then a program this short would not exist (see this page for more details).

## Reference implementation

A more readable version of the previous C code is:

```
unsigned char p(unsigned char x){
     unsigned char
         s[]={1,221,146,79,147,153,11,68,214,215,78,220,152,10,69},
         k[]={0,32,50,6,20,4,22,34,48,16,2,54,36,52,38,18,0};
     if(x != 0) {
         unsigned char l=1, a=2;
         while(a!=x) {
             a=(a<<1)^(a>>7)*29;
             l++;
         }
         unsigned char i = l % 17, j = l / 17;
         if (i != 0) return 252^k[i]^s[j];
         else return 252^k[j];
     }
     else return 252;
}

```

The table `k` is such that `k[x] = L(16-x)`, where `L` is linear in the sense that `L(x^y)==L(x)^L(y)`, and where, like in C, `^` denotes the XOR. However, we did not manage to leverage this property to shorten our implementation. We are not aware of any structure in `s` that could allow a simpler implementation---its output is always in the subfield though, i.e. \\$s\[x\]^{16}=s\[x\]\\$ where the exponentiation is done in the finite field. Of course, you are absolutely free to use a simpler expression of `s` should you find one!

The while loop corresponds to the evaluation of a discrete logarithm in the finite field with 256 elements. It works via a simple brute-force search: the dummy variable `a` is set to be a generator of the finite field, and it is multiplied by this generator until the result is equal to `x`. When it is the case, we have that `l` is the discrete log of `x`. This function is not defined in 0, hence the special case corresponding to the `if` statement.

The multiplication by the generator can be seen as a multiplication by \\$X\\$ in \\$\mathbb{F}\_2\[X\]\\$ which is then reduced modulo the polynomial \\$X^8+X^4+X^3+X^2+1\\$. The role of the `unsigned char` is to ensure that the variable `a` stays on 8 bits. Alternatively, we could use `a=(a<<1)^(a>>7)*(256^29)`, in which case `a` could be an `int` (or any other integer type). On the other hand, it is necessary to start with `l=1,a=2` as we need to have `l=255` when `x` is equal to 1.

More details on the properties of `p` are presented in our paper, with a writeup of most of our optimizations to obtain the previous short implementation.

## Rules

Propose a program that implements the function `p` in less than 1683 bits. As the shorter the program, the more abnormal it is, for a given language, shorter is better. If your language happens to have Kuznyechik, Streebog or `p` as a builtin, you cannot use them.

The metric we use to determine the best implementation is the program length in bytes. We use the bit-length in our academic paper but we stick to bytes here for the sake of simplicity.

If your language does not have a clear notion of function, argument or output, the encoding is up to you to define, but tricks like encoding the value `pi[x]` as `x` are obviously forbidden.

We have already submitted a research paper with our findings on this topic. It is available here. However, should it be published in a scientific venue, we will gladly acknowledge the authors of the best implementations.

By the way, thanks to xnor for his help when drafting this question!

# Answer
# AMD64 Assembly (78 bytes or 624 bits of machine code)

```
uint8_t SubByte(uint8_t x) {
    uint8_t y,z;
    uint8_t s[]=
      {1,221,146,79,147,153,11,68,214,215,78,220,152,10,69};

    uint8_t k[]=
      {0,32,50,6,20,4,22,34,48,16,2,54,36,52,38,18,0};

    if(x) {
      for(y=z=1;(y=(y<<1)^((y>>7)*29)) != x;z++);
      x = (z % 17);
      z = (z / 17);
      x = (x) ? k[x] ^ s[z] : k[z];
    }
    return x^252;
}

```

# 64-bit x86 assembly

```

    ; 78 bytes of AMD64 assembly
    ; odzhan
    bits   64

    %ifndef BIN
      global SubBytex
    %endif

SubBytex:
    mov    al, 252
    jecxz  L2                ; if(x) {
    call   L0
k:
    db     0xfc, 0xdc, 0xce, 0xfa, 0xe8, 0xf8, 0xea, 0xde,
    db     0xcc, 0xec, 0xfe, 0xca, 0xd8, 0xc8, 0xda, 0xee, 0xfc
s:
    db     0x01, 0xdd, 0x92, 0x4f, 0x93, 0x99, 0x0b, 0x44,
    db     0xd6, 0xd7, 0x4e, 0xdc, 0x98, 0x0a, 0x45
L0:
    pop    rbx
    mov    al, 1             ; y = 1
    cdq                      ; z = 0
L1:
    inc    dl                ; z++
    add    al, al            ; y = y + y
    jnc    $+4               ; skip XOR if no carry
    xor    al, 29            ;
    cmp    al, cl            ; if(y != x) goto L1
    jne    L1

    xchg   eax, edx          ; eax = z
    cdq                      ; edx = 0
    mov    cl, 17            ; al = z / 17, dl = z % 17
    div    ecx

    mov    cl, [rbx+rax+17]  ; cl = s[z]
    xlatb                    ; al = k[z]
    test   dl, dl            ; if(x == 0) goto L2
    jz     L2
    xchg   eax, edx          ; al = x
    xlatb                    ; al = k[x]
    xor    al, cl            ; al ^= s[z]
L2:
    ret

```

# Disassembled 64-bit code

```
00000000  B0FC              mov al,0xfc
00000002  67E348            jecxz 0x4d
00000005  E820000000        call qword 0x2a
; k[] = 0xfc, 0xdc, 0xce, 0xfa, 0xe8, 0xf8, 0xea, 0xde,
;       0xcc, 0xec, 0xfe, 0xca, 0xd8, 0xc8, 0xda, 0xee, 0xfc
; s[] = 0x01, 0xdd, 0x92, 0x4f, 0x93, 0x99, 0x0b, 0x44,
;       0xd6, 0xd7, 0x4e, 0xdc, 0x98, 0x0a, 0x45
0000002A  5B                pop rbx
0000002B  B001              mov al,0x1
0000002D  99                cdq
0000002E  FEC2              inc dl
00000030  00C0              add al,al
00000032  7302              jnc 0x36
00000034  341D              xor al,0x1d
00000036  38C8              cmp al,cl
00000038  75F4              jnz 0x2e
0000003A  92                xchg eax,edx
0000003B  99                cdq
0000003C  B111              mov cl,0x11
0000003E  F7F1              div ecx
00000040  8A4C0311          mov cl,[rbx+rax+0x11]
00000044  D7                xlatb
00000045  84D2              test dl,dl
00000047  7404              jz 0x4d
00000049  92                xchg eax,edx
0000004A  D7                xlatb
0000004B  30C8              xor al,cl
0000004D  C3                ret

```

# 32-bit x86 assembly

```

    ; 72 bytes of x86 assembly
    ; odzhan
    bits   32

    %ifndef BIN
      global SubBytex
      global _SubBytex
    %endif

SubBytex:
_SubBytex:
    mov    al, 252
    jecxz  L2                ; if(x) {
    call   L0
k:
    db     0xfc, 0xdc, 0xce, 0xfa, 0xe8, 0xf8, 0xea, 0xde,
    db     0xcc, 0xec, 0xfe, 0xca, 0xd8, 0xc8, 0xda, 0xee, 0xfc
s:
    db     0x01, 0xdd, 0x92, 0x4f, 0x93, 0x99, 0x0b, 0x44,
    db     0xd6, 0xd7, 0x4e, 0xdc, 0x98, 0x0a, 0x45
L0:
    pop    ebx
    mov    al, 1             ; y = 1
    cdq                      ; z = 0
L1:
    inc    edx               ; z++
    add    al, al            ; y = y + y
    jnc    $+4               ; skip XOR if no carry
    xor    al, 29            ;
    cmp    al, cl            ; if(y != x) goto L1
    jne    L1
    xchg   eax, edx          ; al = z
    aam    17                ; al|x = z % 17, ah|z = z / 17
    mov    cl, ah            ; cl = z
    cmove  eax, ecx          ; if(x == 0) al = z else al = x
    xlatb                    ; al = k[z] or k[x]
    jz     L2                ; if(x == 0) goto L2
    xor    al, [ebx+ecx+17]  ; k[x] ^= k[z]
L2:
    ret

```

# Disassembled 32-bit code

```
00000000  B0FC              mov al,0xfc
00000002  E345              jecxz 0x49
00000004  E820000000        call dword 0x29
; k[] = 0xfc, 0xdc, 0xce, 0xfa, 0xe8, 0xf8, 0xea, 0xde,
;       0xcc, 0xec, 0xfe, 0xca, 0xd8, 0xc8, 0xda, 0xee, 0xfc
; s[] = 0x01, 0xdd, 0x92, 0x4f, 0x93, 0x99, 0x0b, 0x44,
;       0xd6, 0xd7, 0x4e, 0xdc, 0x98, 0x0a, 0x45
00000029  5B                pop ebx
0000002A  B001              mov al,0x1
0000002C  99                cdq
0000002D  42                inc edx
0000002E  00C0              add al,al
00000030  7302              jnc 0x34
00000032  341D              xor al,0x1d
00000034  38C8              cmp al,cl
00000036  75F5              jnz 0x2d
00000038  92                xchg eax,edx
00000039  D411              aam 0x11
0000003B  88E1              mov cl,ah
0000003D  0F44C1            cmovz eax,ecx
00000040  D7                xlatb
00000041  7404              jz 0x47
00000043  32440B11          xor al,[ebx+ecx+0x11]
00000047  C3                ret

```
> 41 votes

# Answer
# CJam, ~~72~~ ~~67~~ ~~66~~ 63 bytes

```
ri{_2md142*^}es*]2#~Hmd{5\}e|Fm2b"Ý0$&Ü™ÖD�’
˜×EO“N".*Lts:^i

```

`es*` repeats something by the current timestamp, which is a big number, and it would take too long to finish.

Actually testable version, 64 bytes:

```
ri{_2md142*^}256*]2#~Hmd{5\}e|Fm2b"Ý0$&Ü™ÖD�’
˜×EO“N".*Lts:^i

```

```
00000000: 7269 7b5f 326d 6431 3432 2a5e 7d32 3536  ri{_2md142*^}256
00000010: 2a5d 3223 7e48 6d64 7b35 5c7d 657c 466d  *]2#~Hmd{5\}e|Fm
00000020: 3262 22dd 3024 2612 dc99 d644 0092 0b0a  2b".0$&....D....
00000030: 98d7 454f 934e 0122 2e2a 4c74 733a 5e69  ..EO.N.".*Lts:^i

```

Try it online!

Try all online!

To run this code (on a Linux machine), you need to add the line `en_US.ISO-8859-1 ISO-8859-1` into `/etc/locale.gen` and run `locale-gen`. Then you could use:

```
LANG=en_US.ISO-8859-1 java -jar cjam.jar <source file>

```

Or you could try this equivalent 72 byte UTF-8 version:

```
00000000: 7269 7b5f 326d 6431 3432 2a5e 7d32 3536  ri{_2md142*^}256
00000010: 2a5d 3223 7e48 6d64 7b35 5c7d 657c 466d  *]2#~Hmd{5\}e|Fm
00000020: 3262 22c3 9d30 2426 12c3 9cc2 99c3 9644  2b"..0$&.......D
00000030: 00c2 920b 0ac2 98c3 9745 4fc2 934e 0122  .........EO..N."
00000040: 2e2a 4c74 733a 5e69                      .*Lts:^i

```

### Explanation

```
ri               e# Read input.
{_2md142*^}      e# Copy and divide by 2. If remainder is 1, xor 142.
es*]             e# Repeat a lot of times and wrap all results in an array.
2#               e# Find the first occurrence of 2, -1 if not found.
~                e# Increment and negate.
Hmd              e# Divmod 17. Both the quotient and remainder would be negated.
{5\}e|           e# If remainder = 0, return 5, quotient instead.
Fm2b             e# Subtract 15 from the remainder and expand in base 2.
                 e# In CJam, base conversion only applies to the absolute value.
"...".*          e# Filter 221, 48, 36, 38, 18 by the bits.
                 e# 221, the characters after 18
                 e#   and 18 itself in case quotient - 15 = -15 won't change.
Lt               e# Remove the item s[quotient] xor 220.
                 e# Quotient is 0, 5 or a negative integer from the end,
                 e#   which doesn't overlap with the previously filtered items.
s                e# Flatten, because some characters become strings after the process.
:^i              e# Reduce by xor and make sure the result is an integer.

```

The characters in the string are:

* 221. See below.
* 48, 36, 38, 18. It's the linear decomposition of k based on the characteristics of L in the question.
* 220, the filler value of array s when only array k is used.
* Array s xor 220 reversed, except for the last element, or the first element before reversed, which is the 221 at the beginning of the string.
> 29 votes

# Answer
# Jelly ~~71~~ 59 bytes

```
H^142ƊHḂ?Ƭi2d17U⁸⁴;$Ḣ?$CµṪạ⁴B¬T;;6ị“Œ0$&ØŀWð⁺Ṫ\ḢĠVı⁻¹]°Ẇ‘^/

```

Try it online!

Verify all possibilities

Now rewritten using a reworked version of jimmy23013’s clever CJam answer so be sure to upvote that one too! Uses only 472 bits (28.0% of the naive approach). @jimmy23013 has also saved another byte!

### Explanation

Stage 1

```
         Ƭ        | Repeat the following until no new entries:
       Ḃ?         | - If odd:
     Ɗ            |   - Then following as a monad:
H                 |     - Halve
 ^142             |     - Xor 142
      H           |   - Else: Halve
          i2      | Index of 2 in this list

```

Stage 2

```
d17           | Divmod 17
          $   | Following as a monad:
   U          | - Reverse order
        Ḣ?    | - If head (remainder from divmod) non-zero:
    ⁸         |   - Then: left argument [quotient, remainder]
     ⁴;$      |   - Else: [16, quotient]
           C  | Complement (1 minus)
            µ | Start a new monadic chain

```

Stage 3

```
Ṫ                   | Tail (Complement of remainder or quotient from stage 2)
 ạ⁴                 | Absolute difference from 16
   B                | Convert to binary
    ¬               | Not
     T              | Indices of true values
      ;             | Concatenate (to the other value from stage 2)
       ;6           | Concatenate to 6
         ị“Œ...Ẇ‘   | Index into [19,48,36,38,18,238,87,24,138,206,92,197,196,86,25,139,129,93,128,207]
                 ^/ | Reduce using xor

```

# Original approach

# Jelly, ~~71~~ 66 bytes

```
H^142ƊHḂ?Ƭi2d:j@“ÐḌ‘ɗ%?17ị"“p?Ä>4ɼḋ{zẉq5ʂċ¡Ḅ“`rFTDVbpPBvdtfR@‘^ƒ17

```

Try it online!

Verify all possibilities

A monadic link or full program that takes a single argument and returns the relevant value of `pi[x]`. This is 536 bits, so under a third of the naive storage of pi.

Saved 3 bytes by using the method for finding `l` from jimmy23013’s CJam answer so be sure to upvote that one too!

### Explanation

Stage 1

```
         Ƭ        | Repeat the following until no new entries:
       Ḃ?         | - If odd:
     Ɗ            |   - Then following as a monad:
H                 |     - Halve
 ^142             |     - Xor 142
      H           |   - Else: Halve
          i2      | Index of 2 in this list

```

Stage 2

```
         %?17  | If not divisible by 17
d              | - Then divmod 17
        ɗ      | - Else following as a dyad (using 17 as right argument)
 :             |   - Integer divide by 17
  j@“ÐḌ‘       |   - Join the list 15,173 by the quotient

```

Stage 3

```
ị"“p...Ḅ“`...@‘     | Index into two compressed lists of integers using the output from stage 2 (separate list for each output from stage 2). The third output from stage 2 will be left untouched
               ^ƒ17 | Finally reduce using Xor and 17 as the first argument

```
> 26 votes

# Answer
# C (gcc), ~~157 148 140~~ 139 bytes

Modest improvement over the C example.

```
l,b=17,*k=L"@`rFTDVbpPBvdtfR@";p(x){for(l=256;--l*~-x;)x=2*x^x/128*285;return l%b?k[l%b]^"\xcer?\4@6\xc8\t{|\3q5\xc7\n"[l/b]-b:k[l/b]^188;}

```

Try it online!

# C (gcc), ~~150 142 127~~ 126 bytes

This one depends on gcc and x86 and UTF-8 quirks.

```
l,*k=L"@`rFTDVbpPBvdtfR@";p(x){for(l=256;--l*~-x;)x=2*x^x/128*285;x=l%17?k[l%17]^L"½a.ó/%·øjkò`$¶ù"[l/17]:k[l/17]^188;}

```

Try it online!

Thanks to @XavierBonnetain for -1 and less undefined behaviour.
> 18 votes

# Answer
# Stax, ~~65~~ ~~64~~ ~~62~~ ~~59~~ 58 bytes

```
ç∙¼≥2▼Uó╤áπ╙º┐╩♫∟öv◘≥δ♦Θ╫»─kRWÑâBG")≥ö0╥kƒg┬^S ΔrΩ►╣Wü Ü╕║

```

Run and debug it

Unfortunately, this program uses some instructions that internally use some deprecated stax instructions. I just forgot to update their implementation. This causes some spurious warning to appear, but the results are still correct.

This is inspired by jimmy23013's excellent answer. Some parts have been changed to suit stax better.

Stax programs written in printable ASCII have an alternative representation that saves slightly more than 1 bit per byte, since there are only 95 printable ASCII characters.

Here's the ascii representation of this program formatted for "readability" with comments.

```
{                       begin block
  2|%142*S              given n, calculate (n/2)^(n%2*142)
                         - this seems to be the inverse of the operation in the while loop
gu                      use block to generate distinct values until duplicate is found
                         - starting from the input; result will be an array of generated values
2I^                     1-based index of 2 in the generated values
17|%                    divmod 17
c{Us}?                  if the remainder is zero, then use (-1, quotient) instead
~                       push the top of the main stack to the input stack for later use
"i1{%oBTq\z^7pSt+cS4"   ascii string literal; will be transformed into a variant of `s`
./o{H|EF                interpret ascii codes as base-94 integer
                         - this is tolerant of digits that exceed the base
                        then encode big constant as into base 222 digits
                         - this produces an array similar to s
                         - 0 has been appended, and all elements xor 220
@                       use the quotient to index into this array
"jr+R"!                 packed integer array literal [18, 38, 36, 48]
F                       for each, execute the rest of the program
  ;                     peek from the input array, stored earlier
  v                     decrement
  i:@                   get the i-th bit where i is the iteration index 0..3
  *                     multiply the bit by value from the array literal
  S                     xor with result so far
                        after the loop, the top of the stack is printed implicitly

```

Run this one

Modified version to run for all inputs 0..255
> 15 votes

# Answer
# 05AB1E, ~~101~~ ~~100~~ ~~98~~ ~~97~~ ~~95~~ 94 bytes

```
U•α">η≠ε∍$<Θγ\&@(Σα•₅вV₁[<ÐX*Q#X·₁%Xžy÷Ƶ¹*₁%^₁%U}D17©%DĀiYsès®÷•¾#kôlb¸ù,-ó"a·ú•₅вë\Ƶ∞s®÷Y}sè^

```

-3 bytes thanks to *@Grimy*.

Try it online or verify all test cases.

**Explanation:**

Port of Xavier Bonnetain's C function (1106 bits version) from here, with the same improvement *@ceilingcat* made in his C answer to save 3 bytes, so make sure to upvote him!

```
U                    # Store the (implicit) input in variable `X`
•α">η≠ε∍$<Θγ\&@(Σα• "# Push compressed integer 20576992798525946719126649319401629993024
 ₅в                  # Converted to base-255 as list:
                     #  [64,96,114,70,84,68,86,98,112,80,66,118,100,116,102,82,64]
   V                 # Pop and store this list in variable `Y`
₁                    # Push `i` = 256
 [                   # Start an infinite loop:
  <                  #  Decrease `i` by 1
   Ð                 #  Triplicate `i`
    X*Q              #  If `i` multiplied by `X` is equal to `i` (i==0 or X==1):
       #             #   Stop the infinite loop
  X·₁%               #  Calculate double(`X`) modulo-256
                     #  (NOTE: all the modulo-256 are to mimic an unsigned char in C)
  Xžy÷               #  Calculate `X` integer-divided by builtin integer 128,
      Ƶ¹*            #  multiplied by compressed integer 285,
         ₁%          #  modulo-256
  ^                  #  Bitwise-XOR those together
   ₁%                #  And take modulo-256 again
  U                  #  Then pop and store it as new `X`
 }D                  # After the loop: Duplicate the resulting `i`
   17©               # Push 17 (and store it in variable `®` without popping)
      %              # Calculate `i` modulo-17
       D             # Duplicate it
        Āi           # If it's NOT 0:
          Ysè        #  Index the duplicated `i` modulo-17 into list `Y`
          s®÷        #  Calculate `i` integer-divided by 17
          •¾#kôlb¸ù,-ó"a·ú•
                    "#  Push compressed integer 930891775969900394811589640717060184
           ₅в        #  Converted to base-255 as list:
                     #   [189,97,46,243,47,37,183,248,106,107,242,96,36,182,249]
         ë           # Else (`i` == 0):
          \          #  Discard the duplicated `i` modulo-17, since we don't need it
          Ƶ∞         #  Push compressed integer 188
          s®÷        #  Calculate `i` integer-divided by 17
          Y          #  Push list `Y`
         }s          # After the if-else: swap the integer and list on the stack
           è         # And index the `i` modulo/integer-divided by 17 into the list
            ^        # Then Bitwise-XOR the top two together
                     # (after which the top of the stack is output implicitly as result)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•α">η≠ε∍$<Θγ\&@(Σα•` is `20576992798525946719126649319401629993024`; `•α">η≠ε∍$<Θγ\&@(Σα•₅в` is `[64,96,114,70,84,68,86,98,112,80,66,118,100,116,102,82,64]`; `Ƶ¹` is `285`; `•¾#kôlb¸ù,-ó"a·ú•` is `930891775969900394811589640717060184`; `•¾#kôlb¸ù,-ó"a·ú•₅в` is `[189,97,46,243,47,37,183,248,106,107,242,96,36,182,249]`; and `Ƶ∞` is `188`.
> 10 votes

# Answer
# Python 3, 151 bytes

```
f=lambda x,l=255,k=b'@`rFTDVbpPBvdtfR@':f(x*2^x//128*285,l-1)if~-x*l else[k[l%17]^(0x450a98dc4ed7d6440b99934f92dd01>>l//17*8&255),k[l//17]][l%17<1]^188

```

Try it online!

A function that implements the permutation. The code uses only 7-bit ASCII chars.

Encodes `k` as a Python 3 bytestring, shifted `^64` into the printable range. In contrast, `s` is encoded as the base-256 digits of a numerical constant, and the digits are extracted as `[number]>>[shift]*8&255`. This was shorter than encoding `s` in a string due to the number of escape characters this required, even with an optimal shift `^160` to minimize those.

The discrete-log computation is done backwards. The update `x=x*2^x//128*285` loops forward in the cyclic group by simulating multiplying by the generate, until it reaches the identity `x=1`. We start the discrete log at `l=255` (the cycle length), and decrement it each iteration. To handle the `x=0` case and make it not loop forever, we also terminate when `l=0`, which makes `x=0` map to `l=0` as specified.

---

Python 2 loses out on not having nice bytestrings, so we need to do `map(ord,...)` (ArBo saved a byte here). It lets us use `/` rather than `//` for integer division.

**Python 2, 156 bytes**

```
f=lambda x,l=255,k=map(ord,'@`rFTDVbpPBvdtfR@'):f(x*2^x/128*285,l-1)if~-x*l else[k[l%17]^(0x450a98dc4ed7d6440b99934f92dd01>>l/17*8&255),k[l/17]][l%17<1]^188

```

Try it online!
> 9 votes

# Answer
# JavaScript (ES6), 139 bytes

Similar to the Node.js version, but using characters beyond the ASCII range.

```
f=(x,l=256,b=17,k=i=>"@`rFTDVbpPBvdtfR@¬p?â>4¦é{zãq5§è".charCodeAt(i))=>--l*x^l?f(x+x^(x>>7)*285,l):l%b?k(l%b)^k(b+l/b)^b:k(l/b)^188

```

Try it online!

---

# JavaScript (Node.js),  ~~149~~  148 bytes

Based on Xavier Bonnetain's C implementation (which is presented here).

```
f=(x,l=256,b=17,k=i=>Buffer("@`rFTDVbpPBvdtfR@,p?b>4&i{zcq5'h")[~~i]|3302528>>i-b&128)=>--l*x^l?f(x+x^(x>>7)*285,l):l%b?k(l%b)^k(b+l/b)^b:k(l/b)^188

```

Try it online!

### Encoding

In Xavier's original answer, the tables `s[]` and `k[]` are stored in the following string:

```
"@`rFTDVbpPBvdtfR@\xacp?\xe2>4\xa6\xe9{z\xe3q5\xa7\xe8"
 \_______________/\__________________________________/
         k                         s

```

The first 17 characters are the ASCII representations of `k[i] XOR 64` and the next 15 characters are the ASCII representations of `s[i-17] XOR 173`, or `s[i-17] XOR 64 XOR 17 XOR 252`.

All the ASCII codes for `k[i] XOR 64` are matching printable characters, but 7 ASCII codes for `s[i-17] XOR 173` are beyond \\$126\\$ and need to be escaped. We force them into the printable range by subtracting \\$128\\$.

Here is what we get:

```
original value : 172 112  63 226  62  52 166 233 123 122 227 113  53 167 232
subtract 128?  :   1   0   0   1   0   0   1   1   0   0   1   0   0   1   1
result         :  44 112  63  98  62  52  38 105 123 122  99 113  53  39 104
as ASCII       : "," "p" "?" "b" ">" "4" "&" "i" "{" "z" "c" "q" "5" "'" "h"

```

By reversing the bitmask formed by the 2<sup>nd</sup> row in the above table, we get `110010011001001` in binary, or \\$25801\\$ in decimal.

This bitmask is multiplied by \\$128\\$, so that we can directly perform a bitwise OR with the extracted bit. Hence the formula:

```
| 3302528 >> i - b & 128

```

---

# Building \\$s\\$

*NB: This is just a side note, unrelated to the above answers.*

This code demonstrates how \\$s\\$ can be built by XOR'ing only 4 distinct values together.

In this example, we are using all 15 non-empty subsets of \\$\\{1, 11, 79, 146\\}\\$, but other values can be chosen.

```
console.log(
  [ 0b0001, 0b1100, 0b1000, 0b0100, 0b1001, 0b1010, 0b0010, 0b0110,
    0b1110, 0b1111, 0b0101, 0b1101, 0b1011, 0b0011, 0b0111
  ].map(x =>
    [ 1, 11, 79, 146 ].reduce((p, c, i) =>
      p ^= x >> i & 1 && c,
      0
    )
  )
)

```

Try it online!
> 8 votes

# Answer
# Python 3, 182 bytes

```
def p(x,t=b'@`rFTDVbpPBvdtfR@\xacp?\xe2>4\xa6\xe9{z\xe3q5\xa7\xe8',l=255,d=17):
 if x<2:return 252-14*x
 while~-x:x=x*2^(x>>7)*285;l-=1
 return(188^t[l//d],d^t[l%d]^t[d+l//d])[l%d>0]

```

Try it online!

Python isn't going to win first prize here, but this is still a 10-byte golf of the best Python program here.

# Python 3, 176 bytes

```
p=lambda x,l=255,t=b'@`rFTDVbpPBvdtfR@\xacp?\xe2>4\xa6\xe9{z\xe3q5\xa7\xe8',d=17:2>x<l>254and-14*x+252or(p(x*2^(x>>7)*285,l-1)if~-x else(188^t[l//d],d^t[l%d]^t[d+l//d])[l%d>0])

```

Try it online!

As a lambda, it's six bytes shorter still. It pains me to have to use `if... else`, but I don't see another option for short-circuiting, given how 0 is a possible answer.

# Python 3, 173 bytes

```
p=lambda x,l=255,t=bytes('@`rFTDVbpPBvdtfR@¬p?â>4¦é{zãq5§è','l1'),d=17:2>x<l>254and-14*x+252or(p(x*2^(x>>7)*285,l-1)if~-x else(188^t[l//d],d^t[l%d]^t[d+l//d])[l%d>0])

```

Try it online!

Even shorter in bytes (though I'm not sure about bits, because this isn't pure ASCII anymore), courtesy of ovs.
> 4 votes

# Answer
# C# (Visual C# Interactive Compiler), 141 bytes

```
x=>{var k="@`rFTDVbpPBvdtfR@¬p?â>4¦é{zãq5§è";int l=256,b=17;for(;--l*x!=l;)x=2*x^x/128*285;return l%b>0?k[l%b]^k[b+l/b]^b:k[l/b]^188;}

```

Just a port of the example solution, ported to C#.

Try it online!
> 4 votes

# Answer
# Rust, ~~170~~ 163 bytes

```
|mut x|{let(k,mut l)=(b"QqcWEUGsaASguewCQ\xacp?\xe2>4\xa6\xe9{z\xe3q5\xa7\xe8",255);while l*x!=l{x=2*x^x/128*285;l-=1}(if l%17>0{l+=289;k[l%17]}else{173})^k[l/17]}

```

Try it online!

This is a port of my solution in C, with a slightly different string, that do not require to xor 17. I expect that most of the solutions based the string "@\`rFTDVbpPBvdtfR@\xacp?\xe2\>4\xa6\xe9{z\xe3q5\xa7\xe8" can be improved as well (just change the string, remove the xor 17, and xor 173 instead of 188).

I removed one of the lookups by conditionally adding `17*17` to `l`, as we (more or less) did in the ARM machine code solution.

Rust has type inference and closures, but its casts (even for booleans or between integers) are always explicit, mutability has to be marked, it does not have a ternary operator, integer operations, by default, panic on overflow, and mutating operations (`l+=1`) returns unit. I did not manage to obtain a shorter solution with iterators, as closures+mapping is still fairly verbose.

This seems to make Rust a pretty bad choice for golfing. Nevertheless, even in a language that stresses readability and safety over conciseness, we're far too short.

Update: used an anonymous function, from manatwork's suggestion.
> 4 votes

# Answer
# 05AB1E, 74 bytes

```
₄FÐ;sÉiƵf^])2k>17‰Dθ_i¦16š}<(Rć16α2в≠ƶ0Kì6ª•5›@¾ÂÌLìÁŒ©.ðǝš«YWǝŠ•ƵŠвs<è.«^

```

Port of *@NickKennedy*'s first Jelly answer. I was working on a port of *@jimmy23013*'s CJam answer directly, but I was already at 78 bytes and still had to fix a bug, so it would have been larger. This can definitely still be golfed quite a bit, though.

Try it online or verify all test cases.

**Explanation:**

```
₄F              # Loop 1000 times:
  Ð             #  Triplicate the current value
                #  (which is the implicit input in the first iteration)
   ;            #  Halve it
    s           #  Swap to take the integer again
     Éi         #  If it's odd:
       Ƶf^      #   Bitwise-XOR it with compressed integer 142
]               # Close the if-statement and loop
 )              # Wrap all values on the stack into a list
  2k            # Get the 0-based index of 2 (or -1 if not found)
    >           # Increase it by 1 to make it 1-based (or 0 if not found)
     17‰        # Take the divmod-17 of this
Dθ_i    }       # If the remainder of the divmod is 0:
    ¦16š        #  Replace the quotient with 16
         <      # Decrease both values by 1
          (     # And then negate it
R               # Reverse the pair
 ć              # Extract head; push head and remainder-list
  16α           # Get the absolute difference between the head and 16
     2в         # Convert it to binary (as digit-list)
       ≠        # Invert booleans (0 becomes 1; 1 becomes 0)
        ƶ       # Multiply all by their 1-based indices
         0K     # And remove all 0s
           ì    # And prepend this in front of the remainder-list
            6ª  # And also append a trailing 6
•5›@¾ÂÌLìÁŒ©.ðǝš«YWǝŠ•
                # Push compressed integer 29709448685778434533295690952203992295278432248
  ƵŠв           # Converted to base-239 as list:
                #  [19,48,36,38,18,238,87,24,138,206,92,197,196,86,25,139,129,93,128,207]
     s          # Swap to take the earlier created list again
      <         # Subtract each by 1 to make them 0-based
       è        # And index them into this list
.«^             # And finally reduce all values by bitwise XOR-ing them
                # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `Ƶf` is `142`; `•5›@¾ÂÌLìÁŒ©.ðǝš«YWǝŠ•` is `29709448685778434533295690952203992295278432248`, `ƵŠ` is `239`; and `•5›@¾ÂÌLìÁŒ©.ðǝš«YWǝŠ•ƵŠв` is `[19,48,36,38,18,238,87,24,138,206,92,197,196,86,25,139,129,93,128,207]`.
> 2 votes

---
Tags: code-golf, math, kolmogorov-complexity, cryptography
---


title: Close-Knit Words

text:
# Question
Title: Close-Knit Words
## Introduction

According to Rand Al'Thor's post in the Puzzling SE, a close-knit word is any word that contains three alphabetically consecutive letters (in any order).

Words like **education**, **foghorn** and **cabaret** are all considered close-knit words whereas words like **learning**, **klaxon** and **perform** are not close-knit words.

## Challenge

The challenge is to code-golf a program capable of taking a single word as input (assumed lower case, for all intents and purposes) and to return output that (if available) lists all consecutive letter sets (also in lower case) if it is a close-knit word, and empty output if it is not a close-knit word.

## Examples

```
Input: education
Output: cde

Input: foghorn
Output: fgh

Input: cabaret
Output: abc

Input: hijacking
Output: ghi, hij, ijk

Input: pneumonia
Output: mno, nop

Input: klaxon
Output: <<no output>>

Input: perform
Output: <<no output>>

Input: learning
Output: <<no output>>

```

## Rules

1. Whereas input is to be assumed to be a single lower-case word and output must be lower-case, the nature of the output will vary according to the choice of your coding language. Please select a form of output that will best suit the nature of the challenge, whether it be STDOUT, file output, array, etc.
2. Because this is code-golf, it will be a case of lowest number of bytes being the clear winner.
3. No silly loopholes.
4. I will not accept answers that have the consecutive letters in non-alphabetical order... So `cab` will not be deemed a suitable output for `cabaret`, for example.
5. Special note, while the "triplets" don't necessarily have to be in alphabetical order, but the characters within the triplets must be... so in the case of the word "performance", for example, the output `mno,nop` will be accepted, as will `nop,mno`. In the case of the word "hijacking", there are six ways that the triplets of `ghi`, `hij` and `ijk` could be arranged in a list, and all six permutations are acceptable as output.

Other than that, on your marks, get set, golf!

# Answer
# 05AB1E, ~~7~~ ~~6~~ 5 bytes

Code:

```
3ãAŒÃ

```

Explanation:

```
3ã      # Cartesian product × 3 with input
  AŒ    # All substrings of the alphabet
    Ã   # Setwise intersection

```

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

# Answer
## Python 3.5, 68 bytes

```
w=input()
a=0
while 1:s='%c'*3%(a,a+1,a+2);a+=1;{*s}-{*w}or print(s)

```

Prints output strings, and terminates with error when the character value gets too large.

Generates all strings of three consecutive and prints those that are a subset of the input word.
> 10 votes

# Answer
# Pyth - ~~11~~ ~~10~~ ~~8~~ 7 bytes

Super brute force method.

```
@^z3.:G

```

Test Suite.

```
@            Setwise intersection, finds common strings between the two lists
 ^           Cartesian product
  z          Input
  3          Of length 3
 .:          Substrings. Without second input finds all substrings which is ok
  G          Lowercase aphabet

```
> 8 votes

# Answer
## JavaScript (ES6), ~~95~~ 90 bytes

```
f=
s=>[...s].map(c=>a[parseInt(c,36)]=c,a=[])&&a.map((c,i)=>c+a[i+1]+a[i+2]).filter(c=>!c[3])
;
```

```
<input oninput="o.textContent=f(this.value).join`, `"><div id=o>
```

Missing values concatenate as `undefined`, so the resulting string contains greater than 3 characters. I borrowed the `!c[3]` trick from @ETHproductions to save 5 bytes.
> 7 votes

# Answer
# Jelly, 7 bytes

```
ØaẆfṗ3$

```

This is a monadic link. Try it online!

### How it works

```
ØaẆfṗ3$  Monadic link. Argument: s (string)

Øa       Yield the lowercase alphabet, i.e., a := "abcdefghijklmnopqrstuvwxyz".
  Ẇ      Window; yields all substrings of a.
      $  Combine the two links to the left into a monadic chain.
    ṗ3   Take the third Cartesian power of s, yielding all combinations of three
         characters that can be formed from the letters in s.
   f     Filter; keep only those substrings of a that appear in the Cart. power.

```
> 7 votes

# Answer
## Haskell, 48 bytes

```
f w=filter(all(`elem`w))[take 3[c..]|c<-['a'..]]

```

Generates all triples of three consecutive characters, takes those that use only letters in the input.

---

**53 bytes:**

```
f w=filter(all(`elem`w))[[pred$pred c..c]|c<-['c'..]]

```

The list `['c'..]` contains all unicode characters from `'c'` onward. The list comprehension `[[pred$pred c..c]|c<-['c'..]]` turns them into all strings of 3 consecutive characters from `"abc"` onward. We step backwards with `[pred$pred c..c]` instead of forwards with `[c..succ$succ c]` to avoid an error when taking the successor of the highest unicode character.

These triples are filtered for those that only use letters in the input.
> 4 votes

# Answer
# PHP, 100 bytes

```
for($a="abc",$i=98;$i<123;$a=substr($a,1).chr(++$i))if(strstr(count_chars($argv[1],3),$a))echo"$a,";

```

takes input as command line argument; prints a trailing comma. run with `-r`.
> 4 votes

# Answer
# Python 3.5, 78 bytes

```
s={*input()}
for c in s:o=ord(c);a=chr(o-2);b=chr(o-1);s>{a,b}and print(a+b+c)

```
> 4 votes

# Answer
# C, ~~175~~ 174 bytes

```
main(_,a,m,n)char**a;{char*s=a[1],*t=s;while(*++s)while(s>t&&(n=s[-1])>=*s){m=(*s^n)?*s:0;*s=n;*--s=m;!*t&&++t;}for(;t[1]&t[2];++t)*t==t[1]-1&&*t==t[2]-2&&printf("%.3s ",t);}

```

indented:

```
main(_,a,m,n)char**a;
{
  char*s=a[1],*t=s;
  while(*++s)
    while(s>t&&(n=s[-1])>=*s){
      m=(*s^n)?*s:0;
      *s=n;
      *--s=m;
      !*t&&++t;
    }
  for(;t[1]&t[2];++t)
    *t==t[1]-1&&*t==t[2]-2&&printf("%.3s ",t);
}

```

While doing the sort it replaces duplicate values with 0s, these 0s get sorted to the beginning of the word. Looking for the consecutive values is then trivial.
> 4 votes

# Answer
# MATL, 13 bytes

```
2Y23YCtjmAZ)!

```

Try it online!

```
2Y2    % Push string of lowercase alphabet
3YC    % 2D char array with sliding blocks of size 3, each on a column
t      % Duplicate
j      % Take input
m      % Member function: true for elements of the 2D array that are in the input
A      % All: true for columns that consist of all true values
Z)     % Use as logical index into the columns of the 2D char array
!      % Transpose. Implicitly display

```
> 3 votes

# Answer
# Perl, 36 bytes

Includes +1 for `-n`

Give input on STDIN:

```
perl -nE 'join("",a..z)=~/[$_]{3}(?{say$&})^/' <<< "hijacking"

```

Just the code:

```
join("",a..z)=~/[$_]{3}(?{say$&})^/

```
> 3 votes

# Answer
# T-SQL, 153 bytes

Had to react on the comment from WallyWest, about it being long time since last TSQL answer. Answer was partly inspired by Brian J's answer

**Golfed:**

```
USE MASTER
DECLARE @ varchar(max)='hijacking'

;WITH C as(SELECT distinct ascii(substring(@,number,1))z FROM spt_values)SELECT CHAR(C.z)+CHAR(D.z)+CHAR(E.z)FROM C,C D,C E WHERE c.z+1=d.z and d.z=e.z-1

```

**Fiddle**

**Ungolfed:**

```
USE MASTER -- can be left out if the master database is already being used
DECLARE @ varchar(max)='hijacking'

;WITH C as
(
  SELECT distinct ascii(substring(@,number,1))z
  FROM spt_values
)
SELECT CHAR(C.z)+CHAR(D.z)+CHAR(E.z)
FROM C,C D,C E
WHERE c.z+1=d.z and d.z=e.z-1

```
> 3 votes

# Answer
## Haskell, ~~63~~ ~~60~~ 52 bytes

```
f w=[x|x<-take 3<$>scanr(:)"_"['a'..],all(`elem`w)x]

```

Usage example: `f "hijacking"` -\> `["ghi","hij","ijk"]`.

`scanr(:)"_"['a'..]` builds a list with the tails of the list of all unicode chars starting with `'a'` and lets it end with a `'_'`, i.e. `["abcde...\1114111_", "bcde...\1114111_", "cde...\1114111_", ..., "\1114109\1114110\1114111_", "\1114110\1114111_", "\1114111_", "_"]`. Then we take up to three chars of each string and bind it to `x`. Keep all `x` where every letter of it is in the input parameter `w`.

Edit: @xnor saved ~~3~~ 7 bytes. Thanks!
> 2 votes

# Answer
# Python 3.5, ~~114~~ ~~111~~ ~~88~~ ~~80~~ 79 bytes:

```
lambda X,W=[*map(chr,range(65,91))]:[i*({*X}>={*i})for i in zip(W,W[1:],W[2:])]

```

An anonymous lambda function. Takes input as an *uppercase* string and outputs an array of tuples, with the ones filled with three *uppercase* characters representing all sets of `3` consecutive letters that appear in the input. For example,

```
[(), (), (), (), (), (), ('G', 'H', 'I'), ('H', 'I', 'J'), ('I', 'J', 'K'), (), (), (), (), (), (), (), (), (), (), (), (), (), ()]

```

would be the output for input `HIJACKING`. This output format has been confirmed to be okay by OP. So has the only uppercase input format. However, if you want to input in *only* lowercase, simply replace `range(65,91)` with `range(97,123)`, adding one more byte.

Repl.it with all Test Cases!

## Explanation:

Basically what is happening here is:

1. A list, `W`, is created using `W=[*map(chr,range(65,91))]`, which contains all the uppercase letters in the English alphabet. Because of this, an uppercase input is *always* required.
2. For each tuple, `i`, in a list, which we will call `U`, containing *all* three consecutive letter tuples, i.e.:

```
U=[('A','B','C'),('B','C','D'),('C','D','E'),...]

```

created by `zip(W,W[1:],W[2:])`, each `i` is fully added to the output list as long as all elements in the set version of `i` (`{*i}`) are in the set version of input `X` (`{*X}`), i.e. `{*X}>={*i}`, i.e. `X` is a *superset* of `i`. Otherwise, the empty version of `i` (`()`) is added to the list.
3. Once all the tuples have been gone through with the matches fully added, the list is returned as the final output.
> 2 votes

# Answer
# T-SQL (SQL Server 2014), 217 bytes

## Golfed

```
declare @ table(a char)declare @i int=1while @i<=len(@a)begin insert into @ values(SUBSTRING(@a,@i,1))set @i+=1 end select distinct t.a+u.a+v.a from @ t,@ u,@ v where ASCII(t.a)+1=ASCII(u.a)and ASCII(u.a)+1=ASCII(v.a)

```

## Usage

First declare the variable @a as a char of some sort and assign the input like so

```
declare @a varchar(max) = 'pneumoultramicroscopicsilicovolcanoconiosis'

```

I didn't count the declare as part of my code, but I didn't find a sql standard for input, so I'm willing to change my counting

Output will either be one row for each triple, or no rows if the word is not close knit

## Ungolfed

```
declare @temp table ( letter char(1) ) -- table to hold each letter of the word

declare @i int = 1

while @i <= len(@input) -- split each letter, and each row in @temp will have one letter
begin
    insert into @temp values (SUBSTRING(@input, @i, 1))
    set @i = @i + 1
end

-- join the letters table to itself to get three letter triples, where the three are in adjacent increasing order
-- use distinct because there might be duplicates in the word
select distinct t1.letter + t2.letter + t3.letter
from @temp t1
cross apply @temp t2
cross apply @temp t3
where ASCII(t1.letter) + 1 = ASCII(t2.letter)
and ASCII(t2.letter) + 1 = ASCII(t3.letter)

```
> 2 votes

# Answer
## **R, 220 bytes**

My solution is pretty straightforward. It loops through the possible three letter combinations, loops through and checks the characters of the entered string against the three consecutive letters, and adds them to a string. The string is then only printed when three letters are found (c==4).

```
f<-function(w){if(nchar(w)>2){for(i in 1:24){
c<-1
t<-""
for(k in 1:3){for(j in 1:nchar(w)){if(substr(w,j,j)==intToUtf8(95+k+i)&c<4){
t<-paste(t,substr(w,j,j),sep="")
c<-c+1
break
}}}
if(c==4){print(paste(t))}}}}

```

## input/output

```
> f("education")
> [1] "cde"
> > f("foghorn")
> [1] "fgh"
> > f("cabaret")
> [1] "abc"
> > f("hijacking")
> [1] "ghi"
> [1] "hij"
> [1] "ijk"
> > f("pneumonia")
> [1] "mno"
> [1] "nop"
> > f("klaxon")
> > f("perform")
> > f("learning")
> >

```
> 2 votes

# Answer
# Actually, 13 bytes

Golfing suggestions welcome. Try it online!

```
S3@╧`εj`M3úV∩

```

**Ungolfing**

```
                Implicit input string s.
S               sorted(s).
 3@╧            Push all length-3 combinations of s.
    `εj`M       Join all of those combinations into single strings.
         3úV    Push all slices of the lowercase alphabet of length 1 <= n <= b
            ∩   Push the intersection of the combinations and slices.
                Implicit return.

```
> 2 votes

# Answer
# Scala, 59 bytes

```
(s:Set[Char])=>'a'to'z'sliding 3 filter{_.toSet subsetOf s}

```

Ungolfed:

```
(s:Set[Char]) => ('a' to 'z').sliding(3).filter{threeChars => threeChars.toSet.subsetOf(s)}

```

## Explanation:

```
(s:Set[Char])=>             //define a function with a Set of Chars called s as an argument
'a' to 'z'                  //create a Range of characters 'a' to 'z'
sliding 3                   //create an Iterator(Seq(a, b, c), Seq(b, c, d), Seq(c, d, e), ... , Seq(x, y, z))
filter{_.toSet subSetOf s}  //keep only the triplets which are a subset of s

```
> 2 votes

# Answer
# Java 7, 230 bytes

```
String c(char[]q){java.util.Arrays.sort(q);char a[]=new String(q).replaceAll("(.)\\1","$1").toCharArray(),c=97,i=2;String r="",z="",s;for(;c<'z';z+=c++);while(i<a.length)if(z.contains(s=""+a[i-2]+a[i-1]+a[i++]))r+=s+" ";return r;}

```

This can most likely be golfed, but the challenge was a lot tougher than I originally thought in Java..

**Ungolfed & test cases:**

Try it here.

```
class M{
  static String c(char[] q){
    java.util.Arrays.sort(q);
    char a[] = new String(q).replaceAll("(.)\\1", "$1").toCharArray(),
         c = 97,
         i = 2;
    String r = "",
           z = "",
           s;
    for(; c < 'z'; z += c++);
    while(i < a.length){
      if(z.contains(s = "" + a[i-2] + a[i-1] + a[i++])){
        r += s+" ";
      }
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c("education".toCharArray()));
    System.out.println(c("foghorn".toCharArray()));
    System.out.println(c("cabaret".toCharArray()));
    System.out.println(c("hijacking".toCharArray()));
    System.out.println(c("pneumonia".toCharArray()));
    System.out.println(c("klaxon".toCharArray()));
    System.out.println(c("perform".toCharArray()));
    System.out.println(c("learning".toCharArray()));
    System.out.println(c("dblacghmeifjk".toCharArray()));
  }
}

```

**Output:**

```
cde
fgh
abc
ghi hij ijk
mno nop

abc bcd cde def efg fgh ghi hij ijk jkl klm

```
> 1 votes

# Answer
# JavaScript (Firefox 48), 93 bytes

```
x=>[for(c of a=[...new Set(x,i=0)].sort())if(parseInt(d=c+a[++i]+a[i+1],36)%1333==38&!d[3])d]

```

This lends itself to a **96-byte ES6 version**:

```
x=>[...new Set(x)].sort().map((c,i,a)=>c+a[i+1]+a[i+2]).filter(x=>!x[3]&parseInt(x,36)%1333==38)

```

### How it works

The first major chunk of the function is this:

```
[...new Set(x)].sort()

```

`new Set(string)` creates a Set object that contains one of each unique character in the string. For example, `new Set("foghorn")` will return `Set ["f", "o", "g", "h", "r", "n"]`. We can convert this into an array with `[... ]`, then sort it with the built-in `.sort()`. This turns `"foghorn"` into `["f", "g", "h", "n", "o", "r"]`.

The next step is this:

```
.map((c,i,a)=>c+a[i+1]+a[i+2])

```

This maps each `c`haracter in the `a`rray to the character concatenated with the two items after it. For example, `["f", "g", "h", "n", "o", "r"] => ["fgh", "ghn", "hno", "nor", "orundefined", "rundefinedundefined"]`. (The `undefined`s pop up when you try to access a non-existent member of the array.

The final step is filtering:

```
.filter(x=>!c[3]&parseInt(x,36)%1333==38)

```

First, the `!c[3]&` is to rule out any strings that contain `undefined`. This is necessary because a bug causes the following algorithm to count e.g. `gmundefined` as a consecutive triplet.

All three-consecutive-char strings, when interpreted as base-36 numbers, are 38 modulo 1333. I figured this out by the following calculation:

* 012 (base 36) = 38
* 123 (base 36) = 1371
* 1371 - 38 = 1333
* 1371 mod 1333 ≡ 38 mod 1333 ≡ 38

Therefore, if a three-char string is 38 mod 1333 in base-36, the three characters are consecutive in the alphabet.

### Test snippet

```
function test(x){O.innerHTML=/[^a-z]/.test(x)?"Invalid input":f(x);}
f=x=>[...new Set(x)].sort().map((c,i,a)=>c+a[i+1]+a[i+2]).filter(x=>!x[3]&parseInt(x,36)%1333==38)
```

```
<input id=I value="hijacked">
<button onclick="test(I.value)">Run</button>
<pre id=O>cde,hij,ijk</pre>
```
> 1 votes

# Answer
## PowerShell v2+, 93 bytes

```
param($n)97..120|%{-join[char[]]($_,++$_,++$_)}|?{(-join([char[]]$n|sort|select -u))-match$_}

```

Feels much longer than required, but I can't seem to golf it any further.

Takes input `$n`. Loops from `97` to `120`, constructing contiguous three-letter strings -- that is, up to the `|?`, we'll have `abc`, `bcd`, `cde`, etc. on the pipeline. Then that's fed through a `Where-Object` (the `|?`) to pull out only those items where the clause is true. Here, the clause is 1) the input string `$n`, cast as a `char`-array, `sort`ed and `select -u`nique'd, then `-join`ed back into a string, 2) `-match`ed against the three-letter strings (i.e., regex matching). If it's a match, then the three-letter string is in the word, and so it filters through the `|?`. The results are left on the pipeline and output is implicit.

### Examples

(Note that here the output is space-separated, since we're stringifying the output by concatenation.)

```
PS C:\Tools\Scripts\golfing> 'education','foghorn','cabaret','hijacking','pneumonia','klaxon','perform','learning'|%{"$_ -> "+(.\close-knit-words.ps1 $_)}
education -> cde
foghorn -> fgh
cabaret -> abc
hijacking -> ghi hij ijk
pneumonia -> mno nop
klaxon ->
perform ->
learning ->

```
> 1 votes

# Answer
# Retina, ~~106~~ 56 bytes

```
D`.
O`.
^
abc¶
{`^(.*)¶.*\1.*
$0¶$1
}T`_l`l;`^.*
2`.*¶?

```

Deduplicate, Sort. Add `abc`. Find if the substring is found and append if so. Translate to next substring. Repeat. Then remove first two lines.

**Try it online**

---

Naive solution:

```
D`.
O`.
!&`abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz

```

Deduplicate, Sort, then output overlapping matches of 3 sequential letters.

**Try it online**
> 1 votes

# Answer
## Racket 237 bytes

```
(define(f s)(let((lr(λ(l i)(list-ref l i)))(l(sort(map char->integer(string->list s))<)))(for((i(-(length l)2)))
(when(=(-(lr l(+ i 2))(lr l(+ i 1)))1(-(lr l(+ i 1))(lr l i)))(for((j 3))(display(string(integer->char(lr l(+ i j))))))))))

```

Testing:

```
(f "education")

```

Output:

```
cde

```

Detailed version:

```
(define(f2 s)
  (let ((lr (λ(l i)(list-ref l i)))
        (l (sort (map char->integer (string->list s)) <)))
  (for ((i (-(length l)2)))
    (when (=  (- (lr l (+ i 2)) (lr l (+ i 1)))
              1
              (- (lr l (+ i 1)) (lr l i)))
      (for((j 3))
        (display (string(integer->char (lr l (+ i j))))))))))

```
> 1 votes

# Answer
# Ruby, 50 bytes

`each_cons(3)` gets all consecutive sublists of length 3 from the alphabet `?a..?z`, then use `e&s.chars==e` to select only the ones that have all characters in the target string by using setwise intersection. Returns a list of lists.

```
->s{(?a..?z).each_cons(3).select{|e|e&s.chars==e}}

```

Try it online!
> 1 votes

# Answer
# \[R\], 110 bytes

```
 f=function(b){a=combn(sort(utf8ToInt(b)),3);apply(unique(t(a[,which(apply(diff(a),2,prod)==1)])),1,intToUtf8)}

```

I'm sure its still golfable
> 1 votes

# Answer
# Japt, ~~10~~ 9 bytes

```
;Cã3 fUá3

```

Try it or run all test cases

```
;Cã3 fUá3     :Implicit input of string U
;C            :Lowercase alphabet
  ã3          :Substrings of length 3
     f        :Filter elements contained in
      Uá3     :Permutations of U of length 3

```
> 1 votes

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


# Question
Title: Block-sorting rows and columns in a 2D array
Given a 2D array of integers, let's sort its rows and columns in blocks. This means that you only have to sort a given row or column, but applying the transformations needed for sorting it to every other row or column in the 2D array.

### Rules

* Input will be a 2D array of integers and a 1-indexed integer. This integer will represent the row to be sorted if the number is positive, or the column to be sorted if the number is negative (or the other way round you want). Example: Given a `4x3` (rows x columns) array you can sort the second column with a `-2` argument or the third row with a `3` argument. This second argument will never be zero and its absolute value will never be greater than the corresponding dimension of the array.
* Output will be also a 2D array of integers with the needed transformations applied to sort the given row or column. Alternatively you can just write the array to STDOUT.
* The output array will have the specified row or column sorted in ascending order. Just note that when you need to swap two numbers in a row, the whole columns where the numbers lay will be swapped. And when you need to swap two numbers in a column, the whole rows where the numbers lay will be swapped.
* In the case in which the same number appears several times in the row/column to be sorted, there will be several solutions possible according to the way you swap the values, just do accordingly with the rest of rows/columns to be swapped.

## Examples

```
Positive indices for rows and negative indices for columns

[5  8  7  6                                  [1  3  2  4
 1  3  2  4   order by -3 (3rd column)  -->   9  6  3  0
 9  6  3  0]                                  5  8  7  6]

[5  8  7  6                                  [9  6  3  0
 1  3  2  4   order by -4 (4th column)  -->   1  3  2  4
 9  6  3  0]                                  5  8  7  6]

[5  8  7  6                                  [5  7  8  6
 1  3  2  4     order by 2 (2nd row)  -->     1  2  3  4
 9  6  3  0]                                  9  3  6  0]

[5  8  7  6                                  [6  7  8  5
 1  3  2  4     order by 3 (3rd row)  -->     4  2  3  1
 9  6  3  0]                                  0  3  6  9]

[1  2                                    [1  2     [3  2
 3  2]   order by -2 (2nd column)  -->    3  2] or  1  2]  (both are valid)

[7  5  9  7                                  [5  7  7  9     [5  7  7  9
 1  3  2  4     order by 1 (1st row)  -->     3  1  4  2  or  3  4  1  2
 9  6  3  0]                                  6  9  0  3]     6  0  9  3]

```

This is , so may the shortest code for each language win!

# Answer
> 7 votes
# , 55 bytes

```
function(x,n)`if`(n>0,x[,+x[n,]],x[+x[,-n],])
`+`=order

```

Try it online!

Reassigns the `+` operator (actually a function in R) to the `order` function, which returns the indices of a vector from smallest to largest. Then it's just array manipulation.

# Answer
> 5 votes
## Matlab, 73 62 47 bytes

```
@(m,i){sortrows(m,-i) sortrows(m',i)'}{(i>0)+1}

```

Try it Online!

-11 bytes thanks to @Giuseppe.

-15 bytes thanks to @LuisMendo.

# Answer
> 5 votes
# , 55 bytes

```
f=function(m,i)"if"(i<0,t(f(t(m),-i)),m[,order(m[i,])])

```

Try it online!

Alternative to ngm's answer; a recursive function which was inspired by DimChtz's answer

# Answer
> 4 votes
# Japt, ~~18~~ 17 bytes

*negative for rows and positive for columns*

```
>0?VñgUÉ:ßUa Vy)y

```

Try it online!

# Answer
> 4 votes
# JavaScript (ES6), 90 bytes

```
t=m=>m[0].map((_,x)=>m.map(r=>r[x]))
f=(m,k)=>k<0?m.sort((a,b)=>a[~k]-b[~k]):t(f(t(m),-k))

```

Try it online!

### How?

JS has no native transposition method, so we need to define one:

```
t = m =>              // given a matrix m[]
  m[0].map((_, x) =>  // for each column at position x in m[]:
    m.map(r =>        //   for each row r in m[]:
      r[x]            //     map this cell to r[x]
    )                 //   end of map() over rows
  )                   // end of map() over columns

```

Main function:

```
f = (m, k) =>         // given a matrix m[] and an integer k
  k < 0 ?             // if k is negative:
    m.sort((a, b) =>  //   given a pair (a, b) of matrix rows, sort them:
      a[~k] - b[~k]   //     by comparing a[-k - 1] with b[-k - 1]
    )                 //   end of sort
  :                   // else:
    t(f(t(m), -k))    //   transpose m, call f() with -k and transpose the result

```

*Example with \\$k=2\\$:*

$$M=\pmatrix{5&8&7&6\\1&3&2&4\\9&6&3&0}\rightarrow t(M)=\pmatrix{5&1&9\\8&3&6\\7&2&3\\6&4&0}\rightarrow f(t(M),-2)=\pmatrix{5&\mathbf{\color{red}1}&9\\7&\mathbf{\color{red}2}&3\\8&\mathbf{\color{red}3}&6\\6&\mathbf{\color{red}4}&0}\\f(M,2)=t(f(t(M),-2))=\pmatrix{5&7&8&6\\\mathbf{\color{red}1}&\mathbf{\color{red}2}&\mathbf{\color{red}3}&\mathbf{\color{red}4}\\9&3&6&0}$$

# Answer
> 4 votes
# 05AB1E, ~~25~~ ~~24~~ 14 bytes

```
diø}Σ¹Ä<è}¹diø

```

Whopping -10 bytes thanks to *@Emigna*.

Uses a positive integer-input to sort the rows, negative for columns.

Try it online or verify all test cases.

**Explanation:**

```
di }      # If the (implicit) integer input is positive:
  ø       #  Swap the rows and columns of the (implicit) matrix input
          #   i.e. 3 and [[5,8,7,6],[1,3,2,4],[9,6,3,0]]
          #    → [[5,1,9],[8,3,6],[7,2,3],[6,4,0]]
Σ    }    # Sort the rows of this matrix by:
 ¹Ä       #  Take the absolute value of the input
          #   i.e. -3 → 3
   <      #  Decreased by 1 to make it 0-indexed
          #   i.e. 3 → 2
    è     #  And index it into the current row
          #   i.e. [5,8,7,6] and 2 → 7
          #   i.e. [5,1,9] and 2 → 9
          #  i.e. [[5,1,9],[8,3,6],[7,2,3],[6,4,0]] sorted by [9,6,3,0]
          #   → [[6,4,0],[7,2,3],[8,3,6],[5,1,9]]
          #  i.e. [[5,8,7,6],[1,3,2,4],[9,6,3,0]] sorted by [7,2,3]
          #   → [[1,3,2,4],[9,6,3,0],[5,8,7,6]]
¹di       # And if the integer input was positive:
   ø      #  Swap the rows and columns back again now that we've sorted them
          #   i.e. 3 and [[6,4,0],[7,2,3],[8,3,6],[5,1,9]]
          #    → [[6,7,8,5],[4,2,3,1],[0,3,6,9]]
          # (And implicitly output the now sorted matrix)

```

# Answer
> 3 votes
# MATL, 17 bytes

```
y0>XH?!]w|2$XSH?!

```

Try it online!

Or verify all test cases

### Explanation

```
y       % Implicit inputs: number n, matrix M. Duplicate from below: pushes n, M, n
0>      % Greater than 0?
XH      % Copy into clipboard H
?       % If true
  !     %   Transpose matrix. This way, when we sort the rows it will correspond
        %   to sorting the columns of the original M
]       % End
w       % Swap: moves n to top
|       % Absolute value
2$XS    % Two-input sortrows function: sorts rows by specified column
H       % Push contents from clipboard H
?       % If true
  !     %   Transpose again, to convert rows back to columns
        % Implicit end
        % Implicit display

```

# Answer
> 3 votes
# APL (Dyalog Classic), 23 bytes

```
{⍺<0:⍉(-⍺)∇⍉⍵⋄⍵[;⍋⍺⌷⍵]}

```

Try it online!

# Answer
> 2 votes
# Python 2, ~~71~~ 70 bytes

```
f=lambda m,n:n<0and sorted(m,key=lambda l:l[~n])or zip(*f(zip(*m),-n))

```

Try it online!

---

If `n` is negative, the rows are sorted based on column `n`.

Otherwise the matrix is transposed, sorted the same way, and transposed back again.

# Answer
> 2 votes
# Jelly, 12 bytes

```
ZṠ}¡
çị@ÞA}ç

```

Try it online!

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

```
(a,b)->{int l=a.length,w=a[0].length,k,m,t,i;if(b>0){for(i=0;i<w;i++){for(k=1;k<(w-i);k++){if(a[b-1][k-1]>a[b-1][k]){for(m=0;m<l;m++){t=a[m][k];a[m][k]=a[m][k-1];a[m][k-1]=t;}}}}}else{b*=-1;for(i=0;i<l;i++){for(k=1;k<(l-i);k++){if(a[k-1][b-1]>a[k][b-1]){for(m=0;m<w;m++){t=a[k][m];a[k][m]=a[k-1][m];a[k-1][m]=t;}}}}}return a;}

```

Try it online!

Well guys, this question was very frustrating for me, and I posted my answer KNOWING I was forgetting something, luckily we have legends like Kevin Cruijssen out here to help us out :)

# Java (OpenJDK 8), 281 bytes

```
a->b->{int l=a.length,w=a[0].length,k,m,t,i;if(b>0)for(i=0;i<w;i++)for(k=0;++k<w-i;)for(m=0;a[b-1][k-1]>a[b-1][k]&m<l;a[m][k]=a[m][k-1],a[m++][k-1]=t)t=a[m][k];else for(b*=-1,i=0;i<l;i++)for(k=0;++k<l-i;)for(m=0;a[k-1][b-1]>a[k][b-1]&m<w;a[k][m]=a[k-1][m],a[k-1][m++]=t)t=a[k][m];}

```

Try it online!

# Answer
> 1 votes
# C# (.NET Core), 186 bytes

```
(x,y)=>{Func<int[][],int[][]>shift=a=> a[0].Select((r,i)=>a.Select(c=>c[i]).ToArray()).ToArray();return y>0?shift(shift(x).OrderBy(e=>e[y-1]).ToArray()):x.OrderBy(e=>e[-y-1]).ToArray();}

```

Try it online!

Ungolfed:

```
    private static int[][] Blocksort0a(int[][] array, int sortingInstruction)
    {
        Func<int[][], int[][]> shift = a => a[0].Select((r, i) => a.Select(c => c[i]).ToArray()).ToArray();

        sortingInstruction++;

        array = sortingInstruction < 0 ?
        shift(shift(array).OrderBy(e => e[-sortingInstruction]).ToArray())
             :
        array.OrderBy(e => e[sortingInstruction]).ToArray();

        return null;
    }

```

The shift function we'll use twice, so a function variable will save space. The function iterates through the horizontal dimension of the array on index, and adds every item on that index in of each horizontal array to a new output array (horizontally) - much the same as in Arnoud's JS solution.

Now the ordering is simple, order horizontal array by number-at-index (argument -1), optionally shifting the array before and after sorting.

Seen how the question talks about arrays specifically, we convert to array a few times (very, very wasteful). Feeling a bit silly to use such a verbose language in code golf hehe.

# Answer
> 1 votes
# C# (.NET Core), ~~142/139~~ 138/135 bytes (and yet another -1 by Kevin)

```
(a,s)=>s<0?a.OrderBy(e=>e[~s]).ToArray():a.Select(f=>a[s-1].Select((v,j)=>new{v,j}).OrderBy(e=>e.v).Select(e=>f[e.j]).ToArray()).ToArray()

```

Try it online!

Ungolfed:

```
    private static int[][] Blocksort0b(int[][] array, int sortingInstruction)
    {
        if (sortingInstruction < 0) { return array.OrderBy(e => e[-sortingInstruction - 1]).ToArray(); }
        var rowIndices = array[sortingInstruction - 1].Select((value, index) => (value, index)).OrderBy(e => e.value);
        var newRow = new int[array[0].Length];
        for (var i = 0; i < array.Length; i++)
        {
            int horizontalIndexer = 0;
            foreach (var e in rowIndices)
            {
                newRow[horizontalIndexer++] = array[i][e.index];
            }
            array[i] = newRow.ToArray();
        }
        return array;
    }

```

New all-inline approach; negative answer still orders arrays by element-at-index. Otherwise, a collection of value-index-pair is created of the array-at-index and sorted by value. This effectively creates a collection of indices in order of having-to-be-added. Then for each array, the elements in the predetermined positions are selected. Quite some trimming of code and ugly, ugly, ugly \**silently sobs\** reuse of input parameters is involved, and there you go ... 142 bytes.

Again, the arrays argument is strictly enforced, adding quite some overhead for .ToArray() calls.

135 bytes claim, eh?! C# 7.2 inferred value-tuples would trim an additional three bytes, but tio.run doesn't allow. Therefor, this is the answer i decided to post for easy verification.

# Answer
> 1 votes
# Clean, 95 bytes

```
import StdEnv,Data.List,Data.Func
$n#f=if(n>0)transpose id
=f o sortBy(on(<)\u=u!!(abs n-1))o f

```

Try it online!

# Answer
> 1 votes
# Red, ~~190~~ 185 bytes

```
func[b n][t: func[a][c: length? a/1 a: to[]form a
d: copy[]loop c[append/only d extract a c take a]d]d: does[if n > 0[b: t b]]d
m: absolute n sort/compare b func[x y][x/(m) < y/(m)]d b]

```

Try it online!

## Explanation:

```
f: func [ b n ] [
    t: func [ a ] [                            ; helper transpose function
        c: length? a/1                         ; c is the length of the rows
        a: to-block form a                     ; flatten the list
        d: copy []                             ; an empty block (list)
        loop c [                               ; do as many times as the number of columns
            append/only d extract a c          ; extract each c-th element (an entire column)
                                               ; and append it as a sublist to d
            take a                             ; drop the first element
        ]
        d                                      ; return the transposed block (list of lists)
    ]
   d: does [ if n > 0 [ b: t b ] ]             ; a helper function (parameterless) to transpose
                                               ; the array if positive n
   d                                           ; call the function
   m: absolute n                               ; absolute n
   sort/compare b func[ x y ] [ x/(m) < y/(m) ]; sort the array according to the chosen column
   d                                           ; transpose if positive n
   b                                           ; return the array
]

```

My actual solution is 175 bytes long, but it doesn't work in TIO. Here it is, working normalyl in the Red console:

## Red, 175 bytes

```
func[b n][d: does[if n > 0[c: length? b/1 a: to-block form b
t: copy[]loop c[append/only t extract a c take a]b: t]]d
m: absolute n sort/compare b func[x y][x/(m) < y/(m)]d b]

```

# Answer
> 1 votes
# Kotlin, 192 bytes

```
{m:Array<Array<Int>>,s:Int->if(s<0){m.sortBy{it[-s-1]}}else{val a=Array(m[0].size){c->Array(m.size){m[it][c]}}
a.sortBy{it[s-1]}
(0..m.size-1).map{r->(0..m[0].size-1).map{m[r][it]=a[it][r]}}}}

```

Try it online!

# Answer
> 1 votes
# Ruby, 69 bytes

```
->a,n{f=->x{[0,x.transpose,x][n<=>0]};f[f[a].sort_by{|x|x[n.abs-1]}]}

```

Try it online!

# Answer
> 0 votes
# VBA (Excel), 205 bytes

Yay! 2nd longest byte count! I didn't completely lose :D

Golfed:

```
Sub d(a)
With ActiveSheet.Sort
  .SortFields.Clear
  .SortFields.Add Key:=IIf(a<0,ActiveSheet.Columns(Abs(a)),ActiveSheet.Rows(Abs(a)))
  .SetRange ActiveSheet.UsedRange
  .Orientation=IIf(a<0,1,2)
  .Apply
End With
End Sub

```

This sorts all the data on the open (active) worksheet using UsedRange... which can be buggy, but should only contain cells that have been edited.

UnGolfed:

```
Sub d(a)
  'Clear any Sort preferences that already exists
  ActiveSheet.Sort.SortFields.Clear
  'Use the column if A is negative, the row if A is positive
  ActiveSheet.Sort.SortFields.Add Key:=IIf(a < 0, ActiveSheet.Columns(Abs(a)), ActiveSheet.Rows(Abs(a)))
  'Set the area to sort
  ActiveSheet.Sort.SetRange ActiveSheet.UsedRange
  'Orient sideways if sorting by row, vertical if by column
  ActiveSheet.Sort.Orientation = IIf(a < 0, xlTopToBottom, xlLeftToRight)
  'Actually sort it now
  ActiveSheet.Sort.Apply
End Sub

```

# Answer
> 0 votes
# Perl 6, 43 bytes

```
{($!=$_>0??&[Z]!!*[])o*.sort(*[.abs-1])o$!}

```

Try it online!

Curried function.

### Explanation

```
{                                         } # Block returning function composed of
                                       o$!  # 1. Apply $! (transpose or not)
                     o*.sort(*[.abs-1])     # 2. Sort rows by column abs(i)-1
     $_>0??&[Z]                             # 3. If i > 0 transpose matrix
               !!*[]                        #    Else identity function
 ($!=               )                       #    Store in $!

```

# Answer
> 0 votes
# Physica, 45 bytes

Very similar to Arnauld's JS answer.

```
F=>n;m:n<0&&Sort[->u:u{~n};m]||Zip@F#Zip@m#-n

```

Try it online!

### How it works?

A more elaborate and visual explanation can be found in the linked answer.

```
F=>n;m:           // Create a function F that takes two arguments, n and m.
       n<0&&      // If n < 0 (i.e. is negative)
Sort[->u{~n};m]   // Sort the rows u of m by the result of the function u[~n].
                  // In short, sort by indexing from the end with n.
||    F#Zip@m#-n  // Else, apply F to Zip[m] and -n. Uses a new feature, binding.
  Zip@            // And transpose the result.

```

# Answer
> 0 votes
# , 32 bytes

```
f=.[/:({"1~<:)
g=.(f&.|:|)`f@.(0<])

```

Try it online!

Note: The `g=.` of the main verb doesn't count.

## An explicit version for the same bytes

# , 32 bytes

```
4 :'y(]/:{"1)&.(|:^:(x<0))~<:|x'

```

Try it online!

# Answer
> 0 votes
## Clojure, 91 bytes

```
(fn f[A i](if(< i 0)(sort-by #(nth %(- -1 i))A)(apply map list(f(apply map list A)(- i)))))

```

Argh, `apply map list` * 2.

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