title: Seriously, GolfScript, CJam, or Pyth?

text:
# Question
Title: Seriously, GolfScript, CJam, or Pyth?
Some time ago, the following question was asked: GolfScript, CJam, or Pyth? Based on the title only, I thought that it would be a very nice challenge, but unfortunately, it turned out to be a question asking for tips. Here is the challenge I wanted to read:

> Who said golfing languages were not used in the Real World? As everybody knows, the ratio of bugs per line of code is the same independently of the programming language being used, so there is a clear opportunity to reduce debugging and maintenance costs with those languages. Your company finally saw the light and decided to use Golfscript, CJam and Pyth to develop its products.
>
> Unfortunately, after a couple of months, your hard drives are cluttered with snippets of code and you don't even know which ones are written in which languages (you even suspect some of your programmers of using Perl).
>
> You must write a tool to detect which of CJam, Golfscript or Pyth is the language in which a program is written. The situation is critical, you can use any language you want, but please keep it short (data storage is expensive: the more bytes we use, the more it costs).

# General

* Shortest code win
* Standard loopholes, etc.
* Don't use an online interpreter
* You can write a function or a program
* You can use eval to detect your own language

# Input

* Your input is taken from the standard input stream or as a string
* Input contains only ASCII printable characters and linefeeds
* The size of the input is up to 256 bytes long

# Output

* Output is printed to output stream or returned as a sequence of strings/symbols
* If the input is without doubt a valid *X* program, print or return *X*, *X* ∈ {CJam, Pyth, Golfscript}

**Remark**: "without a doubt" does not mean that you are allowed to answer with a dumb analyzer that consistently fails to detect any language. For Pyth, I expect Simple Programs to be recognized (but no hardcoding). The same goes for CJam (cheat sheet, examples) and Golfscript (examples). The previous links point to each language's specifications. If you use a fuzzy/bayesian approach, "without a doubt" means with a high-level of confidence (you score 99% with your classification, for example). *See below for the actual test suite.*
* If the input is valid in multiple languages, each detected language should be printed/returned. When printed, there must be a separator between multiple outputs (e.g. space, newline, comma...).
* The order in which languages are tried does not matter
* I do not care about case (CJam, cjam, CJAM, SPAM) \[1\]
* If *none of the above language* is detected, print "`Probably Perl`". Thanks to this comment from mbomb007, in the above case you can also output "`Seriously`" for a penalty of 4 bytes (the difference between both strings).

\[1\] Just to be clear, SPAM is invalid

# Examples

* Input

```
"Crime predicted: --
Calling: 1--555-

"30*{_5<{iAa*:mr}&}/

```
* Output (example of multiple return values)

```
["Golfscript", "Cjam"]

```
* Input

```
3

```
* Output (example on standard output)

```
golfscript
cjam
pyth

```
* Input

```
if {} aazd

```
* Output

```
Probably Perl

```

In the last case, the input program produces an error With All Three online interpreters.

# Scoring, winning criterion

Shortest code win. Add 4 bytes if you output "Seriously". Then, apply bonuses.

## Failing tests

The following are snippets that *must not* be recognized as any of the three languages above.

One-liners (i.e. one entry per line)
```
$^X=~/([a-z]+)[^\/]+$/;print$1,$/
<>;map($s-=(-1)**$_/(2*$_-1),1..$_),$s=!print$s,$/for<>
((THIS IS LISP HAIKU) (TRULY THIS IS LISP HAIKU) (THIS IS LISP HAIKU))
(format t"~@(~{~R~^, ~}~).~%~:*~@(~{~:R~^, ~}~)."(loop for i to 99 collect(1+ i)))
print sum(ord(c) for c in 'Happy new year to you!')

```
Brainfuck
```
>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
++++++++++++++++++++++++++++++++++++++++++++++++.
-----------------.
++++++++.
+++++.
--------.
+++++++++++++++.
------------------.
++++++++.

```
Perl
```
@list=( "aaaa",
        "aaaaaaaa",
        "aaaaaaaaaaaaaaa",
        "aaaaaaaaaaaaaaaa",
        "aaaaaaaaaaaaaaaaaaaaaaa",
        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

while (@list) {
    for($i=0;$i<6;$i++){
        print length($list[$i])." ";
    }
    print "\n";
}

```
Fish
```
#ifndef __linux
#include "x.h"
#define X/*\
a=1 set -e
+++++++++++++++++++++_+++++++++++++....Hello World!?:Q:
#endif
    echo "Hello, World!"
    int m(){}

```

## Basic test suite

Those are tests which *must* pass. Belows are *one-liners* for each language where your program must detect the language it is being written in (I did not check which of those are polyglot).

### Pyth

```
*2Q
FNrZTN
FNrZhTN
FNUhTN
VhTN
FNr1hQN
=N5N
K5K
K1FNr1hQ=K*KN
K1FNr1hQ=K*KNK
K1FNr1hQ=K*KN;K
DhZK*3ZRK
L?b*bytb1yQ
A(Z1)VQHA(H+HG

```

### Golfscript

```
;'2706 410'~{.@\%.}do;
;''6666,-2%{2+.2/@*\/10.3??2*+}*`50<~\;
'Hello, world!'
1 2 [\]

```

### CJam

```
"Hello, world"
{`"_~"}_~
"`_~"`_~
T1{_2$+}A*]`
{__'`>\'x>26*2-*-}/
Y38#
N/s:X,8-,{X>9<__{'a<},,\4%{'Z>},,*I={4=}{;}?}/

```

---

## Silver bonus: byte-count * 0.6

All previous tests must pass, as well as the following one-liners. All those snippets are taken from actual CodeGolf answers.

### Pyth

```
VzJ:zZhZpkJ~Zhy}rJ0-G"aeoui
Vzjdm?@zd}N,dt-lzd\ Uz
jd.iSQs*RtQ,\?":0
rsXOtQmO*-GJ"aeiou"J/Q2*%Q2O"hy"4
VhQIq`N_`NN
s["$$\\varphi=1+"*Q"\cfrac1{1+"\\<\dQ"dots"*Q\}"$$
@c"weak trick fair"d-!JlfhT-M.:us_cG.u+NYtKrH7-52hK.zU52 2>J26

