平方ランダム対称


18

チャレンジ

正方ランダム対称行列を返すまたは出力するプログラムまたは関数を作成します。


入力

N:行列のサイズ、すなわち6 x 6


出力

マトリックス。印刷して、文字列として(改行を使用して)返すか、リスト/配列のリスト/配列として返すことができます。


ルール

  1. 少なくともN異なる文字を使用する必要があります。ここNで、は正方行列のサイズです(入力)。文字[a、z] [A、Z]と数字[0、9](そして同時に1桁のみ)のみを使用しているので、あなたはそれN < 27とを仮定することができます。と数字。最後になりましたが、すべての文字/数字はゼロでない確率で発生する必要があります(均一な分布は必要ではありません)。ただし、結果には少なくとも異なる文字/数字が必要です。N > 2N <= 2N

  2. マトリックスは、水平および垂直の両方に対称である必要があります。

  3. 正確に2行2列には、厳密に1桁の1桁の数字を含める必要があります(その位置もランダムにする必要があります)。残りの行/列には文字のみが含まれます。文字を[a、z]および[A、Z]として、そしてもちろん1桁の数字を[0、9]として考えてください。

  4. 簡単にするために、大文字と小文字が区別されない限り、大文字と小文字は関係ないと想定できますa=A, b=B, etc

  5. 可能なすべての出力は、ゼロ以外の確率で発生する必要があります。ランダム分布は均一である必要はありません。


入力:8

出力

c r p s s p r c
r k o z z o k r
u t 2 a a 2 t u
y n q z z q n y
y n q z z q n y
u t 2 a a 2 t u
r k o z z o k r
c r p s s p r c

コメントは詳細なディスカッション用ではありません。この会話はチャットに移動さました
メゴ

回答:


4

、30バイト

NθE⊘⊕θ⭆⊘⊕θ‽βJ‽⊘θ‽⊘θI‽χ‖OO→↓﹪θ²

オンラインでお試しください!リンクは、コードの詳細バージョンです。nが常に偶数の場合、23バイトの場合:

NθE⊘θ⭆⊘θ‽βJ‽⊘θ‽⊘θI‽χ‖C¬

オンラインでお試しください!リンクは、コードの詳細バージョンです。説明:

Nθ

入力します。n

E⊘θ⭆⊘θ‽β

nを作成する bynn2ランダムな小文字の 2つの配列。これは暗黙的に正方形として印刷されます。n2

J‽⊘θ‽⊘θ

正方形内のランダムな位置にジャンプします。

I‽χ

ランダムな数字を印刷します。

‖C¬

マトリックスを完成させるために、水平および垂直に反射します。


14

R124の 118バイト

function(n,i=(n+1)/2,j=n%/%2,m="[<-"(matrix(-letters,i,i),j-1,j-1,0:9-1))cbind(y<-rbind(m,m[j:1,]),y[,j:1])
`-`=sample

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

Rでは、演算子のように見えるものは、パーサーから特別な扱いを受ける関数にすぎません。

演算子(など-)を他の関数に再定義すると、パーサーからの特別な扱いが維持されます。以来-プレフィックスと中置の両方で、私が呼び出す必要がsample1と2つの両方の引数を持つ関数を、私は使用することができます

`-`=sample

欲しいものを手に入れます。

したがって、コード-lettersはに変換されsample(letters)lettersビルトインがランダムにシャッフルされます。しかしj-1、に変換され、ベクターからアイテムsample(j,1)をランダムにサンプリングし1ます1:j

sampleパラメーターの数と最初のパラメーターが何であるかによる関数のこの動作は、実動コードでは非常に痛いので、ここでそのひねくれた性質をうまく利用できることを嬉しく思います!)

そうしないと、コードは、単に必要な結果の左上の象限は、ランダムな要素(置き換えになりj-1j-1ランダムな数字(とビット)0:9-1ビット)、および必要な対称性のためにそれを折ります。偶数と奇数の場合に対処するために必要とされています。ij


