这里的目标是简单地扭转字符串,但
要扭转一圈:将大写字母保留在同一位置。
示例输入1:Hello, Midnightas
示例输出1:SathginDim ,olleh
示例输入2:示例.Q
输出2:q.
规则:
- 输出到STDOUT,从STDIN输入
- 获奖者将于7月13日GMT + 3 12:00(一周)被选出
- 输入只能由ASCII符号组成,这使不使用包含非ASCII字符的任何编码的程序更容易。
- 任何以大写字母结尾的标点符号都必须忽略。
这里的目标是简单地扭转字符串,但
要扭转一圈:将大写字母保留在同一位置。
示例输入1:Hello, Midnightas
示例输出1:SathginDim ,olleh
示例输入2:示例.Q
输出2:q.
规则:
Answers:
lambda s:''.join((z*2).title()[c.isupper()-1]for c,z in zip(s,s[::-1]))
Ruud的-3个字节,再加上另外2个元素的灵感。
FryAmTheEggman的-4个更多字节
lambda s:''.join([z.lower(),z.upper()][c.isupper()]for c,z in zip(s,s[::-1]))
是短三个字节
(z*2).title()[c.isupper()-1]
应该管用。
~c.isupper()
而不是c.isupper()-1
由于规则指定输入为ascii:
lambda s:''.join([z.lower,z.upper]['@'<c<'[']()for c,z in zip(s,s[::-1]))
虽然所有功劳归功于@Mego,但我不敢仅仅评论他的回答。
-lp
)= 33字节此解决方案来自@Ton Hospel(比我的短13个字节)。
s%.%(lc$>$&?u:l)."c chop"%eeg
但是,你需要l
和p
交换机上。运行它:
perl -lpe 's%.%(lc$>$&?u:l)."c chop"%eeg'
-a
拆分,我觉得我过去可以使用多次!我要记住这一点!我想你可以使用保存另一个字节map...,...
,而不是map{...}...
因为你$F
在开始,但!:)
perl -lpe 's%.%(lc$>$&?u:l)."c chop"%eeg
-a
-F
-a
(-n
被暗示)-F
,我前一阵子在perlrun上阅读了它,尝试了一下,但是没有用。但是我现在又尝试了一次,并且效果很好,所以我猜当时我做错了什么。谢谢。
_FQo@UhAl
_ - reversed(input)
F - for i in ^
o - o+=1
Q @ - input[^]
Uh - ^.is_upper()+1
Al - [len, str.lower, str.upper, ...][^](i)
- "".join(^)
Thanks to Emigna for saving a 3 bytes!
Probably gonna get beat by Jelly... Code:
Âuvy¹Nè.lil}?
Uses the CP-1252 encoding. Try it online!.
S.l_v¹lRNèyiu}?
is 1 byte shorter
Âuvy¹Nè.lilë}?
is 14. Just happy I can help you for once :)
Ruvy¹Nè.lil}?
actually. I didn't use the bifurcation and forgot to remove the else. So 13.
PktGtk<)Xk5M(
Pk % Implicit inpput. Flip, lowercase
t % Duplicate
Gtk< % Logical index of uppercase letters in the input string
) % Get letters at those positions in the flipped string
Xk % Make them uppercase
5M( % Assign them to the indicated positions. Implicit display
@lr:?z:1ac.
h@u.,@A@um~t?|h.
Main Predicate:
@lr Reverse the lowercase version of the Input
:?z Zip that reversed string with the Input
:1a Apply predicate 1 to each couple [char i of reverse, char i of Input]
c. Output is the concatenation of the result
Predicate 1:
h@u., Output is the uppercase version of the first char of Input
@A@um~t? The second char of Input is an uppercase letter
| Or
h. Output is the first char of Input
Golfed:
DECLARE @ varchar(99)='Hello, Midnightas'
,@o varchar(99)='',@i INT=0WHILE @i<LEN(@)SELECT
@i+=1,@o+=IIF(ascii(x)=ascii(lower(x)),lower(y),upper(y))FROM(SELECT
SUBSTRING(@,@i+1,1)x,SUBSTRING(@,len(@)-@i,1)y)z
PRINT @o
Ungolfed
DECLARE @ varchar(99)='Hello, Midnightas'
,@o varchar(99)=''
,@i INT=0
WHILE @i<LEN(@)
SELECT @i+=1,@o+=IIF(ascii(x)=ascii(lower(x)),lower(y),upper(y))
FROM
(SELECT SUBSTRING(@,@i+1,1)x,SUBSTRING(@,len(@)-@i,1)y)z
PRINT @o
;`úíuY"ùû"E£`M@ùRZ`i@ƒ`MΣ
Explanation:
;`úíuY"ùû"E£`M@ùRZ`i@ƒ`MΣ
; create a copy of the input
`úíuY"ùû"E£`M for each character in input:
úíuY 0-based index in lowercase English letters, or -1 if not found, increment, boolean negate (1 if uppercase else 0)
"ùû"E£ `û` if the character is lowercase else `ù` (str.lower vs str.upper)
@ùRZ make the other copy of the input lowercase, reverse it, and zip it with the map result
`i@ƒ`M for each (string, function) pair:
i@ƒ flatten, swap, apply (apply the function to the string)
Σ concatenate the strings
The most straightforward way I could think of.
import Data.Char
f a|isUpper a=toUpper|1>0=toLower
zipWith f<*>reverse
(#)
, k
can be rewritten in point-free style: k=reverse>>=zipWith(#)
, that saves a couple bytes :)
b
as f a|isUpper a=toUpper|1>0=toLower
, though this conflicts with Flonk's improvement.
f
and rewrite Flonk's k
to zipWith f<*>reverse
.
s
?
k=
.
Thank you @TimmyD for saving me a whopping 47 bytes (I also saved an additional 6)
Thank you @TessellatingHeckler for saving an additional 13 bytes.
Latest:
param($a)-join($a[$a.length..0]|%{("$_".ToLower(),"$_".ToUpper())[$a[$i++]-in65..90]})
Original:
param($a);$x=0;(($a[-1..-$a.length])|%{$_=$_.tostring().tolower();if([regex]::matches($a,"[A-Z]").index-contains$x){$_.toupper()}else{$_};$x++})-join''
Normal formatting:
Latest (looks best as two lines in my opinion):
param($a)
-join($a[$a.length..0] | %{("$_".ToLower(), "$_".ToUpper())[$a[$i++] -in 65..90]})
Explanation:
param($a)-join($a[$a.length..0]|%{("$_".ToLower(),"$_".ToUpper())[$a[$i++]-in65..90]})
param($a)
# Sets the first passed parameter to variable $a
-join( )
# Converts a char array to a string
$a[$a.length..0]
# Reverses $a as a char array
|%{ }
# Shorthand pipe to foreach loop
("$_".ToLower(),"$_".ToUpper())
# Creates an array of the looped char in lower and upper cases
[$a[$i++]-in65..90]
# Resolves to 1 if the current index of $a is upper, which would output "$_".ToUpper() which is index 1 of the previous array
Original:
param($a)
$x = 0
(($a[-1..-$a.length]) | %{
$_ = $_.tostring().tolower()
if([regex]::matches($a,"[A-Z]").index -contains $x){
$_.toupper()
}else{
$_
}
$x++
}
) -join ''
First time poster here, was motivated because I rarely see PowerShell, but at Any suggestions appreciated.154 152 bytes on this one... I can see why!
I have learned that I must completely change my way of thinking to golf in code and its fun!
.tostring()
with quotes, and by using ASCII integer manipulation rather than regex. Try the following, for 105 bytes -- param($a)-join($a[$a.length..0]|%{if(($x=$a[$i++])-le90-and$x-ge65){"$_".ToUpper()}else{"$_".ToLower()}})
.
param($a)-join($a[$a.length..0]|%{if(65..90-contains$a[$i++]){"$_".ToUpper()}else{"$_".ToLower()}})
X-inY
is shorter than Y-containsX
, and you can change your if
for the fake ternary operator to get 86 bytes - param($a)-join($a[$a.length..0]|%{("$_".ToLower(),"$_".ToUpper())[$a[$i++]-in65..90]})
⌽f¨⍨⊢≠f←819⌶
819⌶
is the case folding function
f←
because its name is long, we assign it to f
⊢≠f
Boolean where text differs from lower-cased text
f¨⍨
use that (1 means uppercase, 0 means lowercase) to fold each letter...
⌽
... of the reversed text
Handles non-ASCII according to the Unicode Consortium's rules.
(λ(s)(build-string(string-length s)(λ(n)((if(char-upper-case?(string-ref s n))char-upcase char-downcase)(list-ref(reverse(string->list s))n)))))
Racket is bad at this whole "golfing" thing.
Shrug As always, any help with shortening this would be much appreciated.
Μid?&γ._pXiS=pxHHpxγγ
Μid?&γ._pXiS=pxHHpxγγ
Μid (Μ)ap (i)nput with (d)is fucntion:
? =pxHH (H is current element) if H = lowercase(H)
&γ._pXiS and set γ to the uppercase entity in the reversed string
pxγ lowercase γ
γ else, return γ
(d)is function
... Sacrifice spelling for the sake of golf!
$_=get;put .flip.samecase($_)
s=>string.Concat(s.Reverse().Select((c,i)=>s[i]>96?char.ToLower(c):char.ToUpper(c)));
A C# lambda where the input and the output is a string. You can try it on .NetFiddle.
I am struggling to understand why I cant achieve to convert char.ToLower(c)
to c+32
. I hope to fix it!
12 bytes saved thanks to @PeterTaylor (c|32
to add 32 to the ascii value of c
and c&~32
to substract 32). The result would be 72 bytes (but can fail on non alpha char).
s=>string.Join("",s.Reverse().Select((c,i)=>(char)(s[i]>96?c|32:c&~32)));
c|32
instead of c+32
, but it won't work with non-alpha characters.
$s=$argv[1];$l=strrev($s);for($i=0;$i<strlen($s);++$i){echo(strtolower($s[$i])!==$s[$i]?strtoupper($l[$i]):strtolower($l[$i]));}
I may attempt to optimize this further but I'll just leave it as is for now.
It'd be three bytes g~G
if we didn't need to read from stdin or write to stdout, but oh well...
vim -es '+normal! g~G' '+%print|q!' /dev/stdin
To test this, run
echo "testString" | vim -es '+normal! g~G' '+%print|q!' /dev/stdin
This is my first submission on here, not sure if this kind of submission is acceptable.
:se ri<cr>C<C-r>"
but then you'll have to figure how to capitalize the right letters.
(s)=>{t=_.From(s);var cnt=t.Count();var caps=t.Select(x=>{return x.toUpperCase()===x&&x.toLowerCase()!==x}).ToArray(),i=-1;return t.AggregateRight((a,b)=>{i++;var c=caps[i];return c?a+b.toUpperCase():a+b.toLowerCase()},"");}
Disclaimer: Using a library I wrote to bring C#'s LINQ to Javascript
Why? Because it's fun to use the wrong tool to do things :P
Usage: Run sed -rf file
, enter text and press Ctrl + D (send EOF).
Golfed:
s/[A-Z]/\a\l&/g;s/^.*$/\f&\v/;:x;s/\f\a/\a\f/;s/\a\v/\v\a/;s/\f(.)(.*)(.)\v/\3\f\2\v\1/;tx;s/\f|\v//g;s/\a./\U&/g
Ungolfed:
s/[A-Z]/\a\l&/g #Prepend all upper-case letters with a
#BEL ASCII character and make them lowercase
s/^.*$/\f&\v/ #Wrap text between a from feed (\f) and a vertical tab (\v)
#These are used as markers
:x #Define a label named x
s/\f\a/\a\f/;s/\a\v/\v\a/ #Move BEL characters outside of the boundary, so they're not moved later
s/\f(.)(.*)(.)\v/\3\2\1/ #This part does the switching itself
#It grabs a character preceded by a form feed and another
#one followed by a vertical tab and swaps them, while keeping the text in-between
#and replaces the marker \f and \v
tx #Conditional jump (t) to label x
#Jumps to the label x if the last substitution (s command) was successful
s/\f|\v//g #Delete markers
s/\a(.)/\u\1/g #Make letters preceded by a BEL upper-case
void c(char[]s){int x=0,y=s.length-1;for(char t;x<y;s[x]=s(t,s[y]),s[y]=s(s[y],t),x++,y--)t=s[x];}char s(char a,char b){return(char)(64<a&a<91?96<b&b<123?b-32:b:64<b&b<91?b+32:b);}
Loads of bytes saved thanks to @LeakuNun's approach.
Ungolfed & test cases:
class Main{
void c(char[] s){
int x = 0,
y = s.length-1;
for(char t; x < y; s[x] = s(t, s[y]),
s[y] = s(s[y], t),
x++,
y--){
t = s[x];
}
}
char s(char a, char b){
return (char)(64 < a & a < 91
? 96 < b & b < 123
? b-32
: b
: 64 < b & b < 91
? b+32
: b);
}
public static void main(String[] a){
print("Hello, Midnightas");
print("TEST");
print("test");
print("Test");
print(".,..,,!@");
print("ABCDefgHijklMNOPqrsTuVWxyz");
print("AbCdEfGHIJKlmnop123");
}
static void print(String s){
char[] t = s.toCharArray();
c(t);
System.out.println(t);
}
}
Output:
SathginDim ,olleh
q.
TSET
tset
Tset
@!,,..,.
ZYXWvutSrqpoNMLKjihGfEDcba
321pOnMLKJIhgfedcba
char[]
.
String a="";
and changed o+=
to 0[i]=
to save bytes, but Java doesn't have a character .toUpperCase()
/ .toLowerCase()
method, and converting from char to String, use upper/lower method, and then back to char again would require (a lot) more bytes. But feel free to fork the linked ideone and come up with something to make char[]
work in less bytes.
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *a,*b,*c;
a=c=strdup(argv[1]);
b=&argv[1][strlen(a)-1];
for(;*a;a++,b--){
*a=(*a>='A'&&*a<='Z')?((*b>='a'&&*b<='z')?*b-32:*b):((*b>='A'&&*b<='Z')?*b+32:*b);
}
puts(c);
free(c);
return 0;
}