# ASCII art reflection

In this challenge, you will be given a text block, and you need to perform reflection on the text.

# Input:

1. A string to be reflected. The text may not be supplied as an array whose elements are the lines of text. For example, "ab\ncd" and ['a','b','\n','c','d'] are allowed, but ['ab','cd'] or [['a','b'],['c','d']] are not. You can assume that all of the lines have the same number of characters (padded with whitespace where needed).
2. A boolean where True indicates Y reflection and False indicates X reflection

The two inputs can be passed in any order.

# Output:

The reflected string. The characters do not change, only their position. The resulting image block should be aligned to the top left (the first row and column must each contain a non-whitespace character). Trailing whitespace (on any of the lines) is allowed.

# Test cases:

False
o /
--|/
|
/ \

/ o
/|--
|
\ /


True
o /
--|/
|
/ \

/ \
|
--|/
o /


True
text

text


False
text

txet


True
P
P
C
G

G
C
P
P


False
P
P
C
G

P
P
C
G


True
abcde
fghij
kl mn
opqrs
tuvwx

tuvwx
opqrs
kl mn
fghij
abcde


• Can we take the boolean in any format (eg. 1 and 0) or we must use True and False? – TuxCrafting Jul 13 '16 at 16:03
• Putting each line in an array is not allowed For some languages that would be the only way, if they don't allow multiline strings – Luis Mendo Jul 13 '16 at 16:30
• @LuisMendo If a language natural string representation can't contain an \n I would go as far as to say that it's not a string representation. – Fatalize Jul 13 '16 at 16:37
• Can you clarify the boolean input a bit? Do I get to pick any two values, one of which is falsey and the other of which is truthy, and make my program work with those; or should my program handle all falsey values one way and all truthy values the other way? – Lynn Jul 13 '16 at 17:28
• Also, a lot of the answers seem to assume the input is rectangular (all lines are padded to the same length using spaces). Is that assumption okay? Either way, you should clarify this in the question. – Lynn Jul 13 '16 at 18:41

## C#, 168144141 120 Bytes

using System.Linq;i=>y=>string.Join("\n",y?i.Split('\n').Reverse():i.Split('\n').Select(x=>string.Concat(x.Reverse())));


New version utilizes the obvious string.Join overload that takes an IEnumerable, the first solution was using it inadvertently I was just able to use it for the else side of the ternary as well.

### Update:

New version is an anonymous lambda and uses currying to save 21 bytes total. This changes usage to be f("text")(false) where f is the anonymous function.

### Ungolfed:

using System.Linq;

//Using currying to save one byte
input => IsYReflect =>
//Lambda makes return implicit
string.Join("\n", IsYReflect
//Y Reflect, just need to reverse the array
? input.Split('\n').Reverse()
//X Reflect, reverse each line into an IEnumerable
: input.Split('\n').Select(x => string.Concat(x.Reverse())));

• Scott Kaye left a comment that has since been removed that triggered me to try some new things and shave off 24 bytes. – user19547 Jul 14 '16 at 20:35
• C#6 expression bodied function saves another 3 bytes – user19547 Jul 14 '16 at 21:38

## Pyke, 7 bytes

!I_)ncX


Try it here!

!I )    - if not boolean:
_     -  input = reversed(input)
nc  - input.split("\n")
X - splat(input)
-  (print lines backwards)


# Brainfuck, 143140 131 bytes

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


Beats C#.

The challenge was easy enough for Brainfuck, and I apparently was tired enough to just have to do it.

Takes the boolean as a 0x00 (falsy) or any other (truthy) byte in the start of the input, then a rectangle-padded string.

Outputs a trailing newline for the Y flip, and none for the X flip.

Requires an interpreter that supports memory locations to the left of the start (unsure if still required) and gives EOF as 0x00. One such interpreter is here. Obviously doesn't support null bytes in the input because of that.

The code has a lot of blocks with 10 +'s or -'s; those can probably be reduced.

### Commented version

