# Transpose a 3x3 matrix across the anti-diagonal

Write a program which takes a 3x3 matrix on stdin and prints its transpose along the anti-diagonal to stdout. You may assume that all elements of the matrix will be integers. Columns are space-separated and rows are newline-separated.

### Example

Input:

1 2 3
3 4 5
1 2 3


Output:

3 5 3
2 4 2
1 3 1


Input:

1 2 3
4 5 6
7 8 9


Output:

9 6 3
8 5 2
7 4 1

• Your example output seems incorrect; it has only been transposed along the second diagonal. Commented Mar 26, 2014 at 4:34
• Also, what are the matrix elements? Digits? Positive integers? Any integers? Floats? Any strings? If numbers, is there an upper limit? Commented Mar 26, 2014 at 4:36
• @IlmariKaronen edited Commented Mar 26, 2014 at 4:46
• So, you're effectively saying that the matrix should be transposed twice along the first diagonal (once in step 1, then again in step 2) as well as along the second diagonal (in step 2)? That's the only way I can make sense of your example output. Commented Mar 26, 2014 at 4:49
• What if the language of choice uses newline to mark end of input? Is [1 2 3; 3 4 5; 1 2 3] an acceptable input format? Commented Dec 20, 2015 at 17:13

# APL - 7

⌽⍉⌽3 3⍴


Example input:

⌽⍉⌽3 3⍴1 2 3 3 4 5 1 2 9
> 9 5 3
2 4 2
1 3 1


ngn APL demo

• Could the downvoter please explain themself? Thanks. Commented Mar 26, 2014 at 6:57
• God love APL. Nice solution! Commented Mar 28, 2014 at 3:49
• @mniip ANy chance you can explain how this works? It's so... concise! I love it! Commented Mar 28, 2014 at 6:17
• 3 3⍴ converts input to a 3x3 matrix. ⌽ reverses it along first dimension, ⍉ transposes it, and then ⌽ reverses it again. Commented Mar 28, 2014 at 17:14
• Function (4 bytes in Dyalog Unicode): ⌽∘⍉⌽, Full program (4): ⌽⍉⌽⎕, Full program (8, raveled input): ⌽⍉⌽3 3⍴⎕. Commented Jul 19, 2018 at 15:37

## Mathematica, 3128 20 bytes

(r=Reverse)[r@#]&


The  is Mathematica's transpose operator (which is displayed as a superscript T in Mathematica).

## Sage, 39

Runs in the interactive prompt

matrix(input()[::-1]).transpose()[::-1]


Sample input:

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


Sample output:

[3 5 3]
[2 4 2]
[1 3 1]


## GolfScript, 18 / 15 / 11 chars

~]-1%3/zip{' '*n}%


This is the straightforward implementation, following pretty much the exact steps given in the question. There's a clever arithmetic trick one could use instead, but it turns out to need more characters.

Sample input:

1 2 3
3 4 5
1 2 9


Sample output:

9 5 3
2 4 2
1 3 1


Ps. If I can use the same output format as in ace's answer (i.e. extra with square brackets around each row), I can save three chars for a total of 15 chars:

~]-1%3/zip{n}%


If a one-line output format like [[9 5 3] [2 4 2] [1 3 1]] is allowed, I can shrink that further to just 11 chars:

~]-1%3/zip

• If I understand your code correctly, I think you misinterpreted the question. For the matrix [[1,2,3],[4,5,6],[7,8,9]], your program should output [[9,6,3],[8,5,2],[7,4,1]], not [[3,6,9],[2,5,8],[1,4,7]]. Commented Mar 26, 2014 at 5:14
• @ace: Yeah, I noticed that. Stupid symmetric example. Fixed. Commented Mar 26, 2014 at 5:15
• You may save one character in each of the first two cases if you include the newline in the map, e.g. {' '*n}%. Commented Mar 26, 2014 at 5:54
• @Howard: Edited, thanks! That'll give me an extra blank line at the end of the output, but I suppose that's acceptable. Commented Mar 26, 2014 at 5:56

# J - 16 (?) char

Taking the 3x3 matrix as a grid from stdin, we get the 16 character:

|:&.|.".1!:1]3#1


This can be made shorter if the input is made more flexible, as in the Sage and APL answers:

|:&.|.".1!:1]1   NB. if stdin input form can be  1 2 3, 4 5 6,: 7 8 9
|:&.|.           NB. if used as an expression like the APL answer


The key is in the |:&.|. portion: this is what transposes the matrix. It reads Transpose (|:) Under (&.) Reverse (|.), meaning you reverse the matrix, transpose it, and then undo your initial reverse.

Demo:

   |:&.|.".1!:1]3#1          NB. three lines input, three output
