ノノグラムパズルを作成する


24

お絵かきロジックはこのような何か(ゲームのスクリーンショットに見える2次元のロジックパズルですPixelo、私のお気に入りのお絵かきロジックゲーム):

空のノノグラムボード

ゲームの目的は、これらの数字がエンコードしている画像を把握することです。ルールは単純です。列または行の数字は、その列または行のどこか、多くのボックスが行で埋められることを意味します。たとえば、上の画像の一番下の行にはボックスを埋めてはならず、その上の行にはすべてのボックスを埋めておく必要があります。下から3番目の行には8つの塗りつぶされたボックスがあり、それらはすべて1列になります。

同じ列または行に2つ以上の数字がある場合は、塗りつぶされたボックスが複数の「実行」されており、それらの間に少なくとも1つのスペースがあり、それらの長さがあります。順序は保持されます。たとえば、上の画像の一番右の列には3つの塗りつぶされたボックスがあり、それらの下に少なくとも1つのスペースがあり、さらにもう1つの塗りつぶされたボックスがあります。

ほぼ完成した同じパズルを次に示します。

ほぼ完成したノノグラムボード

(Xは重要ではなく、プレイヤーが「このマスは間違いなく塗りつぶされていません」と言うためのヒントです。マインスイーパでフラグを考えてください。ルールの意味はありません。)

たとえば、「2 2」というヒントのある中央の列には、2つの長さの塗りつぶされたボックスが2つあることがわかります。

あなたがそれを受け入れることを選択した場合、あなたの使命は、このようなパズルを作成するプログラムまたは機能を書くことです。ボードのサイズは、stdinの単一の整数(5 <= n <= 50)または引数として与えられます(ノノグラムパズルを正方形にする必要はありませんが、この課題ではそうなります)。その後、画像内の塗りつぶされた正方形と塗りつぶされていない正方形をそれぞれ表す一連の1と0が与えられます。最初のnは上の行、次の行などです。2* 1セルのボードを標準出力に戻すか、印刷します(見栄えがよく、列に2桁のヒントを表示できるためです) )、それらはすべて空で、入力データに対応するヒントがあります。

出力フォーマット

出力フォーマット

サンプル

入力:

./nonogram <<< '5 0 1 1 1 0 1 1 0 1 1 1 0 1 0 1 1 1 0 1 1 0 1 1 1 0'
                                 OR
      n(5,[0,1,1,1,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,0,1,1,1,0])

画像:

最初のサンプル画像

出力:

           1
         2 1 2
       3 2 1 2 3
     +----------
    3|
  2 2|
1 1 1|
  2 2|
    3|

入力:

./nonogram <<< '15 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 1 0 1 0 0 1 0 0 0 1 1 1 1 1 0 1 0 1 1 1 1 0 0 0 1 1 1 1 1 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1'

画像:

2番目のサンプル画像

出力:

                   1                       1
                 1 1 3       3 5   5 3   3 1
                 7 2 3 2 4 2 3 210 2 3 0 4 215
               +------------------------------
              2|
              1|
              1|
              1|
              1|
            1 1|
        3 3 1 1|
        1 5 1 1|
          3 5 3|
          1 5 1|
          1 3 1|
      1 1 1 1 1|
1 1 1 1 1 1 1 1|
           11 3|
           11 3|

明確化

  • 出力は、解けるパズルである必要はありません。すべての非グラムが解けるわけではありませんが、それはあなたの関心事ではありません。良いパズルを作るかどうかに関係なく、入力に対応するヒントを出力するだけです。
  • コマンドラインで引数を取るプログラムは許可されます。これは上記のようなものですが、間違った考えを得る可能性があります。それが明確化の目的です。
  • 0塗りつぶされたボックスがない行または列の印刷は必須です。私はどこでも言葉でこれを言いませんが、それはサンプルデータにあります。

私のソリューションはこれでほぼ完了です。行または列に3桁のボックスがないと想定できますか?
激しい14年

2
@voidpigeonは:5<=n<=50仕様なので、任意の3桁の数字があることはできません
カイルKanos