素晴らしい説明と関連するRゴルフのヒントの回答を編集するために+2ができたらいいのにと思います。さらに数バイト
JayCe

なんて素晴らしい解決策と説明でしょう!
-J.Doe

6

Python3、287バイト

ここでゴルフをするのは初めてです。誰かがもっとうまくできると確信しています:

import random as rn, math as m
n=int(input())
x,o=m.ceil(n/2),n%2
c=x-1-o
f=lambda l,n: l.extend((l[::-1], l[:-1][::-1])[o])
q=[rn.sample([chr(i) for i in range(97, 123)],x) for y in range(x)]
q[rn.randint(0,c)][rn.randint(0,c)] = rn.randint(0,9)
for r in q:
    f(r, n)
f(q, n)
print(q)

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

HyperNeurtrino、Ourous、Heiteriaのおかげで、これは193バイトに縮小されました(コメントを参照)。ただし、TFeldは、複数の呼び出しsampleが少なくともN異なる文字を保証するものではないことを正しく指摘しました。

それを念頭に置いて、N実行ごとに少なくとも異なる文字を保証するこの新しいバージョンを試してください。

python3、265の 260バイト、少なくともN異なる文字

from random import *
n=int(input())
x=-(-n//2)
o=n%2
c=x+~o
i=randint
u=[chr(j+97)for j in range(26)]
z,q=u[:],[]
for y in [1]*x:
  shuffle(z)
  q+=[z[:x]]
  z=z[x:] if len(z[x:])>=x else u[:]
q[i(0,c)][i(0,c)]=i(0,9)
for r in[q]+q:r.extend(r[~o::-1])
print(q)

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


1
PPCGへようこそ!いくつかの空白をゴルフアウトできます。記号と記号と文字の間にスペースを入れる必要はありません。a[:-1][::-1]はと基本的に同等a[:-2::-1]でありrandom、のr代わりにインポートrnでき、forループをインライン式に移動できます。オンラインでお試しください!
ハイパーニュートリノ

2
代わりに、基本的には負のfloor-div(事実上上限)mathを使用することにより、インポートを削除できます。tio.run/##XY7LagMxDEX3/...-(-a // 2)math.ceil(a / 2)
HyperNeutrino



1
複数sample()のsは、少なくともN異なる文字を取得することを保証しません。私はを取得することができ[['g', 'x', 'x', 'g'], [7, 'x', 'x', 7], [7, 'x', 'x', 7], ['g', 'x', 'x', 'g']]ましたN=4。これには3つの異なる文字しかありません
-TFeld

3

APL(Dyalog Classic)45 44 43 40バイト

@Adámに-1バイトありがとう

26{(⎕a,⍺⍴⎕d)[⌈∘⊖⍨⌈∘⌽⍨⍺+@(?⊂⌊⍵÷2)?⍵⍴⍺]},⍨

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

反射のあるマトリックスの(max)を使用して対称にするため、アルファベットの後半にバイアスがかけられます

桁は0 ... 25 mod 10から均一に選択されるため、値を小さくするための小さなバイアスがあります。


1
⌊2⍴⍵÷2)?⍵ ⍵⍴26]}⌊⍺⍵÷2)?⍺⍵⍴26]}⍨
アダム

@Adám賢い!
ngn

ええ、私はちょうど実現しました。
アダム

間違っていなければ、⌊⍺⍵÷2→ を変更できます⍺⍵
アダム

@Adám私はできません-Nが奇数の場合、数字は中央に来る可能性があり、それを含む行/列は1つしかありません
-ngn

3

Japt、31バイト(固定桁位置)

;
/2 c
VÆVÆBö}ÃgT0@Mq9îêUvÃêUv

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


Japt、41バイト(ランダムな桁位置)

