同じ場所で大文字化を維持しながら文字列を反転します


28

ここでの目標は、1つのひねりを加えて文字列を単純に逆にすること
です。同じ場所に大文字を保持します。

入力例1:Hello, Midnightas
出力例1:SathginDim ,olleh

入力例2:例の.Q
出力2:q.

ルール:

  • STDOUTへの出力、STDINからの入力
  • 優勝者は7月13日GMT + 3 12:00(1週間)に選出されます
  • 入力はASCIIシンボルのみで構成されている場合があり、非ASCII文字を含むエンコードを使用しないプログラムで簡単に使用できます。
  • 大文字があった位置で終わる句読点は無視する必要があります。

それはアウトプリントの有無にかかわらずですか?それは文字列の有無にかかわらずですか?

「大文字があった位置で終わる句読点は無視する必要があります。」、2番目の例はこの規則と矛盾していませんか?
— ステファノサンフィリッポ

句読点には大文字のバリエーションがないため、ルールと一致しています。

回答:


7

TCC-4バイト

<>ci

オンラインでお試しください!

説明:

     - output is implicit in TCC
<>   - reverse string
  c  - preserve capitalization
   i - get input

9
このtcc.lua課題は、課題が投稿される前のバージョンで機能しましたか?最近、他の3つの課題を解決するコマンドを追加したことを考えると、そうではなかったと思います。回答がチャレンジをポストデートする言語のバージョンを必要とする場合、ヘッダーで非競合としてラベル付けする必要があります。ラベルを追加するか、コードが以前のバージョンで機能したことを証明するときに、ダウン票を削除します。
— デニス

16

Python、71バイト

lambda s:''.join((z*2).title()[c.isupper()-1]for c,z in zip(s,s[::-1]))

オンラインで試す

Ruudから-3バイト、さらに2つのインスピレーション。

-4 FryAmTheEggmanからさらにバイト


lambda s:''.join([z.lower(),z.upper()][c.isupper()]for c,z in zip(s,s[::-1]))3バイト短い
— -Arfie

1
@Ruudありがとう!関数呼び出しをリスト選択の外に移動すると、さらに2つ節約できます!
— メゴ

2
(z*2).title()[c.isupper()-1]動作するはずです。
— -FryAmTheEggman

6
~c.isupper()代わりにc.isupper()-1
— -Lulhum

これは... stdoutに標準入力または出力から入力を取得しません
— ArtOfWarfare

13

Python 2、73バイト

ルールでは入力がasciiであると指定されているため、

lambda s:''.join([z.lower,z.upper]['@'<c<'[']()for c,z in zip(s,s[::-1]))

すべてのクレジットは@Megoに送られますが、彼の答えにコメントするだけの評判はありませんでした。


'@'と '['のASCII値を使用して2バイトを獲得できますか?
— aloisdgは、モニカを復活させる

残念ながら、私はord(c)を使用する必要があります。整数と文字列の比較はPythonでうまく対処できません
— Lulhum

ほぼ私が得たものですが、あなたは最初に+1
— でした-orlp

13

Perl、31 + 2(-lp)= 33バイト

このソリューションは、@ Ton Hospelからのものです(私の場合よりも13バイト短くなっています)。

s%.%(lc$&gt$&?u:l)."c chop"%eeg

しかし、あなたは必要にlなり、pスイッチを入れます。実行するには:

perl -lpe 's%.%(lc$&gt$&?u:l)."c chop"%eeg'

5
こんにちは、PPCGへようこそ!これは素晴らしい!
— -NoOneIsHere

本当にいいね!-a自動分割を使用したことがないので、過去に何度も使用できたと思います!覚えておく必要があります!私はあなたが使用して別のバイトを保存することができると思うmap...,...の代わりに、map{...}...あなたが持っていると$Fいえ開始時に!:)
— ドムヘイスティングス

短いコード(31 + 2バイト):perl -lpe 's%.%(lc$&gt$&?u:l)."c chop"%eeg
— Ton Hospel

-aによって暗示されていることに注意してください-F
— トンホスペル

@TonHospelうわー、ありがとうございました、よくやった、それはいくつかの非常に素晴らしいコードです!に暗示されている-a(そして-n)について-F、私は少し前にperlrunでそれを読み、試してみましたが、うまくいきませんでした。しかし、私は今それをもう一度試しましたが、うまく機能しているので、私はそのとき何か間違ったことをしたと推測しています。ありがとう。
— ダダ