この質問を投稿した後、私は自分で解決策に取り組み始めました。私は(あたりとしてはまだそれを投稿しません、このメタ答え)、しかし、あなたたちはのために努力するために何か持っているので、私は私のバイト数を投稿します:Pythonの2.7で404バイト
undergroundmonorail

最初の例の出力には-、必要以上のものが含まれていませんか?
ヴェンテロ14年

@Ventroあなたは正しいです!これを行うためのプログラムをどのように記述するかは知っていましたが、実際には今までそれをしませんでしたので、サンプル出力は手作業で行いました。おっとっと!(2番目のサンプル出力も台無しにしましたが、答えが出る前に修正しました。)
地下

回答:


9

GolfScript、128文字

~](:k/.{{1,%{,}%.!,+}%}:^~{' ':s*}%.{,}%$-1=:9{s*\+9~)>'|'n}+%\zip^.{,~}%$0=){.~[s]*@+>{s\+-2>}%}+%zip{9)s*\n}%\[9s*'+''--'k*n]\

入力は、スペースで区切られた数字としてSTDINで提供される必要があります。

ここで例をテストできます

コメント付きコード:

# Parse the input into an 2D array of digits. The width is saved to variable k
~](:k/

# Apply the code block ^ to a copy of this array
.
{                # begin on code block
  {              # for each line
   1,%           #   split at 0s (1, => [0]) (leading, trailing, multiple 0s are 
                 #   removed because of operator % instead of /)
   {,}%          #   calculate the length of each run of 1s                 
   .!,+          #   special case: only zeros, i.e. []
                 #   in this case the ! operator yiels 1, thus [0], else []
  }%             # end for
}:^              # end of code block
~                # apply

# Format row headers
{' ':s*}%        # join numbers with spaces
.{,}%$-1=:9      # calulate the length of the longest row header
                 # and save it to variable <9>
{                # for each row
  s*\+           #   prepend padding spaces
  9~)>           #   and cut at length <9> from the right
  '|'n           #   append '|' and newline
}+%              # end for

# Format column headers
\zip^            # transpose input array and apply the code block ^
                 # i.e. calculate length of runs
.{,~}%$0=)       # determine (negative) length of the longest column header
{                # for each column
  .~[s]*@+       #   prepend enough spaces
  >              #   and cut at common length (from right)
  {s\+-2>}%      #   format each number/empty to 2 chars width
}+%              # end for
zip              # transpose column header into output lines
{9)s*\n}%        # prepend spaces to each line and append newline

# Inject separator line
\[
9s*              # spaces
'+'              # a plus sign
'--'k*           # k (width) number of '--'
n                # newline
]\

1
+1素敵な、私はこのポストからかなりの数の良いトリックを学んだ
クリスティアンLupascu

私はなんとか123文字までそれをゴルフすることができました:(~](:k/.zip\]{{1,%{,}%.!,+}%}/{' ':^*}%{.{,}%$-1=}:f~:r{^*\+r~)>'|'n}+%\f{.~)\[^]*@+>{^\+-2>}%}+%zip{r)^*\n}%r^*'+''--'k*n](何らかの理由で、lettercount.comはあなたがそれをコピーすると125文字だと言いますが、それは123文字です)。アルゴリズムの一部は変更されていますが、大部分は依然として同じです。また、いくつかの変数名を変更しました(変数として9を使用するのは賢明ですが、混乱を招くこともあります)が、必要に応じて元に戻すことができます。
ボラティリティ14年

7

ルビー、216 255

n=$*.shift.to_i;k=*$*.each_slice(n)
u=->k{k.map{|i|r=i.join.scan(/1+/).map{|i|"%2d"%i.size}
[*["  "]*n,*r[0]?r:" 0"][-n,n]}}
puts u[k.transpose].transpose.map{|i|" "*(n-~n)+i*""},"  "*n+?++"--"*n,u[k].map{|i|i*""+?|}

これは質問で与えられた正確なサンプル出力を生成しませんが、仕様に従います。例との唯一の違いは、いくつかの先頭のスペース/改行を印刷することです。

例:

$ ruby nonogram.rb 15 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 1 0 1 0 0 1 0 0 0 1 1 1 1 1 0 1 0 1 1 1 1 0 0 0 1 1 1 1 1 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1
# empty lines removed for brevity
                                  1                       1  
                                1 1 3       3 5   5 3   3 1  
                                7 2 3 2 4 2 3 210 2 3 0 4 215
                              +------------------------------
                             2|
                             1|
                             1|
                             1|
                             1|
                           1 1|
                       3 3 1 1|
                       1 5 1 1|
                         3 5 3|
                         1 5 1|
                         1 3 1|
                     1 1 1 1 1|
               1 1 1 1 1 1 1 1|
                          11 3|
                          11 3|

変更ログ:

  • 240-> 231:標準入力の代わりにコマンドライン引数を使用するように入力形式を変更しました。
  • 231-> 230:値チェックをからchunkに移動してスペースを削除しましたmap
  • 230-> 226:[nil]を呼び出す代わりに減算しArray#compactます。
  • 226-> 216:ヒント生成を簡素化します。

あなたはいくつかの余分な改行とスペースを印刷しますが、これまでの私のテストのすべてで、それらは「0以上」の仕様に適合しているので、あなたは大丈夫です。ただし、モニターの左側に空中に数字が浮かんでいるのを見始めたら、この答えを失格にする必要があります:)
地下

1
@undergroundmonorail:出力をするようなAの方法で印刷されてlength(leading spaces + numbers to the left) == 2*nheight(leading newlines + numbers at the top) == n...そう限り、お使いのモニタが大きいため十分であるよう3*n+1 × 2*n+2な文字、あなたは私を失格する必要はありません。:)
ヴェンテロ14年

4

ルビー、434

n=$*[i=0].to_i
a,b=[],[]
a.push $*.slice!(1..n)*""while $*.size>1
(b.push a.map{|c|c[i]}*"";i+=1)while i<n
a,b=*[a,b].map{|c|c.map{|d|e=d.split(/[0]+/).map(&:size).select{|f|f>i=0}.map &:to_s;(e.size>0)?e:[?0]}}
m,k=*[a,b].map{|c|c.map(&:size).max}
s="  "*m
k.times{$><<s+"  "+b.map{|c|(" "+((c.size==k-i)?(c.shift):(" ")))[-2..-1]}*"";i+=1;puts}
puts s+" "+?++?-*n*2
a.each{|c|puts"  "*(m-c.size)+" "+c.map{|d|(" "+d)[-2..-1]}*""+?|}

これをどのように実行しますか?試しましたruby $yourprogram <<< $inputが、得ましたruby_nanograms:7:in '<main>': undefined method '+' for nil:NilClass (NoMethodError)
地下

@undergroundmonorail ruby nonogram.rb 2 1 0 0 12x2
激しい14年

これは良い答えですが0、2番目の例の最後から4番目の列には印刷しません。
地下

+------...行も1つのスペースがインデントされていることに気付きました。
地下モノレール

1
@undergroundmonorail両方を修正しました。
激しい14年

4

GolfScript 149 147

コード

~](:s/.zip{{[0]%{,`}%['0']or}%.{,}%$)\;:¶;{.,¶\-[' ']*\+}%}:f~¶:v;\[f~]\zip{{{.,2\-' '*\+}%''*}:d2*)' '*:z\+{puts}:o~}%z(;'+'s'-'2**++o~{d'|'+o}/

編集:

  • 無駄なスペースを削除
  • もう1つのchar putsを保存するための再利用可能なone-char関数を定義しました

オンラインデモ

コードのやや注釈付きのバージョン

# split lines
~](:s/

# make transposed copy
.zip

#prepare numbers to show in the header
{{[0]%{,`}%['0']or}%.{,}%$)\;:¶;{.,¶\-[' ']*\+}%}:f~¶:v;

# prepare numbers to show in the left column
\[f~]\zip

#print header (vertical hints)
{  {{.,2\-' '*\+}%''*}:d~  2*)' '*:z\+puts}%