;
/2 c
VÆVÆBö}ÃgMq´VÉ ,MqVÉ @Mq9îêUvÃêUv

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


説明

;                               Change to new vars
/2 c                            set implicit var V equal to implicit var U / 2 rounded up
VÆVÆBö}ÃgT0@Mq9îêUvÃêUv        Main function

VÆ                              Range from 0 to V and map
  VÆ                            Range from 0 to V and map
    Bö}Ã                        return random char from alphabet
        gT0@                    map upper-left corner
            Mq9Ã                return random number
                ®êUv            horizontal mirror
                    êUv         vertical mirror

現在、数字は常に同じ場所に挿入されます。課題に基づいて、数字の位置もランダムにする必要があります(ルール4により、奇数の入力の中央の行や列にない場合があります)。
ケビンクルーッセン

課題は数位置は、同様にランダムでなければならないと言うところ私は見てはいけない@KevinCruijssen、私は明確にかかわらのためのOPを頼むよ
ルイス・フェリペ・デ・ジーザス・ムニョス

1
ああ、あなたは本当に正しい。私はそれが他のすべての答えでランダムだと思ったので、それが必須であると誤って仮定したかもしれません。OPの内容が表示されます。私は実際にそれが私の準備の答えのためにその問題を解決するために非常に簡単にそれを作るだろう、それは許さ固定を願っ..;)
ケビンCruijssenに

2

Python 2、259バイト

from random import*
n=input();c=choice;r=range
w,W=n/2,-~n/2
o=n%2
A=map(chr,r(97,123))
l=[c(r(10))]+sample(A,n)+[c(A)for _ in' '*w*w]
l,e=l[:w*w],l[w*w:W*W]
shuffle(l)
l=[l[w*i:w*-~i]+e[i:i+1]for i in range(w)]+[e[-W:]]
for r in l+l[~o::-1]:print r+r[~o::-1]

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


intを直接使用できますか?ところで〜のクールなアイデア。私もそれを考えていましたが、まだ慣れていません。
Teck-freak

2

05AB1E29 40 38 バイト

A.rs;ò©n∍9ÝΩ®DnαLʒ®%Ā}<Ωǝ®ô»¹Éi.º.∊ëº∊

+11バイトはまだ奇数の入力に念頭に置いて規則3を維持しつつ、ランダム位置にある数字を修正する..
-2のおかげバイト@MagicOctopusUrn変化、îïòとの位置を変化させます»

オンライン試して、さらにいくつかのテストケース確認してください

古い(29 27バイト)答えは、常に角のどこに数字が位置するか:

A.rs;ò©n∍¦9ÝΩì®ô»¹Éi.º.∊ëº∊

オンラインそれを試してみてくださいまたはいくつかのより多くのテストケースを検証します

説明:

A           # Take the lowercase alphabet
 .r         # Randomly shuffle it
            #  i.e. "abcdefghijklmnopqrstuvwxyz" → "uovqxrcijfgyzlbpmhatnkwsed"
s           # Swap so the (implicit) input is at the top of the stack
 ;          # Halve the input
            #  i.e. 7 → 3.5
  ò         # Bankers rounding to the nearest integer
            #  i.e. 3.5 → 4
   ©        # And save this number in the register
    n       # Take its square
            #  i.e. 4 → 16
           # Shorten the shuffled alphabet to that length
            #  i.e. "uovqxrcijfgyzlbpmhatnkwsed" and 16 → "uovqxrcijfgyzlbp"
9ÝΩ         # Take a random digit in the range [0,9]
            #  i.e. 3
   ®Dnα     # Take the difference between the saved number and its square:
            #  i.e. 4 and 16 → 12
       L    # Create a list in the range [1,n]
            #  i.e. 12 → [1,2,3,4,5,6,7,8,9,10,11,12]
