# Question
Title: Generate alphabet with 4 copies of each letter
Note that this is not the same as Print the alphabet four times.

This task is to write a program to generate four copies of each letter of the English alphabet, one letter per line, on standard output:

```
A
A
A
A
B
B
B
B

```

etc.

The output should include newlines after each letter.

Lowercase letters and/or extra whitespace are acceptable.

The solution must be a complete program.

This is so answers will be scored in bytes with a lower score being the goal.

# Answer
> 18 votes
## APL (5)

```
⍪4/⎕A

```

Matrix format () of 4-replication (`4/`) of alphabet (`⎕A`).

# Answer
> 12 votes
# Python 2 - 37

```
for i in range(104):print chr(i/4+65)

```

As `i` goes from 0 to 104, it is divided by four and added to the ASCII value for `A`, and the resulting character is printed.

# Answer
> 9 votes
# R, 30 28 27 25

```
write(rep(LETTERS,e=4),1)

```

---

Former version with 30 bytes:

```
cat(rep(LETTERS,e=4),sep="\n")

```

# Answer
> 7 votes
## C, 59

I submit this, an uncompetitively long answer, simply because I don't see a C submission yet. And that makes me sad. :-/

LATER: Props to @moala for doing a "/4" int version of this, saving 13 chars!

```
float i;main(){while(i<26)printf("%c\n",65+(int)i),i+=.25;}

```

# Answer
> 6 votes
# J: ~~18~~ 13

```
4#u:65+i.26 1

```

I'm still pretty shaky with J, so this could probably be improved

# Answer
> 5 votes
# PowerShell: 32 23

**Golfed code:**

```
[char[]](65..90*4)|Sort

```

**Walkthrough:**

`[char[]](`...`)` takes an array of objects and converts them to ASCII characters.
`65..90` are the ASCII codes for A-Z.
`*4` repeats the series 4 times.
`|Sort` sorts the output.

**Note:**

If you want this written to a file, just throw `>`, followed by a file name, at the end.

# Answer
> 5 votes
# Befunge 98 - 18

```
1+::'g`#@_4/'A+,a,

```

Works by storing a number and ending when it reaches 104. Prints out the corresponding character of the alphabet for the number divided by 4, followed by a newline. But if I need not add a newline after each letter, then it is 16 chars:

```
1+::'g`#@_4/'A+,

```

Can be reduced if I can print more characters (ie all of them four times)(~~7~~ 6 chars, even works in Befunge 93):

```
1+:4/,

```

With newline:

```
1+:4/,a,

```

# Answer
> 5 votes
## Ruby, 23

```
puts ([*?A..?Z]*4).sort

```

All credit to @manatwork -- upvote his comment, not this. :)

# Answer
> 5 votes
# C, ~~46~~ ~~44~~ 43

~~46~~:

```
i;main(){while(i<104)printf("%c\n",65+i++/4);}

```

~~44~~:

```
i=260;main(j){for(;(j=i++>>2)<91;puts(&j));}

```

44 too:

```
i=260;main(j){while(j=i++>>2,j<91)puts(&j);}

```

Thanks to @marinus, 43:

```
i=260;main(j){while(j=i++/4,j<91)puts(&j);}

```

Should I add a bounty for getting to 42? :)

# Answer
> 5 votes
## Haskell, 46

```
x a=a++a
main=putStr$['A'..'Z']>>=x.x.(:"\n")

```

# Answer
> 5 votes
**Java: 56**

```
for(int i=0;i<104;)System.out.println((char)(i++/4+65));

```

edit: changed from 'print' to 'println'

# Answer
> 5 votes
# brainfuck, 48 bytes

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

```

Try it online!

Prints in lowercase, separated by carriage returns. Uses wrapping 8 bit cells as well as cells left of the origin, though you can prepend a `>` to counter the latter.

# Answer
> 4 votes
# GolfScript: ~~17~~ 15 characters

```
26,{65+...}%+n*

```

# Answer
> 4 votes
# Bash: 24 characters

```
printf %s\\n {A..Z}{,,,}

```

# Answer
> 4 votes
# Perl 5, 20 bytes

```
print"$_
"x4for A..Z

```

Try it online!

---

# Perl 5 \+ `-M5.10.0`, 20 bytes

```
eval"say;"x4for A..Z

```

Try it online!

# Answer
> 4 votes
## Forth, 37

```
'h 0 [do] [i] 4 / 'A + emit cr [loop]

```

# Answer
> 4 votes
**BrainF\*** ,79 60

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

```

# Answer
> 4 votes
# Actually, 6 bytes

```
4ú*SÖi

```

Try it here!

Explanation

```
4ú*SÖi

4 *         Do 4 times
 ú          Create string of alphabet in lowercase
   S        Sort it
    Ö       Switch Case
     i      Push each character of string

```

4 Bytes with lowercase and no newline:

```
4ú*S

```

# Answer
> 4 votes
# 16-bit x86 machine code MS-DOS COM, 25 bytes

In hex:

```
B409BA160189D7B96800F6C1037502FE05CD21E2F5C3400A24

```

This is a complete MS-DOS .COM program. Copy the byte sequence to the file with .com extension and run it from DOSBox

Disassembly:

```
00: B4 09        mov    ah,0x09         ;INT 21h "Write string to STDOUT" function
02: BA 16 01     mov    dx,0x116        ;Address of the string s ('$'-terminated)
05: 89 D7        mov    di,dx           ;Because there's no way to dereference address in DX
07: B9 68 00     mov    cx,104          ;CX=26*4
_0000000A:
0A: F6 C1 03     test   cl,0x03         ;When lower two bits are zero...
0D: 75 02        jne    _00000011       ;...do not skip the next instruction
0F: FE 05        inc    b,[di]          ;*s++
_00000011:
11: CD 21        int    21              ;Print the string
13: E2 F5        loop   _0000000A       ;Until --CX==0
15: C3           retn
16: 40           db     0x40            ;s[0], starts with 'A'-1
17: 0A           db     0x0A            ;'\n'
18: 24           db     '$'             ;Terminator required by the print function

```

# Answer
> 4 votes
# Jelly, 5 bytes

```
ØAx4Y

```

Try it online!

Explanation:

```
ØAx4Y Main link
ØA    “ABCDEFGHIJKLMNOPQRSTUVWXYZ”
   4  4
  x   Repeat each element of x y times
    Y Join x with newlines

```

# Answer
> 4 votes
# x86-16 ASM, IBM PC DOS, ~~22~~ 19 bytes

**Binary:**

```
00000000: 400a 24b8 1109 8bd6 b168 d0c8 102c cd21  @.$......h...,.!
00000010: e2f8 c3                                  ...

```

Build with `xxd -r` and test in DOSBox or your favorite DOS VM.

**Unassembled:**

```
40 0A 24    DB   '@', 0AH, '$'      ; the letter + NL + '$' string terminator
B8 0911     MOV  AX, 0911H          ; AH = DOS print string; AL = 0001 0001 bit pattern
8B D6       MOV  DX, SI             ; DX to output string
B1 68       MOV  CL, 26*4           ; Loop 4 times for each letter in alphabet
        ALOOP:
D0 C8       ROR  AL, 1              ; roll repeating bit pattern to the right
10 2C       ADC  BYTE PTR[SI], CH   ; add rightmost bit to ASCII character
CD 21       INT  21H                ; print letter to console
E2 F8       LOOP ALOOP              ; continue looping
C3          RET                     ; return to DOS

```

**Notes:**

For most flavors of DOS, we know the values of many CPU registers at the start of execution and we know `SI` is `0100H`, and `CH` is `0`. So by placing the output string in the beginning of the program, `[SI]` will already be pointing to it. These bytes (`'@',0AH,'$'`) decode to two benign instructions (`INC AX`, `OR AH, [SI]`), which have no effect on the program.

`AL` contains the bit pattern of `0001 0001` which is bit rolled right each time and the rightmost bit added to the ASCII value of the output char in memory.

# Answer
> 4 votes
# Vyxal `j`, 5 bytes

```
kAdds

```

Try it Online!

Look ma, no Unicode!

```
kA    # Uppercase output
  dd  # Quadruple
    s # Sorted
      # (j flag) join by newlines

```

# Answer
> 3 votes
# Raku, 34 21 bytes

```
('A'..'Z'Xxx 4)».say

```

# Answer
> 3 votes
# Julia 0.2, 39, 36

```
println([char(i/4+64.5)for i=0:103])