, get mode
[ check truthy input
,[ loop thru input
---------- subtract newline
>+ set flag
< go back to char
[ was not newline
> move to flag
- reset flag
]
> move to flag or one past flag
[ hit flag; was newline
- reset flag
> skip a cell
]
< go to next position
]
< find end of line
[ loop thru lines
[<]> find start of line
[ loop thru line
. print this cell
> go to next cell
]
++++++++++ change to newline
. print newline
<[<]< find end of previous line
]
]
,[ loop thru any input left
---------- subtract newline
>+ set flag
< go back to char
[ was not newline
> move to flag
- reset flag
]
> move to flag or one past flag
[ hit flag; was newline
- clear flag
< go back to char
< go back to line chars
[ loop thru line
. print this cell
< go to previous cell
]
++++++++++. print newline
[>]>> find empty cell
]
< go to next position
]
< go to line
[ loop thru line
. print this cell
< go to previous cell
]


# 32-bit x86 machine code, 76 bytes

In hex:

31c031c9495789f7fcf2aef7d15192b00a89f7f2ae5829f7f7f787f95f4b89c3741287d94b534b8a041eaa75f95b01dea4e2f2c348f7e101c6b00a5651f3a4595e29ce4f4b0f44c3aa75f0c3


Input: EBX: direction flag (0/1), ESI: input string, EDI: output buffer. Input is required to be rectangular.

0:  31 c0               xor eax,eax         ;EAX=0
2:  31 c9               xor ecx,ecx
4:  49                  dec ecx             ;ECX=(uint)-1
5:  57                  push edi
6:  89 f7               mov edi,esi
8:  fc                  cld
9:  f2 ae               repne scasb         ;Scan input string for terminating NULL
b:  f7 d1               not ecx             ;ECX==<input string length (including NULL)>
d:  51                  push ecx
e:  92                  xchg edx,eax        ;EDX=0
f:  b0 0a               mov al,0x0a         ;'\n'
11: 89 f7               mov edi,esi
13: f2 ae               repne scasb         ;Scan input string for the first newline
15: 58                  pop eax             ;EAX==<input string length (including NULL)>
16: 29 f7               sub edi,esi         ;EDI==<single line length (including '\n')>
18: f7 f7               div edi             ;EAX==<# of lines>
1a: 87 f9               xchg ecx,edi        ;ECX=EDI
1c: 5f                  pop edi             ;EDI=<dest buffer>
1d: 4b                  dec ebx             ;Test input flag (0/1)
1e: 89 c3               mov ebx,eax         ;EBX=<# of lines>
20: 74 12               je _vertical
22: 87 d9               xchg ecx,ebx        ;Horisontal flip, exchange ECX & EBX so we can use LOOP
24: 4b                  dec ebx             ;EBX=<single line length (excluding '\n')>
_hfouter:
25: 53                  push ebx
_hfinner:
26: 4b                  dec ebx             ;Decrement inner loop counter
27: 8a 04 1e            mov al,[esi+ebx]    ;AL=ESI[EBX]
2a: aa                  stosb               ;*EDI++=AL
2b: 75 f9               jne _hfinner        ;EBX==0 => break
2d: 5b                  pop ebx
2e: 01 de               add esi,ebx         ;*ESI=='\n' (\0 on the last line)
30: a4                  movsb               ;*EDI++=*ESI++, ESI now points to the next line
31: e2 f2               loop _hfouter       ;--ECX==0 => break
33: c3                  ret                 ;Nothing more to do here
_vertical:
34: 48                  dec eax             ;# of strings less one
35: f7 e1               mul ecx             ;Line length (including '\n')
37: 01 c6               add esi,eax         ;ESI+=ECX*(EAX-1), ESI now points to the beginning of the last line
39: b0 0a               mov al,0x0a         ;'\n'
_vfloop:
3b: 56                  push esi
3c: 51                  push ecx
3d: f3 a4               rep movsb           ;Copy the whole line to the output including newline/NULL at the end
3f: 59                  pop ecx
40: 5e                  pop esi
41: 29 ce               sub esi,ecx         ;Set ESI to the beginning of the previous line
43: 4f                  dec edi             ;*EDI=='\n' (0 on the first iteration), should overwrite it with correct value
44: 4b                  dec ebx             ;Decrement loop counter
45: 0f 44 c3            cmove eax,ebx       ;if (EBX==0) EAX=EBX, this clears EAX on the last iteration
48: aa                  stosb               ;*EDI++=EBX?'\n':0
49: 75 f0               jne _vfloop         ;EBX==0 => break
4b: c3                  ret


