ABACABA都市を作成する


17

これが3番目のABACABA市です。

  _
A|_|
B|__|
A|_|_
C|___|
A|_|
B|__|
A|_|

ABACABAシーケンスから作成され、基本的には次のとおりです。

  • A(1回目の反復)
  • 場所B-AB
  • A-ABAを繰り返します(2回目の反復)
  • 場所C-ABAC
  • ABAの繰り返し-ABACABA(3回目の反復)

そしてあなたはアイデアを得る。

建物の高さ(下線の数で対応)は、A = 1、B = 2などの数字に変換された文字と同じです。

入力

繰り返し数1 <= n <= 26。

出力

行の先頭の文字を含む、順序nのABACABA市。


@DonMuesliハハはい。問題のハイパーリンクになります。

1
数値が26を超えた場合、何を出力する必要がありますか?
アドナン

はい、お願いします:D (簡単ではなかったでしょうか?)

1
有効な入力としてはカウントされません。

2
入力をゼロにすることはできますか?その場合、出力はどうなりますか?また、最初の、たとえば4つの入力と期待される出力をリストしても問題ありません。
ズガルブ

回答:


6

Python 2、82バイト

f=lambda n,s=1:n*"'"and"  _"*s+f(n-1,0)+"_"*(n-2)+"\n%c|%s|"%(64+n,"_"*n)+f(n-1,0)

私は誰もバイナリ再帰メソッドを投稿していないことに気付き、それを試してみることにしました...そして今Sherlock9から借りたトリックで、それは最短のPythonの答えです!(また、xnorにもう1つの短縮を感謝します。)(そして、一握りを剃ったデニス...)

ゴルフをしていない:

def f(n,s=1):
    if n>0:
        strsofar = "  _" if s==1 else ""        #prepend overhang for top-level call
        strsofar += f(n-1,0)                    #build the city above the current line
        strsofar += "_"*(n-2)                   #add the overhang to reach the current tower
        strsofar += "\n%c|%s|" % (64+n, "_"*n)  #write the current (center) line
        strsofar += f(n-1,0)                    #build the city below the current line
        return strsofar
    else: 
        return ""                               #only this line will be executed when n==0 (base case)

print "  _"+f(input())

私はこれを理解していると思うし、それはかなり賢い。私はこの素晴らしい再帰を完全に逃していました。を保存するのsではなく、両側に連結し、2行目をanon関数にすることにより、いくつかの文字を保存できますf=lambda n:n*"?"and f(n-1)+"_"*(n-2)+"\n%c|%s|"%(64+n,"_"*n)+f(n-1);lambda n:" _"+f(n)
。– xnor

次のことを考えていた
...-quintopia

@quintopia f=lambda n,s=1:n*"_"and" _"*s+f(n-1,0)+"_"*(n-2)+"\n%c|%s|"%(64+n,"_"*n)+f(n-1,0)は動作するはずです。
デニス

@Dennis iは、Pythで上記のソリューションを実装することをお勧めします。私はそれが59バイトよりも短いかもしれないと思う...私はそれをやるだろうが、この時点で、それは私の半分だけです
...-quintopia

1
プログラムとして81バイト、関数と同じ長さ
xnor

3

Python 2、99バイト

b=1;i=2**input('  _\n')-1
while i:i-=1;a=len(bin(i&-i))-2;print'%c|%s|'%(64+b,'_'*b)+'_'*(a+~b);b=a

iABACABAシーケンスのth番号を見つけるにはi、バイナリで書き込み、末尾のゼロの数をカウントし、1を追加します。古典的なビットトリックを使用してi&-i2その除算の最大の力を見つけ、iビット長を計算します。実際、iから2**n-1までカウントダウンしますが0、これはABACABAシーケンスが対称であるため問題ありません。

「前の」変数を使用して、シーケンスの現在の番号と最後の番号の両方を追跡しますb。これにより、「オーバーハング」として印刷するアンダースコアの数がわかります。最終的な建物は、0ビット長があるものとして扱われるため、オーバーハングすることなく正しく描画され1ます。

を使用して最初の行を印刷するトリックと同様に、印刷の文字列形式はSp3000から取得されinputます。


3

MATL、59バイト

vi:"t@wv]!-1hPXJtPvX>"'|'@Z"63+h6MJ2+X@)(]XhcJ64+!wh!32H:(!   

これは、言語の現在のリリース(15.0.0)を使用します。

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


(文字を出力に含める必要がなかった場合、次のように動作します、48バイト):

vi:"t@wv]!-1hPXJtPvX>"' |'X@1=o)@Z"63+h6MJ2+X@)(

説明