#print first line
z(;'+'s'-'2**++puts

#print horizontal hints
~{d'|'+ puts}/

4

ジャバスクリプト(E6)314 334 357 410

N=(d,l)=>{J=a=>a.join(''),M=s=>(s.match(/1+/g)||['']).map(x=>x.length),f=' '.repeat(d+1),c=[n='\n'],o=n+f+'+'+'--'.repeat(d);for(i=-1;++i<d;)c[i]=M(J(l.map((e,p)=>p%d-i?'':e))),o+=n+(f+J(M(J(l).substr(i*d,d)).map(P=n=>n>9?n:n<10?' '+n:'  '))+'|').slice(-d-2);for(;--i;)o=n+f+' '+J(c.map(e=>P(e.pop())))+o;return o}

非ゴルフ

N=(d,l)=> {
  J = a => a.join(''),
  M = s => (s.match(/1+/g)||['']).map(x=>x.length),
  f=' '.repeat(d+1), c=[n='\n'], o=n+f+'+'+'--'.repeat(d);
  for(i = -1; ++i < d;)
    c[i] = M(J(l.map((e,p)=>p%d-i?'':e))),
    o += n+(f+J(M(J(l).substr(i*d,d)).map(P=n=>n>9?n:n<10?' '+n:'  '))+'|').slice(-d-2);
  for(;--i;)
    o=n+f+' '+J(c.map(e=>P(e.pop())))+o;
  return o
}

使用法

N(5,[0,1,1,1,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,0,1,1,1,0])

N(15,[0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,0,0,1,0,1,0,0,1,0,0,0,1,1,1,1,1,0,1,0,1,1,1,1,0,0,0,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1,0,0,0,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,0,0,1,0,0,0,1,0,0,0,1,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1])

履歴を編集

1列の検索に使用される正規表現を削除し
ました。配列ではなく、文字列に出力します。ヘルパー関数FILL(F)
3を削除しました。さらに簡単です。これ以上はできません。それでもGolfscriptと比較することはできません:(


いいね 私もJavascriptバージョンを試しましたが、約500バイトで終了し、大きすぎてここに入れることができないと判断しました。オリジナルの変数名を使用して、未作成のバージョンを投稿するとよいでしょう(まだお持ちの場合)。また、これをどのように実行しますか?コピーしてChromeコンソールウィンドウに貼り付けると、「ReferenceError:Invalid left-hand side in assignment」が表示されます。実行する前に変更または追加するものはありますか?
ティグル

@tigrou申し訳ありませんが、 "=>" sintaxはfirefoxでのみ機能します。変数:c列のヒント、d次元、l入力のリスト、o出力、iループ変数、qおよびz temp
edc65 14年


@nderscoreはコードをいじって326を得ました。あなたのコードではRは初期化されていません(何度も何度も試してみると簡単な間違いです)
edc65 14年

1

R、384文字

a=scan();p=function(x)paste(x,collapse="");P=paste0;s=sapply;l=length;f=function(i)lapply(apply(matrix(a[-1],nr=a,b=T),i,rle),function(x)if(any(x$v)){x$l[!!x$v]}else{0});g=function(j,i)apply(s(j,function(x)sprintf("%2s",c(rep("",max(s(j,l))-l(x)),x))),i,p);c=P(g(f(1),2),"|");d=g(f(2),1);h=p(rep(" ",nchar(c[1])-1));e=P(h,"+",p(rep("-",nchar(d[1]))));d=P(h," ",d);cat(d,e,c,sep="\n")

インデントと説明付き:

a=scan() #Takes input

p=function(x)paste(x,collapse="") #Creates shortcuts
P=paste0
s=sapply
l=length

#This function finds the number of subsequent ones in a line (using rle = run length encoding).
#It takes 1 or 2 as argument (1 being row-wise, 2 column-wise
f=function(i)lapply(apply(matrix(a[-1],nr=a,b=T),i,rle),function(x)if(any(x$v)){x$l[!!x$v]}else{0})

#This function takes the result of the previous and format the strings correctly (depending if they are rows or columns)
g=function(j,i)apply(s(j,function(x)sprintf("%2s",c(rep("",max(s(j,l))-l(x)),x))),i,p)

c=paste0(g(f(1),2),"|") #Computes the rows
d=g(f(2),1) #Computes the columns
h=p(rep(" ",nchar(c[1])-1)) 
e=paste0(h,"+",p(rep("-",nchar(d[1])))) #Prepare vertical border
d=paste0(h," ",d) #Pad column indices with spaces
cat(d,e,c,sep="\n") #Prints

使用法:

> a=scan();p=function(x)paste(x,collapse="");P=paste0;s=sapply;l=length;f=function(i)lapply(apply(matrix(a[-1],nr=a,b=T),i,rle),function(x)if(any(x$v)){x$l[!!x$v]}else{0});g=function(j,i)apply(s(j,function(x)sprintf("%2s",c(rep("",max(s(j,l))-l(x)),x))),i,p);c=P(g(f(1),2),"|");d=g(f(2),1);h=p(rep(" ",nchar(c[1])-1));e=P(h,"+",p(rep("-",nchar(d[1]))));d=P(h," ",d);cat(d,e,c,sep="\n")
1: 15 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 1 0 1 0 0 1 0 0 0 1 1 1 1 1 0 1 0 1 1 1 1 0 0 0 1 1 1 1 1 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1
227: 
Read 226 items
                    1                       1  
                  1 1 3       3 5   5 3   3 1  
                  7 2 3 2 4 2 3 210 2 3 0 4 215
                +------------------------------
               2|
               1|
               1|
               1|
               1|
             1 1|
         3 3 1 1|
         1 5 1 1|
           3 5 3|
           1 5 1|
           1 3 1|
       1 1 1 1 1|
 1 1 1 1 1 1 1 1|
            11 3|
            11 3|

1

C-511

Cは、出力を適切にフォーマットするために作成されたものではありません。文字数には、必要なスペース/改行のみが含まれます。

入力は、スペースで区切られた数字のSTDINからです。

#define P printf
#define L(x) for(x=0;x<s/2+1;x++)
#define l(x) for(x=0;x<s;x++)
#define B(x,y) x[i][j]||y==s/2?P("%2d",x[i][j]):P("  ");
a[50][50],i,j,s,h[25][50],v[50][25],H[50],V[50],x[25],y[25];
main(){
    scanf("%d",&s);
    L(j)x[j]=y[j]=s/2+1;
    l(i)l(j)scanf("%d",&a[i][j]);
    for(i=s-1;i>=0;i--)
        for(j=s-1;j>=0;j--)
            a[i][j]?
                !H[j]&&(x[j]--,H[j]=1),
                h[x[j]][j]++,
                !V[i]&&(y[i]--,V[i]=1),
                v[i][y[i]]++:
            (H[j]=V[i]=0);
    L(i){
        L(j)P("  ");
        P(" ");
        l(j)B(h,i);
        P("\n");
    }
    L(i)P("  ");
    P("+");
    l(i)P("--");
    P("\n");
    l(i){
        L(j)B(v,j);
        P("|\n");
    }
}

1

それは数日であり、誰もPythonで答えていないので、ここに私の(おそらくかなり悪い)試みがあります:

Python 2.7- 404 397 380バイト

def p(n,m):
 k=str.join;l=[];g=lambda y:[['  ']*(max(map(len,y))-len(t))+t for t in[[' '*(a<10)+`a`for a in map(len,k("",c).split('0'))if a]or[' 0']for c in y]]
 while m:l+=[map(str,m[:n])];m=m[n:]
 x=g(l);j=k('\n',['  '*max(map(len,x))+'+'+k("",a)for a in zip(*[list(a)+['--']for a in g(zip(*l))])]);return j.replace('+',' ',j.count('+')-1)+'\n'+k('\n',[k("",a+['|'])for a in x])

すぐに未バージョンのバージョンを投稿しますが、現時点ではかなり読みやすいと思います。:)

編集:未ゴルフバージョンを書いている間、私はそれがかなり重要になるように追加できるいくつかの改善に気づきました!説明できない何らかの理由で、上部に改行が追加され、左側にスペースが追加されました(機能的な変更はないと思いますが)が、まだ仕様を満たしています。非ゴルフバージョンが来ています!

ゴルフをしていない:

def nonogram(board_size, pixels):
    def hints(board):
        output = []
        for row in board:
            # Convert the row to a string of 1s and 0s, then get a list of strings
            # that came between two 0s.
            s = "".join(row).split('0')

            # A list of the length of each string in that list.
            l = map(len, s)

            # We now have our horizontal hints for the board, except that anywhere
            # there were two 0s consecutively we have a useless 0.
            # We can get rid of the 0s easily, but if there were no 1s in the row at
            # all we want exactly one 0.
            # Solution:
            output.append([h for h in l if h != 0] or [0])
            # In this context, `foo or bar` means `foo if foo is a truthy value, bar
            # otherwise`.
            # An empty list is falsey, so if we strip out all the strings we hardcode
            # the 0.
        return output

    def num_format(hints):
        # For both horizontal and vertical hints, we want a space before single-
        # digit numbers and no space otherwise. Convert hints to strings and add
        # spaces as necessary.
        output = []

        for row in hints:
            output.append([' '*(a < 10) + str(a) for a in row])
            # Multiplying a string by n repeats it n times, e.g. 'abc'*3=='abcabcabc'
            # The only numbers that need a space are the ones less than 10.
            # ' '*(a < 10) first evaluates a < 10 to get a True or False value.
            # Python automatically converts True to 1 and False to 0.
            # So, if a is a one digit number, we do `' '*(1) + str(a)`.
            # If it's a two digit number, we do `' '*(0) + str(a)`.
        return output

    def padding(hints):
        output = []
        longest = max(map(len, hints)) # how long is the longest row?
        for row in hints:
            output.append(['  ']*(longest - len(row)) + row)
            # Add '  ' to the beginning of every row until it's the same length
            # as the longest one. Because all hints are two characters wide, this
            # ensures all rows of hints are the same length.
        return output

    board = []

    while pixels: # non-empty list == True
        # Make a list of the first (board_size) pixels converted to strings, then
        # add that list to board. Remove those pixels from the list of pixels.
        # When pixels is empty, board has a seperate list for each row.
        board.append([str(n) for n in pixels[:board_size]])
        pixels = pixels[board_size:]

    horizontal_hints = padding(num_format(hints(board)))

    vertical_hints = padding(num_format(hints(zip(*board))))
    # zip(*l) is a common way to transpose l.
    # zip([1,2,3], [4,5,6], [7,8,9]) == [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
    # the star operator unpacks an iterable so the contents can be used as
    # multiple arguments, so
    # zip(*[[1,2,3],[4,5,6],[7,8,9]]) is the same as what we just did.
    # Transposing the board and getting the horizontal hints gives us the
    # vertical hints of the original, but transposed. We'll transpose it back,
    # but we'll also add '--' to the end of all of them to make up the line
    vertical_hints = zip(*[a + ['--'] for a in vertical_hints])

    # add n spaces, where n is the length of the longest horizontal hint, plus
    # one space to the beginning of each line in the vertical hints, then join
    # with newlines to make it all one string.
    vertical_hints = '\n'.join(['  '*max(map(len, horizontal_hints)) + '+' +
                               ''.join(a) for a in vertical_hints])

    # find the number of plus signs in the string
    # replace the first (that many - 1) plus signs with spaces
    vertical_hints = vertical_hints.replace('+', ' ', vertical_hints.count('+')-1)

    # add a pipe to each row of horizontal hints, then join it with newlines
    horizontal_hints = '\n'.join([''.join(a + ['|']) for a in horizontal_hints])

    # add and return
    return vertical_hints + '\n' + horizontal_hints

読みやすさのためにいくつかの変更が行われました(g3つの名前付き関数に分割され、複雑なリストの内包表記がforループになりました)が、論理的にはまったく同じように機能します。

これが、ゴルフをしている人が余分なスペースと改行を印刷しないのに混乱している理由です。¯\ _(ツ)_ /¯


1
うーん、あなたの解決策が見つかりません。(申し訳ありませんが、文字数に関する恐ろしい冗談です。気にしないでください:))
ドアノブ

@dor Aha!今すぐHTTPエラーコードをジョークにしてみてください!:P
地下
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.