r=reverse
f b=unlines.last(map r:[r|b]).lines


Usage example:

f True "abc\ndef\nghi\njkl"
"jkl\nghi\ndef\nabc\n"

f False "abc\ndef\nghi\njkl"
"cba\nfed\nihg\nlkj\n"


Split into lines, either reverse the lines (True) or reverse each line (False) and join into a single string again. In case of a True input, map r:[r|b] is a list of two functions [<reverse each line>, <reverse lines>] and for a False input a list with one function [<reverse each line>]. last picks the last element of this list.

# Jelly, 8 bytes

ṣ⁷ṚU⁴?j⁷


Try it here.

ṣ⁷         Split over newlines.
ṚU⁴?     If ⁴ (2nd argument), then Ṛ (reverse rank ∞), else U (reverse rank 1).
j⁷   Join with newlines.


# Python, 56 bytes

lambda s,r:'\n'.join(s[::2*bool(r)-1].split('\n')[::-1])


Call with a string s and any truthy/falsey value r.

• It doesn't work that way. Your program has to either take any truthy value, or take only True, which could also be 1. You cannot restrict input to be only 0 or 2. – mbomb007 Jul 13 '16 at 18:41
• Yeah, I didn't think through my answer. @mbomb007 is correct here, it needs to work for any truthy/falsy value for your language. – Nathan Merrill Jul 13 '16 at 19:04
• @NathanMerrill Just an FYI, you can avoid stuff like the 3 byte answer by saying that the input should not encode any additional information. This would have allowed the second answer (which I thought was rather clever), but of course what you would like to see is up to you. – FryAmTheEggman Jul 13 '16 at 19:22
• This answer is invalid according to OP as it outputs this for test case # 1 when it should instead be outputting what is given in the post for that test case (i.e. space padded to the length of the first line). – R. Kap Jul 13 '16 at 20:37

# Python 3.5, 61 bytes:

lambda f,j:[print(r[::-1])for r in j[::[1,-1][f]].split('\n')]


A simple anonymous lambda function that assumes rectangular input. Call it by by first naming the function, and then calling it wrapped inside print(). In other words, if the function were named H, call it like print(H(<Bool value>, <String>)), where <Bool Value> is any true or false value (i.e. 0/1, true/false, etc.) and <String> is the input string.

See it in Action! (repl.it)

Here is another version with the same length that also assumes rectangular input, but this time a named function, i.e. you don't have to name it first nor wrap it inside print():

def J(f,j):[print(r[::-1])for r in j[::[1,-1][f]].split('\n')]


Simply call this one likeJ(<Bool Value>,<String>).

See this in Action! (repl.it)

However, I'm not the one to stop there. Although we are allowed to assume rectangular input, I also created a version that does not assume that type of input. Therefore, it will space-pad all of the lines to the same length based on the line with the maximum length if and only if the <Bool> input is False, as only a X-reflection will result in the string being "flipped". Now, without further ado, here is the non-rectangular assuming version with a length of 134 129 bytes in the form of a normal function:

def J(f,j):print('\n'.join([' '*((max([len(i)for i in j.split('\n')])-len(r))*(not f))+r[::-1]for r in j[::[1,-1][f]].split('\n')]))


See this Last One in Action! (repl.it)

# Brachylog, 2624 16 bytes

t1,?h@nr~@nw|hrw


Expects a list containing the string and the boolean 1 or 0, e.g.