ʒ   }       # Filter this list by:
 ®%Ā        #  Remove any number that's divisible by the number we've saved
            #   i.e. [1,2,3,4,5,6,7,8,9,10,11,12] and 4 → [1,2,3,5,6,7,9,10,11]
     <      # Decrease each by 1 (to make it 0-indexed)
            #  i.e. [1,2,3,5,6,7,9,10,11] → [0,1,2,3,5,6,7,9,10]
      Ω     # Take a random item from this list
            #  i.e. [0,1,2,3,5,6,7,9,10] → 6
       ǝ    # Replace the character at this (0-indexed) position with the digit
            #  i.e. "uovqxrcijfgyzlbp" and 3 and 6 → "uovqxr3ijfgyzlbp"
®ô          # Split the string into parts of length equal to the number we've saved
            #  i.e. "uovqxr3ijfgyzlbp" and 4 → ["uovq","xr3i","jfgy","zlbp"]
  »         # Join them by new-lines (this is done implicitly in the legacy version)
            #  i.e. ["uovq","xr3i","jfgy","zlbp"] → "uovq\nxr3i\njfgy\nzlbp"
   ¹Éi      # If the input is odd:
            #  i.e. 7 → 1 (truthy)
          # Intersect mirror the individual items
            #  i.e. "uovq\nxr3i\njfgy\nzlbp"
            #   → "uovqvou\nxr3i3rx\njfgygfj\nzlbpblz"
        .∊  # And intersect vertically mirror the whole thing
            #  i.e. "uovqvou\nxr3i3rx\njfgygfj\nzlbpblz"
            #   → "uovqvou\nxr3i3rx\njfgygfj\nzlbpblz\njfgygfj\nxr3i3rx\nuovqvou"
  ë         # Else (input was even):
   º∊       #  Do the same, but with non-intersecting mirrors

従来のバージョンでは必要ないので、2バイトを節約することもできます»
Emigna

@EmignaはOPで検証済みであり、実際には位置もランダムでなければなりません。入力が奇数のルール3により+11バイトが修正されました。>。>また、ï暗黙的に行われたため、レガシーで3バイトを保存できました。残念ながら、置換の代わりに挿入するため、これは40バイトバージョンには適用されません。
ケビンクルーッセン

@MagicOctopusUrnリンクしたTIOには28バイトではなく29バイトの回答が含まれていましたが、正しいリンクはありますか?の失敗について2は、入力がであることが保証されています3 <= N <= 26
ケビンクルーッセン

1
@KevinCruijssenあなたは正しい、私はバカだ、ここに私が働いていたものがあります
魔法のタコ

@MagicOctopusUrnああ、その銀行家たちが丸めていることを知りませんでした。それは私の現在の答えにもバイトを節約します!:Dそして、最初にランダムな数字を追加してからシャッフルすることも非常に賢明なアプローチです。ただし、nアルファベットのnランダムな文字ではなく、常にアルファベットの最初の文字があるため、100%有効かどうかはわかりません。そして、最初に改行で結合してからミラーを実行するだけで、バイトを節約できます。-2バイトをありがとう!:) PS:末尾のを削除すると、28バイトで1バイトを保存できます}。:)
ケビンクルーイセン

2

C(gcc) 198 197 196バイト

ceilingcatのおかげで2バイト節約されました。

#define A(x)(x<n/2?x:n-1-x)
#define R rand()
S(n,x,y){int s[x=n*n];for(srand(s),y=R;x;)s[x]=97+(--x*31+y)%71%26;y=n/2;for(s[R%y+n*(R%y)]=48+R%10;x<n*n;++x%n||puts(""))putchar(s[A(x%n)+A(x/n)*n]);}

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

説明:

// Coordinate conversion for symmetry
#define A (x) (x < n / 2 ? x : n - 1 - x)
// Get a random and seed
#define R rand()