9

Pyth、13 11 10 9バイト

思い出させてくれたV@FryAmTheEggmanと、もう1バイトの@LeakyNunに感謝します。

srV_Qm!/G

オンラインでお試しください! 今モバイルで、リンクを少し更新しています


srV_Qm!rId0は11ですが、そのマップを短くすることが可能だと思います
— ...-FryAmTheEggman

@FryAmTheEggmanを削除してd、バイトを保存しました。
— リーキー修道女

srV_Qm!/Gバイトを保存する必要があります
— Leaky Nun

8

Python、66バイト

f=lambda s,i=0:s[i:]and(s[~i]*2).title()[~('@'<s[i]<'[')]+f(s,i+1)

インデックスを再帰i的に処理s[~i]し、後ろから文字を取得s[i]し、前から文字を取得します。資本であることは、隣接する範囲にあるものとしてチェックされます@ABC...XYZ[。FryAmTheEggmanの功績によるもの(_*2).title()です。



5

JavaScript(ES6)、95 83バイト

s=>[...t=s.toLowerCase()].reverse().map((c,i)=>s[i]==t[i]?c:c.toUpperCase()).join``

編集:@ edc65のおかげで12バイトを大幅に節約しました。


s => r = [... l = s.toLowerCase()]。reverse()。map((c、i)=> s [i]!= l [i]?c.toUpperCase():c) .join`` -10
— edc65

@ edc65ありがとう!(注:r=は不要です。)
— ニール

5

パイク、11 10 9バイト

_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(^)

最初にエラーが表示され、次に正しい答えが表示されました。i.imgur.com/uTcH27F.png

これは常に発生するため、警告を無効にするをクリックして無効にすることができます。
— ブルー

なるほど。申し訳ありませんが、私はパイクが苦手です

私がそれを使用している唯一の男だからかもしれません
— ブルー

4

05AB1E、19 16 15 13バイト

エミグナのおかげで3バイトを節約してにます!

おそらくゼリーに打たれるでしょう...コード:

Âuvy¹Nè.lil}?

CP-1252エンコードを使用します。オンラインでお試しください!。


S.l_v¹lRNèyiu}?1バイト短い
— エミグナ

@Emignaすごいありがとう!それはとても賢いです。
— アドナン

Âuvy¹Nè.lilë}?私は一度だけあなたを助けることができてうれしいです:)
— エミグナ

@Emignaそれはすごい!分岐の非常に良い使用:)。
— アドナン

Ruvy¹Nè.lil}?実際に。私は分岐を使用せず、他を削除するのを忘れました。13.だから、
— Emigna


3

J、30バイト

