In this challenge, you will be given a text block, and you need to perform reflection on the text.
Input:
- 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). - A boolean where
Trueindicates Y reflection andFalseindicates 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
This is a code-golf, so answer with the shortest answer in your favorite language!
25 Answers 25
C#, (削除) 168 (削除ここまで) (削除) 144 (削除ここまで) (削除) 141 (削除ここまで) 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())));
-
\$\begingroup\$ Scott Kaye left a comment that has since been removed that triggered me to try some new things and shave off 24 bytes. \$\endgroup\$user19547– user195472016年07月14日 20:35:40 +00:00Commented Jul 14, 2016 at 20:35
-
\$\begingroup\$ C#6 expression bodied function saves another 3 bytes \$\endgroup\$user19547– user195472016年07月14日 21:38:24 +00:00Commented Jul 14, 2016 at 21:38
Pyke, 7 bytes
!I_)ncX
!I ) - if not boolean:
_ - input = reversed(input)
nc - input.split("\n")
X - splat(input)
- (print lines backwards)
Brainfuck, (削除) 143 (削除ここまで) (削除) 140 (削除ここまで) 131 bytes
,[,[---------->+<[>-]>[->]<,]<[[<]>[++++++++++.>]++++++++++.<[<]<]],[---------->+<[++++++++++>-]>[-<<[.<]++++++++++.[>]>>]<,]<[.<]
Beat(削除) s (削除ここまで) 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
, read next input
]
< find end of line
[ loop thru lines
[<]> find start of line
[ loop thru line
++++++++++ add newline back
. 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
++++++++++ add newline back
> 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
, read next input
]
< 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
Haskell, (削除) 51 (削除ここまで) (削除) 49 (削除ここまで) 45 bytes
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.
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.
-
\$\begingroup\$ It doesn't work that way. Your program has to either take any truthy value, or take only
True, which could also be1. You cannot restrict input to be only0or2. \$\endgroup\$mbomb007– mbomb0072016年07月13日 18:41:43 +00:00Commented Jul 13, 2016 at 18:41 -
\$\begingroup\$ Yeah, I didn't think through my answer. @mbomb007 is correct here, it needs to work for any truthy/falsy value for your language. \$\endgroup\$Nathan Merrill– Nathan Merrill2016年07月13日 19:04:17 +00:00Commented Jul 13, 2016 at 19:04
-
\$\begingroup\$ @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. \$\endgroup\$FryAmTheEggman– FryAmTheEggman2016年07月13日 19:22:50 +00:00Commented Jul 13, 2016 at 19:22
-
\$\begingroup\$ 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). \$\endgroup\$R. Kap– R. Kap2016年07月13日 20:37:53 +00:00Commented Jul 13, 2016 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.
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>).
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')]))
Brachylog, (削除) 26 (削除ここまで) (削除) 24 (削除ここまで) 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
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
-
\$\begingroup\$ It really doesn't make sense that this doesn't work \$\endgroup\$Fatalize– Fatalize2016年07月13日 17:37:32 +00:00Commented Jul 13, 2016 at 17:37
-
1\$\begingroup\$ @Fatalize It's because of how MATL and MATLAB read the input. Each line is a different input \$\endgroup\$Luis Mendo– Luis Mendo2016年07月13日 17:42:08 +00:00Commented Jul 13, 2016 at 17:42
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.
Pyth, 10 bytes
j?Q_.z_M.z
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
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 /
-
1\$\begingroup\$
perl -ne 'print/T/?reverse<>:map~~reverse,<>'should save you 13 bytes :-) \$\endgroup\$Dada– Dada2017年01月12日 23:49:15 +00:00Commented Jan 12, 2017 at 23:49 -
\$\begingroup\$ @Dada that is indeed a big saving! No idea why I wouldn't have done that but I'll update, thanks! \$\endgroup\$Dom Hastings– Dom Hastings2017年01月13日 08:24:20 +00:00Commented Jan 13, 2017 at 8:24
APL (Dyalog Unicode), (削除) 9 (削除ここまで) (削除) 11 (削除ここまで) 9 bytes (SBCS)
Fixed answer (削除) but only had to add 2 bytes (削除ここまで) and kept it the same length thanks to @Adám
⌽[⎕]⎕FMT⎕
Takes a character vector using \r as a separator through STDIN first, then 1 or 0. Requires 0-indexing.
⎕ accepts input. ⎕FMT formats it into a character matrix because of \r. ⌽[⎕] reflects that over either the x- or y-axis, depending on the second input. With 0-indexing, ⌽[0] or just ⌽ reflects over the x-axis, ⌽[1] or ⊖ over the y-axis.
-
-
1\$\begingroup\$ Also, you have to set
⎕IO←0to abide by the truthy/falsey rule. \$\endgroup\$Adám– Adám2020年12月23日 15:19:02 +00:00Commented Dec 23, 2020 at 15:19 -
1\$\begingroup\$ Tends to be the case with older challenges. \$\endgroup\$Adám– Adám2020年12月23日 16:43:46 +00:00Commented Dec 23, 2020 at 16:43
-
1
-
1\$\begingroup\$
⍉is actually "reorder axes", by default (i.e monadically) into reverse order. \$\endgroup\$Adám– Adám2021年01月05日 20:35:37 +00:00Commented Jan 5, 2021 at 20:35
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
/|--
|
\ / "
-
\$\begingroup\$ I see a different output for
f(c,0)when I try - maybe yourcdoesn't have all the spaces in the right places. \$\endgroup\$Neil– Neil2016年07月13日 20:42:49 +00:00Commented Jul 13, 2016 at 20:42 -
\$\begingroup\$ Is the trailing white space after the first "o /" significant? \$\endgroup\$Peter Mortensen– Peter Mortensen2016年07月13日 22:40:42 +00:00Commented Jul 13, 2016 at 22:40
-
\$\begingroup\$ @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. \$\endgroup\$Charlie Wynn– Charlie Wynn2016年07月14日 17:30:56 +00:00Commented Jul 14, 2016 at 17:30
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;}
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
-
1\$\begingroup\$ 8 bytes (
U|Xto|ćand€Rtoí) Perhaps these builtins weren't available when you posted your answer, but they are still available in the legacy version of 05AB1E regardless. :) \$\endgroup\$Kevin Cruijssen– Kevin Cruijssen2020年09月15日 08:05:20 +00:00Commented Sep 15, 2020 at 8:05
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>
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"
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 .
-
\$\begingroup\$ You could probably save a bunch of bytes with this mapping \$\endgroup\$DJMcMayhem– DJMcMayhem2017年01月13日 20:44:56 +00:00Commented Jan 13, 2017 at 20:44
05AB1E, 8 bytes
|ćiRëí}»
|ćiRëí}» # full program
» # join...
| # list of lines in input...
ć # excluding the first element...
R # reversed...
i # if...
ć # first element of...
| # list of lines in input...
i # is truthy...
ë # else...
í # with each element in list reversed...
» # by newlines
} # end if statement
# implicit output
1and0) or we must useTrueandFalse? \$\endgroup\$\nI would go as far as to say that it's not a string representation. \$\endgroup\$