S (n, x, y)
{
   // the array to store matrix values (x is the array size)
   // Note that we do not need the whole array, only its first quarter
   int s[x = n * n];

   // iterate n*n-1 times until x is zero
   for (srand(s), y = R; x;)
       // and fill the array with pseudo-random sequence of letters
       s[x] = 97 + (--x * 31 + y) % 71 % 26;

   // this is the max. coordinate of the matrix element where a digit may occur
   y = n / 2;

   // drop a random digit there
   s[R % y + n * (R % y)] = 48 + R % 10;

   // Now we output the result. Note that x is zero here
   for (; 
       x < n * n; // iterate n*n times
       ++x % n || puts ("") // on each step increase x and output newline if needed
       )
       // output the character from the array
       putchar (s[A (x % n) + A (x / n) * n]);
}

1

JavaScript(ES6)、 213の 209 206バイト

n=>(a=[],F=(x=y=d=c=0,R=k=>Math.random()*k|0,g=y=>(r=a[y]=a[y]||[])[x]=r[n+~x]=v.toString(36))=>y<n/2?F(g(y,R[v=R(m=~-n/2)<!d&x<m&y<m?R(d=10):R(26)+10]=R[v]||++c,g(n+~y))&&++x<n/2?x:+!++y,R):!d|c<n?F():a)()

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

コメント済み

n => (                             // n = input
  a = [],                          // a[][] = output matrix
  F = (                            // F = main recursive function taking:
    x = y =                        //   (x, y) = current coordinates
    d = c = 0,                     //   d = digit flag; c = distinct character counter
    R = k =>                       //   R() = helper function to get a random value in [0,k[
      Math.random() * k | 0,       //         also used to store characters
    g = y =>                       //   g() = helper function to update the matrix
      (r = a[y] = a[y] || [])[x]   //         with horizontal symmetry
      = r[n + ~x] = v.toString(36) //         using the base-36 representation of v
  ) =>                             //
    y < n / 2 ?                    // if we haven't reached the middle row(s) of the matrix:
      F(                           //   do a recursive call to F():
        g(                         //     invoke g() ...
          y,                       //       ... on the current row
          R[v =                    //       compute v = next value to be inserted
            R(m = ~-n/2) < !d &    //       we may insert a digit if no digit has been
            x < m &                //       inserted so far and the current coordinates are
            y < m ?                //       compatible: 2 distinct rows / 2 distinct columns
              R(d = 10)            //         if so, pick v in [0, 9] and update d
            :                      //       else:
              R(26) + 10           //         pick v in [10, 35] for a letter
          ] = R[v] || ++c,         //       set this character as used; update c accordingly
          g(n + ~y)                //       invoke g() on the mirror row
        ) &&                       //     end of outer call to g()
        ++x < n / 2 ?              //     if we haven't reached the middle column(s):
          x                        //       use x + 1
        :                          //     else
          +!++y,                   //       increment y and reset x to 0
        R                          //     explicitly pass R, as it is used for storage
      )                            //   end of recursive call to F()
    :                              // else:
      !d | c < n ? F() : a         //   either return the matrix or try again if it's invalid
)()                                // initial call to F()

1

掃除346 312バイト

明日もっとゴルフをします

import StdEnv,Data.List,Math.Random,System.Time,System._Unsafe
$n#q=twice(transpose o\q=zipWith((++)o reverse o drop(n-n/2*2))q q)[[(['a'..'z']++['0'..'9'])!!(c rem 36)\\c<-genRandInt(toInt(accUnsafe(time)))]%(i*n/2,i*n/2+(n-1)/2)\\i<-[1..(n+1)/2]]
|length(nub(flatten q))>=n&&sum[1\\c<-q|any isDigit c]==2=q= $n

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


1

Python 3 3、197バイト

@Emignaが述べたように、奇数の値に対しては機能しませんN(質問を適切に理解していませんでした)

from random import*
def m(N):M=N//2;E=reversed;R=range;B=[randint(48,57),*(sample(R(97,123),N)*N)][:M*M];shuffle(B);r=R(M);m=[k+[*E(k)]for k in[[chr(B.pop())for i in r]for j in r]];m+=E(m);return m

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