(={"_1 toupper@]|.@,.])tolower

非ASCIIをサポートしていません


"toupper" "tolower"コードポイントを使用して短縮できませんか?
— リーキー修道女

@LeakyNunたぶん、確かに言うことはできません
— マイル

3

Brachylog、28バイト

@lr:?z:1ac.
h@u.,@A@um~t?|h.

説明

  • 主な述語:

    @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
    
  • 述語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
    

3

TSQL、175バイト

ゴルフ:

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

非ゴルフ

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

フィドル


入力をハードコーディングしますか?
— 猫

@catが唯一の方法です。SQLでは、STDINまたは入力コマンドはありません。あなたはstackoverflowのを見れば、それはすべての質問が解決されている方法です-あなたもcodegolfに私の他の回答を見ることができます
— t-clausen.dk

ああ、そうです、以前にSQLユーザーとこの会話をしたことは間違いなく覚えています(たぶん)。それは奇妙ですが、うまくいくはずです。
— 猫

1
@catこれまでこの会話はありませんでしたが、以前にバイトカウントを手伝ってくれました
— -t-clausen.dk

3

実際には、25バイト

;`úíuY"ùû"E£`M@ùRZ`i@ƒ`MΣ

オンラインでお試しください!

説明:

;`úí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

3

Haskell、83 80 75 71バイト

私が考えることができる最も簡単な方法。

import Data.Char
f a|isUpper a=toUpper|1>0=toLower
zipWith f<*>reverse

のパラメータを交換すると(#)、kポイントフリースタイルで書き換えることができます:k=reverse>>=zipWith(#)、それは数バイトを節約します:)
— フランク

The second line can be point-free in b as f a|isUpper a=toUpper|1>0=toLower, though this conflicts with Flonk's improvement.
— xnor

あなたはのXNORのバージョンを使用することができますfし、Flonkの書き換えkにしますzipWith f<*>reverse。
— nimi

パラメータを削除する必要はありませんsか?
— リン

はい。また、をカットすることもできますk=。
— xnor

3

PowerShellの、154、152、99, 86 bytes

なんと47バイト節約してくれてありがとう@TimmyD(さらに6バイトも節約した)

@TessellatingHecklerにさらに13バイトを保存していただきありがとうございます。

最新:

param($a)-join($a[$a.length..0]|%{("$_".ToLower(),"$_".ToUpper())[$a[$i++]-in65..90]})

元の:

param($a);$x=0;(($a[-1..-$a.length])|%{$_=$_.tostring().tolower();if([regex]::matches($a,"[A-Z]").index-contains$x){$_.toupper()}else{$_};$x++})-join''

通常のフォーマット:

最新(私の意見では2行として最適に見えます):

param($a)
-join($a[$a.length..0] | %{("$_".ToLower(), "$_".ToUpper())[$a[$i++] -in 65..90]})

説明:

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

元の:

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 154 152 bytes on this one... I can see why! Any suggestions appreciated.

I have learned that I must completely change my way of thinking to golf in code and its fun!


Hello, and welcome to PPCG! This is great!
— NoOneIsHere

Welcome to PPCG! Nice to see another PowerShell user around here. You can cut out quite a bit by replacing the .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()}}).
— AdmBorkBork

Brilliant! We can make that even shorter by using a range instead of -le and -ge: param($a)-join($a[$a.length..0]|%{if(65..90-contains$a[$i++]){"$_".ToUpper()}else{"$_".ToLower()}})
— ThePoShWolf

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]})
— TessellatingHeckler

Man, I feel like I've missed out on a lot of tricks having never code golfed before. Its almost like learning to code all over again!
— ThePoShWolf

2

Dyalog APL, 12 bytes

⌽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.



2

Racket, 146 bytes

(λ(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.



2

Jolf, 21 bytes

Try it here!

Μid?&γ._pXiS=pxHHpxγγ

Explanation

Μ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!
— Steven H.


2

C#, 86 85 bytes

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)));

1
It would be c|32 instead of c+32, but it won't work with non-alpha characters.
— Peter Taylor

@PeterTaylor It works great! Thank you!
— aloisdg says Reinstate Monica

1

PHP, 128 bytes

$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.


1

Octave, 51 50 bytes

@(s)merge(isupper(s),b=flip(toupper(s)),tolower(b))

@(s)merge(s>64&s<91,b=flip(toupper(s)),tolower(b))

1

VIM, 46 bytes

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.


Nice, I love golfing in vim! However, this program doesn't actually reverse the string, it just toggles the capitalization. You can reverse the string with :se ri<cr>C<C-r>" but then you'll have to figure how to capitalize the right letters.
— DJMcMayhem

@DrGreenEggsandIronMan Oh man I completely missed that! Back to the drawing board!
— DoYouEvenCodeBro

1

Javascript (using external library) (224 bytes)

(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

Image 1


Calling out the person who downvoted this without an explanation. Any reason for that?
— applejacks01

It's likely that they wanted you to count the library as well, although using an external library is fully within the boundaries of standard policy.
— Addison Crump

1
I'm not downvoter, but If you are using an external library, at least mention the name in your answer, and for an obscure library, please provide a link to the repository.
— n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

1

Sed, 113 + 1 = 114 bytes

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

1

Java 7, 221 217 180 bytes

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:

Try it here.

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

You can input and output char[].
— Leaky Nun

@LeakyNun Actually I (believe I) can't in less amount of bytes. It would allow the removal of 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.
— Kevin Cruijssen

1
180 bytes that can be golfed further (by not modifying it in place).
— Leaky Nun

0

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;
}

Input should be taken from stdin.
— Anmol Singh Jaggi

As this is code-golf please put in the number of bytes this program would cost.

I could reduce it significantly depending on the rules, but I can't find any rules.
— user56095
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.