```

### Golfscript

```
);:|;{0):0;|$:§-1%" - "§" = ""0"4$~§~-+-4>:|n|6174`=!}do"Iterations: "0"."
'-+,/'{)))))}%
4:echo(2+2);
#undef X;A!"$%&'()*+-[,.]/0123456789:<=>?@BCDEFGHIJKLMNOPQRSTUVWYZ\^_`abcghijklmopqrstvwxyz{|}~
{`),32>^.}.~
"126,32>''+".~\-'.~\-"'-
"),@`^^32>#.~".~
...[[]]{{}}&%%++++5i
  *++..0011125::::;;;?bbbbcccc{}
"This program wasn't written in "o"GolfScript"", it was built for ""CJam"oo"!"

```

### CJam

```
"Q"c("ASSW"1$("aRD"(((T1
%\@_@){;_0}*__*)\15
"This program wasn't written in "o"GolfScript"", it was built for ""CJam"oo"!"
"P2"1e3K51_,1>K*$K*~]N*
li__,\mf:i2m1+:*/fb:+
ri:B__(^2/):G/,{_BBG/@-(#G@*G(B2/*+*}/]:+
{1$+S@]_1=4+1$`,-S*"2$~"}21D2$~
[S'-26*N]:Z[S'|:PS24*PN]:RR'(PS5*qi:XD=X0<-X2%2*+:Y[" ^ "_" > ""(O)"" - "__]=S8*Y[" ^ ""   "" < ""(O)"" - "__]=S5*P')NRRXD=[SPS7*'oA*S7*PN]:QR?Y[[SPS5*'oSC*'oS5*PN]:T_R[SPS7*'oS8*'oS7*PN]RRR]=QY2=TR?RRZ
li4H#+2bW%32<2b
q~:R100:H*\d:T/i){R-H*HT-/m]}6*_H)<*
"JamesBdo,"YZ+/)BA*c+Y*Y%:BS@SB)))[JW:Z____)ci+*]U*

```

---

## Gold bonus: previous-score * 0.8

### Pyth

Compare
```
jdm@cd)._-FQcj"
is
equal greater less
to than
"Qb

```
Snowman
```
M@GCHgc"  ___

  ___
   _"bhzgc" (_*_)
 _===_
 .....
  /_\\"bhzs[g"  \ "@z4\(g"-.oO"@z2g" ,._"@z1g"-.oO"@z3\)g"  / "@z5)s[g" < /"@z4\(gc"
 :
] [
> <"b@z6\)g" > \\"@z5)++" ("gc"
 :
\" \"
___"bez\)

```

### CJam

Big
```
rri:Hri:Vri:Q[q~]3/_Qa3*a+_|$W%:Pf{\a#}:AH/:B0ff*
P,,[AHAW%HBz:+_W%V\V]2/
ff{~@@f=/::|1#}0Ua4*t:R;
P0f<
V{H{BI=J=_2$=
0R{"I>! I+V<J>! J+H<"4/+4/z{~~}%:&1$*\)}%);2$-|t
}fJ}fI
[P,{_La#\1$0t1$f-}*;;]
{:TR=2/~\~V\-,>\f{\_3$=@~H\-,>{Tt}/t}~}/
:~Pf=:~
~]S*N

```
Snowman
```
q:Q;SS"
 _===_,___
 ....., _
  /_\,___
 (_*_)"',/0{Q=~(=}:G~N" \ "4G'(".oO-"_2G",._ "1G@3G')" / "5GN"< / "4G'(" : ] [> <   "3/6G')"> \ "5GNS'(" : \" \"___   "3/7G')

```

### Golfscript

Lorem Ipsum
```
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras imperdiet est ut sem commodo scelerisque. Sed ut ultricies enim. Nam eget lectus suscipit, gravida turpis a, volutpat tellus. Cras efficitur luctus neque, at semper massa condimentum at posuere.

```
Digital clock
```
:*{32' _':$@'14'{?~!=}:&~32}%n*{:x' |':|\'1237'&$x'017'&|x'56'&}%n*{:x|\'134579'&$x'147'&|x'2'&}%

```
Happy birthday
```
4,{"Happy Birthday "["To You""Dear GolfScript"]@2==n}%

```
Farey sequence
```
~:c[,{){.}c(*}%.c/zip{+}*]zip{~{.@\%.}do;1=},{~<},{~\10c?*\/}${'/'*}%', '*'F'c`+' = {0/1, '+\', 1/1}'

```

# Answer
> 4 votes
# Ruby, (135 + 4) * 0.6 * 0.8 = 66.72

This runs on Windows and I'm too tired to shorten it by running on Unix.

```
(a=[%w(javaw -jar cjam),%w(python pyth),%w(rubyw golfscript)].map{|c|c[-1]if system(*c,?f,'> NUL','2>','NUL')}-[nil])==[]?'Seriously':a

```

I did these things but I'm not sure if they're allowed:

* Rename `cjam-[version].jar` to `cjam`, `pyth.py` to `pyth`, `golfscript.rb` to `golfscript`.
* Read from file `f` instead of getting input. (Add `IO.write(?f,gets);` to the beginning to fix that, and the new length is (153 + 4) * 0.6 * 0.8 = 75.36)

# Answer
> 42 votes
## Python 2, 332 * 0.6 * 0.8 = 159.36

```
import os
from subprocess import*
from tempfile import*
f,n,a=NamedTemporaryFile(delete=0),open(os.devnull,'w'),''
f.write(os.read(0,256))
f.close()
for l in["CJam","java","-jar","cjam.jar"],["Pyth","./pyth.py"],["Golfscript","./golfscript.rb"]:a+=(l[0]+' ')*(call(args=l[1:]+[f.name],stdout=n,stderr=n)>0)
print a or'Probably Perl'

```

As far as I'm aware, this is within the rules. Requires the Pyth, CJam, and Golfscript interpreters (`pyth.py`, `cjam.jar`, and `golfscript.rb`) in the current directory, and Python 3, Java, and Ruby installed. Simple test: try running the program. If it returns with `0`, we're good. If not, it's invalid. A named temporary file (e.g. a file created in `$TMP`) is created to hold the program, since CJam doesn't have a script option. The `delete=False` flag is necessary to prevent the file from being deleted when it is closed (the OS will take care of it for us). The file has to be closed before attempting to read from it (though manually flushing the file should also work, but this is simpler). `stdout` and `stderr` are redirected to `/dev/null` to suppress output/errors (note that this makes it only work on \*NIX systems).

Extra fun: try running the given code in all 4 languages, to see what we get:

```
import sys
from subprocess import*
from tempfile import*
c=["Cjam","java","-jar","cjam.jar"]
p=["Pyth","./pyth.py"]
g=["Golfscript","./golfscript.rb"]
e=["Perl","perl"]
f=NamedTemporaryFile(delete=False)
s=sys.stdin.read()
f.write(s)
f.close()
n=open('/dev/null','w+')
a=''
for l in [c,p,g,e]:
    try:
        print '%s: %s'%(l[0],check_output(args=l[1:]+[f.name],stderr=n))
    except:
        continue
n.close()

```

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


title: Program my autodialer

text:
# Question
Title: Program my autodialer
Back in the day, telephone autodialers used punched cards with one column for each digit of the number to be dialed. Columns had seven rows. The first three rows represented the numbers (1,2,3), (4,5,6), and (7,8,9) respectively. The last three rows rotated this arrangement by 90°: (1,4,7), (2,5,8), and (3,6,9). The middle row was used for 0. Any digit 1-9 would have two holes punched - one in the first three rows, and one in the bottom three rows. Zero would only have the middle row punched. Let's visualize the punched column for the number 6 (`.` is unpunched, `x` is punched, guide on left is just to illustrate the encoding):

```
123 .
456 x
789 .
 0  .
147 .
258 .
369 x

```

We look for which row(s) contain the number we're trying to dial. For 6, this is the second row, and the ninth row. These two rows are punched, the remaining five rows are unpunched. Here are the punched patterns for all digits 0-9:

```
    0 1 2 3 4 5 6 7 8 9
123 . x x x . . . . . .
456 . . . . x x x . . .
789 . . . . . . . x x x
 0  x . . . . . . . . .
147 . x . . x . . x . .
258 . . x . . x . . x .
369 . . . x . . x . . x

```

Your goal is to (write a program or function to) punch these cards for me.

Input: A number, taken in any reasonable format (string, integer, list of integers, &c.), not to exceed 9999999999999.

Output: The grid of punched columns corresponding to the number input. You don't need the headers or extra spacing shown above, just the punched columns themselves. Leading/trailing newlines are ok, as is whitespace between rows/columns *as long as it is consistent*. Speaking of, as long as they are consistent, you may use any (non-whitespace) character for punched, and any other character for unpunched (while it should be obvious, please specify what characters you are using).

This is code-golf, so shortest code wins. Standard loopholes are disallowed.

Test cases (all use `.` for unpunched, `x` for punched):

```
In: 911
Out: .xx
     ...
     x..
     ...
     .xx
     ...
     x..

In: 8675309
Out: ....x..
     .x.x...
     x.x...x
     .....x.
     ..x....
     x..x...
     .x..x.x

In: 5553226
Out: ...xxx.
     xxx...x
     .......
     .......
     .......
     xxx.xx.
     ...x..x

```

# Answer
# Jelly, 13 bytes

```
9s3,Z$j0ċþDZY

```

Try it online!

`1` = punctured, `0` = not punctured.
> 4 votes

# Answer
# Pyth, 25 bytes

```
.tm?djNmX*3NkZ.Dtd3X*7N3Z

```

Uses `0` for punched and `"` for unpunched.
Try it here

### Explanation

```
.tm?djNmX*3NkZ.Dtd3X*7N3Z
  m                      Q  For each number in the (implicit) input...
   ?d                       ... if the number is nonzero...
              .Dtd3         ... get (n - 1) divmod 3...
       mX*3NkZ              ... replace each position in `"""` with `0`...
     jN                     ... and stick them together with `"`. ...
                   X*7N3Z   ... Otherwise, `"""0"""`.
.t                          Transpose the result.

```
> 3 votes

# Answer
# JavaScript (ES6), ~~60~~ 54 bytes

Takes input as an array of integers. Returns a binary matrix, with **0** = unpunched / **1** = punched.

```
a=>[14,112,896,1,146,292,584].map(n=>a.map(i=>n>>i&1))

```

Try it online!
> 3 votes

# Answer
# 05AB1E, ~~16~~ 15 bytes

Uses **0** and **1**.

```
ε9ÝÀ3ôD¨ø«¢O}ø»

```

Try it online!

**Explanation**

```
ε           }     # apply to each digit in input
 9Ý               # push the range [0 ... 9]
   À              # rotate left
    3ô            # split into pieces of 3
      D¨          # duplicate and remove the last digit (0)
        ø         # transpose
         «        # append
          ¢O      # sum the counts of each in the current digit
             ø    # transpose
              »   # format output

```
> 3 votes

# Answer
# SOGL V0.12, 23 bytes

```
,{r"ΧL→▓lφ℮o¤κ²‘7nwι}⁰H

```

Try it Here!

Compression.
> 2 votes

# Answer
# Python 2, 84 bytes

```
lambda a:[''.join(`(ord('(1Aa2Bb4Dd'[int(n)])-32)>>k&1`for n in a)for k in range(7)]

```

Try it online!

`0/1` is used for unpunched/punched.
> 2 votes

# Answer
# Python 3, ~~84~~ 80 bytes

```
def f(s):[print(*[int(i in[~-n//3,6--n%3-3*(n<1)])for n in s])for i in range(7)]

```

Try it online!
> 2 votes

# Answer
# , 31 20 bytes

-11 bytes thanks to FrownyFrog!

```
(e."1],0,|:)1+i.@3 3

```

Try it online!

# , 31 bytes

```
1*@|:@:#.(a,0,|:a=.1+i.3 3)=/~]

```

Try it online!

Takes the input as a list of digits

0 - unpunched, 1 - punched

## Explanation:

```
   a=.1+i.3 3 - generates the matrix and stores it into a
1 2 3
4 5 6
7 8 9

   (a,0,|:a=.1+i.3 3) - generates the entire comparison table
1 2 3
4 5 6
7 8 9
0 0 0
1 4 7
2 5 8
3 6 9

   ]=/ - creates an equality table between the input and the comparison table

 ((a,0,|:a=.1+i.3 3)=/~]) 9 1 1
0 0 0
0 0 0
0 0 1
0 0 0
0 0 0
0 0 0
0 0 1

1 0 0
0 0 0
0 0 0
0 0 0
1 0 0
0 0 0
0 0 0

1 0 0
0 0 0
0 0 0
0 0 0
1 0 0
0 0 0
0 0 0

  1*@|:@:#. - adds the tables, transposes the resulting table and finds the magnitude

  (1*@|:@:#.(a,0,|:a=.1+i.3 3)=/~])  9 1 1
0 1 1
0 0 0
1 0 0
0 0 0
0 1 1
0 0 0
1 0 0

```
> 2 votes

# Answer
# C (clang), ~~108~~ 107 bytes

```
c,i;f(*q){char*r;for(i=~0;i++<6;puts(""))for(r=q;c=*r++;c-=48,putchar(".X"[(c--?16<<c%3|1<<c/3:8)>>i&1]));}

```

Try it online!

Takes input number as string. Prints output in `.` and `X` as in examples.

# Credits

-1 byte thanks @ASCII-only
> 2 votes

# Answer
# Canvas, ~~27~~ 25 bytes

```
｛９＋├３÷ｕ４％ ×#＋#¹╷３％５＋１╋］↶↕

```

Try it here!
> 1 votes

# Answer
# Charcoal, 28 bytes

```
Ｅ⁴⭆θＩ⁼ι÷﹪⊖λχ³Ｅ³⭆θＩ∧Ｉλ¬﹪⁻⊖λι³

```

Try it online! Link is to verbose version of code. Uses 0/1, but can support arbitrary characters at a cost of 1 byte: Try it online!. Explanation:

```
Ｅ⁴              Loop from 0 to 3
  ⭆θ            Loop over input string and join
           λ     Current character
         ⊖      Cast to integer and decrement
        ﹪  χ    Modulo predefined variable 10 (changes -1 to 9)
       ÷    ³   Integer divide by literal 3
     ⁼ι         Compare to outer loop variable
    Ｉ           Cast to string
                Implicitly print each outer result on a separate line

Ｅ³              Loop from 0 to 2
  ⭆θ            Loop over input string and join
            λ   Current character
           ⊖    Cast to integer and decrement
          ⁻  ι  Subtract outer loop variable
         ﹪    ³ Modulo by literal 3
        ¬       Logical not
       λ        Inner loop character
      Ｉ         Cast to integer
     ∧          Logical and
    Ｉ           Cast to string
                Implicitly print each outer result on a separate line

```
> 1 votes

# Answer
# Perl 5 `-F`, 52 bytes

```
for$i(123,456,789,0,147,258,369){say map$i=~$_|0,@F}

```

Try it online!

Uses `1` for punched and `0` for unpunched.
> 0 votes

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


title: Will you be my Weaver?

text:
# Question
Title: Will you be my Weaver?
I've been recently playing through 'The Weaver' and I think it presents an interesting challenge for .

# Premise:

The Weaver is a game wherein you are given a number of ribbons coming from 2 directions 90 degrees apart and your goal is to swap them at certain intersections to achieve a desired output.

Like this: This is a swap: This isn't:

# Input:

3 arrays:

* Top ribbons (left to right)
* Left ribbons (top to bottom)
* The coordinates of the intersections to swap

# Output:

2 arrays:

* Bottom ribbons (left to right)
* Right ribbons (top to bottom)

# Examples:

I'll use the above image as the first example:

Input: `[r, y, b], [r, y, b], [(0, 1), (2, 1), (2, 2)]`

What happens:

```
   r   y   b
   r   y   b
r r r r•y y y y
   r   r   b
y y y y y y y y
   r   r   b
b b b b•r r•b b
   r   b   r
   r   b   r

```

Where  represents a swap.

Output: `[r, b, r], [y, y, b]`

---

Input: `[a, b, c], [d, e, f], [(0, 0), (2, 1)]`

What happens:

```
   a   b   c
   a   b   c
d d•a a a a a a
   d   b   c
e e e e e e e e
   d   b   c
f f f f•b b b b
   d   f   c
   d   f   c

```

Output: `[d, f, c], [a, e, b]`

---

Input: `[a, b], [a, b, c], [(0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (3, 1)]`

What happens:

```
   a   b
   a   b
a a a a•b b
   a   a
b b•a a•a a
   b   a
c c•b b•a a
   c   b
   c   b

```

Output: `[c, b], [b, a, a]`

# Notes:

* The examples show coordinates given as `(row, column)` though you may take them as `(column, row)`.
* The top row and left column may have ribbons of the same color
* The board can be rectangular
* All coordinates will be non-negative (`>=0`) (or strictly positive (`>=1`) if you choose 1-indexing)
* Ignore any swaps that are outside the board
* You may choose to work with letters (`[a-zA-Z]`), integers (`[0-9]`) or both
* The ribbons in your output must match the ribbons in the input exactly (`a -> a`)
* You may assume the list of swaps is sorted in any way you want, as long as it's consistent (if you do, please specify how it should be sorted)
* You may take the swap coordinates as 0 or 1-indexed
* Default loopholes are forbidden

# More examples:

```
Input:
[b], [r], []
Output:
[b], [r]

Input:
[b], [r], [(0, 0)]
Output:
[r], [b]

Input:
[r, p, y], [r, y, p], [(0, 0), (1, 2), (2, 1), (3, 2)]
Output:
[r, p, y], [r, y, p]

Input:
[b, y, o, r],
[r, o, b, y],
[(0, 0), (2, 0), (3, 2)]
Output:
[b, y, y, r],
[b, o, r, o]

```

The last example relates to this case (if that makes it easier to visualize):

This is so the shortest answer in bytes for each language wins.

# Answer
# Python 3, 74 bytes

```
def g(a,b,l):
 for x,y in l:
  if x<len(a)and y<len(b):a[x],b[y]=b[y],a[x]

```

Try it online!

Requires `l` to be sorted in lexicographical order. `a` and `b` are lists of characters representing (left ribbon, top ribbon).

Returns by modifying the list `a` and `b`.
> 8 votes

# Answer
# Jelly, ~~37~~ ~~35~~ 30 bytes

```
ṙ"z0U1¦Zḟ€0ṙ"N}
<Ạ¥ÐfL€}⁹ṭṚç/Y

```

Try it online!

Dyadic program, take 0-indexing list of swap indices as left argument (sorted in reverse lexicographical order) and (left ribbon, top ribbon) as right argument. Returns (right ribbon, bottom ribbon).

---

Jelly is a tacit language. There is (almost) no variable to work with, so doing anything involves more than two variables at once is a mess.

The first link takes `[l,t]` as its left argument, `[x,y]` (0-indexing) as its right argument, and return `[l,t]` with `l[x]` and `r[y]` exchanged.

```
ṙ"z0U1¦Zḟ€0ṙ"N}
ṙ"               Zipwith rotate. Current value: `[l ṙ x, t ṙ y]`
                   (so l[x] and r[x] becomes l[0] and r[0] respectively)
  z0             Zip, fill with 0. Elements at corresponding (new) indices are
                   paired together, with 0 as the filler.
    U1¦          Reverse the pair at index `1` (first index).
       Zḟ€0      Zip again and filter out the `0`s, effectively undo the z0.
           ṙ"N}  Zipwith rotate by negative shift amount, reverse of `ṙ"`.

```

So basically "`U1¦` under `ṙ"z0`".

---

The second link simply filter out OoB indices (`<Ạ¥Ðf L€`), append the second argument (`⁹ṭ`), reverse (), and reduce over `ç` (similar to Haskell's `foldl`)
> 3 votes

# Answer
# Python 2, 193 bytes

```
def f(t,l,s):
 m=[[x,y]for y in[0]+l for x in[0]+t];L=len(t)+1
 for i in range(len(m)):
  if i%L:m[i]=[m[i-L][0],m[i-1][1]][::[1,-1][(i/L,i%L)in s]]
 s=sum(m,[]);print s[2-L*2::2],s[4*L-1::2*L]

```

Try it online!

Takes 1-indexed swap coordinates
> 2 votes

# Answer
# APL (Dyalog Classic), ~~31~~ 30 bytes

```
{⊃{⌽@(0 1,¨⍺)⊢⍵}/(⍵∩,⍳≢¨⍺),⊂⍺}

```

Try it online!

The left argument is a pair of character vectors - left ribbons and top ribbons. The right argument is a vector of coordinate pairs - swap locations. Returns a pair of right ribbons and bottom ribbons. (Note that unlike in the examples, I use the order left-top and right-bottom for the ribbons in order to be consistent with the row-col axis order in the coordinates.)

Swaps must be sorted so that a swap to the upper-left of another comes ~~before~~ *after* it. If two swaps are to the lower-left/upper-right of each other, their order doesn't matter.

EDIT: saved one byte () by requiring reverse order of swaps in the input
> 2 votes

# Answer
# Javascript, ~~87~~ ~~76~~ 62 bytes

```
(c,r,s)=>{for([i,j]of s)if(r[i]&&c[j])[r[i],c[j]]=[c[j],r[i]]}

```

Try it online!

Same trivial algorithm as the Python 3 answer. Uses arrays as coordinate tuples. Requires ribbon colors to be designated by truthy values. Requires coordinates to be partially ordered so that `x1,y1` comes before `x2,y2` if either `x1 < x2 && y1 = y2` or `x1 = x2 && y1 < y2`. Returns by modifying input arrays.
> 1 votes

# Answer
# Ruby, ~~56~~ 54 bytes

```
->t,l,s{s.map{|i,j|a=t[j];t[j]&&=l[i]||a;a&&l[i]&&=a}}

```

Try it online!

A port of user202729's Python 3 answer with some ruby tricks

Coordinates have to be lexicographically sorted
> 0 votes

---
Tags: code-golf, array, geometry, game
---


title: All Light All Light All Light!

text:
# Question
Title: All Light All Light All Light!
This challenge is completely ripped off*heavily inspired by* All Light, developed by Soulgit Games.

# Challenge

You are an electrician, and it's your job to wire up all the lights to the battery.

* The lights and battery are laid out in a grid.
* You can connect a light or battery to the nearest light or battery to its north, south, east, and west.
* The battery can have any number of connections.
* Each light specifies how many connections it requires. You must make *exactly* that many connections to that light.
* You can create single connections or double connections between two lights (or light and battery).
* Wires cannot cross.
* There must be a path from each light to the battery.
* At least one valid solution is guaranteed to exist.

Given the position of the battery and each light, and the number of connections each light requires, output the connections between them that admit these properties.

# Win Condition

This is , so the shortest code in each language wins.

# Test Cases

I/O is flexible as usual.

For input I will be using a 2d array the size of the grid which stores positive integers for lights, zeros for blank spaces, and -1 for the battery. Another good choice might be a list of lights, where a light is a tuple containing the light's position and number of required connections.

For output I will be using a list of connections, where a connection is a tuple containing the starting position and ending position. If a connection is doubled then I will have 2 of them in the list (another option is to include this parameter in the tuple). Another good option could be some sort of grid layout.

If you are using a coordinate system you may specify the starting index and where you index from. My examples will be 0-indexed and use (0, 0) as the top left corner (row, column). (I am using {} simply to introduce another type of delimiter so it is easier to read, *not* because they are sets.)

***Here is a graphical view of the test cases: Tests 1-12***

### Test 1:

`[-1 | 0 | 1 ] => [{(0, 0), (0, 2)}]`

### Test 2:

`[-1 | 0 | 2 ] => [{(0, 0), (0, 2)}, {(0, 0), (0, 2)}]`

### Test 3:

`[-1 ]
 [ 0 ] => [{(0, 0), (2, 0)), ((0, 0), (2, 0)}]
 [ 2 ]`

### Test 4:

`[ 1 | 0 |-1 | 0 | 2 ] => [{(0, 0), (0, 2)}, {(0, 2), (0, 4)}, {(0, 2), (0, 4)}]`

### Test 5:

`[ 2 ]
[ 0 ]
[-1 ] => [{(0, 0), (2, 0)}, {(0, 0), (2, 0)}, {(2, 0), (4, 0)}]
[ 0 ]
[ 1 ]`

### Test 6:

`[ 1 | 0 | 0 ]
[ 0 | 0 | 0 ] => [{(0, 0), (2, 0)}, {(2, 0), (2, 2)}]
[ 2 | 0 |-1 ]`

### Test 7:

`[ 4 | 0 | 0 |-1 ]
[ 0 | 0 | 0 | 0 ] => [{(0, 0), (0, 3)}, {(0, 0), (0, 3)},
[ 2 | 0 | 0 | 0 ] {(0, 0), (3, 0)}, {(0, 0), (3, 0)}]`

### Test 8:

`[ 2 | 0 |-1 | 0 | 2 ] [{(0, 0), (0, 2)}, {(0, 0), (0, 2)},
[ 0 | 0 | 0 | 0 | 0 ] => {(0, 2), (0, 4)}, {(0, 2), (0, 4)},
[ 0 | 0 | 1 | 0 | 0 ] {(0, 2), (2, 2)}]`

### Test 9:

`[ 0 | 0 | 2 | 0 | 0 ]
[ 0 | 0 | 0 | 0 | 0 ]
[ 1 | 0 |-1 | 0 | 1 ] => [{(0, 2), (2, 2)}, {(0, 2), (2, 2)}, {(2, 0), (2, 2)},
[ 0 | 0 | 0 | 0 | 0 ] {(4, 2), (2, 2)}, {(2, 4), (2, 2)}, {(2, 4), (2, 2)}]
[ 0 | 0 | 2 | 0 | 0 ]`

### Test 10:

`[-1 | 2 | 3 | 2 ] => [{(0, 0), (0, 3)}, {(0, 0), (0, 3)},
 {(0, 0), (0, 3)}, {(0, 0), (0, 3)}]`

### Test 11:

`[-1 | 0 | 0 | 0 ]
[ 3 | 0 | 0 | 0 ]
[ 3 | 0 | 0 | 3 ] => [{(0, 0), (1, 0)}, {(1, 0), (2, 0)}, {(1, 0), (2, 0)},
[ 0 | 0 | 0 | 0 ] {(2, 0), (2, 3)}, {(2, 3), (4, 3)}, {(2, 3), (4, 3)}]
[ 0 | 0 | 0 | 2 ]`

### Test 12:

`[ 2 | 0 | 0 ] [{(0, 0), (1, 0)}, {(0, 0), (1, 0)}, {(1, 0), (1, 1)},
[ 3 |-1 | 0 ] => {(1, 1), (2, 1)}, {(1, 1), (2, 1)}, {(2, 0), (2, 1)},
[ 2 | 5 | 1 ] {(2, 0), (2, 1)}, {(2, 1), (2, 2)}]`

# Answer
# JavaScript (Node.js), ~~393~~ ~~391~~ 378 bytes

```
a=>(R=[],f=(a,[x,...y],z,Y)=>x?f(a.map(t=>[...t]),y,z,Y)||f(a,y,[...z,x],Y.map(p=>p.map(q=>q-Y[x[0]][x[1]]?q:Y[x[2]][x[3]])),--a[x[0]][x[1]],--a[x[2]][x[3]]):/[1-9]/.test(a)|Y.some(t=>t.some(u=>u-Y[I][J]&&u))?0:z)(a=a.map(A=(b,i)=>b.map((x,j)=>x&&(A[i]+1&&R.push([i,A[i],i,j]),f[j]+1&&R.push([f[j],j,i,j]),A[I=i]=j,f[J=j]=i,x/=x>0))),[...R,...R],C=[],a.map(p=>p.map(q=>q&&++C)))

```

Try it online!

```
a=>(
    a=a.map(
        A=(b,i)=>
            b.map(
                (x,j)=>
                    x&&(                                  // A[i]+1 <==> A[i] is NOT NaN
                        A[i]+1&&R.push([i,A[i],i,j]),     // Use A and f to store last
                        f[j]+1&&R.push([f[j],j,i,j]),     // existance of row and column
                        A[I=i]=j,f[J=j]=i,x/=x>0          // -1 => -Inf, +n => n
                    )
            ),
            R=[],
            f=([x,...y],z,Y)=>
                x?
                    f(
                        y,[...z,x],
                        Y.map(p=>p.map(q=>q-Y[x[0]][x[1]]?q:Y[x[2]][x[3]])), // merge
                        --a[x[0]][x[1]],--a[x[2]][x[3]]
                    )||
                    f(y,z,Y,++a[x[0]][x[1]],++a[x[2]][x[3]])
                :
                    /[1-9]/.test(a)|
                    Y.some(t=>t.some(u=>u-Y[I][J]&&u)) // not totally merged
                    ?0:z
    ),f)([...R,...R],[],a.map(p=>p.map(q=>q&&++C),C=0)
)

```
> 2 votes

---
Tags: code-golf
---


# Question
Title: How to swap elements in a vector using an anonymous function in Octave?
Swapping two elements in a vector/matrix is very simple in Octave:

```
x='abcde';
x([4,1])=x([1,4])
x =
   dbcae

```

Unfortunately, I have yet to find a way to do this inside an anonymous function. While the function below is syntactically correct, it only gives back the two elements that are swapped, not the entire `x` vector:

```
f=@(x)(x([4,1])=x([1,4]))
f(x)
ans =
     ad

```

Is there a way to achieve the desired behavior using anonymous functions in a golfy way? Can several elements be swapped this way using an anonymous function?

I *could* create an indexing vector: `f=@(x)x([4,2,3,1,5])`, but creating such a vector dynamically will likely take a lot of bytes too.

# Answer
> 21 votes
# Argument List

```
f=@(x,y=x([4 1])=x([1 4]))x;

```

Try it online!

# Answer
> 11 votes
# Be `eval`

```
f=@(x)eval"x([4 1])=x([1 4])"

```

Try it online!

---

In Matlab the parentheses cannot be omitted:

```
f=@(x)eval('x([4 1])=x([1 4])')

```

# Answer
> 8 votes
## Cell array

One option is to use a cell array, like this:

```
f=@(x){x([1,4])=x([4,1]);x}{2}

```

Try it online!

---
Tags: code-golf, array, tips, octave
---


# Question
Title: The Top Ten Elements You Won't BELIEVE Are In This Array
AKA: Generate Clickbait From an Array.

Given an array of integers, generate some cringe-worthy clickbait based on its arrangement and length:

* If it's 20 elements or less, you can make a Top X List. *Parameters: length of the array.*
* Prime numbers are celebrities, so anytime two of them are next to each other it'll pass as gossip. *Parameters: the two adjacent primes in the order they appear in the array.*
* If any number appears twice or more in the array, then it's shocking and unbelievable and everyone needs to hear about it. If multiple numbers appear twice, make a news story for each one. Only print this once per unique number. *Parameters: occurrence of the number measured by total appearance.*
* If you see 3+ elements in ~~sorted~~ monotonically increasing order, followed by a sudden decrease, then tell of how they're sorted and tease about what happens next. Only do this once per straight. *Parameters: length of the straight.*

These are the respective clickbaits you should use:

```
The Top {{N}} Array Elements
{{N1}} And {{N2}} Were Spotted Together, You Won't Believe What They Did
These {{N}} Elements Will Blow Your Mind
{{N}} Elements Sort Themselves, Find Out What Comes Next

```

Remember, you represent a cheap media company, so you'll need to milk this and print every possible title. If there are 2 identical titles, print them both.

For example, if you're given this array…

```
1,2,3,4,2,1,1,5,6

```

You should output all of these, in arbitrary order:

```
The Top 9 Array Elements
2 And 3 Were Spotted Together, You Won't Believe What They Did
These 2 Elements Will Blow Your Mind
These 3 Elements Will Blow Your Mind
4 Elements Sort Themselves, Find Out What Comes Next

```

Note the *lack* of this title:

```
3 Elements Sort Themselves, Find Out What Comes Next

```

As code golf, the shortest answer in bytes wins.

# Answer
> 5 votes
# Jelly, 142 bytes

```
I>-ṣ0ṖS€ỊÐḟ‘ɓĠL€ḟ1,ɓ¹ƝÆPẠ$ÐfW;ɓLẋ<¥21W;ż@€"“æƥu®ụ³Km&|°ẓz“ṿ$¥{d3ɓFȤSJẎVḍnṃ*¹0Ḟ¬ȤɲƝċƲạB'ɼɓ.€⁺Ƒ“¢ßUṡʠx\~⁻ḅėʠAƓḳ¶e<“½ė!Ƙ¥Ḍ3]⁷ṀƭȮþċ⁽?ṫĠƁÆȦØ⁾Ż»ṣ€⁷¤

```

A monadic link accepting a list of integers, returning a list of lists of clickbaits (each of which is a list of characters and integers). For a full program printing line-feed separated clickbaits just add `ẎY` to the end.

**Try it online!** (Footer makes a single list of clickbaits and then separates them with new-lines.)
...or see **the example** given in the question.

### How?

The 99 right-most bytes of this Link form a nilad (a function with zero arguments, i.e. a constant):

```
“...“...“...“...»ṣ€⁷¤
                    ¤ - nilad followed by link(s) as a nilad:
“...“...“...“...»     - list of compressed strings (the four clickbait-texts with the
                      -   integers replaced with line-feed characters)
                   ⁷  - literal line-feed character
                 ṣ€   - split-at for €ach (read to interweave with the integers)

```

Let's label these text-parts as `X`, now the Link is:

```
I>-ṣ0ṖS€ỊÐḟ‘ɓĠL€ḟ1,ɓ¹ƝÆPẠ$ÐfW;ɓLẋ<¥21W;ż@€"X - Link: list of integers Z
                                             - # get the monotonically increasing runs:
I                                            - incremental differences of Z
 >-                                          - greater than -1 (vectorises)
   ṣ0                                        - split at zeros
     Ṗ                                       - pop (discard final run)
      S€                                     - sum each (length - 1 for all runs)
         Ðḟ                                  - filter discard if:
        Ị                                    -   insignificant (discard any 0s or 1s)
           ‘                                 - increment (yielding all run-lengths >= 3)
            ɓ                                - new dyadic chain with that on the right
                                             - # get the multiplicities:
             Ġ                               - group indices of Z by value
              L€                             - length of €ach
                ḟ1                           - filter discard 1s
                  ,                          - pair with right (the run-lengths)
                   ɓ                         - new dyadic chain with that on the right
                                             - # get the prime-pairs
                     Ɲ                       - for each pair in Z
                    ¹                        -   identity (do nothing)
                          Ðf                 - filter keep if:
                         $                   -   last two links as a monad:
                      ÆP                     -     is prime? (vectorises)
                        Ạ                    -     all?
                            W                - wrap in a list
                             ;               - concatenate with right ([multiplicities,runs])
                              ɓ              - new dyadic chain with that on the right
                                             - # get top count as a list
                               L             - length
                                   21        - literal 21
                                  ¥          - last two links as a dyad
                                 <           -   less than? (1 if 20 or less, else 0)
                                ẋ            -   repeat ([length] if 20 or less, else [])
                                     W       - wrap in a list (i.e. [[length]] or [[]])
                                      ;      - concatenate with right ([[prime pairs],[multiplicities],[run-lengths]])
                                             - ...now we have [[length],[prime pairs],[multiplicities],[run-lengths]]
                                          "X - zip with X (the text-parts)
                                         €   -   for each (item in the current list):
                                       ż@    -     interleave with swapped arguments

```

# Answer
> 2 votes
# Java 10, ~~467~~ ~~457~~ ~~456~~ 453 bytes

```
a->{int l=a.length,i=0,p=0,P=0,m[]=new int[999],t;String e=" Elements ",r=l<21?"The Top "+l+" Array"+e+"\n":"";for(;i<l;r+=i>0&&p(p)>1&p(t=a[i-1])>1?p+" And "+t+" Were Spotted Together, You Won't Believe What They Did\n":"",m[a[i++]]++)if(p<(p=a[i]))P++;else{r+=P>2?P+e+"Sort Themselves, Find Out What Comes Next\n":"";P=1;}for(;l-->0;r+=m[l]>1?"These "+m[l]+e+"Will Blow Your Mind\n":"");return r;}int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}

```

Assumes the input-array will contain values `0 < N < 1000` (`[1,999]`).

Try it online.

```
a->{                     // Method with integer-array parameter and String return-type
  int l=a.length,        //  Length of the input-array
      i=0,               //  Index-integer
      p=0,               //  Previous item, starting at 0
      P=0,               //  Sequence-counter, starting at 0
      m[]=new int[999],  //  Element-counter array, starting filled with 0s
      t;                 //  Temp-integer to reduce the byte-count
  String e=" Elements ", //  Temp-String " Elements " to reduce byte-count
         r=l<21?         //  If the size of the input-array is 20 or less:
            "The Top "+l+" Array"+e+"\n"
                         //    Start the result-String with 'length' gossip-line
           :             //   Else:
            "";          //    Start the result-String empty
  for(;i<l               //  Loop over the input-array
      ;                  //    After every iteration:
       r+=i>0&&          //     If this is not the first item,
           p(p)>1&p(t=a[i-1])>1?
                         //     and the current and previous items are both primes:
             p+" And "+t+" Were Spotted Together, You Won't Believe What They Did\n":"",
                         //      Append the 'two primes' gossip-line
       m[a[i++]]++)      //     Increase the counter of the current value by 1
    if(p<(p=a[i])        //   If the previous item is smaller than the current:
      P++;               //    Increase the sequence-counter by 1
    else{                //   Else:
      r+=P>2             //    If the sequence-counter is 3 or larger:
          P+e+"Sort Themselves, Find Out What Comes Next\n":"";
                         //     Append the 'sequence' gossip-line
      P=1;}              //    Reset the sequence-counter to 1
  for(;l-->0;            //  Loop over the Element-counter array
      r+=m[l]>1?         //   If this element occurred at least two times:
          "These "+m[l]+e+"Will Blow Your Mind\n":"");
                         //    Append the 'occurrence' gossip-line
  return r;}             //  Return the result

// Separated method to check if the given number is a prime
// If `n` is a prime, it remains the same; if not: either 1 or 0 is returned
int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}

```

# Answer
> 1 votes
* still golfing but help will be much appreciated

# JavaScript (Node.js), 397 bytes

```
a=>a.map(x=>(l<=x?s++:(s>2&&r.push(s+" Elements Sort Themselves, Find Out What Comes Next"),s=1),P(x)&&P(l)&&r.push(l+` And ${x} Were Spotted Together, You Won't Believe What They Did`),c[l=x]=-~c[x]),c=[s=l=r=[]])&&c.map((x,i)=>x>1&&c.indexOf(x)==i&&r.push(`These ${x} Elements Will Blow Your Mind`))&&[...r,...a[20]?[]:[`The Top ${a.length} Array Elements`]]
P=(n,i=1)=>n>1&&++i*i>n||n%i&&P(n,i)

```

Try it online!

# Answer
> 1 votes
# JavaScript (Node.js), ~~351~~ ~~350~~ ~~349~~ 347 bytes

```
a=>a.map((x,i)=>c[s=x>=l?-~s:++s>2&&(t+=s+` Elements Sort Themselves, Find Out What Comes Next
`),P(x)&P(l)&&(t+=l+` And ${x} Were Spotted Together, You Won't Believe What They Did
`),l=x]=-~c[x],t=a[20]?'':`The Top ${a.length} Array Elements
`,c=[s=l=P=(n,i=n)=>n%--i?P(n,i):1/i])+c.map(x=>x>1&&(t+=`These ${x} Elements Will Blow Your Mind
`))&&t

```

Try it online!

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


# Question
Title: Count the words in a text and display them
The code should take input a text (not mandatory can be anything file, stdin, string for JavaScript, etc):

```
This is a text and a number: 31.

```

The output should contain the words with their number of occurrence, sorted by the number of occurrences in descending order:

```
a:2
and:1
is:1
number:1
This:1
text:1
31:1

```

Notice that 31 is a word, so a word is anything alpha-numeric, number are not acting as separators so for example `0xAF` qualifies as a word. Separators will be anything that is not alpha-numeric including `.`(dot) and `-`(hyphen) thus `i.e.` or `pick-me-up` would result in 2 respectively 3 words. Should be case sensitive, `This` and `this` would be two different words, `'` would also be separator so `wouldn`and `t` will be 2 different words from `wouldn't`.

Write the shortest code in your language of choice.

Shortest correct answer so far:

# Answer
> 27 votes
## grep and coreutils  ~~44~~  42

```
grep -io '[a-z0-9]*'|sort|uniq -c|sort -nr

```

Test:

```
printf "This is a text and a number: 31." |
grep -io '[a-z0-9]*'|sort|uniq -c|sort -nr

```

Results in:

```
  2 a
  1 This
  1 text
  1 number
  1 is
  1 and
  1 31

```

### Update

* Use case-insensitive option and shorter regex. Thanks Tomas.

# Answer
> 18 votes
# Java 8: 289

Which is pretty good, since java is a very non-golfy language.

```
import java.util.stream.*;class C{static void main(String[]a){Stream.of(a).flatMap(s->of(s.split("[\\W_]+"))).collect(Collectors.groupingBy(x->x,Collectors.counting())).entrySet().stream().sorted(x,y->x.getValue()-y.getValue()).forEach(e->System.out.println(e.getKey()+":"+e.getValue()));}

```

Ungolfed:

```
import java.util.stream.*;
class C {
    static void main(String [] args){
        Stream.of(args).flatMap(arg->Stream.of(arg.split("[\\W_]+")))
            .collect(Collectors.groupingBy(word->word,Collectors.counting()))
            .entrySet().stream().sorted(x,y->x.getValue()-y.getValue())
            .forEach(entry->System.out.println(entry.getKey()+":"+entry.getValue()));
    }
}

```

Run from the command line:

```
java -jar wordCounter.jar This is a text and a number: 31.

```

# Answer
> 17 votes
## APL (57)

```
⎕ML←3⋄G[⍒,1↓⍉G←⊃∪↓Z,⍪+⌿∘.≡⍨Z←I⊂⍨(I←⍞)∊⎕D,⎕A,⎕UCS 96+⍳26;]

```

e.g.

```
      ⎕ML←3⋄G[⍒,1↓⍉G←⊃∪↓Z,⍪+⌿∘.≡⍨Z←I⊂⍨(I←⍞)∊⎕D,⎕A,⎕UCS 96+⍳26;]
This is a text and a number: 31.
 a       2
 This    1
 is      1
 text    1
 and     1
 number  1
 31      1

```

Explanation:

* `⎕D,⎕A,⎕UCS 96+⍳26`: numbers, uppercase letters, lowercase letters
* `(I←⍞)∊`: read input, store in `I`, see which ones are alphanumeric
* `Z←I⊂⍨`: split `I` in groups of alphanumeric characters, store in `Z`
* `+⌿∘.≡⍨Z`: for each element in `Z`, see how often it occurs
* `Z,⍪`: match each element in `Z` pairwise with how many times it occurs
* `G←⊃∪↓`: select only the unique pairs, store in `G`
* `⍒,1↓⍉G`: get sorted indices for the occurrences
* `G[`...`;]`: reorder the lines of `G` by the given indices

# Answer
> 8 votes
# C#: ~~153c~~ ~~144c~~ ~~142c~~ ~~111c~~ ~~115c~~ ~~118c~~ ~~114c~~ 113c

*(via LINQPad in "C# Statements" mode, not including input string)*

## Version 1: 142c

```
var s = "This is a text and a number: 31."; // <- line not included in count
s.Split(s.Where(c=>!Char.IsLetterOrDigit(c)).ToArray(),(StringSplitOptions)1).GroupBy(x=>x,(k,e)=>new{s,c=e.Count()}).OrderBy(x=>-x.c).Dump();

```

Ungolfed:

```
var s = "This is a text and a number: 31.";
s.Split(                                                     // split string on multiple separators
    s.Where(c => !Char.IsLetterOrDigit(c))                   // get list of non-alphanumeric characters in string
     .ToArray(),                                             // (would love to get rid of this but needed to match the correct Split signature)
    (StringSplitOptions)1                                    // integer equivalent of StringSplitOptions.RemoveEmptyEntries
).GroupBy(x => x, (k, e) => new{ s = k, c = e.Count() })     // count by word
 .OrderBy(x => -x.c)                                         // order ascending by negative count (i.e. OrderByDescending)
 .Dump();                                                    // output to LINQPad results panel

```

Results:

## Version 2: 114c

(`[\w]` includes `_`, which is incorrect!; `[A-z]` includes `[ \ ] ^ _ ``; settling on `[^_\W]+`)

```
var s = "This is a text and a number: 31."; // <- line not included in count
Regex.Matches(s, @"[^_\W]+").Cast<Match>().GroupBy(m=>m.Value,(m,e)=>new{m,c=e.Count()}).OrderBy(g=>-g.c).Dump();

```

Ungolfed:

```
Regex.Matches(s, @"[^_\W]+")                                   // get all matches for one-or-more alphanumeric characters
     .Cast<Match>()                                            // why weren't .NET 1 collections retrofitted with IEnumerable<T>??
     .GroupBy(m => m.Value, (m,e) => new{ m, c = e.Count() })  // count by word
     .OrderBy(g => -g.c)                                       // order ascending by negative count (i.e. OrderByDescending)
     .Dump();                                                  // output to LINQPad results panel

```

Results: (as Version 1)

# Answer
> 7 votes
### R, 58 char

```
sort(table(unlist(strsplit(scan(,""),"[[:punct:]]"))),d=T)

```

Usage:

```
sort(table(unlist(strsplit(scan(,""),"[[:punct:]]"))),d=T)
1: This is a text and a number: 31.
9:
Read 8 items

     a     31    and     is number   text   This
     2      1      1      1      1      1      1

```

# Answer
> 6 votes
# Python ~~101~~ 97

```
import re
a=re.split('[_\W]+',input())
f=a.count
for w in sorted(set(a),key=f)[::-1]:print w,f(w)

```

Now works with newline:

```
$ python countword.py <<< '"This is    a text and a number: 31, and a\nnewline"'
a 3
and 2
31 1
number 1
newline 1
is 1
text 1
This 1

```

# Answer
> 6 votes
## PHP - 84 bytes

```
<?$a=array_count_values(preg_split('/[_\W]+/',$argv[1],0,1));arsort($a);print_r($a);

```

Input is accepted as a command line argument, e.g.:

```
$ php count-words.php "This is a text and a number: 31."

```

Output for the sample string:

```
Array
(
    [a] => 2
    [number] => 1
    [31] => 1
    [and] => 1
    [text] => 1
    [is] => 1
    [This] => 1
)

```

# Answer
> 6 votes
## perl6: 49 characters

```
.say for get.comb(/\w+/).Bag.pairs.sort(-*.value)

```

Comb input for stuff matching `\w+`, put resulting list of words in a `Bag`, ask for their pairs and sort them by negative value. (The `*` is a Whatever star, it's not multiplication here)

output:

```
"a" => 2
"This" => 1
"is" => 1
"text" => 1
"and" => 1
"number" => 1
"31" => 1

```

# Answer
> 5 votes
**PowerShell (40)**

```
$s -split"\W+"|group -ca|sort count -des

```

$s is a variable that contains the input string.

# Answer
> 5 votes
# GNU awk + coreutils: 71 69

```
gawk 'BEGIN{RS="\\W+"}{c[$0]++}END{for(w in c)print c[w],w}'|sort -nr

```

Although `gawk asort` works on associative arrays, it apparently does not preserve the index values, necessitating the external `sort`

```
printf "This is a text and a number: 31." |
gawk 'BEGIN{RS="\\W+"}{c[$0]++}END{for(w in c)print c[w],w}'|sort -nr
2 a
1 This
1 text
1 number
1 is
1 and
1 31

```

# GNU awk 4.x: 100 93

A slightly larger but pure gawk solution using `PROCINFO` to set the default sort order for the associative array (appears to require a relatively recent gawk - \> 4.x?)

```
BEGIN{RS="\\W+";PROCINFO["sorted_in"]="@val_num_desc"}
{c[$0]++}
END{for(w in c)print c[w],w}

```

# Answer
> 4 votes
## Perl 69

```
$h{$_}++for<>=~/\w+/g;print"$_: $h{$_}
"for sort{$h{$b}-$h{$a}}keys%h

```

Added recommendations from @primo and @protist

# Answer
> 4 votes
## Powershell: ~~57~~ ~~55~~ ~~53~~ ~~62~~ 57

*(not including input string)*

```
$s = "This is a text and a number: 31."    # <-- not counting this line...
[Regex]::Matches($s,"[^_\W]+")|group -ca|sort{-$_.Count}

```

returns:

```
Count Name                      Group
----- ----                      -----
    2 a                         {a, a}
    1 and                       {and}
    1 31                        {31}
    1 number                    {number}
    1 This                      {This}
    1 is                        {is}
    1 text                      {text}

```

(with props to @microbian for group -ca)

# Answer
> 3 votes
# Groovy 77 82

changed regex from `[^\w]+` to `[^\d\p{L}]+` in order to solve problem with underscore

```
String s = 'This is a text and a number: 31'

def a=s.split(/[^\d\p{L}]+/)
a.collectEntries{[it, a.count(it)]}.sort{-it.value}

```

without first line, 82 characters

output:

```
[a:2, This:1, is:1, text:1, and:1, number:1, 31:1]

```

# Answer
> 3 votes
# EcmaScript 6

## Version 1 (108 characters)

```
s.split(_=/[^a-z\d]/i).map(x=>_[x]=-~_[x]);keys(_).sort((a,b)=>_[a]<_[b]).map(x=>x&&console.log(x+':'+_[x]))

```

## Version 2 (102 characters)

```
s.split(_=/[^a-z\d]/i).map(x=>_[x]=-~_[x]);keys(_).sort((a,b)=>_[a]<_[b]).map(x=>x&&alert(x+':'+_[x]))

```

## Version 3 (105 characters)

```
s.match(_=/\w+/g).map(x=>_[x]=-~_[x]);alert(keys(_).sort((a,b)=>_[a]<_[b]).map(x=>x+':'+_[x]).join('\n'))

```

## Version 4 (94 characters)

```
s.match(_=/\w+/g).map(x=>_[x]=-~_[x]);keys(_).sort((a,b)=>_[a]<_[b]).map(x=>alert(x+':'+_[x]))

```

## Version 5 (without alert; 87 characters)

```
s.match(_=/\w+/g).map(x=>_[x]=-~_[x]);keys(_).sort((a,b)=>_[a]<_[b]).map(x=>x+':'+_[x])

```

## Version 6 (100 characters)

```
keys(_,s.match(_=/\w+/g).map(x=>_[x]=-~_[x])).sort((a,b)=>_[a]<_[b]).map(x=>console.log(x+':'+_[x]))

```

---

## Output:

```
a:2
31:1
This:1
is:1
text:1
and:1
number:1

```

# Answer
> 3 votes
# Javascript - ~~132~~ 126 chars !

### (Shortest JS code)

```
o={},a=[]
for(i in s=s.split(/[\W_]+/))o[z=s[i]]=o[z]+1||1
for(j in o)a.push([j,o[j]])
a.sort(function(b,c){return c[1]-b[1]})

```

Improved the regex and some edits.

---

## Ungolfed

```
s = s.split(/[\W_]+/), o={}, a=[]; // split along non-char letters, declare object and array

for (i in s) { n = s[i]; o[n] = o[n] + 1 || 1 } // go through each char and store it's occurence

for (j in o) a.push( [j, o[j]] ); // store in array for sorting

a.sort(function (b, c){ return c[1] - b[1]; }); // sort !

```

---

> \<= // make s = "How shiny is this day is isn't is"
>
> =\> \[ \[ 'is', 3 \],
> \[ 'How', 1 \],
> \[ 'shiny', 1 \],
> \[ 'this', 1 \],
> \[ 'day', 1 \],
> \[ 'isn', 1 \],
> \[ 't', 1 \] \]

---

### Old - ~~156~~ ~~143~~ ~~141~~ ~~140~~ 132 chars

```
s=s.split(/[^\w]+/g),o={}
for(i in s){n=s[i];o[n]=o[n]+1||1}a=[]
for(j in o)a.push([j,o[j]])
a.sort(function(b,c){return c[1]-b[1]})

```

---

Gave a first try at golfing. Feedback appreciated.

# Answer
> 2 votes
# Ruby ~~58~~ ~~82~~ 65

```
h=Hash.new 0
gets.scan(/[\d\w]+/){h[$&]+=1}
p *h.sort_by{|k,v|-v}

```

Test run:

```
$ ruby counttext.rb <<< "This is a text and a number: 31."
["a", 2]
["text", 1]
["This", 1]
["is", 1]
["and", 1]
["number", 1]
["31", 1]

```

---

Edit 58-\>80: Ok, I was way off. I forgot to sort the words by occurrences. Also, `Array#uniq` is not an enumerator, but uses a given block to compare elements, so passing `puts` to it didn't filter out duplicates (not that it says that we should).

# Answer
> 2 votes
## Python - 95 ( now ***87*** thanks to @primo)

```
d=__import__('re').findall(r'\w+',raw_input())
print sorted(map(lambda y:(y,d.count(y)),d))

```

Sample input :

```
'This is a text and a number: 31'

```

Sample output :

```
[('This', 1),('is', 1), ('a', 2),('text', 1),('and', 1),('a', 2),('number', 1),('31', 1)]

```

Any improvement sugestion would be appreciated

# Answer
> 2 votes
# JavaScript 160 144 (Edited: to meet requirements)

```
f=Function;o={};s.replace(/\w+/g,f('a','o[a]=++o[a]||1'));Object.keys(o).sort(f('b,c','return o[c]-o[b]')).map(f('k','console.log(k+" "+o[k])'))

```

Unminified:

```
f=Function;
o = {};
s.replace(/\w+/g, f('a','o[a]=++o[a]||1'));
Object.keys(o).sort(f('b,c', 'return o[c]-o[b]')).map(f('k','console.log(k+" "+o[k])'))

```

Logs each word to console in order, passing the following string:

`s="This is sam}}ple text 31to test the effectiveness of this code, you can clearly see that this is working-as-intended, but you didn't doubt it did you?.";`

Outputs:

```
you 3
this 2
is 2
can 1
text 1
31to 1
test 1
the 1
effectiveness 1
of 1
This 1
code 1
sam 1
ple 1
clearly 1
see 1
that 1
working 1
as 1
intended 1
but 1
didn 1
t 1
doubt 1
it 1
did 1

```

I don't have the heart to use `alert()`.

# Answer
> 2 votes
## EcmaScript 6, 115 100 87 (without prompt&alert)

Thanks to @eithedog:

```
s.match(/\w+/g,a={}).map(w=>a[w]=-~a[w]),keys(a).map(w=>[w,a[w]]).sort((a,b)=>b[1]-a[1])

```

With prompt and alert (100):

```
prompt(a={}).match(/\w+/g).map(w=>a[w]=-~a[w]);alert(keys(a).map(w=>[w,a[w]]).sort((a,b)=>b[1]-a[1]))

```

Run it in Firefox.

# Answer
> 2 votes
**F# - 169**

```
let f s=(s+"").Split(set s-set(['a'..'z']@['A'..'Z']@['0'..'9'])|>Set.toArray)|>Seq.where((<>)"")|>Seq.countBy id|>Seq.sortBy((~-)<<snd)|>Seq.iter((<||)(printfn"%s:%d"))

```

Degolfed:

```
let count (s : string) =
    s.Split (set s - set (['a'..'z']@['A'..'Z']@['0'..'9']) |> Set.toArray)
 |> Seq.where ((<>) "")
 |> Seq.countBy id
 |> Seq.sortBy ((~-) << snd)
 |> Seq.iter ((<||) (printfn "%s:%d"))

```

Output when called from fsi:

```
> "This is a text and a number: 31." |> f
a:2
This:1
is:1
text:1
and:1
number:1
31:1
val it : unit = ()

```

**Update:** Some explanation as requested in the comments.

Uses set functions to generate an array of non alphanumeric characters in the input to pass to String.Split, then uses sequence functions to filter out empty strings, generate word counts and print the result.

Some golfing tricks: Adds an empty string to the function argument s to force type inference of the argument as a string rather than explicitly declaring the type. Uses Seq.where rather than Seq.filter to save a few characters (they are synonyms). Mixes forward pipe and ordinary function application in an attempt to minimize characters. Uses currying and (op) syntax to treat \<\> ~- and \<|| operators as regular functions to avoid declaring lambdas to filter empty strings, sort by descending count and print tuples.

# Answer
> 2 votes
# Pure Bash (no external programs), 164

This is longer than I'd hoped, but I wanted to see if the necessary counting and sorting (in the right direction) could be done purely with `bash` arrays (associative and non-associative):

```
declare -A c
for w in ${@//[[:punct:]]/ };{ ((c[$w]++));}
for w in ${!c[@]};{ i=${c[$w]};((m=i>m?i:m));s[$i]+=$w:;}
for((i=m;i>0;i--));{ printf "${s[i]//:/:$i
}";}

```

Save as a script file, `chmod +x`, and run:

```
$ ./countoccur This is a text and a number: 31.
a:2
and:1
number:1
text:1
31:1
is:1
This:1
$

```

# Answer
> 2 votes
# q (50)

```
desc count each group" "vs ssr[;"[^0-9A-Za-z]";" "]

```
* ssr replaces non alphanumeric
* " "vs splits the result into a symbol list
* count each group counts creates a dict matching distinct elements of the list with the number of occurances
* desc sorts the dict by descending values

edit: fixed accidentally matching ascii 58-64 and 91-96

# Answer
> 2 votes
# k \[71 chars\]

```
f:{s:" ",x;`_k!m@k:|(!m)@<.:m:#:'=`$1_'(&~((),/:s)like"[a-zA-Z0-9]")_s}

```

Any other character except alphanumeric chars will be considered as delimiter.

### example

```
f "This is a text and a number: 31."
a     | 2
31    | 1
number| 1
and   | 1
text  | 1
is    | 1
This  | 1

```

### example

```
f "won't won won-won"
won| 4
t  | 1

```

# Answer
> 2 votes
# Javascript (135)

```
u=/\w+/g
for(i=s.length;i--;)for(w in a=s.match(u))u[w=a[w]]=u[w]||a.reduce(function(p,c){return p+=w==c},0)==i&&!console.log(w+":"+i)

```

Unminified:

```
u=/\w+/g;for (i=s.length;i--;)
    for(w in a=s.match(u))
        u[w=a[w]] = u[w] ||
           a.reduce(function(p,c){return p+=w==c},0)==i && !console.log(w+":"+i)

```

Loops over every possible number of matches in descending order, and outputs words with that number of occurrences. Just to be horrible.

Notes: Alert would have reduced the length some. Strictly speaking alphanumeric should be `[^\W_]`

# Answer
> 2 votes
# Haskell (153 = 104 code + 49 import)

Pretty straight-forward, totally composed function... no argument even necessary! This is my first golf, so go easy, maybe? :)

```
import Data.Char
import Data.List
import Data.Ord
so=reverse.(sortBy$comparing snd).(map(\t@(x:_)->(x,length t))).group.sort.(map$filter isAlphaNum).words

```

Output:

```
*Main> so "This is a text and a number: 31."
[("a",2),("text",1),("number",1),("is",1),("and",1),("This",1),("31",1)]

```

# Answer
> 2 votes
# AWK

```
awk -vRS='[^A-Za-z0-9]' '$0{c[$0]++}END{for(i in c)print c[i]"\t"i": "c[i]|"sort -nr|cut -f2-"}'

```

Does the job without gawkish extensions:

```
$ echo 'This is a text and a number: 31.' | awk -vRS='[^A-Za-z0-9]' '$0{c[$0]++}END{for(i in c)print c[i]"\t"i": "c[i]|"sort -nr|cut -f2-"}'
a: 2
This: 1
text: 1
number: 1
is: 1
and: 1
31: 1

```

If printing "count: word" instead, it would be a bit shorter but I wanted to mimic the given example output...

# Answer
> 2 votes
# Tcl, 99 bytes

```
proc C s {lmap w [split [regsub -all \[^\\w|\ \] $s {}]] {dict inc D $w}
lsort -s 2 -inde 1 -de $D}

```

Try it online!

# Answer
> 1 votes
Python 2.X (108 - Characters)

```
print'\n'.join('{}:{}'.format(a,b)for a,b in __import__("collections").Counter(raw_input().split()).items())

```

Python 3.X (106 - Characters)

```
print('\n'.join('{}:{}'.format(a,b)for a,b in __import__("collections").Counter(input().split()).items())

```

# Answer
> 1 votes
# Python 3 - 76

The requirement of splitting on non-alphanumeric chars unfortunately extends the code by 19 chars. The output of the following is shown correctly. If you are not sure, add a `.most_common()` after the `.Counter(...)`.

```
i=__import__
print(i('collections').Counter(i('re').findall('\w+',input())))

```

### In/Output

Given the input of `This is a text and a number: 31.` you get following output:

```
Counter({'a': 2, 'is': 1, 'This': 1, 'and': 1, '31': 1, 'number': 1, 'text': 1})

```

I tried it with other values like

```
1 2 3 4 5 6 7 8 2 1 5 3 4 6 8 1 3 2 4 6 1 2 8 4 3 1 3 2 5 6 5 4  2 2 4 2 1 3 6

```

to ensure, the output-order does not rely on the key's value/hash. This example produces:

```
Counter({'2': 8, '3': 6, '1': 6, '4': 6, '6': 5, '5': 4, '8': 3, '7': 1})

```

But as I said, `print(i('collections').Counter(i('re').findall('\w+',input())).most_common())` would return the results as an *definitly* ordered list of tuples.

---

## Python 3 - 57 *(if a space would be enough for splitting :P)*

```
print(__import__('collections').Counter(input().split()))

```

# Answer
> 1 votes
# Haskell - 137

```
import Data.List
count text=let textS=(words(text\\".-\':")) in (sortBy (\(_,n) (_,m) -> compare m n)).nub$map(\t->(t,(length.(filter(==t)))textS)) textS

```

# Answer
> 1 votes
**J, 35+?**

```
(~.(([\:]);]\:]),.@(+/"1@=))@(>@;:)

```

Doesn't fully work though. Problem is that the splitting into words ';:' monad doesn't handle non-alplanumeric characters in quite the right way. Any suggestions?

Here's how you use it:

```
(~.(([\:]);]\:]),.@(+/"1@=))@(>@;:) 'This is a text and a number: 31.'
┌───────┬─┐
│a      │2│
│This   │1│
│is     │1│
│text   │1│
│and    │1│
│number:│1│
│31.    │1│
└───────┴─┘

```

# Answer
> 1 votes
# LiveScript \- 74 (translation of ECMA one)

```
s.match(/[^_\W]+/g,a={})map (->-~=a[it]),keys(a)map(->[it,a[it]])sort (.1-&1.1)

```

# Answer
> 1 votes
# Clojure

```
(defn wc [s]
  (let [mc #(assoc % %2 (inc (get % %2 0)))]
    (sort-by #(- (val %))
             (reduce mc {} (re-seq #"\w+" (.toLowerCase s))))))

```

example:

```
(wc "hi mom hi dad hello peter hello dad hi")
;; (["hi" 3] ["hello" 2] ["dad" 2] ["peter" 1] ["mom" 1])

```

# Answer
> 1 votes
# Smalltalk, 91 78

```
input in s

(s allRegexMatches:'\w+')asBag valuesAndCountsDo:[:c :n|(c,$:)print.n printNL]

```

input:

> pick-me-up This is a text and a number: 31.

output:

```
31:1
pick:1
text:1
me:1
number:1
up:1
is:1
a:2
and:1
This:1

```

# Answer
> 1 votes
# Python (95):

```
a=sorted(raw_input().split(__import__("string").punctuation))
for i in set(a):print i,a.count(i)

```

Pretty straightforward, I'd say.

# Answer
> 1 votes
## Mathematica, 56 bytes

What, no Mathematica answer yet? This one is not quite a winner, but it's both concise *and* quite expressive:

```
f=SortBy[Tally@StringCases[#,WordCharacter..],-Last@#&]&

```

Calling `f["This is a text and a number: 31."]` yields

```
{
 {"a", 2},
 {"31", 1},
 {"and", 1},
 {"is", 1},
 {"number", 1},
 {"text", 1},
 {"This", 1}
}

```

# Answer
> 1 votes
# shell utils, also 42 characters

```
tr -sc [:alnum:] \\n|sort|uniq -c|sort -rn

```

Another approach that equals Thor's answer.

# Answer
> 1 votes
Will never win but wanted to try anyway...

# C# (118)

```
var i = "This is a text and a number: 31.";
//The above line is not counted
Regex.Split(i,@"[\W_]").Where(w=>w!="").GroupBy(g=>g).OrderBy(o=>-o.Count()).Select(s=>new{s.Key,V=s.Count()}).Dump();

```

Ungolfed:

```
Regex.Split(i, @"[\W_]")                         //split by special chars
     .Where(w => w != "")                        //remove empty
     .GroupBy(g => g)                            //group by word
     .OrderBy(o => -o.Count())                   //order by reversed count
     .Select( s => new { s.Key, V = s.Count() }) //select value and count
     .Dump();                                    //write to screen (LinQPad)

```

# Answer
> 1 votes
# J 69

Should handle corner-cases like ' - etc, at the huge cost of including all alphanumeric characters (`u:62$,65 97 48+/i.26`):

```
(>@~.,.':',.":@#/.~)(#~*@#&>)(<;._1~-.@e.&(u:62$,65 97 48+/i.26))'.',

```

Usage: just append whatever string to be counted bewteen single quotes (mind that you need to double single quotes in the string).

Example:

```
   (>@~.,.':',.":@#/.~)(#~*@#&>)(<;._1~-.@e.&(u:62$,65 97 48+/i.26))'.','This is a text and a number: 31. More-tests wouldn''t be bad'
This  :1
is    :1
a     :2
text  :1
and   :1
number:1
31    :1
More  :1
tests :1
wouldn:1
t     :1
be    :1
bad   :1

```

# Answer
> 1 votes
**Python 2 - 61**

Assuming the input is in variable `s`, which is more realistic in real programming than user input anyway.

```
import re,collections as c
print c.Counter(re.split('\W+',s))

```

**output**

```
Counter({'a': 2, 'and': 1, '': 1, 'This': 1, 'text': 1, 'is': 1, 'number': 1, '31': 1})

```

This isn't really good output me thinks. It has an empty word and isn't readable. Here's a version with neat output (90):

**Python 2 (neat) - 90**

```
import re,collections as c
d=c.Counter(re.split('\W+',s))
for w in d:
  if w:print w+':'+`d[w]`

```

**output**

```
a:2
and:1
This:1
text:1
is:1
number:1
31:1

```

# Answer
> 1 votes
## Clojure

```
(defn count-words [string]
  (as-> string s
        (clojure.string/replace s #"[^a-zA-Z0-9 ]" "")
        (clojure.string/split s #"\W")
        (frequencies s)
        (sort-by val s)
        (reverse s)))

(clojure.pprint/pprint (count-words "This is a text and a number: 31."))

;; => (["a" 2] ["31" 1] ["number" 1] ["and" 1] ["text" 1] ["is" 1] ["This" 1])

```

I thought I would beat markw's concision with this approach, but I didn't.

# Answer
> 1 votes
# Perl 6, ~~53~~ 39 bytes

```
{.comb(/<-[_\W]>+/).Bag.sort:{-.value}}

```

I use `.comb` to find every word matching the regexp `<-[_\W]>+`. In Perl 6, character classes are written `<[]>` instead of `[]`, and negative character classes `<-[]>` instead of `[^]`.

We then transform the list of words to a `Bag` (a set that keeps the number of occurences), and we sort said bag by their value.

# Answer
> 0 votes
**C# (332)**

*This is my original program after excluding white spaces. Please pardon me if I did mistake in counting*

```
using System;
using System.Collections.Generic;
using System.Linq;

class P
{
    static void Main(String[] A)
    {
        Dictionary<string,int> D=new Dictionary<string,int>();
        foreach(string s in A)
        {
            if(!D.ContainsKey(s))
                D.Add(s,1);
            else D[s]+= 1;
        }
        foreach(KeyValuePair<string,int> i in D.OrderByDescending(k=>k.Value))
            Console.WriteLine(i.Key+":" + i.Value);
    }
}

```

This is program with lots of character saving after suggestions from my dear friend jimbobmcgee

```
using System;
using System.Collections.Generic;
using System.Linq;

class P
{
    static void Main(string[] A)
    {
       var D = new Dictionary<string, int>();
       foreach (var v in A)
       {
          if (!D.ContainsKey(v))
            D[v] = 1;
          else D[v] += 1;
       }
     foreach (var v in D.OrderBy(k=>-k.Value))
     {
        Console.WriteLine(v.Key+": "+v.Value);
     }
   }
}

```

**Output**

# Answer
> 0 votes
**JavaScript (ES5), 146**

```
 F=Function;a={};r="return ";b="b";x=prompt().match(/\w+/g);alert(""+x.filter(F(b,r+"!~(a[b]=~-a[b])")).map(F(b,r+"-a[b]+':'+b")).sort().reverse())

```

> =\>| This is a text and a number: 31.
> \<=| 2:a,1:text,1:number,1:is,1:and,1:This,1:31

# Answer
> 0 votes
**JAVA CODE**

```
 String s="This is a text and a number: 31";
                String[] stringArray = s.split(" ");
                final Map<String, Integer> counter = new HashMap<String, Integer>();
                for (String str : stringArray)
                    counter.put(str, 1 + (counter.containsKey(str)counter.get(str): 0));
                List<String> list = new ArrayList<String>(counter.keySet());
                Collections.sort(list, new Comparator<String>() {
                    @Override
                    public int compare(String x, String y) {
                        return counter.get(y) - counter.get(x);
                    }
                });
                list.toArray(new String[list.size()]);
                for (String str : list) {
                    int frequency = counter.get(str);
                    System.out.println(str + ":" + frequency);
                }

```

**OUTPUT**

```
 a:2
 text:1
 is:1
 31:1
 number::1
 This:1
 and:1

```

# Answer
> 0 votes
# Python3 (244 bytes)

```
import re, collections as c, sys
t=''
with open(sys.argv[1]) as f:
    t+=f.read()
d=c.Counter([s for s in (re.sub('[\s\W]','\n',t).split('\n')) if s])
for x in sorted(d.items(), key=lambda x: x[1])[::-1]:
    print('{}:{}'.format(x[0],x[1]))

```

Works also with newlines, tabs etc. in the sample text.

## Output

```
> $ python3 wc.py test.txt
a:2
text:1
is:1
This:1
and:1
number:1
31:1

```

---
Tags: code-golf
---


title: Word Search Solver

text:
# Question
Title: Word Search Solver
I got to wondering yesterday if I could write a program to comb through a given word search and output the answers. It was actually surprisingly easy. Now I wonder just how small we can get.

# Rules

* Your first input is a string or collection of n lines, each of which is n characters long
* Your second input is a list of words in any format to find in the puzzle
* All words in the search list are guaranteed to be in the puzzle
* Words can be oriented in any of the four cardinal directions, as well as diagonally both forwards and backwards
* Only uppercase A-Z characters will be present in the puzzle
* Your code must find every word in the the search string, and output the coordinate position of the starting letter, where 0,0 is the top left character.
* In the event that you locate more than one instance of the same word, you may handle it however you like. Output it multiple times, or only once, it's up to you

# Examples/Test Cases

Given the following board:

```
ABCD
EFGH
IJKL
MNOP

```

And the following search string:

```
ABCD,CGKO,POMN,NJF,AFKP,CFI,LGB,MJGD

```

Your program should output the following, in any order:

```
ABCD at 0,0
CGKO at 0,2
PONM at 3,3
NJF at 3,1
AFKP at 0,0
CFI at 0,2
LGB at 2,3
MJGD at 3,0

```

As always, shortest answer wins

# Answer
> 4 votes
# JavaScript (Node.js), 154 152 150 141 bytes

* thanks to Arnauld for reducing by 2 bytes

returns array of locations (it was a string with new lines before)

```
(b,w)=>w.map(s=>[...b].map((_,p)=>[1,-1,r=b.search`
`,-r,~r,++r,-~r,~r].map(d=>[...s].every((c,i)=>c==b[p+d*i])?s+=" at "+[p/r|0,p%r]:0))&&s)

```

Try it online!

# Answer
> 3 votes
# Python 2, 213 bytes

```
lambda a,W:[(w,i,j)for w in W for i in R(L(a))for j in R(L(a[0]))for U in R(9)if U-4and g(i,j,U/3-1,U%3-1,a).find(w)==0]
g=lambda i,j,u,v,a,s='':L(a)>i>=0<=j<L(a[0])and g(i+u,j+v,u,v,a,s+a[i][j])or s
L=len;R=range

```

Try it online!

`g` takes a starting location `i,j` and a direction `u,v` and via recursion extracts the string starting at that location in that direction.

`f` then visits each starting location `i,j` and direction `U/3-1,U%3-1` and checks each word `w` to see if the resulting string starts with `w`.

# Answer
> 2 votes
# Python 3, ~~149~~ 147 bytes

```
def g(b,w):h=b.find('\n')+1;return[f'{y} at {i//h},{i%h}'for y in w for i in range(len(b))for d in(1,h+1,h,h-1,-1,~h,-h,1-h)if y==b[i::d][:len(y)]]

```

Try it online!

### Ungolfed version

```
def g(b,w):
    h = b.find('\n') + 1                              # width of a row plus the '\n'
    a = []
    for y in w:                                       # iterate over the words
        for i in range(len(b)):                       #   iterate over the game board
            for d in(1,h+1,h,h-1,-1,~h,-h,1-h):       #     for each possible direction
                if y==b[i::d][:len(y)]:               #       see if the word matches
                    a.append(f'{y} at {i//h},{i%h}')
    return a

```

The main idea is that `b[i::d]` selects a slice from the game board. The slice starts as position `i` and extends in the direction `d`. For example, `d = h+1` corresponds to the southeast diagonal, whereas `d = ~h`, which is the same as `-h-1`, corresponds to the northwest diagonal. `[:len(y)]` chops the slice off at the same length as the word being searched.

---
Tags: code-golf, string, word-search
---


title: Escape from the tarpit (Robbers)

text:
# Question
Title: Escape from the tarpit (Robbers)
This is a challenge based around defining languages and proving they are Turing complete.

This is the robbers' thread. The cops' thread is here.

# Robbers

The cops will post definitions of Turing-complete languages. Your task is to crack them by proving that they are indeed Turing complete. See the cops' challenge for more details and formal specifications.

# Answer
> 6 votes
# ais523's answer - Blindfolded Arithmetic

(I hope my proof is understandable. I can't check my own proof e.g. with a Try it online! link so I'm not sure)

All code in this post will be Python pseudocode, with `rep n:` repeat `n` times. All conditionals must be either `0` or `1`.

It's provable that the value of `i` is always \>0 in the program execution, so `i/i` always give `1`.

Define some building blocks:

`if c: a = a + b` is equivalent to `d = b * c; a = a + d;` assuming `d` is unused.
So, let `(statement)` be `if c: statement` where `c` can be some condition.

`b = b * 2**N` (where `N` is a compile-time constant) is equivalent to

```
rep N: b = b + b

```

`b = a / 2**N` is equivalent to

```
b = i / i
b = b * 2**N
b = a / b

```

`b = a % 2**N` is equivalent to

```
b = a / 2**N
b = b * 2**N
b = a - b

```

---

Any 2-symbol Turing machine with `N` states can be written like this:

```
while True:
    if state == 0:
        # process state 0
    if state == 1:
        # process state 1
    .
    .
    .
    if state == HALTING_STATE:
        0 / 0
    .
    .
    .
    if state == N-1:
        # process state N-1
    state = newstate

```

where each `# process state` block looks like this

```
# optional (not all states need this)
tape.move_left()

# optional
tape.move_right()

# optional
tape.flip()

new_state = a if tape.value() else b

```

This needs to be translated to BFA compatible code.

---

Two variables `i` and `a` will be used to represent the tape and `state` (and `tape` as well)

The content of `i` at each wraparound:

* `N` least significant bits are equal to `2**state` (i.e., the `state`'th significant bit is on, all other bits are off)
* The rest of bits form the right half of the tape.

The content of `a` at each wraparound:

* The left half of the tape.

The tape pointer is on the least significant bit of `a`.

---

At the beginning of each loop, `N` bits are inserted between the tape part and the state part in `i`:

```
d = i / 2**N
d = d * 2**N
i = i - d
d = d * 2**N
i = i + d

```

At each `# process state i` block, the structure of `i` is:

* `M-N` least significant bits: the remaining part of the old value of `state` (`state >> i`). (where `M = 2*N - i`)
* `N` next LSB: (partial) value of `new_state` (or `0` if it's not defined yet in that loop)
* Rest: Tape.

Of course `M` is a compile time constant.

(as an exception, the "process halting state" block can be implemented as

```
if i%2: b = b - b; b = b / b;

```

or equivalently (assume `c` isn't used)

```
c = i % 2; b = i / i; if c: b = b - b; b = b / b;

```

)

---

More rewriting:

* `(tape.move_left())` (the outer `()` stands for conditional, as always)

```
# allocate a free bit on (i)
b = i / 2**M
(i = i + b)
# copy that bit from (a) to (i)
b = a % 2
b = b * 2**M
(i = i + b)
# remove a byte from (a)
b = i/i
(b = b + b)
a = a / b

```
* `(tape.move_right())`

```
# allocate (M+1) bits at the end of (a)
(a = a * 2**(M+1))

# copy that from (i) to (a)
b = i % 2**(M+1)
(a = a + b)

# remove the (M) bits from (a) that is over-copied from (i)
b = i/i # now b==1
rep M: (b = b + b)
a = a / b # if the conditional fails a = a / 1 is a no-op.

# clear that bit on (i)
b = a % 2
b = b * 2**M
(i = i - b)

# remove the bit from (i)
b = i / 2**(M+1)
b = b * 2**M
(i = i - b)

```
* `(tape.flip())`

```
b = a % 2
b = b * 2
(a = a - b)
b = i/i
(a = a + b)

```
* `(new_state = a if tape.value() else b)`

> TODO

---

There are 2 remaining issues:

* Only the bits to the left of the pointer is outputted, and
* `if not tape_value(): tape.move_left()` (and the equivalent `move_right`) is not directly supported.

To solve those problems,

* A TM with only a half of the tape is still TC.

> You can interlace the positive-index cells with the negative-index ones, and replace every movement with a double-movement (doubling the number of states). You'll also need to mark two cells at the left with special symbols so you know to shift by one and turn around (1 extra symbol; 1 extra state), and you'll need to have a reversed copy of every state for when you're in negative-land and every movement is backwards (again doubling the number of states).

(source)

So, it's possible to:

1. Make the tape from 2 interleaving infinite tapes.
2. One of them only have one `1` denoting the right end of the tape. The other is used to store data.
3. At program halt, instead of immediately exiting, move right until hit the end of the tape.

So the whole tape are stored in the right half (i.e., `i`) and readable at program termination.

---

> Am I still missing something?

---
Tags: popularity-contest, cops-and-robbers, language-design
---


title: Number of surjections

text:
# Question
Title: Number of surjections
## Task

Given 2 positive integers `n` and `k`, where `n > k`, output the number of surjections from a set of `n` distinguishable elements to a set of `k` distinguishable elements.

## Definition

A function f: S → T is called a surjection if for every t∈T there is s∈S such that f(s) = t.

## Example

When `n=3` and `k=2`, the output is `6`, since there are `6` surjections from `{1,2,3}` to `{1,2}`:

1. `1↦1, 2↦1, 3↦2`
2. `1↦1, 2↦2, 3↦1`
3. `1↦1, 2↦2, 3↦2`
4. `1↦2, 2↦1, 3↦1`
5. `1↦2, 2↦1, 3↦2`
6. `1↦2, 2↦2, 3↦1`

## Testcases

```
n k output
5 3 150
8 4 40824
9 8 1451520

```

## Reference

## Scoring

This is . Shortest answer in bytes wins.

Standard loopholes apply.

# Answer
# Jelly, ~~5~~ 4 bytes

```
ṗṬML

```

This is an **O(kn)** brute force solution.

Try it online!

### How it works

```
ṗṬML  Main link. Left argument: k. Right argument: n.

ṗ     Cartesian power; yield the list of all n-tuples over {1, ..., k}.
      Each tuple represents a (not necessarily surjective) function from
      {1, ..., n} to {1, ..., k}.
 Ṭ    Apply the "untruth" atom to each tuple.
      Ṭ maps a list of indices to an array with 1's at those indices, and exactly
      as many zeroes as needed to build the array.
      Examples:
           [1, 2, 3, 3, 3] -> [1, 1, 1]
           [1, 3, 5]       -> [1, 0, 1, 0, 1]
           [2, 6, 2, 4, 4] -> [0, 1, 0, 1, 0, 1]
  M   Yield all indices of maximal elements, i.e., all indices of [1] * k.
   L  Take the length.

```
> 6 votes

# Answer
# Haskell, 48 bytes

```
s(_,1)=1
s(1,_)=0
s(m,n)=n*(s(m-1,n-1)+s(m-1,n))

```

Try it online!

### Why is the surjection count `s(m,n)=n*s(m-1,n-1)+n*s(m-1,n)`?

in order to harvest `n` images, i can either

* squeeze a singleton `[m]` creation into any of the `n` boundaries surrounding `n-1` groups
* or add my new `m` into any of `n` already existing groups of `[1..m-1]`

# Haskell, 38 bytes

```
m#n|n<2=1|m<2=0|o<-m-1=n*(o#(n-1)+o#n)

```

Try it online!
> 4 votes

# Answer
# Lean, 66 bytes

```
def s:_->nat->nat|(m+1)(n+1):=(n+1)*(s m n+s m(n+1))|0 0:=1|_ _:=0

```

Try it online!

---

## Proof of correctness

Try it online!

---

## Explanation

Let us ungolf the function:

```
def s : nat->nat->nat
| (m+1) (n+1) := (n+1)*(s m n + s m (n+1))
| 0     0     := 1
| _     _     := 0

```

The function is defined by pattern matching and recursion, both of which have built-in support.

We define `s(m+1, n+1) = (n+1) * (s(m, n) + s(m, n+1)` and `s(0, 0) = 1`, which leaves open `s(m+1, 0)` and `s(0, n+1)`, both of which are defined to be `0` by the last case.

Lean uses lamdba calculus syntax, so `s m n` is `s(m, n)`.

---

Now, the proof of correctness: I stated it in two ways:

```
def correctness : ∀ m n, fin (s m n) ≃ { f : fin m → fin n // function.surjective f } :=
λ m, nat.rec_on m (λ n, nat.cases_on n s_zero_zero (λ n, s_zero_succ n)) $
λ m ih n, nat.cases_on n (s_succ_zero m) $ λ n,
calc fin (s (nat.succ m) (nat.succ n))
   ≃ (fin (n + 1) × (fin (s m n + s m (n + 1)))) :
  (fin_prod _ _).symm
... ≃ (fin (n + 1) × (fin (s m n) ⊕ fin (s m (n + 1)))) :
  equiv.prod_congr (equiv.refl _) (fin_sum _ _).symm
... ≃ (fin (n + 1) × ({f : fin m → fin n // function.surjective f} ⊕
         {f : fin m → fin (n + 1) // function.surjective f})) :
  equiv.prod_congr (equiv.refl _) (equiv.sum_congr (ih n) (ih (n + 1)))
... ≃ {f // function.surjective f} : s_aux m n

def correctness_2 (m n : nat) : s m n = fintype.card { f : fin m → fin n // function.surjective f } :=
by rw fintype.of_equiv_card (correctness m n); simp

```

The first one is what is really going on: a bijection between `[0 ... s(m, n)-1]` and the surjections from `[0 ... m-1]` onto `[0 ... n-1]`.

The second one is how it is usually stated, that `s(m, n)` is the cardinality of the surjections from `[0 ... m-1]` onto `[0 ... n-1]`.

---

Lean uses type theory as its foundation (instead of set theory). In type theory, every object has a type that is inherent to it. `nat` is the type of natural numbers, and the statement that `0` is a natural number is expressed as `0 : nat`. We say that `0` is of type `nat`, and that `nat` has `0` as an inhabitant.

Propositions (statements / assertions) are also types: their inhabitant is a proof of the proposition.

---

* `def`: We are going to introduce a definition (because a bijection is really a function, not just a proposition).
* `correctness`: the name of the definition
* `∀ m n`: for every `m` and `n` (Lean automatically infers that their type is `nat`, because of what follows).
* `fin (s m n)` is the type of natural numbers that is smaller than `s m n`. To make an inhabitant, one provides a natural number and a proof that it is smaller than `s m n`.
* `A ≃ B`: bijection between the type `A` and the type `B`. Saying bijection is misleading, as one actually has to provide the inverse function.
* `{ f : fin m → fin n // function.surjective f }` the type of surjections from `fin m` to `fin n`. This syntax builds a subtype from the type `fin m → fin n`, i.e. the type of functions from `fin m` to `fin n`. The syntax is `{ var : base type // proposition about var }`.
* `λ m` : `∀ var, proposition / type involving var` is really a function that takes `var` as an input, so `λ m` introduces the input. `∀ m n,` is short-hand for `∀ m, ∀ n,`
* `nat.rec_on m`: do recursion on `m`. To define something for `m`, define the thing for `0` and then given the thing for `k`, build the thing for `k+1`. One would notice that this is similar to induction, and indeed this is a result of the Church-Howard correspondence. The syntax is `nat.rec_on var (thing when var is 0) (for all k, given "thing when k is k", build thing when var is "k+1")`.

Heh, this is getting long and I'm only on the third line of `correctness`...
> 4 votes

# Answer
# , 19 bytes

```
-/@(^~*]!0{])],i.@-

```

Try it online!

## Explanation

```
-/@(^~*]!0{])],i.@-  Input: n (LHS), k (RHS)
                  -  Negate k
               i.@   Range [k-1, k-2, ..., 0]
             ]       Get RHS
              ,      Join, forms [k, k-1, ..., 0]
   (        )        Dyad between n (LHS), [k, k-1, ..., 0] (RHS)
           ]           Get RHS
         0{            Select value at index 0
       ]               Get RHS
        !              Binomial coefficient
    ^~                 Raise each in RHS to power of n
      *                Multiply
-/@                  Reduce from right to left using subtraction (forms alternating sum)

```
> 3 votes

# Answer
# Husk, 7 bytes

```
#`¦ḣ¹π²

```

Try it online!

### Explanation

```
#`¦ḣ¹π²  Inputs: n (²), implicit k (¹)
     π²  Cartesian power of [1..k] to n
#        Count if:
   ḣ¹      Range [1..k]
 `¦        Is a subset

```
> 3 votes

# Answer
# Python 2, ~~56 53~~ 50 bytes

```
f=lambda n,k:n/k and(1/k or f(n-1,k-1)+f(n-1,k))*k

```

Try it online!

-3 bytes thanks to H.PWiz.

-3 bytes thanks to Dennis.

* If `n<k` not all `k` can be mapped onto thus there are no surjections. `n/k and` takes care of this.
* Taking `f(0,0)=1` gives us the only nonzero base case we need. `1/k or` achieves this.
> 2 votes

# Answer
# , 49 bytes

```
function(n,k,j=0:k)((-1)^(k-j)*j^n)%*%choose(k,j)

```

Try it online!

Implements one of the formulas by Mario Catalani:

```
T(n, k) = Sum_{j=0..k} (-1)^(k-j)*j^n*binomial(k, j)

```

or alternately:

```
T(n, k) = Sum_{j=0..k} (-1)^j*binomial(k, j)*(k-j)^n

```

which yields the same byte count in R.
> 2 votes

# Answer
# Ruby, 46 bytes

```
f=->n,k{k>n ?0:k+n<1?1:k*(f[n-=1,k]+f[n,k-1])}

```

Try it online!

Standard recursive approach...
> 2 votes

# Answer
# Brain-Flak, 142 bytes

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

```

Try it online!

This uses the standard inclusion-exclusion formula.

I can't write up a full explanation at this time, but here's a high-level explanation:

```
# Compute k-th row of Pascal's triangle
({}<({}()){({}[(())]<<>{({}({})<>)<>}{}>)}{}>)<>

# Multiply each element by n^j (and reverse to other stack)
{<>(({}<>)<{({}[()]<([])({([{}]()({}))([{}]({}))}{}[{}])>)}{}({}<>)>)<>}

# Compute alternating sum
<>{}{}{({}<>[{}])<>}<>

```
> 2 votes

# Answer
# Pari/GP, 38 bytes

```
(n,k)->Pol(exp(x+O(x^n))-1)^k*n!\x^n%x

```

Try it online!

Using the formula by Vladimir Kruchinin on OEIS:

```
E.g.f.: (exp(x)-1)^k = sum T(n,k)x^n/n!

```
> 2 votes

# Answer
# JavaScript (Node.js), 43 bytes

```
T=(n,k)=>n<k?0:k+n<1||k*(T(--n,k)+T(n,k-1))

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 10 bytes

```
sLsãʒêgQ}g

```

Try it online!

**Explanation**

```
sLsã       # Cartesian product of range(k) repeated n times
    ʒ   }  # Filter by ...
     êgQ   # Connected uniquified length == k  (every item in range(k) appears at least once)
         g # Count

```
> 1 votes

---
Tags: code-golf, arithmetic, set-theory
---


title: Minimally sort a list into a matrix

text:
# Question
Title: Minimally sort a list into a matrix
Given an unsorted list of unique strictly positive integers, minimally sort it into a 2D matrix. The input list is guaranteed to be of composite length, which means the output matrix is not necessarily square, but is of size `n x m` with `n,m > 1`.

"Minimally sort" here means the following:

* Sort the list in ascending order.
* Compact the output matrix as much as possible -- minimize the sum of the dimensions of the matrix (for example, for `20` input elements as input, a `5x4` or `4x5` output matrix is required, and not a `2x10`).
* Compact the sorted numbers as far to the upper-left of the matrix as possible, starting with the first element in the sorted list.
* This can be thought of as sorting the list, then slicing it along the matrix's anti-diagonals, starting with the upper-left.

## Examples:

For input `1..20` output is either a 5x4 or a 4x5 matrix as follows:

```
 1  2  4  7 11
 3  5  8 12 15
 6  9 13 16 18
10 14 17 19 20

 1  2  4  7
 3  5  8 11
 6  9 12 15
10 13 16 18
14 17 19 20

```

For input `[3, 5, 12, 9, 6, 11]` output is a 2x3 or 3x2 as follows

```
3  5  9
6 11 12

 3  5
 6  9
11 12

```

For input `[14, 20, 200, 33, 12, 1, 7, 99, 58]`, output is a 3x3 as follows

```
 1   7  14
12  20  58
33  99 200

```

For input `1..10` the output should be a 2x5 or 5x2 as follows

```
1 2 4 6  8
3 5 7 9 10

1  2
3  4
5  6
7  8
9 10

```

For input `[5, 9, 33, 65, 12, 7, 80, 42, 48, 30, 11, 57, 69, 92, 91]` output is a 5x3 or 3x5 as follows

```
 5  7 11 33 57
 9 12 42 65 80
30 48 69 91 92

 5  7 11
 9 12 33
30 42 57
48 65 80
69 91 92

```

### Rules

* The input can be assumed to fit in your language's native integer type.
* The input and output can be given by any convenient method.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 10 votes
# Jelly, ~~24~~ ~~22~~ 20 bytes

```
pS€ỤỤs
LÆDżṚ$SÞḢç/ịṢ

```

Try it online!

Saved 2 bytes thanks to @Jonathan Allan.

## Explanation

```
pS€ỤỤs  Helper link. Input: integer a (LHS), integer b (RHS)
p       Cartesian product between [1, 2, ..., a] and [1, 2, ..., b]
 S€     Sum each pair
   Ụ    Grade up
    Ụ   Grade up again (Obtains the rank)
     s  Split into slices of length b

LÆDżṚ$SÞḢç/ịṢ  Main link. Input: list A
L              Length
 ÆD            Divisors
     $         Monadic pair
    Ṛ            Reverse
   ż             Interleave
                 Now contains all pairs [a, b] where a*b = len(A)
      SÞ       Sort by sum
        Ḣ      Head (Select the pair with smallest sum)
         ç/    Call helper link
            Ṣ  Sort A
           ị   Index into sorted(A)

```

# Answer
> 4 votes
# Python 2, ~~160~~ ~~158~~ ~~153~~ 151 bytes

-2 bytes thanks to Erik the Outgolfer
-2 bytes thanks to Mr. Xcoder

```
s=sorted(input())
l=len(s)
x=int(l**.5)
while l%x:x+=1
n=1
o=eval(`l/x*[[]]`)
while s:
 for i in range(l/x)[max(0,n-x):n]:o[i]+=s.pop(0),
 n+=1
print o

```

Try it online! or Try all test cases

# Answer
> 4 votes
# R ~~110~~ 95 bytes

```
function(x){n=sum(x|1)
X=matrix(x,max(which(!n%%1:n^.5)))
X[order(col(X)+row(X))]=sort(x)
t(X)}

```

Try it online!

### How it works

```
f <- function(x) {
  n <- sum(x|1)                           # length
  p <- max(which(!n%%1:n^.5))             # height of matrix
  X <- matrix(x, p)                       # initialize matrix
  X[order(col(X) + row(X))] <- sort(x)    # filling the matrix using position distance to the top left corner
  t(X)                                    # probably required by OP
}

```

Giuseppe saved a whopping 15(!) bytes by the following tricks

* replacing `length(x)` by `sum(x|1)` (-1 byte)
* `floor()` is not required as `:` rounds down anyway (-7)
* `^.5` is shorter than `sqrt()` (-3)
* using `col(X) + row(X)` instead of `outer` (nice!)
* could not get rid of the `t(X)` though - disappointing ;)

### Original solution

```
function(x){
n=length(x)
p=max(which(!n%%1:floor(sqrt(n))))
X=outer(1:p,1:(n/p),`+`)
X[order(X)]=sort(x)
t(X)}

```

It would look more fancy with `outer` being replaced by `row(X)+col(X)`, but that would require to initialize the output matrix `X` first.

Try it online!

# Answer
> 3 votes
# JavaScript (ES6), 172 bytes

```
l=>(n=l.sort((a,b)=>b-a).length,w=l.findIndex((_,i)=>!(i*i<n|n%i)),a=l=>[...Array(l)],r=a(n/w).map(_=>a(w)),a(w+n/w).map((_,x)=>r.map((s,y)=>x-y in s&&(s[x-y]=l.pop()))),r)

```

## Explanation

```
l=>(                                // Take a list l as input
 l.sort((a,b)=>b-a),                // Sort it
 n=l.length,                        // Get the length n
 w=l.findIndex((_,i)=>!(i*i<n|n%i)),// Find the first integer w where w >= √n and n % w = 0
 a=l=>[...Array(l)],                // Helper function a
 r=a(n/w).map(_=>a(w)),             // Create the grid r of size w, n/w
 a(w+n/w).map((_,x)=>               // For every x from 0 to w + n/w:
  r.map((s,y)=>                     //  For every row s in r:
   x-y in s&&(                      //   If the index x-y is in s:
    s[x-y]=l.pop()))),              //    Set s[x-y] to the next element of l
 r)                                 // Return r

```

## Test Cases

```
f=l=>(n=l.sort((a,b)=>b-a).length,w=l.findIndex((_,i)=>!(i*i<n|n%i)),a=l=>[...Array(l)],r=a(n/w).map(_=>a(w)),a(w+n/w).map((_,x)=>r.map((s,y)=>x-y in s&&(s[x-y]=l.pop()))),r)

l=m=>console.log(JSON.stringify(m))

l(f([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]))
l(f([3,5,12,9,6,11]))
l(f([14,20,200,33,12,1,7,99,58]))
l(f([1,2,3,4,5,6,7,8,9,10]))
```

# Answer
> 3 votes
# Octave, 151 bytes

```
function f(v)n=floor(sqrt(l=nnz(v)));while i=mod(l,n);++n;end;A=nan(m=l/n,n);for k=[1:m 2*m:m:l];do A(k)=sort(v)(++i);until~mod(k+=m-1,m)|k>l;end;A'end

```

Using three different kinds of loop constructs.

Try it online!

**Unrolled:**

```
function f(v)
    n = floor(sqrt(l=nnz(v)));

    while i = mod(l,n);
        ++n;
    end;

    A = nan(m=l/n, n);

    for k = [1:m 2*m:m:l];
        do
            A(k) = sort(v)(++i);
        until ~mod(k+=m-1, m) | k>l;
    end;

    A'
end

```

# Answer
> 3 votes
# Perl 5, 132 bytes

```
sub d{$,=0|sqrt(@_=sort{$a-$b}@_);--$,while@_%$,;map{$r++,$c--for@_/$,..$c;$a[$r++][$c--]=$_;$c=++$i,$r=0if$r<0||$c<0||$r>=$,}@_;@a}

```

Try it online!

Subroutine returns a 2-D array. TIO link includes footer code for displaying test result.

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

```
f=s=>{l=s.length;i=Math.sqrt(l)|0;for(;l%++i;);p=(x)=>(x/i|0+x%i)*l+x%i;m=[...Array(l).keys()].sort((x,y)=>p(x)-p(y));return s.sort((a,b)=>a-b).map((x,i)=>m.indexOf(i)).reduce((a,b,d,g)=>!(d%i)?a.concat([g.slice(d,d+i)]):a,[])}

```

**Explanation**

```
f=s=>{                         // Take array `s` of numbers as input
  l=s.length                   // short-hand for length
  i=Math.sqrt(l)|0             // = Math.floor(Math.sqrt(l))
  for(;l%++i;);                // i = width
  j=l/i                        // j = height

  p=(x)=>(x/i|0+x%i)*l+x%i     // helper to calculate (sort-of) ~manhattan
                                 // distance (horizontal distance weighted
                                 // slightly stronger), from top-left corner
                                 // to the number x, if numbers 0,...,l are
                                 // arranged left-to-right, top-to-bottom
                                 // in an l=i*j grid

  m=[...Array(l).keys()]         // range array
  .sort((x,y)=>p(x)-p(y)),       // manhatten-sorted, sort-of...

  return s.sort((a,b)=>a-b)      // sort input array by numbers,
    .map((x,i,w)=>w[m.indexOf(i)])    // then apply inverse permutation of the
                                 // range-grid manhatten-sort mapping.
    .reduce(                     // slice result into rows
      (a,b,d,g)=>!(d%i)?a.concat([g.slice(d,d+i)]):a
      ,[]
     )
}

```

# Answer
> 0 votes
# Husk, 15 bytes

```
ḟȯΛ≤Σ∂MCP¹→←½ḊL

```

This works by brute force, so longer test cases may time out. Try it online!

## Explanation

```
ḟȯΛ≤Σ∂MCP¹→←½ḊL  Implicit input, a list of integers x.
              L  Length of x (call it n).
             Ḋ   List of divisors.
            ½    Split at the middle.
          →←     Take last element of first part.
                 This is a divisor d that minimizes d + n/d.
        P¹       List of permutations of x.
      MC         Cut each into slices of length d.
ḟ                Find the first of these matrices that satisfies this:
     ∂            Take anti-diagonals,
    Σ             flatten them,
 ȯΛ≤              check that the result is sorted (each adjacent pair is non-decreasing).

```

# Answer
> 0 votes
# C (gcc), ~~269~~ ~~253~~ 226 bytes

```
j,w,h,x,y;c(int*a,int*b){a=*a-*b;}f(A,l)int*A;{int B[l];qsort(A,l,4,c);for(w=h=j=2;x=w*h-l;j++)l%j||(w=h,h=j),w=h*h-l?w:j;for(;j=x<w*h;x++)for(y=0;y<=x;y++)x-y<w&y<h?B[x-y+y*w]=*A++:0;for(;j<l;printf("\n%d "+(j++%w>0),B[j]));}

```

Try it online!

---

# C (gcc), 214 bytes, using `-zexecstack`-lambdas

* Thanks to ceilingcat for this hackier, yet slimmer version.

```
j,w,h,x,y;f(A,l)int*A;{int B[l];qsort(A,l,4,L"\x62b078bǃ");for(w=h=j=2;x=w*h-l;j++)l%j||(w=h,h=j),w=h*h-l?w:j;for(;j=x<w*h;x++)for(y=0;y<=x;y++)x-y<w&y<h?B[x-y+y*w]=*A++:0;for(;j<l;printf("\n%d "+(j++%w>0),B[j]));}

```

Try it online!

# Answer
> 0 votes
# Java 10, ~~199~~ ~~188~~ 186 bytes

```
a->{int j=a.length,m=0,n,i=0,k=0;for(n=m+=Math.sqrt(j);m*n<j;n=j/++m);var R=new int[m][n];for(java.util.Arrays.sort(a);i<m+n;i++)for(j=0;j<=i;j++)if(i-j<n&j<m)R[j][i-j]=a[k++];return R;}

```

Try it online.

Based on my answer here.

**Explanation:**

```
a->{                        // Method with int-array parameter and int-matrix return-type
  int j=a.length,           //  Length of the input-array
      m=0,n,                //  Amount of rows and columns
      i=0,k=0;              //  Index integers
   for(n=m+=Math.sqrt(j);   //  Set both `m` and `n` to floor(√ `j`)
       m*n<j;               //  Loop as long as `m` multiplied by `n` is not `j`
       n=j/++m);            //   Increase `m` by 1 first with `++m`
                            //   and then set `n` to `j` integer-divided by this new `m`
   var R=new int[m][n];     //  Result-matrix of size `m` by `n`
   for(java.util.Arrays.sort(a);
                            //  Sort the input-array
       i<m+n;)              //  Loop as long as `i` is smaller than `m+n`
     for(j=0;j<=i;j++)      //   Inner loop `j` in range [0,`i`]
       if(i-j<n&j<m)        //    If `i-j` is smaller than `n`, and `j` smaller than `m`
                            //    (So basically check if they are still within bounds)
         R[j][i-j]=a[k++];  //     Add the number of the input array at index `k`,
                            //     to the matrix in the current cell at `[j,i-j]`
  return R;}                //  Return the result-matrix

```

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