randint()+ sample()+ への呼び出しshuffle()は多すぎると思います。インプレースシャッフルを取り除くことは素晴らしいことです:)

この部分(文字と数字を選択する部分)をもう少しゴルフできると確信しています。


奇妙に正しいとは思えませんN
エミグナ

くそー、Nそれが奇数だとマトリックスがどのように対称になるか分からないので、私は常に偶数だと思っていました!
エテン

1
これらは、奇数の対称マトリックスの例です。
エミグナ

わかりました、ありがとう、私はそのようにそれを見なかった!さて、私の答えは当時のままでは価値がないと思います。
エテン

1

Pythonの2275の 266バイト

from random import*
def f(n):
 R=range;C=choice;A=map(chr,R(97,123));b=N=n-n/2;c=`C(R(10))`;s=[c]+sample(A,n-1)+[C(A)for i in R(N*N-n)]
 while b:shuffle(s);i=s.index(c);b=n%2>(i<N*N-N>N-1>i%N)
 a=[r+r[~(n%2)::-1]for r in[s[i::N]for i in R(N)]];return a+a[~(n%2)::-1]

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

文字のリストのリストとして配列を返します。ルール1を満たすために、キャラクターのプールを設定します。

s = [c]                        # the unique digit...
     + sample(A,n-1)           # then sample without replacement `n-1` chars in a-z, 
                               # so we have `n` distinct chars
     + [C(A)for i in R(N*N-n)] # and fill out the rest with any in a-z

次のトリッキーなビットはルール3 です。数字を含む列と行がちょうど2つ必要です。これは、n奇数の場合、選択された数字が中央の列または中央の行に表示されないことを意味します。2回反射された正方形のサブ配列を使用して配列を構築するため、以下を使用してこれをs実現します。

while b:            # to save a couple bytes, `b` is initialized 
                    # to `N`, which is greater than 0.
    shuffle(s)      # shuffle at least once...
    i = s.index(c)  # c is the unique digit used
    b = n%2 
             >      # if n is even, 0>(any boolean) will be false,
                    # so exit the loop; otherwise n odd, and we are
                    # evaluating '1 > some boolean', which is equivalent 
                    # to 'not (some boolean)'
         (i<N*N-N   # i is not the last column of s...
             >      # shortcut for ' and ', since N*N-N is always > N-1
          N-1>i%N)  # is not the last row of s

つまり、少なくとも1回シャッフルします。そして、nが奇数の場合、数字がの最後の列または最後の行にある場合、ループを続けsます。


1

Pyth、48バイト

L+b_<b/Q2JmO/Q2 2jy.eyXWqhJkbeJOT<csm.SGQK.EcQ2K

こちらからオンラインでお試しください。

プログラムは、回文機能の定義、数値の場所の選択、およびメイン機能の3つの部分に分かれています。

Implicit: Q=eval(input()), T=10, G=lower case alphabet

L+b_<b/Q2   Palindromisation function
L           Define a function, y(b)
      /Q2   Half input number, rounding down
    <b      Take that many elements from the start of the sequence
   _        Reverse them
 +b         Prepend the unaltered sequence

JmO/Q2 2   Choose numeric location
  O/Q2     Choose a random number between 0 and half input number
 m     2   Do the above twice, wrap in array
J          Assign to variable J

jy.eyXWqhJkbeJOT<csm.SGQK.EcQ2K   Main function
                           cQ2    Divide input number by 2
                         .E       Round up
                        K         Assign the above to K
                    .SG           Shuffle the alphabet
                  sm   Q          Do the above Q times, concatenate
                 c      K         Chop the above into segments of length K
                <             K   Take the first K of the above
  .e                              Map (element, index) as (b,k) using:
       qhJk                         Does k equal first element of J?
      W                             If so...
     X     b                          Replace in b...
            eJ                        ...at position <last element of J>...
              OT                      ...a random int less than 10
                                    Otherwise, b without replacement
    y                               Apply palindromisation to the result of the above
 y                                Palindromise the set of lines