v        % vertically concatenate the stack contents: gives an empty array
i:       % input number n. Generate [1,2,...,n]
"        % for each k in [1,2,...n]
  t      %   duplicate
  @      %   push k
  wv     %   swap, vertically concatenate
]        % end. Poduces the numeric ABACABA: [1 2 1 3 1 2 1]: ceiling heights
!        % transpose into a row
-1h      % append -1
PXJ      % reverse array. Copy into clipboard J
tP       % duplicate. Reverse again, so undo the reversing
v        % vertically concatenate reversed and non-reversed row arrays
X>       % max of each column. Gives array of wall heights: [1 2 2 3 3 2 2 1]
"        % for each value in that array
  '|'    %   push "floor" char
  @      %   push height
  Z"     %   create string with that many spaces
  63+    %   transform spaces into "wall" chars, '_'
  h      %   concatenate horizontally
  6M     %   push "floor" char '|' again, to be used as ceiling
  J      %   push array of ceiling heights
  2+X@)  %   index into that to get height of current building
  (      %   at that position, overwrite the string with '|'
]        % end
Xhc      % concatenate all strings into a 2D char array, padding with spaces
J        % push array of ceiling heights (numeric ABACABA sequence)
64+      % add 64 to transform into letters
!        % transpose into column array
wh       % swap, concatenate horizontally. This appends letters below the floor
!        % transpose
32H:(    % overwrite first two positions (in linear order) with spaces
!        % transpose back. Implicitly display

とてもいい答えですが、建物の前に文字を出力する必要もあります:p。
アドナン

解決しました。とにかくOPの説明を待っている
ルイスメンドー

1
実際にこれを尋ねましたが、コメントを削除しました。これは応答でした:p。
アドナン

非常にエレガントなソリューション。

2

CJam、37 35バイト

SS'_Lri{[H)'_*_2>N@H'A+'|@'|6$]+}fH

これは、@ quintopiaのanswerからの再帰アルゴリズムの反復実装です。

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

使い方

SS'_     e# Push two spaces and an underscore.
L        e# Push "".
ri       e# Read an integer I from STDIN.
{        e# For each H in [0 ... I-1]:
  [      e#   Set an array marker.
    H)   e#     Push Push H+1.
    '_*  e#     Push a string of that many underscores.
    _2>  e#   Push a copy and remove the first two underscores.
    N    e#   Push a linefeed.
    @    e#   Rotate the longer string of underscores on top of it.
    h'A+ e#   Add H to the character 'A', pushing the corresponding letter.
    '|  e#    Push a vertical bar.
    @   e#    Rotate the string of underscores on top of it.
    '|  e#    Push another vertical bar.
    6$  e#    Push a copy of the previous iteration (initially "").
  ]     e#   Wrap everything up to the former marker in an array.
}fH     e#

1

JavaScript(ES6)、162バイト

n=>(a=[...Array(1<<n)]).map((_,i)=>i?(a[i]=String.fromCharCode(64+(n=1+Math.log2(i&-i)))+`|${"_".repeat(n)}|`,a[i-1]+='_'.repeat(--n&&--n)):a[i]='  _')&&a.join`\n`

\nリテラルの改行文字はどこですか。


\n誰かが疑問に思っていた場合、最後にあります。
電卓

1

Python 2、123 121バイト

f=lambda n:n*[n]and f(n-1)+[n]+f(n-1)
L=f(input('  _\n'))
for i,j in zip(L,L[1:]+L):print'%c|%s|'%(64+i,'_'*i)+'_'*(j+~i)

ideoneリンク @xsotのおかげで2バイト)

f数値のリストとしてABACABAシーケンスを生成しf(3) = [1, 2, 1, 3, 1, 2, 1]ます。ABACABAシーケンスチャレンジと比較して入力が1オフセットされているため、で1 バイトゴルフすることができますf

最初の行は個別に印刷され、その後、現在の番号と次の番号を考慮した式を使用して他のすべての行が印刷されます。楽しみのために、最初の行はを使用して印刷されinput()ます。


あなたは置き換えることができ[0]L
xsot

@xsotああ、それはかなりうまくいく:)(xnorが答えを投稿するように!)
Sp3000

1

Pyth- 64 62バイト

おそらくもっとゴルフできるかもしれませんが、今のところは十分です。

Lsl.&Jhb_J"  _"Vtt^2Qpr@G=ZyN1p"|_"p*\_Zp\|W<=hZyhNp\_)d)"A|_|

ここで試してみてください!

説明:

            |Predefined vars: Q = evaluated input, G = lowercase alphabet
L           |Lambda definition. y(b) = return (following code)
   .&       |bitwise and
     Jhb    |J = b + 1, pass b + 1 to the bitwise and
        _J  |-J
  l         | base 2
 s          |̲c̲o̲n̲v̲e̲r̲t̲ ̲t̲o̲ ̲i̲n̲t̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲
          "  _"                              |print "  _" with a trailing newline
               Vtt^2Q                        |For N in 2^Q - 2
                     pr      1               |print in caps
                         =ZyN                |Z = y(N) remember the first lambda?
                       @G                    |G[Z], basically convert 1-26 to A-Z
                              p"|_"          |print "|_", no trailing newline
                                   p*\_Z     |print "_" Z times
                                        p\|  |̲p̲r̲i̲n̲t̲ ̲"̲|̲"̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲ ̲
                                           W<=hZyhN             |While ++Z<y(N+1)
                                                   p\_          |print "_"
                                                      )k        |end while,
                                                                |print newline
                                                        )"A|_|  |end for,
                                                                |print "A|_|"

0

Python 3.5-262 236 220バイト:

@CatsAreFluffyのおかげで-16バイト!私の機能全体がついに一行になりました!:)

from collections import*
def a(v):o=OrderedDict;j=[chr(i+97)for i in range(26)];d=o((j[i],('  '+'_'*(i+1)+'\n'+j[i]+'|'+'_'*(i+1)+'|'))for i in range(26));f=lambda w:'a'[w:]or f(w-1)+j[w]+f(w-1);[print(d[g])for g in f(v)]

それは少し長いかもしれません、そしてそれは建物の間に新しい行を印刷するかもしれませんが、それは必要なことをします。確認するために自分でテストすることができます。

編集:

私の以前のゴルフコードは、正しいパターンをまったく印刷しませんでした。しかし、今では上に示したものがそうであり、それは私の意見では良いことです。また、自分で実行して確認することもできます。

注:プログラムは、すべての「建物」の後ろにすべて小文字を印刷します。大丈夫だと思います。

説明付きのゴルフバージョン

from collections import*
def a(v):
    o=OrderedDict # Assign the OrderedSict function to "o"
    j=[chr(i+97)for i in range(26)] # Create a list with all 26 lowercase letters of the alphabet
    d=o((j[i],('  '+'_'*(i+1)+'\n'+j[i]+'|'+'_'*(i+1)+'|'))for i in range(26)) # Create a dict assigning each letter it's corresponding building with its corresponding length
    f=lambda w:'a'[w:]or f(w-1)+j[w]+f(w-1) # Return the ABACABA sequence based on the user input
    [print(d[g])for g in f(v)] # Print out the building according to the sequence returned by the above lambda function (thanks to @CatsAreFluffy for this method to print it! :) )

基本的には、コレクションモジュールの順序付き辞書関数を最初にインポートしてから、順序付き辞書を作成し、リスト「j」の各小文字を対応する建物に割り当て、対応する長さをアンダースコアで指定します。次に、f=lambda w:"a"[w:]or f(w-1)+j[w]+f(w-1)関数を使用してユーザーの入力に基づいてシーケンスを計算し、それによって返されたシーケンスに基づいて、それぞれの対応する文字が背後にある建物が印刷されます。


あなたは、インポートすることができますOrderedDictとしてoの代わりに?そして、変更oppしてitemまでjも動作します。
Rɪᴋᴇʀ

if(すべての入力は1≤v≤26)をドロップし、に変更range(26)してrange(v)、のreturn"\n".join(f(v))代わりに使用できますfor
電卓

-2bytes:使用from collections import*してo=OrderedDictの代わりにfrom collections import OrderedDict as o
CalculatorFeline

実際には、変化@CatsAreFluffy range(26)range(v)もたらしますIndex Error。また、実行return"\n".join(f(v))するとシーケンスのみが返されますが、建物自体は返されません。それ以外は、あなたのヒントはかなり良かったです。ありがとう!:)
R. Kap

まあ、私はPython 3.5(3.4.1を持っている)を持っていません。多分それはアップグレードする時です
CalculatorFeline

0

ルビー、129バイト

無名関数。複数行の文字列を返します。

->x{a=->n{n<1?[]:(b=a[n-1];b+[n]+b)}
r="  _
"
a[x].zip(a[x][1,9**x]<<0).map{|n,m|r+=(64+n).chr+"|#{?_*n}|#{?_*(m+~n)if m>n}
"}
r}

0

JavaScript(ES6)、143

バックティック内には、重要でカウントされる2つの改行があります。

n=>`  _
`+(r=n=>n?[...r(n-1),n,...r(n-1)]:[])(n).map((x,i,t,u=n=>'|'+'_'.repeat(n>0&&n))=>String.fromCharCode(x+64)+u(x)+u(t[i+1]-x-1)).join`
`

...または文字を小文字にできる場合は138。

n=>`  _
`+(r=n=>n?[...r(n-1),n,...r(n-1)]:[])(n).map((x,i,t,u=n=>'|'+'_'.repeat(n>0&&n))=>(x+9).toString(36)+u(x)+u(t[i+1]-x-1)).join`

少ないゴルフ

n=>{
  // recursive function for ABACABA returning an array of integers
  var r=n=>n?[...r(n-1),n,...r(n-1)]:[]
  // function to build "|__..."
  // if argument <=0 just returns the vertical bar
  var u=n=>'|'+'_'.repeat(n>0&&n)
  var t = r(n)
  t = t.map((x,i)=>
    // current building + extension to the len of next building if needed
    String.fromCharCode(x+64)+u(x)+u(t[i+1]-x-1)
  )
  return ' _\n' // the top line is fixed
    + t.join('\n')
}

テスト

solution=
n=>`  _
`+(r=n=>n?[...r(n-1),n,...r(n-1)]:[])(n).map((x,i,t,u=n=>'|'+'_'.repeat(n>0&&n))=>String.fromCharCode(x+64)+u(x)+u(t[i+1]-x-1)).join`
`

function update() {
  var n=+N.value
  if (n>=0 && n<=26) O.textContent=solution(n)
}

update()
#N { width: 2em }
N:<input id=N value=4 oninput='update()'><pre id=O></pre>


弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.