1 2 3
4 5 6
7 8 9
9 6 3
8 5 2
7 4 1

1 2 3,3 4 5,:1 2 9        NB. a matrix
1 2 3
3 4 5
1 2 9
|:&.|. 1 2 3,3 4 5,:1 2 9  NB. the logic
9 5 3
2 4 2
1 3 1


# K, 3/7/20(?) bytes

K is similar enough to APL that a character-for-character transliteration of @mniip's solution works:

|+|3 3#


In action:

  |+|3 3#1 2 3 3 4 5 1 2 9
(9 5 3
2 4 2
1 3 1)


This behaves identically, modulo the way output is prettyprinted. However, I should note that neither this solution nor the solution it is based on actually operate on stdin/stdout. To implement this as per a stricter interpretation of the spec in Kona-compatible K3 it's necessary to use 0: and jump through some hoops:

0:,/'2$|+|3 3#. 0:  Write to stdout (0:) the join over each (,/') of the two-wide string format (2$) of the anti-diagonal transpose (|+|) of the 3x3 reshape (3 3#) of the eval (.) of stdin (0:).

In action:

indigo:kona je\$ ./k antidiag.k
K Console - Enter \ for help

1 2 3 3 4 5 1 2 9
9 5 3
2 4 2
1 3 1


There's a pretty good reason that APL-family programmers tend to avoid problems that force the use of stdin/stdout. Arguably, with flexible IO requirements, this could be solved with simply |+|:

  |+|(1 2 3;3 4 5;1 2 9)
(9 5 3
2 4 2
1 3 1)


# Vyxal, 4 bytes

RÞTR


Try it Online!

R    # Vectorised reverse
ÞT  # Transpose
R # Vectorised reverse


# Brain-Flak-c, 2628 bytes

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


If it weren't for IO requirements this could have been 842 bytes but hey it was a good challenge :P I'm sure there's a lot that can be golfed here and I will see if I can find some of those spots later but right now I need to stop staring at brackets.

Try it online!

# BQN, 3 bytes

⌽˘⌽


Try it online!

### Explanation

⌽˘⌽
⌽ 1. Reverse over [leading axis][1]
⌽˘  2. Reverse over "major cells"


# MATLAB, 15 bytes

Rotate the matrix 180 degrees, and transpose it. This takes the input where columns are space separated and rows are newline separated. Outputs on the same format.

@(A)rot90(A,2)'

ans([1 2 3
4 5 6
7 8 9])

ans =

9     6     3
8     5     2
7     4     1


### Racket, 42 bytes

(λ(m[r reverse])(r(apply map list(r m))))


Takes a list of lists of numbers as input, and outputs the same type.

Thought I might as well find a use case for some of the tips I'd written up some years ago!

Try it online!

# Thunno, $$\6\log_{256}(96)\approx\$$ 4.94 bytes

.rZt.r


Attempt This Online!

.r reverses each row; Zt transposes; .r reverses each row.

# Fortran (GFortran), 87 98101 bytes

integer A(3,3);read*,((A(i,j),j=1,3),i=1,3);print'(3i3)',((A(4-i,4-j),i=1,3),j=1,3)
end


# JavaScript (Node.js), 83 97 bytes

-14 bytes thanks to @noodleman !

Input and output are the matrixes exactly in the string format specified by OP.

This surely is the shortest JS answer using this format!

s=>s.split(/\s/).map((e,i,a)=>a[i+(2-i%3-(i/3|0))*4]+(i%3<2? :i>6?:
)).join


Try it online!

Let me explain a bit:
First we split the input string on all whitespaces, which gives us a one-dimensional array.

Then, we switch each item with their corresponding targets by transforming the current value of the (one-dimensional) index this way:
i+(2-i%3-(i/3|0))*4.

And finally, we concatenate all the elements while adding the   and \n after the right items (but specifically not after the last item).

• Replace the whole .split .join .split thing with .split(/\s/) to save 14 bytes: Try it online! Commented Jun 1, 2023 at 15:40
• @noodleman Oh wow, thank you! I really should learn about regex, i never think about it! Commented Jun 1, 2023 at 15:45
• Well since you don't know, \s matches any whitespace character. Commented Jun 1, 2023 at 15:46

# R, 78

write.table(matrix(rev(unlist(strsplit(readLines(),' '),' ')),3),qu=F,r=F,c=F)
# Copy and paste the input
# If the prompt is not on a new line, press enter after the last line
# Type Ctrl+D


I discovered the rev() function on SO, it helped me to understand than the transformation is just reversing the input and putting it in the matrix from top to bottom, and left to right.

I also discovered that the argument row.names=T (T for true) can be shortened to r=T, saving 16 chars.

## Explanations:

• readLines() reads STDIN and return a vector with 3 elements (each one is a string)
• strsplit() splits the strings in the vector by using space as a separator
• unlist() makes a flat list from a vector
• rev() puts the list in reverse order
• matrix([list], 3) creates a matrix from the list, the argument 3 indicates that there is 3 elements per row
• write.table([matrix], qu=F, r=F, c=F) prints the matrix without quotes, rows and columns labels

## TI-BASIC, 50

Input A:rowSwap(A,1,dim(A
AnsT→A:rowSwap(A,1,dim(A

• This will throw an error when you try to store a matrix to the real variable A. Commented May 17, 2015 at 4:37
• In addition, it doesn't take input in the right format, which should be space-separated numbers. Commented May 17, 2015 at 4:44

## CJam, 13 bytes

q~]W%3/zSf*N*


Test it here.

CJam is newer than this challenge. This solution is very similar to the GolfScript one.

### Explanation

q~   e# Read input and evaluate, pushing all 9 numbers on the stack.
]    e# Wrap them in an array.
W%   e# Reverse it - this performs a 180° rotation.
3/   e# Split into rows of length 3.
z    e# Transpose.
Sf*  e# Join integers in each row with spaces.
N*   e# Join the rows with linefeeds.


If there was no constraint on 3x3 inputs, we could either compute the line width with a square root:

q~]W%_,mQ/zSf*N*


Or we could perform the anti-diagonal transpose as vertical flip, transpose, vertical flip (like my Mathematica answer does):

qN/Sf/W%zW%Sf*N*


In either case, we'd have 16 bytes.

# R, 37 bytes

write(scan()[rep(9:7,e=3)-3*0:2],1,3)


Try it online!

Simply changes the order of the elements of the input vector.

Well, actually a basic approach is shorter:

### R, 35 bytes

write(matrix(rev(scan()),3,,T),1,3)


Try it online!

# Jelly, 3 bytes

ṚZṚ


Try it online!

Uses Python list format for I/O.

# Japt, 3 bytes

yÔÔ


Try it

yÔÔ     :Implicit input of 2D array
y       :Transpose
Ô      :Reverse rows
Ô     :Reverse array


# Factor + math.matrices, 27 bytes

[ anti-flip simple-table. ]


anti-flip postdates build 1525, the one TIO uses, so here's a picture of running this in Factor's REPL:

Note that in a standard output context, simple-table. outputs its elements with spaces in between. In the REPL, it's a little fancier.

# 05AB1E, 7 (or 3) bytes

|€#øRí»


Try it online.

With less strict I/O rules it would be 3 bytes instead, with I/O being a 3x3 matrix of integers:

øRí


Try it online.

Explanation:

         #  e.g. input = "1 2 3\n4 5 6\n7 8 9"
|        # Take all input-lines as a list of strings
#  STACK: ["1 2 3","4 5 6","7 8 9"]
€#      # Split each line by spaces
#  STACK: [["1","2","3"],["4","5","6"],["7","8","9"]]
ø     # Zip the matrix, swapping rows with columns
#  STACK: [["1","4","7"],["2","5","8"],["3","6","9"]]
R    # Reverse the order of rows in the matrix
#  STACK: [["3","6","9"],["2","5","8"],["1","4","7"]]
í   # Reverse each row of the matrix
#  STACK: [["9","6","3"],["8","5","2"],["7","4","1"]]
»  # Join each row by spaces, and then everything by newlines
#  STACK: "9 6 3\n8 5 2\n7 4 1"
# (after which it is output implicitly)


Here some alternatives with different order of operations:

øíR
Ríø
íRø
íøí
RøR


# flax, 2 bytes

Ṙ∝


ATO doesn't have the lastest commit of flax (because I keep discovering bugs). So here is an image of it in action:

# JavaScript, 103 bytes

Expects string input and outputs string

s=>(s=s.split
.map(x=>x.split ))[0].map((_,c)=>s.map((_,r)=>s[2-r][2-c])).map(x=>x.join ).join



Try it:

f=s=>(s=s.split
.map(x=>x.split ))[0].map((_,c)=>s.map((_,r)=>s[2-r][2-c])).map(x=>x.join ).join

;[
1 2 3
3 4 5
1 2 3,
1 2 3
4 5 6
7 8 9
].forEach(x=>console.log(f(x)))

# JavaScript, 45 bytes

Expects 2D array input and outputs 2D array

m=>m[0].map((_,c)=>m.map((_,r)=>m[2-r][2-c]))


Try it:

f=m=>m[0].map((_,c)=>m.map((_,r)=>m[2-r][2-c]))

;[
[
[1, 2, 3],
[3, 4, 5],
[1, 2, 3]
],
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
].forEach(x=>console.log(JSON.stringify(f(x))))