j                                 Join on newlines, implicit print

複数のシャッフルアルファベットを使用すると、一意の文字の数が常に入力数よりも多くなるようにする必要があります。


1

Python 2 / Python 3、227バイト

from random import*
def m(N):n=N-N//2;r=range;C=choice;c=n*[chr(i+97)for i in r(26)];shuffle(c);c[C([i for i in r(n*(N-n))if(i+1)%n+1-N%2])]=`C(r(10))`;R=[c[i*n:i*n+n]+c[i*n:i*n+n-N%2][::-1]for i in r(n)];return R+R[::-1][N%2:]

少しゴルフをする:

from random import * # get 'choice' and 'shuffle'
def matrix(N):
    n = ceil(N/2) # get the size of the base block
    # get a shuffleable lowercase alphabet
    c = [chr(i+97)for i in range(26)]
    c = n*c # make it large enough to fill the base-block
    shuffle(c) # randomize it
    digit = choice('1234567890') # get random digit string
    ## this is only needed as to prevent uneven side-length matrices
    #  from having centerline digits.
    allowed_indices = [i for i in range( # get all allowed indices
        n*(N-n)) # skip those, that are in an unmirrored center-line
        if(i+1)%n  # only use those that are not in the center column
                 +1-N%2] # exept if there is no center column
    index = choice(allowed_indices) # get random index
    c[index]=digit # replace one field at random with a random digit
    ## 
    R=[]
    for i in range(n):
        r = c[i*n:i*n+n] # chop to chunks sized fit for the base block
        R.append(r+r[::-1][N%2:]) # mirror skipping the center line
    return R+R[::-1][N%2:] # mirror skipping the center line and return

以下の古い、ほぼ正しいバージョン:

Python2、Python3、161バイト

from random import *
N=26
n=N-N//2
c=[chr(i+97)for i in range(26)]
R=[ r+r[::-1][N%2:]for r in[(shuffle(c),c[:n])[1]for i in range(n)]]
R+=R[::-1][N%2:]
print(R)

N個の異なる要素はほとんど保証されているようです。

Python 2 / Python 3、170バイト

from random import*
def m(N):n=N-N//2;r=range;c=n*[chr(i+97)for i in r(26)][:n*n];shuffle(c);R=[_+_[::-1][N%2:]for _ in[c[i*n:i*n+n]for i in r(n)]];return R+R[::-1][N%2:]

ルール3を忘れたようです。また、どういうわけか[:n * n]が入り込みました。


あなたの答えは、それが対称行列を構築する方法で、非常に賢いですが、あなたは(あなたがあなたの結果のいずれかの数字を持っていないとして)、また5の(支配例えば、もし満たさないルール3を持っているn = 3、あなたが含む出力を持っていることはありません'z'、したがって、すべての出力)が可能ではありません。
チャスブラウン

まあ私を漬けて...あなたは正しい@ChasBrownです!まあ、[:n * n]は別のアプローチからの剰余であり、率直に言ってそこにあるべきではありません。ただし、ルール3については正しいです。修正する必要があります。ちょっと教えて
Teck-freak

ここで解決策を試してみましたが、インデックスエラーがありました...ところで、TryItOnlineはPPCGで非常に便利です!(また、この問題は私が最初に思ったよりもはるかにトリッキーです...)
チャスブラウン

エラーなく10000回以上実行しました。
テックフリーク

それを見つけた。「:」が欠落していました。スクリプトから直接コピーしましたが、失われたに違いありません。「...:-1] [N%2] for i ...」ではなく、「...:-1] [N%2:] for i ...」である必要があります。
テックフリーク
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.