run_from_file('code.bl',["P
|    P
|    C
|    G":1]).


### Explanation

t1,              If the tail of the input is 1
?h@n              Split the string on \n
r             Reverse the resulting list
~@n          Join the list of strings with \n
w         Write to STDOUT
|                Or
hr                   Reverse the string
w                  Write to STDOUT


# MATL, 11 bytes

10&Ybc2i-&P


Try it online!

The first input is the multiline string. Since MATL doesn't recognize \n as linefeed, the multiline string should be defined as a concatenation of substrings, or individual characters, and 10 (ASCII for line feed, which is interpreted as a character). Concatenation in MATL is [... ...] or [..., ...] (commas are optional). So for example, input can be as follows (concatenation of a string, linefeed, and another string):

['first line' 10 'second']


or equivalently (concatenation of individual characters)

['f' 'i' 'r' 's' 't' ' ' 'l' 'i' 'n' 'e' 10 's' 'e' 'c' 'o' 'n' 'd']


or (same with commas)

['f', 'i', 'r', 's', 't', ' ', 'l', 'i', 'n', 'e', 10, 's', 'e', 'c', 'o', 'n', 'd']


The second input can be entered as 1/0 or equivalently as T/F for true/false respectively.

### Explanation

10     % Push 10 (ASCII for linefeed)
&Yb    % Take input string implicitly. Split at linefeeds. Gives a cell array
c      % Convert to a 2D char array, right-padding with spaces
i~Q    % Input Boolean value. Negate and add 1. Gives 1/2 for true/false resp.
&P     % Flip along that dimension (1: vertically; 2: horizontally). Display implicitly


# Pyth, 10 bytes

j?Q_.z_M.z


Test suite.

j?Q_.z_M.z  first line evaluated as Q, all other lines as .z
?Q         if Q:
_.z         yield reverse(.z)
_M.z  else: yield map(reverse, .z)
j           join by newlines


# Bash + common linux utils, 16

((\$1))&&tac||rev


Boolean value (zero or non-zero) passed as a command-line parameter. I/O of text block via STDIN/STDOUT. Assumes that all lines are the same length, as indicated in the comments.

# C (Ansi), 193 Bytes

## Golfed:

i,y,x;main(g,o,p)char**o;{p=(o[1][0]=='t');while(o[2][++i]!='\n');p?y=(strlen(o[2])-1)/i:(x=i);do do printf("%c",o[2][x+y*i]);while(p?++x<i:x-->0);while(p?x=0,y--:++y<(x=i-1,strlen(o[2])/i));}


## Ungolfed:

i,y,x;
main(g,o,p)char**o;{
p=(o[1][0]=='t');
while(o[2][++i]!='\n');
p?y=(strlen(o[2])-1)/i:(x=i);
do{
do{
printf("%c",o[2][x+y*i]);
}while(p?++x<i:x-->0);
}while(p?x=0,y--:++y<(x=i-1,strlen(o[2])/i));
}


## Usage:

### Compilation Arguments:

gcc -O3 -ansi


### Example Input:

Input is a t or not t for true of false followed by a newspace lead and trailed string.

./reverseString t "
truck
ducky
quack
moose
"


### Example Output:

moose
quack
ducky
truck


# JavaScript (ES 6) 83 bytes

(c,b)=>(p=c.split
)&&(b?p.reverse():p.map(a=>a.split.reverse().join)).join



f=(c,b)=>(p=c.split
)&&(b?p.reverse():p.map(a=>a.split.reverse().join)).join

f("abcde\nfghij\nkl mn\nopqrs\ntuvwx",1)

c="
o /
--|/
|
/ \
";

f(c,1)
" / \
|
--|/
o / "

f(c,0)
"/ o
/|--
|
\ / "

• I see a different output for f(c,0) when I try - maybe your c doesn't have all the spaces in the right places. – Neil Jul 13 '16 at 20:42
• Is the trailing white space after the first "o /" significant? – Peter Mortensen Jul 13 '16 at 22:40
• @PeterMortensen & Neil: I'm pretty sure that's from my copy-pasting. The javascript console puts your beginning " on the first line and makes everything look terrible so I formatted it a bit when I pasted in here. Very likely I have a bug too. – Charlie Wynn Jul 14 '16 at 17:30

# Julia, 59 bytes

x\y=(y=split(y,'
');! =reverse;join(x?!y:[!a for a=y],'
'))


Try it online!

# J, 29 bytes

}:@,@(,.&LF@{|."1,:|.)>@cutLF


LHS input is the boolean where 0 is false and 1 is true. RHS is the string input.

# Java 99 bytes

public String[] reverse(String[]a){
int i=-1,j=a.length;
for(;++i<--j;){
String b=a[i];
a[i]=a[j];
a[j]=b;
}
return a;
}


Golfed:

String[] e(String[]a){int i=-1,j=a.length;for(;++i<--j;){String b=a[i];a[i]=a[j];a[j]=b;}return a;}


## Perl, 35 bytes

34 bytes code + 1 for -n.

Requires the input lines be padded with spaces. 13 (!) bytes saved thanks to @Dada.

print/T/?reverse<>:map~~reverse,<>


### Usage

perl -ne 'print/T/?reverse<>:map~~reverse,<>' <<< 'False
o /
--|/
|
/ \ '

/ o
/|--
|
\ /

perl -ne 'print/T/?reverse<>:map~~reverse,<>' <<< 'True
o /
--|/
|
/ \ '
/ \
|
--|/
o /

• perl -ne 'print/T/?reverse<>:map~~reverse,<>' should save you 13 bytes :-) – Dada Jan 12 '17 at 23:49
• @Dada that is indeed a big saving! No idea why I wouldn't have done that but I'll update, thanks! – Dom Hastings Jan 13 '17 at 8:24

## Mathematica, 70 bytes

If[#,Reverse,StringReverse]@ImportString[#2,l="Lines"]~ExportString~l&


Anonymous function, takes a boolean value as first argument (explicitly True or False in Mathematica) and the (multiline) string as the second argument. Imports the string as a list of strings corresponding to the lines of the multiline string (the string is NOT passed to the function as an array). If True, reverse the list. If False StringReverse the list, which automatically is applied to each element in turn. Then export the list as a string, where each element is a new line.

# JavaScript (ES6), 76

s=>b=>(s=s.split
,b?s.reverse():s.map(r=>[...r].reverse().join)).join



F=s=>b=>(s=s.split
,b?s.reverse():s.map(r=>[...r].reverse().join)).join

function test()
{
var rows=I.value, r

// Trim trailing newlines, pad to blank
rows=rows.split('\n')
while(!(r=rows.pop()));
rows.push(r)
var maxlen=Math.max(...rows.map(r=>r.length))
rows=rows.map(r=>r+' '.repeat(maxlen-r.length)).join\n

var t1=F(rows)(false)
var t2=F(rows)(true)

O.textContent = 'False\n'+t1+'\n\nTrue\n'+t2
}

test()
#I { width:50%; height:10em }
<textarea id=I>
o /
--|/
|
/ \
</textarea>
<button onclick=test()>Go</button>
<pre id=O></pre>

# 05AB1E, 10 bytes

U|XiRë€R}»


# Explanation

U          Remove the first input line and store it in variable X
|         Aggregate the rest of the input into an array
XiR      If x is true, revert the array
ë€R   Else revert each element
}  End if
» Join everything with newlines and implicitly display


Try it online!

# Vim, 33 bytes

Changed previous V answer to Vim. Any V answer would be way different, so it wasn't really fair.

DgJ:if@"
g/^/m0
el
se ri
en
cG"


Try it online!

Hexdump

00000000: 4467 4a3a 6966 4022 0a67 2f5e 2f6d 300a  DgJ:if@".g/^/m0.
00000010: 656c 0a73 6520 7269 0a65 6e0a 6347 1222  el.se ri.en.cG."
00000020: 08                                       .
• You could probably save a bunch of bytes with this mapping – James Jan 13 '17 at 20:44