```

# Answer
> 3 votes
# Mathematica ~~50 41~~ 30

With help from alephalpha and Mark S.

```
Print/@{#,#,#,#}&/@Alphabet[];

```

# Answer
> 3 votes
# Q (13)

.........

```
-1@''4#'.Q.A;

```

# Answer
> 3 votes
**AWK, 48**

Lets try it with AWK...

```
END{s=65;for(i=104;i--;s+=0==i%4)printf"%c\n",s}

```

As suggested by manatwork we can get rid of 2 chars

**AWK, 46 (Edit)**

```
END{for(i=104;i--;s+=0==i%4)printf"%c\n",s+65}

```

**AWK,40** (editing MarkReed's code)

```
END{for(;i<104;){printf"%c\n",i++/4+65}}

```

# Answer
> 3 votes
## PowerShell, 21

```
65..90|%{,[char]$_*4}

```

A slightly different approach to Iszi's. And shorter :-)

# Answer
> 3 votes
**C# LINQ ~~115 Bytes~~110 Bytes**

```
Enumerable.Range(65, 26).SelectMany(i => Enumerable.Repeat(i,4))
.ToList().ForEach(i=> Console.WriteLine((char)i));

```

# Answer
> 3 votes
# 05AB1E, 6 bytes

```
A4×{S»

```

Explanation:

```
A       # Push 'abcdefghijklmnopqrstuvwxyz'
 4×     # Repeat four times
   {    # Sort
    S   # Split into list
     »  # Join by newlines
        # Implicit print

```

Without newlines, 4 bytes

```
A4×{

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 5 bytes

```
Aε4F=

```

Try it online!

# Answer
> 3 votes
# C# (Visual C# Interactive Compiler), 46 bytes

```
for(var a=259;a++<363;WriteLine((char)(a/4)));

```

Try it online!

# Answer
> 3 votes
## Canvas, 5 bytes

```
Ｚ４１＊⟳

```

Try it here!

Explanation:
```
Code        | Explanation                                  | Stack
------------+----------------------------------------------+------------------------------
Ｚ          | The uppercase alphabet                       | "ABC..."
  ４１＊     | Stretched by 4 horizontally and 1 vertically | "AAAABBBBCCCC..."
        ⟳  | Rotated clockwise                            | "A¶A¶A¶A¶B¶B¶B¶B¶C¶C¶C¶C¶..."
            | Print ToS (implicit)                         |

```

With  replaced with `\n` upon printing.

# Answer
> 3 votes
# VBA, 30 bytes

An anonymous VBE immediate window function that takes no input and outputs to the console.

```
For i=260To 363:?Chr(i\4):Next

```

# Answer
> 3 votes
# Kotlin, ~~66~~ 59 bytes

Save 7 bytes removing for loop.

```
fun main(a:Array<String>){repeat(104){println('A'+(it/4))}}

```

Try it online!

# Answer
> 3 votes
# jq `-nr`, 27 bytes

```
range(104)/4+65|[.]|implode

```

Try it online!

`implode` seems to convert floating point to their floored value, which is quite useful here.

# Answer
> 3 votes
# jq `-nr`, 32 bytes

```
range(26)+65|[.]|implode|.,.,.,.

```

Try it online!

`.,.,.,.` may just be the funniest thing I've written on this site. This language's generator system never ceases to amaze me.

# Answer
> 2 votes
# Dc: 35 characters

```
[rdP10Pr1-d1<p]sp65[5lpx+d91>l]dslx

```

# Answer
> 2 votes
# F#: ~~61~~ ~~62~~ 49

```
for i in 'A'..'Z'do for j in 0..4 do printfn"%c"i

```

# Answer
> 2 votes
# Scala, 42

```
('A'to'Z')map(x=>List.fill(4)(println(x)))

```

# Answer
> 2 votes
## PHP, 53

```
for($i=65;$i<91;$i++)echo str_repeat(chr($i)."\n",4);

```

# Answer
> 2 votes
# Matlab, 38

```
x=repmat(char(65:90)',1,4)';disp(x(:))

```

# Answer
> 2 votes
# Javascript 55

`for(i=65;i<91;i+=1/4)document.write("&#"+(i|0)+";<br>")`

1 character shorter, but outputs to the screen instead of console.

# Answer
> 2 votes
## Pyke, 6 bytes (noncompetitive)

```
G4m*_X

```

Try it here!

Or 4 bytes without newline separation

```
G4m*

```

# Answer
> 2 votes
# CJam, 15 13 characters

```
'[,65>4f*e_N*

```

Probably very golf-able; I'm new to CJam and even code golfing.

# Answer
> 2 votes
# Swift 3, 53

`(0...103).map{print(String(UnicodeScalar($0/4+65)!))}`

***IF*** one day Apple decided to include `Foundation` by default, we could have

`(0...103).map{print(String(format:"%c",$0/4+65))} //49 bytes`

# Answer
> 2 votes
# Common Lisp, 58 bytes

```
(dotimes(i 26)(format t"~4@{~c
~:*~}"(code-char(+ 65 i))))

```

### Explanation

```
(dotimes(i 26) ; loop for i from 0 to 25
(format t"~4@{~c
~:*~} ;output four times character given by (code-char(+ 65 i)) followed by newline

```

Try it online!

# Answer
> 2 votes
# Japt `-R`, ~~7~~ 6 bytes

```
;B²²¬n

```

Test it

```
;B²²¬n
;B         :Uppercase alphabet
  ²        :Duplicate
   ²       :Duplicate
    ¬      :Split
     n     :Sort
           :Implicitly join with newlines

```

# Answer
> 2 votes
# Vim, 27 bytes

```
:h<_
jjYZZPVUqqx4O<C-r>"<esc>jq25@q

```

Thanks @Lynn for the trick of grabbing the alphabet from helpfiles.

# Answer
> 2 votes
# Brain-Flak, 122 bytes

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

```

this is 120 bytes of source code, and `+2` bytes for the `-Ar` flags.

Try it online!

# Answer
> 2 votes
# Pyth, 8 bytes

-2 bytes thanks to Mr. Xcoder

```
VGj*4rN1

```

Try it online!

**Explanation**

```
VG          # For N in G (the alphabet)...
     rN1    # ...convert N to uppercase...
   *4       # ...generate the string NNNN...
  j         # ...join on newlines
            # Implicit print for each iteration

```

# Answer
> 2 votes
# PHP, 36 bytes

```
while($i<104)echo"
",chr($i++/4+65);

```

bonus version, **38 bytes**

```
while($i<104)echo"@K"^chr($i++/4+1).A;

```

Run with `-nr` or try it online.

# Answer
> 2 votes
# Perl 6, 22 bytes

```
.say xx 4 for "A".."Z"

```

Even though this is an old challenge, I found a different approach to the Perl 6 answer, so I decided to post it.

Try it online!

# Answer
> 2 votes
# ///, 73 bytes

```
/./\/A
A
A
A
\/A\///~/.B.C.D.E.F.G.H.I.J.K.L.M.N.O.P.Q.R.S.T.U.V.W.X.Y.Z.

```

## Try It Online!

This just replace `.` by `/AAAA/A/` to get `AAAA/A/B/AAAA/A/C/AAAA...` (newlines excluded for legibility). The `/~/` is the first part of a dummy replacement which does nothing; it's there to grab initial `/` from the first replacement. We don't need to worry about the final `/A/` (`/Z/` by the time the interpreter gets there), because /// simply exits if it encounters EOF while reading a replacement

# Answer
> 2 votes
# Pyth - 7 Bytes

```
VrG1V4N

```

Explanation

```
VrG1V4N
V       For each character N in
  G     The alphabet
 r 1    Converted to uppercase:
    V4  For each variable from 0 to 3:
      N Implicitly print N

```

# Answer
> 2 votes
# Whitespace, ~~126~~ 117 bytes

```
[S S S T    S S S S S S N
_Push_64][S N
S _Duplicate][N
S S S N
_Create_Label_LOOP][S N
N
_Discard_top][S S S T   N
_Push_1][T  S S S _Add][S N
S _Duplicate][S N
S _Duplicate][S S S T   S T T   S T T   N
_Push_91][T S S T   _Subtract][N
T   S S S N
_Jump_to_Label_EXIT_if_0][S S S T   S S N
_Push_4][N
S S T   N
_Create_Label_INNER_LOOP][S S S T   N
_Push_1][T  S S T   _Subtract][S N
S _Duplicate][N
T   T   S N
_Jump_to_Label_LOOP_if_negative][S N
T   _Swap_top_two][S N
S _Duplicate][T N
S S _Print_as_character][S S S T    S T S N
_Push_10][T N
S S _Print_as_character][S N
T   _Swap_top_two][N
S N
T   N
_Jump_to_Label_INNER_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (containing raw spaces, tabs and new-lines only).

**General explanation in pseudo-code:**

```
Integer i = 64
Start Loop:
  i = i+1
  If i == 91: Exit program with error
  Integer j = 4
  Start Inner Loop:
    j = j-1
    If j is negative: Go to the next iteration of the outer Loop
    Print i as character
    Print new-line
    Go to the next iteration of the Inner Loop

```

**Example run:**

```
Command        Explanation                            Stack            STDOUT    STDERR

SSSTSSSSSSN    Push 64                                [64]
SNS            Duplicate top (64)                     [64,64]
NSSSN          Create Label_LOOP                      [64,64]
 SNN            Discard top                           [64]
 SSSTN          Push 1                                [64,1]
 TSSS           Add (64+1)                            [65]
 SNS            Duplicate top (65)                    [65,65]
 SNS            Duplicate top (65)                    [65,65,65]
 SSSTSTTSTTN    Push 91                               [65,65,65,91]
 TSST           Subtract (65-91)                      [65,65,-26]
 NTSSSN         If 0: Jump to Label_EXIT              [65,65]
 SSSTSSN        Push 4                                [65,65,4]
 NSSTN          Create Label_INNER_LOOP               [65,65,4]
  SSSTN          Push 1                               [65,65,4,1]
  TSST           Subtract (4-1)                       [65,65,3]
  SNS            Duplicate top (3)                    [65,65,3,3]
  NTTSN          If negative: Jump to Label_LOOP      [65,65,3]
  SNT            Swap top two                         [65,3,65]
  SNS            Duplicate top (65)                   [65,3,65,65]
  TNSS           Print as character                   [65,3,65]        A
  SSSTSTSN       Push 10                              [65,3,65,10]
  TNSS           Print as character                   [65,3,65]        \n
  SNT            Swap top two                         [65,65,3]
  NSNTN          Jump to Label_INNER_LOOP             [65,65,3]

  SSSTN          Push 1                               [65,65,3,1]
  TSST           Subtract (2-1)                       [65,65,2]
  SNS            Duplicate top (2)                    [65,65,2,2]
  NTTSN          If negative: Jump to Label_LOOP      [65,65,2]
  SNT            Swap top two                         [65,2,65]
  SNS            Duplicate top (65)                   [65,2,65,65]
  TNSS           Print as character                   [65,2,65]        A
  SSSTSTSN       Push 10                              [65,2,65,10]
  TNSS           Print as character                   [65,2,65]        \n
  SNT            Swap top two                         [65,65,2]
  NSNTN          Jump to Label_INNER_LOOP             [65,65,2]

  SSSTN          Push 1                               [65,65,2,1]
  TSST           Subtract (2-1)                       [65,65,1]
  SNS            Duplicate top (1)                    [65,65,1,1]
  NTTSN          If negative: Jump to Label_LOOP      [65,65,1]
  SNT            Swap top two                         [65,1,65]
  SNS            Duplicate top (65)                   [65,1,65,65]
  TNSS           Print as character                   [65,1,65]        A
  SSSTSTSN       Push 10                              [65,1,65,10]
  TNSS           Print as character                   [65,1,65]        \n
  SNT            Swap top two                         [65,65,1]
  NSNTN          Jump to Label_INNER_LOOP             [65,65,1]

  SSSTN          Push 1                               [65,65,1,1]
  TSST           Subtract (1-1)                       [65,65,0]
  SNS            Duplicate top (1)                    [65,65,0,0]
  NTTSN          If negative: Jump to Label_LOOP      [65,65,0]
  SNT            Swap top two                         [65,0,65]
  SNS            Duplicate top (65)                   [65,0,65,65]
  TNSS           Print as character                   [65,0,65]        A
  SSSTSTSN       Push 10                              [65,0,65,10]
  TNSS           Print as character                   [65,0,65]        \n
  SNT            Swap top two                         [65,65,0]
  NSNTN          Jump to Label_INNER_LOOP             [65,65,0]

  SSSTN          Push 1                               [65,65,0,1]
  TSST           Subtract (0-1)                       [65,65,-1]
  SNS            Duplicate top (-1)                   [65,65,-1,-1]
  NTTSN          If negative: Jump to Label_LOOP      [65,65,-1]

 (Note: Contains additional trailing `[65,` here, but we'll ignore that for now.)
 SNS            Discard top                           [65]
 SSSTN          Push 1                                [65,1]
 TSSS           Add (65+1)                            [66]
 SNS            Duplicate top (66)                    [66,66]
 SNS            Duplicate top (66)                    [66,66,66]
 SSSTSTTSTTN    Push 91                               [66,66,66,91]
 TSST           Subtract (66-91)                      [66,66,-25]
 NTSSSN         If 0: Jump to Label_EXIT              [66,66]
 SSSTSSN        Push 4                                [66,66,4]
 NSSTN          Create Label_INNER_LOOP               [66,66,4]
  SSSTN          Push 1                               [66,66,4,1]
  TSST           Subtract (4-1)                       [66,66,3]
  SNS            Duplicate top (3)                    [66,66,3,3]
  NTTSN          If negative: Jump to Label_LOOP      [66,66,3]
  SNT            Swap top two                         [66,3,66]
  SNS            Duplicate top (66)                   [66,3,66,66]
  TNSS           Print as character                   [66,3,66]        B
  SSSTSTSN       Push 10                              [66,3,66,10]
  TNSS           Print as character                   [66,3,66]        \n
  SNT            Swap top two                         [66,66,3]
  NSNTN          Jump to Label_INNER_LOOP             [66,66,3]

  ... etc. etc. for all letters in the alphabet

 SNN            Discard top                           [90]
 SSSTN          Push 1                                [90,1]
 TSSS           Add (90+1)                            [91]
 SNS            Duplicate top (91)                    [91,91]
 SNS            Duplicate top (91)                    [91,91]
 SSSTSTTSTTN    Push 91                               [91,91,91]
 TSST           Subtract (91-91)                      [91,91,0]
 NTSSSN         If 0: Jump to Label_EXIT              [91,91]                    error
                (Label_EXIT doesn't exit, so exits program with an error to STDERR)

```

# Answer
> 2 votes
# Pyt, 6 bytes

```
ʊ4*ąşÁ

```

Explanation:

```
ʊ     Pushes "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4*    Quadruples the string
ą     Convert to array of characters
ş     Sort the array in ascending order
Á     Push contents of the array onto the stack
      implicit output

```

Try it online!

---

If outputting it as an array is acceptable:

# Pyt, 5 bytes

```
ʊ4*ąş

```

# Answer
> 2 votes
# SmileBASIC, 29 bytes

```
FOR I=260TO 363?CHR$(I/4)NEXT

```

# Answer
> 2 votes
# K (oK), ~~17~~ 16 bytes

**Solution:**

```
`0:`c$+,65+&26#4

```

Try it online!

**Explanation:**

```
`0:`c$+,65+&26#4 / the solution
            26#4 / generate a vector of 26 4s
           &     / where, turns this into 0 0 0 0 1 1 1 1 2 2 2 2 etc
        65+      / add 65 to this vector
       ,         / enlist (,:) each-both (')
      +          / flip
   `c$           / convert to characters
`0:              / print to stdout

```

**Notes:**

* -1 byte with thanks to @ngn!

# Answer
> 2 votes
# **@NUM**, 43 bytes

```
#1@13#0@65|#1$#0$#1$#0$#1$#0$#1$#0$+<90{*0}

```

(I messed up on some of the code, now it works, but is almost double the size...)

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

```
ＦαＥ⁴ι

```

-1 byte thanks to *@Neil*.

Try it online (verbose) or try it online (pure).

**Explanation:**

Loop over the characters of the uppercase alphabet:

```
For(a)
Ｆα

```

Create an array of size 4, each mapped to the current letter. (Items of an Array are each printed on a separated line by default.)

```
Each(4, i)
Ｅ⁴ι

```

# Answer
> 2 votes
# Cardinal, 68 bytes

```
%+v
(A+
~ =
([t
' >t*~v
8 v~'n<
D<v< #
-~
~+,
 ,,
 ,,~
 ,,-
 ,~
>^R^

```

Try it online!

## Explanation

```
%+v
(A+
~ =
([t
' >t*~v
8 v~'n<
**** #

```

Sets up loops for printing and corrects timing between loops. Right column sets up space to be printed in a loop of 25 times while left column sets up letters of alphabet starting with A to be printed.

```
D<v<
-~
~+,
 ,,
 ,,~
 ,,-
 ,~
>^R^

```

Left 2 columns print out each letter in alphabet while right 2 columns print out newlines.

### How the loops work:

The inactive value of the pointer is set to the number of times to iterate through the loop. The timing of the loops is set up so that it will print alphabet character then newline four times before decrementing the inactive value of the pointer. The alphabet character to print was selected at the start by assigning the ascii value of A to the active value of the pointer "(A" in the code. After each loop of printing, this active value is incremented by one to print the next character in the alphabet.

# Answer
> 2 votes
## Keg, 20 bytes (SBCS on Keg wiki)

```
AZɧ^(\
(3|$:\
)$(8|,

```

Push range from A to Z and then 4-speak it.

# Answer
> 2 votes
# Brian & Chuck, 32 bytes

```
A{<?
!{>-_{.>.<.>.<.>.<.+>.>-?

```

Try it online!

code:

```
Brian:
A                       ["A", 11, 26] Variables: Letter, newline+1, letter count
{<?                        restart current code portion of Chuck

Chuck:
code 1:
{>-                        go to "newline+1" and decrement it, so it becomes a newline

code 2:
{                          go to letter
.>.<.>.<.>.<               print letter and newline three times
.+                         print and increment letter
>.                         print 4th newline
>-                         decrement counter
?                          if counter > 0, switch to Brian (who just restarts Chuck's code 2)

```

# Answer
> 2 votes
# naz, 72 bytes

```
9a1a2x1v9m2x2v3d2m4a1x1f1a2x3v1o1v1o3v1o1v1o3v1o1v1o3v1o1v1o3v3x2v1l0x1f

```

**Explanation** (with `0x` commands removed)

```
9a1a2x1v                                         # Set variable 1 equal to 10 (newline)
9m2x2v                                           # Set variable 2 equal to 90 ("Z")
3d2m4a                                           # Set the register to a value of 64 ("@")
1x1f                                             # Function 1
    1a                                           # Add 1 to the register
      2x3v                                       # Store the new value in variable 3
          1o1v1o3v1o1v1o3v1o1v1o3v1o1v1o         # Output it, then a newline, four times
                                        3v       # Load variable 3 into the register
                                          3x2v1l # Jump back to the start of the function
                                                 # if the register is less than variable 2
1f                                               # Call function 1

```

# Answer
> 2 votes
# Jelly, 7 bytes

```
ØAṄ4¡€*

```

Try it online!

## Explanation

```
ØAṄ4¡€*
   ØA: alphabet
   Ṅ: print w/ new line
   4¡: repeat 4 times
   €: each
   *: to error out(see below)

```

The reason I use the `*` is to error out the code so it wont print the whole alphabet at the end (I'm very new to jelly). If anyone can tell me what character to use in combination with  to achieve this, I would appreciate it!

# Answer
> 2 votes
# Vyxal, 6 bytes

```
4kA*s⁋

```

Try it Online!

```
4      - Literal
 kA    - Uppercase alphabet
   *   - Multiplication
    s  - Sort
     ⁋ - Join by newlines

```

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

```
kA4•

```

Try it Online!

Multiplies each letter of the alphabet by 4, and joins on newlines.

# Answer
> 1 votes
### Bash 28 26

```
echo {a..z}{,,,}|tr \  \\n

```

# Answer
> 1 votes
# Q, 16

........

```
-1@'(,/)4#'.Q.A;

```

# Answer
> 1 votes
### 4DOS, 59 (including newlines)

Why? Because not enough people use it any more and it's still the same size as C and shorter than F#!

```
do i=65 to 90
@for %j in (1 2 3 4) do echo %@CHAR[%i]
enddo

```

# Answer
> 1 votes
## JavaScript (59 56)

```
for(i=65;i<91;i+=1/4)console.log(String.fromCharCode(i))

```

# Answer
> 1 votes
# Clojure ~~41~~ 45 bytes

```
(doseq[i(range 65 91 0.25)](println(char i)))

```

# Answer
> 1 votes
# C#, 86 bytes

```
class P{static void M(){for(var i=65d;i<91;i+=.25)System.Console.WriteLine((char)i);}}

```

a full program...

# Answer
> 1 votes
# LINQ, 59 bytes

```
from i in Enumerable.Range(0, 104)select(char)(65+i/4)+"\n"

```

LINQ expression, try it with LinqPad. The `select` part is a bit too C#ist but I guess that fine.

```
from i                        // for each variable
in Enumerable.Range(0, 104)   // in the range 0, 26*4
select(char)(65+i/4)+"\n"     // get the letter and a newline

```

# Answer
> 1 votes
# C#, 88 bytes

```
var s="";int i,j;for(i=0;i++<26;){for(j=0;j++<4;)s+=(char)(i+64)+"\n";}Console.Write(s);

```

Try it with this REPL shell: https://csharppad.com/

# Answer
> 1 votes
# dc, 23 bytes

```
260[d4/PAP1+d364>M]dsMx

```

Try it online!

Since precision is 0 by default, 260, 261, 262, and 263 all return 65 when divided by 4. All we need to do, then, is start with 260 on the stack, and continue duplicating the top of stack, dividing by 4, printing that code point and a line feed and then incrementing by one until we hit 364 (91\*4).

# Answer
> 1 votes
# SOGL V0.12, 5 bytes

```
Z{4⌡T

```

Try it Here!

# Answer
> 1 votes
# Taxi, ~~1215~~ 449 bytes

~~(I am calling this the Magna Carta byte count)~~

It turns out to be *way* shorter to just hard code the text.

```
'A\nA\nA\nA\nB\nB\nB\nB\nC\nC\nC\nC\nD\nD\nD\nD\nE\nE\nE\nE\nF\nF\nF\nF\nG\nG\nG\nG\nH\nH\nH\nH\nI\nI\nI\nI\nJ\nJ\nJ\nJ\nK\nK\nK\nK\nL\nL\nL\nL\nM\nM\nM\nM\nN\nN\nN\nN\nO\nO\nO\nO\nP\nP\nP\nP\nQ\nQ\nQ\nQ\nR\nR\nR\nR\nS\nS\nS\nS\nT\nT\nT\nT\nU\nU\nU\nU\nV\nV\nV\nV\nW\nW\nW\nW\nX\nX\nX\nX\nY\nY\nY\nY\nZ\nZ\nZ\nZ' is waiting at Writer's Depot.Go to Writer's Depot:w 1 r 3 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.

```

Try it online!

Ungolfed / formatted:

```
'A\nA\nA\nA\nB\nB\nB\nB\nC\nC\nC\nC\nD\nD\nD\nD\nE\nE\nE\nE\nF\nF\nF\nF\nG\nG\nG\nG\nH\nH\nH\nH\nI\nI\nI\nI\nJ\nJ\nJ\nJ\nK\nK\nK\nK\nL\nL\nL\nL\nM\nM\nM\nM\nN\nN\nN\nN\nO\nO\nO\nO\nP\nP\nP\nP\nQ\nQ\nQ\nQ\nR\nR\nR\nR\nS\nS\nS\nS\nT\nT\nT\nT\nU\nU\nU\nU\nV\nV\nV\nV\nW\nW\nW\nW\nX\nX\nX\nX\nY\nY\nY\nY\nZ\nZ\nZ\nZ' is waiting at Writer's Depot.
Go to Writer's Depot: west 1st right 3rd left 2nd left.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.

```

# Answer
> 1 votes
# Tcl, 51 bytes

```
time {puts [format %c [expr (259+[incr i])/4]]} 104

```

Try it online!

# Answer
> 1 votes
## Lua, 53 Bytes

Simple solution, we're using the range `[260,363]` which is `65*4` and `90*4+3` (letter `A` and `Z`) to iterate.

Then we just have to do an euclidian division by 4 and print out each letter 4 times this way.

**Edit: Approved @MCAdventure10's edit that pointed out a rounding error that made only one `Z` being printed out, it wasn't deviating from my original idea and didn't change the byte count, thus,I approved it.**

```
for i=260,363 do print(("").char(math.floor(i/4)))end

```

# Answer
> 1 votes
# Funky, 32 bytes

```
fori=0i<104i++print("%c"%65+i/4)

```

Try it online!

# Answer
> 1 votes
# F# (.NET Core), 43 bytes

```
for i in 260..363 do printfn"%c"(char(i/4))

```

Try it online!

# Answer
> 1 votes
# Add++, 19 bytes

```
L,91 65rbU€C4€*JbUn

```

Try it online!

## How it works

```
L,			; Create an anonymous function
	91 65rbU	; Push [65 ... 90]	STACK = [65 66 ... 89 90]
	€C		; Convert to chars;	STACK = ['A' 'B' ... 'Y' 'Z']
	4€*		; Repeat each 4 times;	STACK = ['AAAA' ... 'ZZZZ']
	JbUn		; Join by newlines;	STACK = ['A\nA\n ... Z\nZ']

```

# Answer
> 1 votes
# Jelly, 5 bytes

```
ØAx4Y

```

Try it online!

# Answer
> 1 votes
# Python 2.7, 78 bytes

```
x='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for e in x:
    for d in range(0, 4):
        print e

```

# Answer
> 1 votes
# Attache, 28 bytes

```
Print@Char=>Flat!4&`&=>65:90

```

Try it online!

# Answer
> 1 votes
**BRAINF** **115 BYTES...**

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

```

I know this isn't going to in any awards for being the smallest, but I just thought it would be funny to use one of the hardest to understand languages.

**Breakdown of Code**

Cell zero is used for counting for setup, cell 1 and 3 are used to print, and cell two is used to count for the printing sequence

0 1 2 3 \[setup\]\[newline char\]\[print counter\]\[output char (set to A to begin)\]

```
++++[->+++>+++>+++<<<]>+>+>+  sets cells 1, 2, and 3 to 13(new line)
<<<++++[->>+++>+++<<<]>>+>+   sets cells 2 and 3 to 26 (length of alphabet)
<<<+++++++++++++[->>>+++<<<]  sets cell  3 to 65(A)
>>[->.<<.>>.<<.>>.<<.>>.<<.>>+<] increments cell 3, prints alternating between cell 1
                              and 3, and decrements cell 2.

```

Here is a Brainf compiler to test it (use the one w/out any newlines)

# Answer
> 1 votes
# Python 2, 39 bytes

```
i=65;exec('print chr(i);'*4+'i+=1;')*26

```

Try it online!

# Answer
> 1 votes
## 05AB1E, 6 bytes

```
A€D€D»

```

Try it online!

### Explanation

```
A        # push lowercase alphabet
 €       # for each char:
  D      # duplicate it
   €D    # duplicate each char again
     »   # join by newlines
         # implicit output

```

# Answer
> 1 votes
# cQuents, 18 bytes

```
|
#104&h64+k,Z,Z,Z

```

Try it online!

# Explanation

```
|
                  use newline as delimiter
#104              default input n = 104
    &             print first n terms in sequence
                  each term is the next term in the comma-delimited sequence, restarting
                  and incrementing k when the end of the terms list is reached
     h64+k        chr ( 64 + k )
          ,Z,Z,Z  next three terms equal the previous term

```

# Answer
> 1 votes
# GolfScript, 17 bytes

```
91,65>''+{...}%n*

```

Try it online!

# Explanation

```
91,65>            # Genearate initial alphabet
      ''+         # Convert to a string
         {...}%   # For every item, copy 3 times
               n* # Join the resulting string by newlines
                  # (because a string is a codepoint array)

```

# Answer
> 1 votes
# Burlesque, 16 bytes

```
@AZr@4?*{)'
}\mQ

```

Try it online!

```
@AZr@ # Array of A-Z as chars
4?*   # 4 of each as strings
{
 )'   # Add a newline between each letter
}\m   # Map for each string of 4 and concatenate
Q     # Pretty print for newlines instead of "\n"

```

# Answer
> 1 votes
# Google Sheets, 40

Output per cell:

```
=ArrayFormula(CHAR(SEQUENCE(104,1,260)/4

```

If newlines are important, 49:

```
=ArrayFormula(JOIN("
",CHAR(SEQUENCE(104,1,260)/4

```

No, `Sequence` does not support floating point steps.

# Answer
> 1 votes
# Julia 1.0, 26 bytes

```
@.print((('A':'Z')*"
")^4)

```

Try it online!

# Answer
> 1 votes
# Haskell, 43 bytes

```
main=mapM(putStrLn.pure)$['A'..'Z']<*[1..4]

```

Try it online!

This has two parts `mapM(putStrLn.pure)` takes a list of characters and prints each on it's own line.

`['A'..'Z']<*[1..4]` produces the list of desired characters. It does this with the monadic operator `(<*)` which works like `(>>)` except it keeps the values from the first arguement instead of the second.

# Answer
> 1 votes
# Excel, 21 bytes

```
=CHAR(ROW(260:363)/4)

```

Link to Spreadsheet

I think this would have worked when the question was asked if 104 cells were selected and `Ctrl`+`Shift`+`Enter` were used.

# Answer
> 1 votes
**Python 3, ~~46~~ 45 bytes**

```
print(*["\n%c"%(i//4+65)for i in range(104)])

```

**Python 3, 39 bytes**

```
for i in range(104):print(chr(i//4+65))

```

I prefer the first solution for being a true one-liner. But a correction of Justin's answer leads to a shorter solution.

# Answer
> 1 votes
# F#, 57 bytes

```
for i in 97..122 do for _ in 0..3 do printf"%c\n"(char i)

```

Try it online!

Loop through the alphabet (`for i in 97..122`), then through 4 times (`for _ in 0..3`), and finally print the character with a newline (`printf"%c\n"(char i)`).

Here is another one, 71 bytes:

```
for i in 97..122 do printf"%s"(String.replicate 4(string(char i)+"\n"))

```

Ungolfed code:

```
for i in 97..122 do for _ in 0..3 do printf "%c\n" (char i)

```

# Answer
> 1 votes
# Noether, 22 bytes

```
65~i91(0~l4(iBP?!l)!i)

```

Try it online!

# Answer
> 1 votes
# Zsh, 21 bytes

```
eval '<<<'{A..Z}{,,,}
```

Attempt This Online!

# Answer
> 1 votes
# Google Sheets, 48 bytes

```
=flatten(sort(if({1,1,1,1},char(row(A65:A90)))))

```

# Answer
> 1 votes
# Pip `-n`, 10 bytes

```
_MWV(zRL4)

```

Try It Online!

```
_MWV(zRL4)
    (zRL4)     ; repeat z="abcde...xyz" 4 times, forming the list [z,z,z,z]
  WV           ; weave the the 4 z's together, forming the string "aaaabbbb...yyyyzzzz"
_M             ; convert to a list
               ; implicitly joined by newlines by the -n flag and printed

```

# Answer
> 1 votes
## **Excel**, 28 bytes.

```
=CHAR(SEQUENCE(104,,65,1/4))

```

*No need to drag it will spill if one uses* **MS365** or **Excel 2021**.

# Answer
> 0 votes
# ///, 207 bytes

```
A
A
A
A
B
B
B
B
C
C
C
C
D
D
D
D
E
E
E
E
F
F
F
F
G
G
G
G
H
H
H
H
I
I
I
I
J
J
J
J
K
K
K
K
L
L
L
L
M
M
M
M
N
N
N
N
O
O
O
O
P
P
P
P
Q
Q
Q
Q
R
R
R
R
S
S
S
S
T
T
T
T
U
U
U
U
V
V
V
V
W
W
W
W
X
X
X
X
Y
Y
Y
Y
Z
Z
Z
Z

```

# Answer
> 0 votes
# bash shell, 19 bytes

```
echo {A..Z}{,,,}'
'

```

# Answer
> 0 votes
# Factor \+ `sequences.repeating spelling`, 38 bytes

```
ALPHABET 4 repeat 10 interleaved print

```

Attempt This Online!

```
ALPHABET       ! "abcdefghijklmnopqrstuvwxyz"
4 repeat       ! "aaaabbbbccccddddeeeeffffgggghhhhiiiijjjjkkkkllllmmmmnnnnooooppppqqqqrrrrssssttttuuuuvvvvwwwwxxxxyyyyzzzz"
10 interleaved ! "a\na\na\na\nb\nb\nb\nb\nc\nc\nc\nc\nd\nd\nd\nd\ne\ne\ne\ne\nf\nf\nf\nf\ng\ng\ng\ng\nh\nh\nh\nh\ni\ni\ni\ni\nj\nj\nj\nj\nk\nk\nk\nk\nl\nl\nl\nl\nm\nm\nm\nm\nn\nn\nn\nn\no\no\no\no\np\np\np\np\nq\nq\nq\nq\nr\nr\nr\nr\ns\ns\ns\ns\nt\nt\nt\nt\nu\nu\nu\nu\nv\nv\nv\nv\nw\nw\nw\nw\nx\nx\nx\nx\ny\ny\ny\ny\nz\nz\nz\nz"
print          ! (print to stdout)

```

# Answer
> 0 votes
# Wren, 57 bytes

```
for(c in 65..90)System.write((String.fromByte(c)+"\n")*4)

```

Try Wren

# Answer
> 0 votes
# Headascii, 59 bytes

```
+++++[]]ONE.+++++[]]]]]++^[]]+[U{D-^)!:RP]PRP]PRP]PRP]PN][}

```

"Try it" on DSO (links to a version which only supports number output, but should get the point across)

Alternatively, try it here, but code will have to be pasted in as shown:

```
erun("+++++[]]ONE.+++++[]]]]]++^[]]+[U{D-^)!:RP]PRP]PRP]PRP]PN][}")

```

short breakdown:

```
+++++[]]O                                        save 10 to global array
         NE                                      go to next code block
.                                                code block separator
+++++[]]]]]++^                                   set r1 to 27
              []]+[                              set r2 to 55
                   U                             grab 10 from the global array
                    {D-^) :                   }  while --r1 + 1 != 0
                           RP                      send out ascii 10 (newline)
                             ]P                    send out ascii 10 + r2 (letter)
                               RP]PRP]PRP]P        (four times total)
                                           N][     r2++
                         !                       finally, print all 'send out' chars

```

However, I must note that if instead of using `erun` we run it with `lrun`, newlines are automatically appended at the end of each print (and `!` is no longer required because technically it's a Headass program), making this 38 byter possible:

# Headass `lrun`, 38 bytes

```
+++++[]]]]]++^+++++[]][{D-^):N][]PPPP}

```

DSO link, still prints as numbers, must-paste-in-code interpreter link

Which... I guess its just dawning on me that that's a different.. Version? ...But I'm not going to go and mark all my Headas(s|cii) answers based on which "interpreter" they use unless it's actually relevant to the challenge :P

Oh and of course, a breakdown:

```
+++++[]]]]]++^                          set r1 to 27
              +++++[]][                 set r2 to 64
                       {D-^):        }  while --r1 != 0
                             N][]PPPP     print ++r2 four times

```

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


title: Sort and Re-apply Deltas of an Array

text:
# Question
Title: Sort and Re-apply Deltas of an Array
It seems that any Simple Modification of deltas using a consistent function can almost always be done some other shorter way, *Dennis*. Thus, the only solution I can imagine to make this harder, is to introduce some sort of inconsistent function.

**Sorting.**

Your task is to take an array of integers, sort their deltas, and recompile that to give the new array of integers.

## EG.

For the input:

```
1  5 -3  2  9

```

Get the following Deltas:

```
  4 -8  5  7

```

Then, sort these Deltas, Yielding:

```
 -8  4  5  7

```

And reapply them, which gives:

```
1 -7 -3  2  9

```

## Input/Output

You will be given a list/array/table/tuple/stack/etc. of signed integers as input through any standard input method.

You must output the modified data once again in any acceptable form, following the above delta sorting method.

You will receive N inputs where `0 < N < 10` where each number falls within the range `-1000 < X < 1000`

## Test Cases

```
1 5 -3 2 9   -> 1 -7 -3 2 9
-5 -1 -6 5 8 -> -5 -10 -7 -3 8
-8 1 -7 1 1  -> -8 -16 -16 -8 1
8 -9 3 0 -2  -> 8 -9 -12 -14 -2
-5 -2 -5 5 0 -> -5 -10 -13 -10 0
-1 9 -1 -7 9 -> -1 -11 -17 -7 9

```

## Notes

* As stated in above, you will always receive at least 1 input, and no more than 9.
* The first and last number of your output, will **always** match that of the input.
* Only Standard Input Output is accepted
* Standard loopholes apply
* This is , so the lowest byte-count wins!
* Have fun!

# Answer
# Jelly, 7 bytes

```
IṢ;@Ḣ+\

```

Try it online!

### How it works

```
IṢ;@Ḣ+\  Main link. Argument: A (array)

I        Increments; compute the deltas.
 Ṣ       Sort them.
    Ḣ    Head; pop and yield the first element of A.
  ;@     Concatenate with swapped arguments.
     +\  Take the cumulative sum.

```
> 4 votes

# Answer
# MATL, 8 bytes

```
1)GdShYs

```

Try it online!

```
1)   % Implicit input. Get its first entry
G    % Push input again
d    % Differences
S    % Sort
h    % Concatenate
Ys   % Cumulative sum. Implicit display

```
> 5 votes

# Answer
# Mathematica, 40 bytes

```
FoldList[Plus,#&@@#,Sort@Differences@#]&

```

Pure function taking a list of (anythings) as input and returning a list. `FoldList[Plus` starts with a number (in this case, `#&@@#`, the first element of the input) and repeatedly adds elements of the self-explanatory list `Sort@Differences@#`. This mimics the behavior of the built-in `Accumulate`, but the first number would need to be prepended to the list of differences by hand, which makes the byte-count higher (as far as I can tell).
> 3 votes

# Answer
# 05AB1E, 9 bytes

-4 thanks to Emigna

```
¬=s¥{vy+=

```

Try it online!

```
¬         # Get the head
 =        # Print
  s¥{     # Get sorted Deltas
     vy   # For each
       += # Add to the previous value and print

```
> 3 votes

# Answer
# Haskell, 59 Bytes

```
import Data.List
f l@(a:b)=scanl1(+)$a:(sort$zipWith(-)b l)

```

Breakdown:

```
f l@(a:b) =           --we create a function f that takes as input a list l with head a and tail b
zipWith(-)b l        --we make a new list with the deltas
sort$                    --sort it
a:                          --prepend a to the list
scanl1(+)$          --create a new list starting with a and adding the deltas to it cumulatively

```
> 2 votes

# Answer
# Python 2, 92 bytes

```
l=input();p=0;d=[]
r=l[0],
for e in l:d+=e-p,;p=e
for e in sorted(d[1:]):r+=r[-1]+e,
print r

```
> 2 votes

# Answer
# Python 2,

# 90 bytes

```
x=input()
print[sum(sorted(map(int.__sub__,x[1:],x[:-1]))[:i])+x[0]for i in range(len(x))]

```

# 84 bytes

Saved 6 bytes on using lambda. Thanks to ovs!

```
lambda x:[sum(sorted(map(int.__sub__,x[1:],x[:-1]))[:i])+x[0]for i in range(len(x))]

```

Try it online!

Breaking down the code,

```
>>> x
[1, 5, -3, 2, 9]
>>> map(int.__sub__,x[1:],x[:-1]) #delta
[4, -8, 5, 7]
>>> sorted(map(int.__sub__,x[1:],x[:-1])) #sorted result
[-8, 4, 5, 7]
>>> [sorted(map(int.__sub__,x[1:],x[:-1]))[:i]for i in range(len(x))]
[[], [-8], [-8, 4], [-8, 4, 5], [-8, 4, 5, 7]]
>>> [sum(sorted(map(int.__sub__,x[1:],x[:-1]))[:i])+x[0]for i in range(len(x))]
[1, -7, -3, 2, 9]

```

Happy Coding!
> 2 votes

# Answer
## JavaScript (ES6), 68 bytes

```
([p,...a])=>[s=p,...a.map(e=>p-(p=e)).sort((a,b)=>b-a).map(e=>s-=e)]

```

In JavaScript it turns out to be golfier to compute the Inverse Deltas of an Array. These are then sorted in descending order and cumulatively subtracted from the first element.
> 2 votes

# Answer
# Husk, 7 bytes

```
∫:←¹OẊ-

```

Try it online!
> 2 votes

# Answer
# Python 2, 97 bytes

```
p=input()
d=[p[i+1]-p[i] for i in range(len(p)-1)]
o=p[:1]
for n in sorted(d):o+=o[-1]+n,
print o

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), 93 bytes

```
(p,M=[p[0]])=>p.map((a,b)=>p[b+1]-a).sort((a,b)=>a-b).map((a,b)=>M=[...M,M[b]+a])[p.length-2]

```
> 1 votes

# Answer
# Pyth, 11 bytes

```
.u+NYS.+QhQ

```

This just does the obvious thing described in the statement.

Try It Online

```
      .+Q    Take the deltas of the input
     S       sort it
.u           Cumulative reduce
  +NY        using addition
         hQ  starting with the first element of the input

```

Suggestions for further golfing welcome.
> 1 votes

# Answer
# Julia 0.5, 30 bytes

```
!x=[x[];x|>diff|>sort]|>cumsum

```

Try it online!
> 1 votes

# Answer
# Python 2 with numpy, ~~67~~ 56 bytes

```
from numpy import*
lambda l:cumsum(l[:1]+sorted(diff(l)))

```

Let numpy compute the deltas, sort them, prepend the first element, and let numpy compute the cumulative sums. Pretty cheap?
> 1 votes

# Answer
# PHP, 89 bytes

```
for($a=$argv;n|$i=$a[++$x+1];)$d[]=$i-$a[$x];for(sort($d);$x-$y++;)echo$a[1]+=$d[$y-2],_;

```

Run like this:

```
php -nr 'for($a=$argv;n|$i=$a[++$x+1];)$d[]=$i-$a[$x];for(sort($d);$x-$y++;)echo$a[1]+=$d[$y-2],",";' 1  5 -3  2  9;echo
> 1_-7_-3_2_9_

```

# Explanation

```
for(
  $a=$argv;          # Set input to $a.
  n | $i=$a[++$x+1]; # Iterate over input.
)
  $d[] = $i-$a[$x];  # Add an item to array $d, with the difference between
                       the current and previous item.

for(
  sort($d);          # Sort the delta array.
  $x-$y++;           # Loop as many times as the previous loop.
)
  echo
    $a[1]+=$d[$y-2], # Print the first input item with the delta applied
                     # cumulatively. First iteration takes $d[-1], which
                     # is unset, so results in 0.
    _;               # Print underscore as separator.

```
> 1 votes

# Answer
# Pushy, 17 bytes

```
@ZL:&v+;Fg@Lt:K-#

```

Try it online!

```
@ZL:&v+;F           \ Calculate cumulative sum
         g          \ Sort
          @Lt:K-#   \ Calculate and print deltas

```
> 1 votes

# Answer
# Perl 6, 31 bytes

```
{[\+] @_[0],|sort @_[1..*]Z-@_}

```

Try it

## Expanded:

```
{
  [\+]            # triangle produce values using &infix<+>
    @_[0],        # starting with the first argument
    |             # slip the following into this list
      sort        # sort the following

         # generate the list of deltas

         @_[1..*] # the arguments starting with the second one
         Z[-]     # zipped using &infix:<->
         @_       # the arguments
}

```
> 0 votes

# Answer
## Batch, 197 bytes

```
@set n=%1
@set s=
:l
@set/ad=5000+%2-%1
@set s=%s% %d%
@shift
@if not "%2"=="" goto l
@echo %n%
@for /f %%a in ('"(for %%b in (%s%)do @echo %%b)|sort"') do @set/an+=%%a-5000&call echo %%n%%

```

`sort` doesn't sort numerically, so I bias all the differences by 5000.
> 0 votes

# Answer
## bash + sort, 102 bytes

```
echo $1
n=$1
shift
for e in $*
do
echo $((e-n))
n=$e
done|sort -n|while read e
do
echo $((n+=e))
done

```

## sh + sort + expr, 106 bytes

```
echo $1
n=$1
shift
for e in $*
do
expr $e - $n
n=$e
done|sort -n|while read e
do
n="$n + $e"
expr $n
done

```
> 0 votes

# Answer
## Clojure, 46 bytes

```
#(reductions +(first %)(sort(map -(rest %)%)))

```

One day I'm going to make Cljr language which has shorter function names than Clojure.
> 0 votes

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


title: Longest equal subsequences

text:
# Question
Title: Longest equal subsequences
# Definitions

* A subsequence may not be contiguous, e.g. `[1, 1, 1]` is a subsequence of `[1, 2, 1, 2, 1]`.
* An equal subsequence is a subsequence in which every element is equal.
* The longest equal subsequence may not be unique, e.g. `[1, 1]` and `[2, 2]` are both longest equal subsequences of `[2, 1, 1, 2]`.

# Input

A non-empty list of positive integers in one of the format below:

* as the native implementation of an array of positive integers in your language
* as a string of newline-separated integers in decimal
* as a string of newline-separated integers in unary
* any other reasonable formats

# Output

All of the longest equal subsequences in any order in one of the formats below:

* as a 2D nested array in your language (if the input is an array)
* as a flattened array with the equal elements being contiguous
* any other reasonable format

# Scoring

Although we are looking for something long, the code used should be as short as possible in terms of number of bytes, since this is

# Testcases

Inputs:

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

```

Outputs:

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

```

Note that for the outputs above, any order is valid.

A flattened array is also valid, as long as the equal elements are contiguous.

# Answer
# Jelly, 5 bytes

```
ĠLÐṀị

```

Try it online!

### How it works

```
ĠLÐṀị  Main link. Argument: A (array)

Ġ      Group; partition the indices of A by their corresponding values.
 LÐṀ   Select all index arrays with maximal length.
    ị  Unindex; retrieve the items of A at the specified indices.

```
> 8 votes

# Answer
# Brachylog, 7 bytes

```
⊇ᶠ=ˢlᵍh

```

Try it online!

## Explanation

```
⊇ᶠ=ˢlᵍh
⊇ᶠ        Find all subsequences
  =ˢ      Keeping only those for which all elements are equal
    lᵍ    Group by length
      h   Take the first group

```

's natural order generates the longest subsequences first, so those are the ones that end up in the first group.
> 5 votes

# Answer
# Pyth, 5 bytes

```
S.M/Q

```

Test suite

Explanation:

This is implicitly `S.M/QZQ`. `.M` is the maximal function, so `.M/QZQ` selects all elements where the value of `/QZ`, count the number of occurrences of the element in the input, is maximal. `S` then sorts the list so that identical elements are contiguous.
> 5 votes

# Answer
## bash, 66 bytes

```
sort|uniq -c|sort -rn|awk 'NR==1{a=$1}$1==a{for(i=a;i--;)print$2}'

```

This seems like it should be way shorter, but I can't figure out how.

```
sort                  # sort the input
|uniq -c              # group runs of identical lines and prefix with count
|sort -rn             # sort by count, with largest at top
|awk '                # pipe to awk...
  NR==1{a=$1}         # on the first line, set the variable "a" to field 1
  $1==a{              # on any line, if first field is a (max count)...
    for(i=a;i--;)     # a times...
    print$2           # print the second field
  }
'

```

Try it online!

Thanks to Leaky Nun for 3 bytes!
> 3 votes

# Answer
# Python 2, ~~68~~ 63 bytes

```
lambda x:sorted(n for n in x if x.count(n)/max(map(x.count,x)))

```

Try it online!
> 3 votes

# Answer
# Actually, 23 bytes

```
;╗⌠;╜ck⌡M;♂NM╗⌠N╜=⌡░♂FS

```

Try it online, or run all test cases!

Thanks to Leaky Nun for pointing out a one-byte improvement that really should've been obvious to me

-3 bytes from relaxed output format

Explanation:

```
;╗⌠;╜ck⌡M;♂NM╗⌠N╜=⌡░♂FS
;╗                        save a copy of the input to register 0
  ⌠;╜ck⌡M                 for each value in the input list:
   ;                        make a copy on the stack
    ╜c                      count the occurrences in the input list (from register 0)
      k                     make a list: [value, count]
         ;♂N             make a copy, take last value of each list in the 2D list
            M╗           store the maximum count in register 0
              ⌠N╜=⌡░     filter the other copy of the list of [value, count] lists:
               N╜=         take items where the count equals the maximum count
                    ♂FS  take first items (values) and sort them

```
> 2 votes

# Answer
# Stacked, ~~55~~ ~~52~~ 43 bytes

```
sorted rle toarr:[1#]map MAX@K[1#K=]YES rld

```

Try it online!

Works by run-length encoding the input, sorting by occurrences, keeping occurances for which the number of occurrences is maximal, and run length decoding. Outputs through a flat list, as is acceptable by the challenge.
> 2 votes

# Answer
# Mathematica, ~~42~~ ~~31~~ 25 bytes

*Thanks @GregMartin for 5 bytes and @MartinEnder for another byte!*

```
MaximalBy[Length]@*Gather

```

## Explanation

```
MaximalBy[Length]@*Gather  (*                       {1, 2, 3, 2, 1}       *)
                   Gather  (* Gather same numbers:  {{1, 1}, {2, 2}, {3}} *)
                 @*        (* Function composition                        *)
MaximalBy[Length]          (* Find longest:         {{1, 1}, {2, 2}}      *)

```
> 2 votes

# Answer
# K (ngn/k), 18 bytes

```
{x{b=|/b:#'x}#.=x}

```

Try it online!
> 2 votes

# Answer
# Python 2, 138 bytes

```
lambda l:[[x[0]]*x[1] for x in next(__import__('itertools').groupby(__import__('collections').Counter(l).most_common(),lambda x:x[1]))[1]]

```
> 1 votes

# Answer
# Octave, 47 bytes

```
[~,b,c]=mode(input(0));disp([repmat(c,1,b){:}])

```

Try it online!

### Explanation

The second and third outputs of `mode` (obtained as `[~,b,c]=mode(...)`) respectively give the number of repetitions (`b`) and a column cell array (`c`) of the most repeated elements in the input (`input(0)`) . The cell array `c` is then repeated horizontally `b` times (`repmat(c,1,b)`), converted to a comma-separated list (`{:}`) and contatenated horizontally (`[...]`) to give a numeric matrix, which is displayed (`disp(...)`).
> 1 votes

# Answer
# MATL, 10 bytes

```
3#XMg1bX"&

```

Try it online!

### Explanation

Similar to my Octave answer. Consider input `[10, 20, 30, 20, 10]` as an example.

```
3#XM   % Three-output version of mode function. Gives the first mode, the
       % number of repetitions, and a cell array with all modes
       % STACK: 10, 2, {10; 20}
g      % Convert from cell array to matrix
       % STACK: 10, 2, [10; 20]
1      % Push 1
       % STACK: 10, 2, [10; 20], 1
b      % Bubble up in the stack
       % STACK: 10, [10; 20], 1, 2
X"     % Repeat those number of times vertically and horizontally
       % STACK: 10, [10, 10; 20, 20]
&      % Specify that implicit display will show only the top of the stack.
       % Since this is singleton cell array that contains a matrix, that
       % matrix is directly displayed

```
> 1 votes

# Answer
# 05AB1E, ~~8~~ 5 bytes

Outputs a flat list in order

```
.M¹Ã{

```

Uses the **05AB1E** encoding. Try it online!
> 1 votes

# Answer
# CJam, 22 bytes

```
{$e`z~\__:e>f=.*\]ze~}

```

This is an anonymous block (function) that takes the input from the top of the stack and repaces it with the output. The output is a flattened array withequal elements being contiguous.

Try it online!

### Explanation

Consider input `[10 20 30 20 10 ]` as an example.

```
{      e# Begin block
       e#   STACK: [10 20 30 20 10]
  $    e#   Sort
       e#   STACK: [10 10 20 20 30]
  e`   e#   Run-length encoding
       e#   STACK: [[2 10] [2 20] [1 30]]
  z    e#   Zip
       e#   STACK: [[2 2 1] [10 20 30]]
  ~    e#   Dump array contents onto the stack
       e#   STACK: [2 2 1] [10 20 30]
  \    e#   Swap
       e#   STACK: [10 20 30] [2 2 1]
  __   e#   Duplicate twice
       e#   STACK: [10 20 30] [2 2 1] [2 2 1] [2 2 1]
  :e>  e#   Fold maximum over array. Gives the maximum of the array
       e#   STACK: [10 20 30] [2 2 1] [2 2 1] 2
  f=   e#   Map "is equal" with number (2) over the array ([2 2 1])
       e#   STACK: [10 20 30] [2 2 1] [1 1 0]
  .*   e#   Vectorized multiplication
       e#   STACK: [10 20 30] [2 2 0]
  \    e#   Swap
       e#   STACK: [2 2 0] [10 20 30]
  ]    e#   Pack into array
       e#   STACK: [[2 2 0] [10 20 30]]
  z    e#   Zip
       e#   STACK: [[2 10] [2 20] [0 30]]
  e~   e#   Run-length decoding
       e#   STACK: [10 10 20 20]
}      e# End block

```
> 1 votes

# Answer
# Perl 5, 58 bytes

```
sub{sort grep$x{$_}>$m,grep{$/=$x{$_}++;$m=$/if$m<$/;1}@_}

```
> 1 votes

# Answer
# Husk, 5 bytes

```
→kLk=

```

Try it online!
> 1 votes

# Answer
# Japt `-h`, 4 bytes

```
ü üÊ

```

Try it

```
ü üÊ     :Implicit input of array
ü        :Group & sort by value
  üÊ     :Group & sort by length
         :Implicit output of last element

```
> 1 votes

# Answer
# Nibbles, 5 bytes (10 nibbles)

```
/=~=~$$,$@

```

```
/=~=~$$,$@
   =~       # group
     $      # the input
      $     # by its own values,
 =~         # now group each of these groups
       ,$   # by their lengths
            # (group of longest groups comes last),
/           # fold over this list-of-lists from right
         @  # always returning the second argument
            # (so this fold just returns the last item,
            # which is the list of the longest groups
            # of values)

```
> 1 votes

# Answer
# APL (Dyalog), 22 bytes

Requires `⎕ML←3` which is default on many systems.

### Program: `s/⍨(⌈/=⊢)≢¨s←⊂⍨(⍋⊃¨⊂)⎕`

get numeric (evaluated) input

`(``)` tacit function
the indices of ascending items
`⊃¨` each pick from
the entire array

`⊂⍨` partition by cutting at its increases

`s←` store as *s*

`≢¨` tally each

`(``)` tacit function
`⌈/` the maximum (tally)
`=` equals
the argument (the tallies)

`s/⍨` filter *s* with that

### Function: `{s/⍨(⌈/=⊢)≢¨s←⊂⍨⍵[⍋⍵]}`

`{``}` anonymous function where argument is

`⍵[⍋⍵]` sort (lit. index with indices of ascending items)

`⊂⍨` partition by cutting at its increases

`s←` store as *s*

`≢¨` tally each

`(``)` tacit function
`⌈/` the maximum (tally)
`=` equals
the argument (the tallies)

`s/⍨` filter *s* with that Try it online!
> 0 votes

# Answer
## CJam, 24 bytes

```
{$e`_$W=0=\{0=1$=},e~\;}

```

I wanted to do this in 05ab1e, but I gave up :P

This is a block. Input and output are arrays on the stack.

Try it online!

Explanation:

```
{                      e# Stack:                | [1 2 3 2 1]
 $                     e# Sort:                 | [1 1 2 2 3]
  e`                   e# RLE encode:           | [[2 1] [2 2] [1 3]]
    _$W=               e# Copy elements:        | [[2 1] [2 2] [1 3]] [2 1]
       0=              e# First element:        | [[2 1] [2 2] [1 3]] 2
         \             e# Swap:                 | 2 [[2 1] [2 2] [1 3]]
          {0=1$=},     e# Filter where x[0]==2: | 2 [[2 1] [2 2]]
                  e~   e# RLE decode:           | 2 [1 1 2 2]
                    \; e# Delete back:          | [1 1 2 2]
                      }

```
> 0 votes

# Answer
# PHP, 69 Bytes

```
<?print_r(preg_grep("#".max($r=array_count_values($_GET))."#",$r));

```

Online Version

## Output Format

key = value , value = count

```
Array
(
    [1] => 2
    [2] => 2
)

```

## PHP, 96 Bytes

```
<?foreach($_GET as$v)$r[$m[]=count($l=preg_grep("#^{$v}$#",$_GET))][$v]=$l;print_r($r[max($m)]);

```

Online Version

## Output Format

1D Key= value

2D Key = position in the input array for each value

```
Array
(
    [1] => Array
        (
            [0] => 1
            [4] => 1
        )

    [2] => Array
        (
            [1] => 2
            [3] => 2
        )

)

```

## PHP, 97 Bytes

```
<?foreach($_GET as$v)$r[count($l=preg_grep("#^{$v}$#",$_GET))][$v]=$l;ksort($r);print_r(end($r));

```
> 0 votes

# Answer
## JavaScript (ES6), ~~84~~ 83 bytes

Returns a sorted flattened array.

```
a=>a.sort().filter((_,i)=>b[i]==Math.min(...b),b=a.map(i=>a.filter(j=>i-j).length))

```

### Test cases

```
let f =

a=>a.sort().filter((_,i)=>b[i]==Math.min(...b),b=a.map(i=>a.filter(j=>i-j).length))

console.log(JSON.stringify(f([1, 2, 3])))
console.log(JSON.stringify(f([1, 2, 2, 1])))
console.log(JSON.stringify(f([1, 2, 3, 2, 1])))
console.log(JSON.stringify(f([1, 2, 1, 2, 3, 4, 1])))
```
> 0 votes

# Answer
## Clojure, 65 bytes

```
#(let[P partition-by C count](last(P C(sort-by C(P +(sort %))))))

```

Ungolfed:

```
(def f #(->> %
             (sort-by      identity)   ; sort so that identical values are one after another, same as sort
             (partition-by identity)   ; partition by identity (duh!)
             (sort-by      count)      ; sort by item count
             (partition-by count)      ; partition by item count
             last))                    ; get the last partition

```
> 0 votes

# Answer
# C#, 145 Bytes

```
l=>{var t=Enumerable.Range(0,l.Max()+1).Select(i=>l.Count(a=>a==i));return t.Select((a,i)=>Enumerable.Repeat(i,a)).Where(d=>d.Count()==t.Max());}

```

This must be possible better as well, however I'm kind of stuck.

**Explanation**

```
l =>                                                   //Takes the list
{                                                      //...
    var t = Enumerable.Range(0, l.Max() + 1)           //Makes a range till the count, so that the items together with their indices are double defined (i.e. the items are 0,1,2,3... and the indices are the same)
                      .Select(i =>                     //Takes the items
                          l.Count(a => a == i));       //And replaces them with the count of themselves in the list (so the item has the index with its old value and the count as it's actual value)
    return t.Select((a, i) =>                          //Then it takes this list and selects the items together with the indices
        Enumerable.Repeat(i, a))                       //Repeats them as often as they appeared in the list
                  .Where(d => d.Count() == t.Max());   //And just keeps those which appear the maximum amount of times
};                                                     //...

```

Probably a totally different approach would be much shorter, so the C# challenge is still open :)
> 0 votes

# Answer
# Ruby, 57 bytes

```
->a{a.reject{|i|a.map{|j|a.count j}.max>a.count(i)}.sort}

```

Try it online!
> 0 votes

# Answer
# Factor \+ `math.combinatorics`, 46 bytes

```
[ all-subsets [ all-eq? ] filter all-longest ]

```

Try it online!

* `all-subsets` Get all the subsets of the input
* `[ all-eq? ] filter` Get the ones where all the elements are the same
* `all-longest` Get all the longest of these
> 0 votes

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


# Question
Title: Decompose binary into alternating subsequences
**This was inspired by *Problem 13 - Non-Repeating Binary* of HP CodeWars' recent competition.**

Let's take a random decimal number, say

```
727429805944311

```

and look at its binary representation:

```
10100101011001011111110011001011101010110111110111

```

Now split that binary representation into subsequences where the digits `0` and `1` alternate.

```
1010 010101 10 0101 1 1 1 1 1 10 01 10 0101 1 1010101 101 1 1 1 101 1 1

```

And convert each subsequence back into decimal.

```
10 21 2 5 1 1 1 1 1 2 1 2 5 1 85 5 1 1 1 5 1 1

```

## The Task

Take a single, positive integer as input and output the sequence of positive integers obtained by the above process.

## Details

* Input and output must be in decimal or unary.
* Numbers in the output must be separated in a sensible, human-readable fashion, and they must be in decimal or unary. No restriction on white space. Valid output styles: `[1,2,3]`, `1 2 3`, `1\n2\n3` where `\n` are literal newlines, etc.

## Test cases

```
 Input | Output
     0 | 0
     1 | 1
     2 | 2
     3 | 1 1
     4 | 2 0
     5 | 5
     6 | 1 2
     7 | 1 1 1
     8 | 2 0 0
     9 | 2 1
    10 | 10
    50 | 1 2 2
   100 | 1 2 2 0
  1000 | 1 1 1 1 10 0 0
 10000 | 2 1 1 2 0 2 0 0 0
 12914 | 1 2 2 1 1 2 2
371017 | 5 42 10 2 1

```

Additional note: all numbers in the output should be of the form `(2^k-1)/3` or `2*(2^k-1)/3`. That is, `0 1 2 5 10 21, 42, 85, 170, ...`, which is A000975 in the OEIS.

# Answer
> 11 votes
# Pyth, ~~17~~ 16 bytes

*1 byte thanks to Jakube*

```
iR2cJ.BQx1qVJ+dJ

```

Demonstration

A nice, clever solution. Uses some lesser known features of Pyth, like `x<int><list>` and `c<str><list>`.

```
iR2cJ.BQx1qVJ+dJ
                    Q = eval(input())
    J.BQ            Store in J the input in binary.
          qV        Vectorize equality function over
            J+dJ    J and J with a leading dummy char, to get the offset right.
                    This calculates whether each element matches its successor.
        x1          Find all of the indexes of 1 (True) in this list.
   cJ                Chop J at those locations.
iR2                  Convert from binary back to base ten and output.

```

# Answer
> 7 votes
# Mathematica, 47 bytes

```
#+##&~Fold~#&/@#~IntegerDigits~2~Split~Unequal&

```

Ungolfed:

```
FromDigits[#,2]&/@Split[IntegerDigits[#,2],Unequal]&

```

`Split[list,f]` splits a list into multiple lists, breaking at the position between `a` and `b` iff `f[a,b]` does not return `True`.

`FromDigits[n,2] => Fold[#+##&,n]` is a neat tip from alephalpha.

# Answer
> 7 votes
# Python, 86 bytes

Since I got horribly outgolfed in Pyth, lets just do it in Python again.

```
import re
lambda n:[int(s,2)for s in re.sub("(?<=(.))(?=\\1)"," ",bin(n)[2:]).split()]

```

Try it here!

## Explanation

We start with converting the input number `n` into a binary string. `bin(n)[2:]` takes care of that. We need to discard the first 2 chars of this string since `bin()` returns the string in the format `0b10101`.
Next we need to identify the borders of the subsequences. This can be done with the regex `(?<=(.))(?=\1)` which matches the zero-length positions in the string which have the same number to the left and right.
The obvious way to get a list of all subsequences would be to use `re.split()` which splits a string on a certain regex. Unfortunately this function does not work for zero-length matches. But luckily `re.sub()` does, so we just replace those zero-length matches with spaces and split the string on those after that.
Then we just have to parse each of those subsequences back into a decimal number with `int(s,2)` and are done.

# Answer
> 4 votes
# JavaScript (ES6) 58 ~~62 63~~

**Edit** 1 byte saved thx @ETHproductions

**Edit** 4 bytes saved thx @Neil

```
x=>x.toString(2).replace(/((.)(?!\2))*./g,x=>'0b'+x-0+' ')

```

```
f=x=>x.toString(2).replace(/((.)(?!\2))*./g,x=>'0b'+x-0+' ')

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

;[
[     0,'0'],
[     1,'1'],
[     2,'2'],
[     3,'1 1'],
[     4,'2 0'],
[     5,'5'],
[     6,'1 2'],
[     7,'1 1 1'],
[     8,'2 0 0'],
[     9,'2 1'],
[    10,'10'],
[    50,'1 2 2'],
[   100,'1 2 2 0'],
[  1000,'1 1 1 1 10 0 0'],
[ 10000,'2 1 1 2 0 2 0 0 0'],
[ 12914,'1 2 2 1 1 2 2'],
[371017,'5 42 10 2 1']
].forEach(t=>{
  var i=t[0],k=t[1],r=f(i)
  console.log(i+' -> '+r+(r.trim()==k.trim() ? ' ok':'ko (should be '+k+')'))
})
```

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

# Answer
> 4 votes
# Jelly, 12 bytes

```
BI¬-ẋż@BFṣ-Ḅ

```

Try it online! or verify all test cases.

### How it works

```
BI¬-ẋż@BFṣ-Ḅ  Main link. Argument: n

B             Convert n to base 2.
 I            Compute the increments, i.e., the differences of consecutive digits.
  ¬           Apply logical NOT.
   -ẋ         Repeat -1 that many times, for the logical NOT of each difference.
              [0, 0] / [1, 1] ->   0    -> 1 -> [-1]
              [0, 1] / [1, 0] -> 1 / -1 -> 0 -> []
       B      Yield n in base 2.
     ż@       Zip the result to the right with the result to the left.
        F     Flatten the resulting list of pairs.
         ṣ-   Split at occurrences of -1.
           Ḅ  Convert each chunk from base 2 to integer.

```

# Answer
> 4 votes
# Bash + GNU utilities, 51

```
dc -e2o?p|sed -r ':;s/(.)\1/\1 \1/;t'|dc -e2i?f|tac

```

Input taken from STDIN.

* `dc -e2o?p` reads input integer from STDIN and outputs a base 2 string
* `sed -r ':;s/(.)\1/\1 \1/;t'` splits the base 2 string with a space everywhere there are same consecutive digits
* `dc -e2i?f` reads the split binary in one go, putting the each part on the stack, then `f` dumps the whole `dc` stack (output numbers in reverse order) ...
* ... which is corrected by `tac`.

# Answer
> 3 votes
# Pyth, ~~22~~ 21 bytes

```
&Qu?q%G2H&
GH+yGHjQ2Z

```

Try it online: Demonstration

Really a tedious task in Pyth.

### Explanation:

```
&Qu?q%G2H&\nGH+yGHjQ2Z   implicit: Q = input number
                  jQ2    convert Q to base 2
  u               jQ2Z   reduce ^: for each digit H update the variable G=0:
   ?q%G2H                   if G%2 == H:
          \nG                  print G
         &   H                 then update G with H
              +yGH           else: update G with 2*G+H
  u                      print the last G also
&Q                       handle Q=0 special: only print 0 once

```

# Answer
> 3 votes
# Pyth, 26 bytes

```
iR2c:.BQ"(?<=(.))(?=\\1)"d

```

Try it here!

## Explanation

```
iR2c:.BQ"(?<=(.))(?=\\1)"d   # Q = input number

     .BQ                     # Convert input to binary
    :   "(?<=(.))(?=\\1)"d   # insert a whitespace between the subsequences
   c                         # split string on whitespaces
iR2                          # convert each subsequence into decimal

```

Since Python's split() function doesn't split on zero-length matches, I have to replace those matches with a space and split the result on that.

# Answer
> 3 votes
# 05AB1E, 18 bytes

Code:

```
b2FNð«N«Dð-s:}ð¡)C

```

Explanation:

```
b                   # Convert input to binary
 2F          }      # Do the following twice ( with N as range variable)
   Nð«N«            #    N + space + N
        D           #    Duplicate this
         ð-         #    Delete spaces from the duplicate string
           s        #    Swap the top two elements
            :       #    Replace the first string with the second
              ð¡    # Split on spaces
                )   # Wrap into an array
                 C  # Convert all element back to decimal

```

Try it online!

Uses **CP-1252** encoding.

# Answer
> 3 votes
# MATL, ~~18~~ 17 bytes

```
YBTyd~Thhfd1wY{ZB

```

**Try it online!**

```
YB      % input number. Convert to binary string
T       % push true value
y       % duplicate binary string and push it at the top of the stack
d~      % true for each value that equals the previous one
T       % push true value
hh      % concatenate: true, indices, true
f       % find indices of true values
d       % consecutive differences: lenghts of alternating sequences
1wY{    % split binary string according to those lengths
ZB      % convert each substring into decimal number

```

# Answer
> 3 votes
## zsh, ~~67~~ ~~63~~ 55 bytes

```
for i in `grep -oP '1?(01)*0?'<<<$[[##2]$1]`;<<<$[2#$i]

```

I don't know why, but this doesn't work in Bash.

Thanks to Dennis for 8 bytes!

# Answer
> 2 votes
# APL (APL), ~~21~~ 25 bytes

Now handles 0 as well.

```
{0::0⋄2⊥¨⍵⊂⍨1,2=/⍵}2⊥⍣¯1⊢

```

Try it online!

`2⊥⍣¯1⊢` convert to base-2, using as many bits as needed (lit. inverse from-base-2 conversion)

`{``}` apply the following anonymous function

`0::` if any error happens:

`0` return 0

now try:

`2=/⍵` pairwise equality of the argument (will fail one 0's length-0 binary representation)

`1,` prepend 1

`⍵⊂⍨` use that to partition the argument (begins new section on each 1)

`2⊥¨` convert each from base-2

# Answer
> 2 votes
## PHP, ~~171~~ ~~168~~ ~~162~~ ~~160~~ ~~158~~ ~~121~~ ~~120~~ ~~131~~ ~~124~~ ~~118~~ ~~116~~ ~~113~~ 112 bytes

```
function d($i){for(;$d<$l=strlen($b=decbin($i));){$c.=$u=$b[$d];echo$u==$b[++$d]||$d==$l?bindec($c).$c=" ":"";}}

```
**Exploded view**
```
function d($i) {
  for ( ; $d < $l = strlen($b = decbin($i)); ) {
    $c .= $u = $b[$d];
    echo $u == $b[++$d] || $d == $l ? bindec($c) . $c = " "
                                    : "";
  }
}

```

Use `d(int)` and you're off, output is an `echo`ed string of `int`s separated by a space.

**Edits:**
**-3:** Moved `$b` definition into `strlen()` call.
**-6:** Removed `$c` instantiation.
**-2:** **Finally** fixed the concatenation issue.
**-2:** No brackets for single-line `for()`.
**-37:** **Total overhaul.** Going with `Array` chunklets instead of repeated `Array`-\>`String`-\>`Array` calls.
**-1:** Sneaky `$c` reset.
**+11:** **Bugfix.** Was missing final chunk. No more.
**-7:** Don't need to instantiate `$d` at all? Nice.
**-6:** `return`-\>`echo`.
**-2:** Crunching `$c`.
**-3:** Ternary, my first love.
**-1:** Sneaky sneaky `$u`.

# Answer
> 2 votes
# Java 8, ~~127~~ 119 bytes

```
l->new java.util.ArrayList<Long>(){{for(String s:l.toBinaryString(l).split("(?<=(.))(?=\\1)"))add(l.parseLong(s,2));}};

```

There's probably a better regular expression out there to split the string on. I'm not proficient at regex, but I'll keep experimenting.

-8 bytes thanks to @FryAmTheEggman

# Answer
> 2 votes
## Convex 0.2+, 25 bytes

Convex is a new language that I am developing that is heavily based on CJam and Golfscript. The interpreter and IDE can be found here. Input is an integer into the command line arguments. This uses the **CP-1252** encoding.

```
2bs®(?<=(.))(?=\\1)"ö2fbp

```

Explanation:

```
2bs                         Convert to binary string
   ®(?<=(.))(?=\\1)"        Regex literal
                    ö       Split string on regex
                     2fb    Convert each split string into decimal integer
                        p   Print resulting array

```

# Answer
> 2 votes
# Japt, 7 bytes

```
¤ò¥ mn2

```

Test it

---

## Explanation

```
¤ò¥ mn2
           :Implicit input of integer U.
¤          :Convert to binary string.
 ò¥        :Split to an array by checking for equality.
    m      :Map over array.
     n2    :Convert to base-10 integer.

```

# Answer
> 1 votes
# Haskell, ~~147~~, 145 bytes

```
x%[]=[x]
x%(y:z)|or.(zipWith(==)<*>tail)$y:x=x:[]%(y:z)|1<2=(y:x)%z
b x|x<2=[x]|1<2=b(div x 2)++[mod x 2]
map(sum.zipWith((*).(2^))[0..]).([]%).b

```

`map(sum.zipWith((*).(2^))[0..]).([]%).b` is an unnamed function that computes the list.

Less golfed:

```
alternating :: Eq a => [a] -> Bool
alternating = or . (zipWith (==) <*> tail)

-- (%) is the partitioning function
(%) :: Eq a => [a] -> [a] -> [[a]]
x % [] = [x]

x % (y:z) | alternating (y : x) = x : [] % (y:z)
          | otherwise = (y : x) % z

bits :: Integral t => t -> [t]
bits x | x < 2     = [x]
       | otherwise = bits (div x 2) ++ [mod x 2]

unBits :: Num c => [c] -> c
unBits = sum . zipWith ((*) . (2^)) [0..]

f :: Integer -> [Integer]
f = map unBits . ([]%) . bits

```

# Answer
> 1 votes
## Python 3, 115 bytes

```
def f(s):
 s=bin(s);r=[s[2]]
 for i in s[3:]:
  if i==r[-1][-1]:r+=[i]
  else:r[-1]+=i
 return[int(x,2)for x in r]

```

## Explanation

```
def f(s):
 s=bin(s)                   # convert input in binary
 r=[s[2]]                   # initialize the result with the first char after the 'b' in binary string
 for i in s[3:]:            # loop on other element
  if i==r[-1][-1]:          # if the last element of the last string equal the current element
   r+=[i]                   # we add the current element in a new string
  else:
   r[-1]+=i                 # we add the current element to the last sting
 return[int(x,2)for x in r] # convert binary string in integer

```

## Results

```
>>> [print(i,f(i)) for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 50, 100, 1000, 10000, 12914, 371017]]
0 [0]
1 [1]
2 [2]
3 [1, 1]
4 [2, 0]
5 [5]
6 [1, 2]
7 [1, 1, 1]
8 [2, 0, 0]
9 [2, 1]
10 [10]
50 [1, 2, 2]
100 [1, 2, 2, 0]
1000 [1, 1, 1, 1, 10, 0, 0]
10000 [2, 1, 1, 2, 0, 2, 0, 0, 0]
12914 [1, 2, 2, 1, 1, 2, 2]
371017 [5, 42, 10, 2, 1]

```

**previous solution (118 bytes)**

```
def f(s):
 s=bin(s);r=s[2]
 for i in s[3:]:
  if i==r[-1]:r+='a'+i
  else:r+=i
 return[int(x,2)for x in r.split('a')]

```

# Answer
> 1 votes
# Perl, 53 bytes

Includes +1 for `-p`

Run with the number on STDIN

```
perl -p alterbits.pl <<< 371017

```

`alterbits.pl`:

```
$_=sprintf"0b%b",$_;s/(.)\K(?=\1)/ 0b/g;s/\S+/$&/eeg

```

# Answer
> 1 votes
## PowerShell, 103 bytes

```
[regex]::Matches([convert]::ToString($args[0],2),"(01)+0?|(10)+1?|.").Value|%{[convert]::toint32($_,2)}

```

Since I'm horrible at regex, I'm using the same expression as edc65's answer.

Absolutely destroyed by the lengthy .NET calls to do conversion to/from binary, and the .NET call to get the regex matches. Otherwise pretty straightforward. Takes the input `$args[0]`, `convert`s it to binary, feeds it into `Matches`, takes the resultant `.Value`s, pipes them through a loop `|%{...}` and `convert`s those values back to `int`. Output is left on the pipeline and implicitly printed with newlines.

---

### For extra credit - a (mostly) non-regex version at 126 bytes

```
$l,$r=[char[]][convert]::ToString($args[0],2);$l+-join($r|%{(" $_",$_)[$l-bxor$_];$l=$_})-split' '|%{[convert]::toint32($_,2)}

```

We again take input `$args[0]` and `convert` it to binary. We re-cast as a char-array, storing the first character in `$l` and the remaining characters in `$r`. We then send `$r` through a loop `|%{...}` where every iteration we select from either the character prepended with a space or just the character, depending upon the result of a binary xor with `$l`, and then set `$l` equal to the character. This effectively ensures that if we have the same character twice in a row, we prepend a space between them.

The output of the loop is `-join`ed together and appended to the first character `$l`, then `-split` on spaces (which is technically a regex, but I'm not going to count it). We then do the same loop as the regex answer to `convert` and output integers.

# Answer
> 1 votes
# Java 345 bytes

```
package com.ji.golf;
import java.util.regex.*;
public class Decompose {
  public static String decompose(long l) {
    String o="";
    String s=Long.toBinaryString(l);
    Matcher m=Pattern.compile("(01)+(0)?|(10)+(1)?|(1)|(0)").matcher(s);
    while(m.find()){String c=s.substring(m.start(),m.end());o+=Integer.parseInt(c, 2)+" ";}
    return o;
  }
}

```

## Test

```
package com.ji.golf;
public class DecompseTest {
  public static void main(String[] args) {
    String[] inOut = new String[]{
        "0,0",
        "1,1",
        "2,2",
        "3,1 1",
        "4,2 0",
        "5,5",
        "6,1 2",
        "7,1 1 1",
        "8,2 0 0",
        "9,2 1",
        "10,10",
        "50,1 2 2",
        "100,1 2 2 0",
        "1000,1 1 1 1 10 0 0",
        "10000,2 1 1 2 0 2 0 0 0",
        "12914,1 2 2 1 1 2 2",
        "371017,5 42 10 2 1"
    };
    for (String s : inOut) {
      String[] io = s.split(",");
      String result = Decompose.decompose(Long.parseLong(io[0]));
      System.out.println("in: " + io[0] + ", reusult: [" +  result.trim() + "], validates? " + result.trim().equals(io[1].trim()));
    }
  }
}

```

## Output

```
in: 0, reusult: [0], validates? true
in: 1, reusult: [1], validates? true
in: 2, reusult: [2], validates? true
in: 3, reusult: [1 1], validates? true
in: 4, reusult: [2 0], validates? true
in: 5, reusult: [5], validates? true
in: 6, reusult: [1 2], validates? true
in: 7, reusult: [1 1 1], validates? true
in: 8, reusult: [2 0 0], validates? true
in: 9, reusult: [2 1], validates? true
in: 10, reusult: [10], validates? true
in: 50, reusult: [1 2 2], validates? true
in: 100, reusult: [1 2 2 0], validates? true
in: 1000, reusult: [1 1 1 1 10 0 0], validates? true
in: 10000, reusult: [2 1 1 2 0 2 0 0 0], validates? true
in: 12914, reusult: [1 2 2 1 1 2 2], validates? true
in: 371017, reusult: [5 42 10 2 1], validates? true

```

# Answer
> 1 votes
# Julia, ~~70~~ 57 bytes

```
n->map(i->parse(Int,i,2),split(bin(n),r"(?<=(.))(?=\1)"))

```

This is an anonymous function that accepts an integer and returns an integer array. To call it, assign it to a variable.

The approach here is similar to DenkerAffe's nice Python answer. We get the binary representation of `n` using `bin(n)`, and split the resulting string at all matches of the regular expression `(?<=(.))(?=\1)`. It's actually a zero-length match; `(?<=(.))` is a positive lookbehind that finds any single character, and `(?=\1)` is a positive lookahead that finds the matched character in the lookbehind. This locates the places where a number is followed by itself in the binary representation. Just `parse` each as an integer in base 2 using `map` and voila!

# Answer
> 1 votes
# C, ~~137~~ 129 bytes

```
main(){unsigned long a,b=scanf("%lu",&a),c=!!a;while(a>=b*2)b*=2;while(b)b/=2,c=c*(~(a^a/2)&b|!b?!printf("%lu\n",c):2)+!!(a&b);}

```

Input and output are on the standard streams.

# Answer
> 1 votes
# , 16 bytes

```
#:#.;.1~1,2=/\#:

```

Try it online!

## Explanation

```
#:#.;.1~1,2=/\#:  Input: integer n
              #:  Convert from decimal to list of binary digits
          2  \    For each overlapping sublist of size 2
           =/       Reduce using equals
        1,        Prepend 1
#:                Binary digits
    ;.1~          Partition those binary digits at the 1s in the previous list
  #.                Convert each partition from a list of binary digits to decimal

```

# Answer
> 1 votes
# Jelly, 9 bytes

```
BI¬0;œṗBḄ

```

Try it online!

# Answer
> 1 votes
# q/kdb+, 52 bytes

**Solution:**

```
{2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}

```

**Examples:**

```
q){2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}0
,0
q){2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}1
,1
q){2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}3
1 1
q){2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}8
2 0 0
q){2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}10000
2 1 1 2 0 2 0 0 0
q){2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}12914
1 2 2 1 1 2 2
q){2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}371017
5 42 10 2 1
q){2 sv'cut[0,(&)(~)differ a]a:(63^(*)(&)a)_a:0b vs x}727429805944311
10 21 2 5 1 1 1 1 1 2 1 2 5 1 85 5 1 1 1 5 1 1

```

**Explanation:**

`q` is interpreted right-to-left.

Cast input to binary, trim off leading zeros, find indices where different, invert to get indices where the same, split list on these indices, convert back to base-10. Looks a little heavy compared to the APL solution though...

```
{2 sv'cut[0,where not differ a]a:(63^first where a)_a:0b vs x} / ungolfed solution
{                                                            } / lambda function
      cut[                    ]                                / cut a list at indices, cut[indices]list
                                                      0b vs x  / converts to 64bit binary representation
                                                    a:         / save as a
                                                   _           / drop 'n' elements from a
                                 (                )            / evaluate this
                                     first where a             / returns first occurance of true in list a
                                  63^                          / fill result with 63 if null (to handle input of 0)
                               a:                              / save as a, we've stripped off all the left-most 0s
                      differ a                                 / whether or not item in list a is different to previous
                  not                                          / the inversion of this result
            where                                              / these are the points where we have 00 or 11
          0,                                                   / add the first index too!
  2 sv'                                                        / 2 sv converts binary back to base-10, ' for each list

```

# Answer
> 1 votes
# PHP, 98 bytes

```
function($x){foreach(str_split(decbin($x))as$c)$o[$p+=$c==$d].=$d=$c;return array_map(bindec,$o);}

```

Try it online!

# Answer
> 1 votes
# Husk, 5 bytes

```
mḋġ≠ḋ

```

Try it online!

# Answer
> 1 votes
# Ruby, ~~49~~ 48 bytes

-1 byte thanks to Sʨɠɠan

Uses the regexp from edc65’s JavaScript answer.

```
->n{("%b"%n).scan(/((.)(?!\2))*./){p $&.to_i 2}}

```

Attempt This Online!

# Answer
> 0 votes
# PHP, 147

```
$b=decbin($argv[1]);$a=[$t=$b[0]];$k=0;for($i=1;$i<strlen($b);$i++){$v=$b[$i];if($v==$t)$k++;$t=$v;$a[$k].=$v;}foreach($a as$c)echo bindec($c).' ';

```

Need to put extra space at last of output as their are no restriction. Notices are displayed for short coding.

Ungolfed version

```
$n=$argv[1];
$b=decbin($n);
$l=strlen($b);
$t=$b[0];
$a=[0=>$t];$k=0;
for($i=1;$i<$l;$i++){
    $v=$b[$i];
    if($v==$t){
        $k++;
    }
    $t=$v;$a[$k].=$v;
}
foreach($a as $c){
    echo bindec($c).' ';
}

```

# Answer
> 0 votes
# Retina, 60

```
+`(1+)\1
$1a
a1
1
(?<=(.))(?=\1)
¶
+`1(a*)\b
a$.1$*1;
a

;
1

```

Try it online! Or try a slightly modified version for all test cases (with decimal I/O).

Unfortunately, zero length matches seem to have two "sides", causing duplication when used with the regex from the third stage. Only costs one byte though.

Takes input as unary, outputs as unary. Not really sure about using different in/out unary values, but that would save 4 bytes.

# Answer
> 0 votes
# Factor \+ `math.unicode`, 45 bytes

```
[ >bin [ ≠ ] monotonic-split [ bin> ] map ]

```

Try it online!

---
Tags: code-golf, sequence, base-conversion, binary, subsequence
---


title: Show a balanced binary tree

text:
# Question
Title: Show a balanced binary tree
Given an integer \\$n \> 1\\$, output a balanced binary tree with \\$n\\$ leaf nodes.

The tree should be constructed out of  (space), `\` and `/` (slashes). Each slash represents a branch.

* A node is represented by adjacent slashes: `/\`. There must be a root node at the top of the tree (i.e. the first row of the output).
* To construct the next row of the output, take each slash in the previous row at position \\$i\\$. You can do one of the following:
    + Terminate the branch: put a space. That branch now ends in a leaf.
    + Extend the branch: put a slash in the same direction as the slash above (i.e. if there's a `\` in column \\$i\\$ above, put a `\` in column \\$i+1\\$; if there's a `/` in column \\$i\\$ above, put a `/` in column \\$i-1\\$.
    + Create another branch: put an internal node (`/\`) at the appropriate location below the slash above.
* You cannot have different branches converge - i.e. no `\/`.

Since this is a *balanced* binary tree, at each branching off point, the height of the left and right subtrees cannot differ by more than one. In other words, you must fill up level \\$l\\$ with leaves/branches before putting leaves/branches in level \\$l+1\\$.

### Examples

A balanced binary tree with \\$2\\$ nodes could look like:

```
/\

```

or

```
 /\
/  \

```

but not, for example,

```
 /\
 \/
 /\

```

If \\$n=3\\$, you could have

```
  /\
 /\ \

```

or

```
  /\
 / /\
/ /  \

```

If \\$n=4\\$, you could have

```
  /\
 /  \
/\  /\

```

but not

```
 /\
/\/\

```

or

```
/\
  \
  /\
 /\

```

Standard loopholes apply, shortest code wins.

# Answer
# Charcoal, 47 bytes

```
Ｎθ≔Ｌ↨⊖θ²ηＦηＦ⌊⟦Ｘ²ι⁻θＸ²ι⟧«≔Ｘ²⁻⊖ηιζＪ×ζ⊕×⁴κ±⊖ζ↗ζ↓↘ζ

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｎθ≔Ｌ↨⊖θ²ηＦη

```

Input `n` and loop up until the ceiling of its logarithm to base 2. (This represents the "height" of the tree.)

```
Ｆ⌊⟦Ｘ²ι⁻θＸ²ι⟧«

```

Loop over the branches in pairs. (For the last row, the number of branches might be less than a power of 2, so that the final number of leaves is `n`.)

```
≔Ｘ²⁻⊖ηιζＪ×ζ⊕×⁴κ±⊖ζ↗ζ↓↘ζ

```

Draw each pair of branches. Bottom branches are 1 character tall while each higher branch is extended to be twice as tall in total as the previous.

If trailing blank lines are allowed then the last  can be removed. (Alternatively, I'm hoping to fix the Charcoal bug that generates those blank lines, but there are so many edge cases that it will take some time to work through them all.)
> 2 votes

---
Tags: code-golf, ascii-art, open-ended-function
---


title: Find the inverse of a 3 by 3 matrix

text:
# Question
Title: Find the inverse of a 3 by 3 matrix
## Challenge

Given nine numbers, `a, b, c, d, e, f, g, h, i`, as input which correspond to the square matrix:

$$\mathbf{M} = \begin{pmatrix}a& b& c\\ d& e& f\\ g& h& i\end{pmatrix}$$

Find the inverse of the matrix, \\$\mathbf{M}^{-1}\\$ and output its components.

## Inverse Matrix

The inverse of a matrix 3 by 3 obeys the following equation:

$$\mathbf{MM}^{-1} = \mathbf{M}^{-1}\mathbf{M} = \mathbf{I} = \begin{pmatrix}1&0&0\\0&1&0\\0&0&1\end{pmatrix}$$

And can be calculated as:

$$\mathbf{M}^{-1} = \frac{1}{\det(\mathbf{M})}\mathbf{C}^T$$

Where \\$\mathbf{C}\\$ is the matrix of cofactors:

$$\mathbf{C}=\begin{pmatrix}ei-fh&fg-di&dh-eg\\ch-bi&ai-cg&bg-ah\\bf-ce&cd-af&ae-bd\end{pmatrix}$$

And \\$\mathbf{C}^T\\$ is the transpose of \\$\mathbf{C}\\$:

$$\mathbf{C}^T = \begin{pmatrix}ei-fh&ch-bi&bf-ce\\fg-di&ai-cg&cd-af\\dh-eg&bg-ah&ae-bd\end{pmatrix}$$

And \\$\det(\mathbf{M})\\$ is the determinant of \\$\mathbf{M}\\$:

$$\det(\mathbf{M}) = a(ei-fh)-b(di-fg)+c(dh-eg)$$

## Worked Example

For example, let's say the input is `0, -3, -2, 1, -4, -2, -3, 4, 1`. This corresponds to the matrix:

$$\mathbf{M} = \begin{pmatrix}0&-3&-2\\1&-4&-2\\\-3&4&1\end{pmatrix}$$

Firstly, let's calculate what's known as the determinant using the formula above:

$$\det(\mathbf{M}) = 0(-4\times1-(-2)\times4) - (-3)(1\times1-(-2)\times-3) + (-2)(1\times4-(-4)\times-3) = 1$$

Next let's calculate the matrix of cofactors:

$$\mathbf{C} = \begin{pmatrix}-4\times1-(-2)\times4& -(1\times1-(-2)\times-3)&1\times4-(-4)\times-3\\\-(-3\times1-(-2)\times4)&0\times1-(-2)\times-3&-(0\times4-(-3)\times-3)\\\-3\times-2-(-2)\times-4&-(0\times-2-(-2)\times1)&0\times-4-(-3)\times1\end{pmatrix}$$

$$= \begin{pmatrix}4&5&-8\\\-5&-6&9\\\-2&-2&3\end{pmatrix}$$

We then need to transpose \\$\mathbf{C}\\$ (flip the rows and columns) to get \\$\mathbf{C}^T\\$:

$$\mathbf{C}^T = \begin{pmatrix}4&-5&2\\5&-6&-2\\\-8&9&3\end{pmatrix}$$

Finally, we can find the inverse as:

$$\mathbf{M}^{-1} = \frac{1}{\det(\mathbf{M})}\mathbf{C}^T = \frac{1}{1}\begin{pmatrix}4&-5&2\\5&-6&-2\\\-8&9&3\end{pmatrix}=\begin{pmatrix}4&-5&2\\5&-6&-2\\\-8&9&3\end{pmatrix}$$

So the output would be `4, -5, -2, 5, -6, -2, -8, 9, 3`.

## Rules

* The given matrix will always have an inverse (i.e. non-singular). The matrix may be self-inverse
* The given matrix will always be a 3 by 3 matrix with 9 integers
* The numbers in the input will always be integers in the range \\$-1000 \leq n \leq 1000\\$
* Non-integer components of the matrix may be given as a decimal or a fraction

## Examples

```
Input > Output
1, 0, 0, 0, 1, 0, 0, 0, 1 > 1, 0, 0, 0, 1, 0, 0, 0, 1
0, -3, -2, 1, -4, -2, -3, 4, 1 > 4, -5, -2, 5, -6, -2, -8, 9, 3
1, 2, 3, 3, 1, 2, 2, 1, 3 > -1/6, 1/2, -1/6, 5/6, 1/2, -7/6, -1/6, -1/2, 5/6
7, 9, 4, 2, 7, 9, 3, 4, 5 > -1/94, -29/94, 53/94, 17/94, 23/94, -55/94, -13/94, -1/94, 31/94

```

## Winning

The shortest code in bytes wins.

# Answer
> 19 votes
# MATL, 54 bytes

```
th3LZ)t,3:q&XdpswP]w-lw/GtY*tXdsGXdsUw-IXy*2/+GtXds*-*

```

Try it online!

Just to keep it interesting, doesn't use the inbuilt matrix division or determinant functions to do it.

Instead, computes the determinant using the Rule of Sarrus.

And the adjugate (transposed cofactor matrix) using Cayley–Hamilton formula.

$$ {\displaystyle \operatorname {adj} (\mathbf {A} )={\frac {1}{2}}\left((\operatorname {tr} \mathbf {A} )^{2}-\operatorname {tr} \mathbf {A} ^{2}\right)\mathbf {I} \_{3}-\mathbf {A} \operatorname {tr} \mathbf {A} +\mathbf {A} ^{2}.} $$

### Commented code:

```
% Finding determinant
th    % concatenate the matrix to itself sideways
3LZ)  % chop off the last column (since the Rule of Sarrus doesn't need it)
t     % duplicate this matrix (say S)
,     % do this twice:
  3:q&Xd  % get the first three diagonals of S
  ps      % multiply each diagonal's values and add the results
  wP      % switch and flip the matrix (to get the popposing diagonals next time)
]w    % close loop, switch to have correct order of sums
-     % subtract - we now have the determinant
lw/   % invert that

% Finding adjugate using Cayley–Hamilton formula
GtY*  % A^2 term (last term of the formula)
tXds  % trace(A^2) for term 1 of formula
GXdsU % (trace(A))^2 for term1 of formula
w-    % (trace(A))^2 - trace(A^2)
IXy*  % multiply that by the identity matrix
2/    % divide that by 2 - term 1 complete
+
GtXds* % A*trA for term 2 of formula
-      % subtract to get adj(A)

*      % multiply by the inverse of determinant we found earlier
       % implicit output

```

We could go even ~~more insane~~ purer by replacing the matrix multiplication `GtY*` done for \\$ A^2 \\$, with something like `3:"Gt!@qYS*!s] 3$v t&v 3:K-&Xd` (Try it on MATL Online).

The more direct and obvious way:

## 4 bytes

```
-1Y^

```

Try it online!

*(-1 byte thanks to @Luis Mendo.)*

`-1` \- Push the literal -1

`Y^` \- Raise input to that power (implicit input, implicit output)

# Answer
> 14 votes
**APL(Dyalog Classic),1 byte**

Try it online!

if a flat lis is required this is 8 bytes

```
,∘⌹3 3∘⍴

```

Try it online!

# Answer
> 9 votes
# **R, ~~51~~ ~~35~~ ~~27~~ ~~8~~ 5 bytes**

```
solve

```

Try it online!

First go at doing one of these golf challenges. Sorry if my formatting is wrong!

Saved a total additional 11 bytes thanks to Giuseppe! Saved an additional 19 bytes thanks to JAD!

# Answer
> 5 votes
# Jelly, 3 bytes

```
æ*-

```

Try it online!

Assuming we can take input and provide as a 2D list of integers. If a flat list of integers is really required for both input and output, then this works for 6 bytes.

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

*Saved 2 bytes thanks to @Mr.Xcoder*
*Saved 1 byte thanks to @ETHproductions*

Takes input as 9 distinct values.

```
(a,b,c,d,e,f,g,h,i)=>[x=e*i-h*f,c*h-b*i,b*f-c*e,y=f*g-d*i,a*i-c*g,d*c-a*f,z=d*h-g*e,g*b-a*h,a*e-d*b].map(v=>v/=a*x+b*y+c*z)

```

Try it online!

# Answer
> 4 votes
# , 2 bytes

```
%.

```

Just a built-in primitive

Try it online!

# Answer
> 3 votes
# Python 2, 139 bytes

```
def F(a,b,c,d,e,f,g,h,i):x=e*i-f*h;y=f*g-d*i;z=d*h-e*g;print[j/(a*x+b*y+c*z)for j in x,c*h-b*i,b*f-c*e,y,a*i-c*g,c*d-a*f,z,b*g-a*h,a*e-b*d]

```

Try it online! (Has `return` instead of `print` for ease of testing.)

# Answer
> 2 votes
# Python 3, 77 bytes

```
import numpy
lambda l:(numpy.matrix(l).reshape(-1,3)**-1).ravel().tolist()[0]

```

Takes input as a flat list.

It's 63 bytes if input is taken as a 2D array:

```
import numpy
lambda l:(numpy.matrix(l)**-1).ravel().tolist()[0]

```

# Answer
> 2 votes
# Google Sheets, 16 bytes

```
=MINVERSE(A1:C3)

```

Input is in the range `A1:C3`

Built-ins are boring

# Answer
> 1 votes
# Clean, 143 bytes

```
import StdEnv
$a b c d e f g h i#p=e*i-h*f
#q=f*g-d*i
#r=d*h-g*e
=[v/(a*p+b*q+c*r)\\v<-[p,c*h-b*i,b*f-c*e,q,a*i-c*g,d*c-a*f,r,g*b-a*h,a*e-d*b]]

```

Try it online!

# Answer
> 1 votes
# Pari/GP, 6 bytes

```
m->1/m

```

Takes multiplicative inverse in the matrix ring \\$\mathrm{M}\_n\\$.

Try it online!

# Answer
> 1 votes
# Perl 5, 179 bytes

```
sub{($a,$b,$c,$d,$e,$f,$g,$h,$i)=@_;map$_/($a*$x+$b*$y+$c*$z),$x=$e*$i-$f*$h,$c*$h-$b*$i,$b*$f-$c*$e,$y=$f*$g-$d*$i,$a*$i-$c*$g,$c*$d-$a*$f,$z=$d*$h-$e*$g,$b*$g-$a*$h,$a*$e-$b*$d}

```

Try it online.

# Answer
> 1 votes
# APL (Dyalog), 7 bytes

```
,⌹3 3⍴⎕

```

Takes input as a flat list and outputs as a flat list

**Try it online!**

# Answer
> 1 votes
# Factor \+ `math.matrices.extras`, 5 bytes

```
recip

```

Try it online!

# Answer
> 1 votes
# Ruby \+ `-rmatrix`, 24 bytes

```
->a{Matrix[*a].inv.to_a}

```

Or, if taking in and outputting a Matrix is apart of standard I/O, then this becomes 10 bytes.

```
->a{a.inv}

```

Attempt This Online!

# Answer
> 0 votes
# Perl, 226 + 4 (`-plF,` flag) = 230 bytes

```
$_=join', ',map$_/($a*$x+$b*$y+$c*$z),$x=($e=$F[4])*($i=$F[8])-($f=$F[5])*($h=$F[7]),($c=$F[2])*$h-($b=$F[1])*$i,$b*$f-$c*$e,$y=$f*($g=$F[6])-($d=$F[3])*$i,($a=$F[0])*$i-$c*$g,$c*$d-$a*$f,$z=$d*$h-$e*$g,$b*$g-$a*$h,$a*$e-$b*$d

```

Try it online.

# Answer
> 0 votes
# Noether, 168 bytes

```
I~aI~bI~cI~dI~eI~fI~gI~hI~iei*fh*-a*di*fg*-b*-dh*eg*-c*+~zei*fh*-z/P","~nPch*bi*-z/PnPbf*ce*-z/PnPfg*di*-z/PnPai*cg*-z/PnPcd*af*-z/PnPdh*eg*-z/PnPbg*ah*-z/PnPae*bd*-z/P

```

**Try it online**

# Answer
> 0 votes
## Clojure, 165 bytes

```
(fn[a b c d e f g h i](let[M map C(M -(M *[e f d c a b b c a][i g h h i g f d e])(M *[f d e b c a c a b][h i g i g h e f d]))](for[i C](/ i(apply +(M *[a b c]C))))))

```

I'm sorry this outputs C in transpose, and I'm feeling lazy to re-do those long character sequences to fix it at the moment.

---
Tags: code-golf, math, matrix, linear-algebra
---