回転合計


26

入力として正の整数を含む正方行列を取得し、行列の「回転和」を計算します。

回転合計:

元の行列と同じ行列を90、180、270度回転させた合計を取ります。

マトリックスが次のとおりであると仮定します。

 2    5    8
 3   12    8
 6    6   10

回転した合計は次のようになります。

2    5    8     8    8   10    10    6    6     6    3    2
3   12    8  +  5   12    6  +  8   12    3  +  6   12    5  = 
6    6   10     2    3    6     8    5    2    10    8    8   

26   22   26
22   48   22
26   22   26

テストケース:

ダッシュで区切られた入力と出力、改行で区切られた異なるテストケース。より便利な形式のテストケースは、ここにあります

1
-------------
4

1 3
2 4
-------------
10   10 
10   10    

14    6    7   14
 6   12   13   13
 6    2    3   10
 5    1   12   12
-------------
45   37   24   45
24   30   30   37
37   30   30   24
45   24   37   45    

14    2    5   10    2
18    9   12    1    9
 3    1    5   11   14
13   20    7   19   12
 2    1    9    5    6
-------------
24   29   31   41   24
41   49   31   49   29
31   31   20   31   31
29   49   31   49   41
24   41   31   29   24

各言語のバイト単位の最短コードが優先されます。説明を強くお勧めします!

回答:


9

Python 2、78バイト

以前の再帰的アプローチから2バイトのゴルフをしてくれたDennisに感謝します。

f=lambda*l:l[3:]and[map(sum,zip(*d))for d in zip(*l)]or f(zip(*l[0][::-1]),*l)

オンラインでお試しください!またはテストスイートをご覧ください。


パイソン2、80 81 83 85バイト(非再帰的)

入力をシングルトンリストとして受け取ります

l=input()
exec"l+=zip(*l[-1][::-1]),;"*3
print[map(sum,zip(*d))for d in zip(*l)]

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

コード機能

これは全体として分析するにはかなり長いので、1つずつ確認してみましょう。

f = lambda *l:                # This defines a lambda-function that can accept any number
                              # of arguments (the matrix) using starred expressions.
l[3:] and ...X... or ...Y...  # If l[3:] is truthy (that is, the length of the list is
                              # higher than 3), return X, otherwise Y.

[map(sum,zip(*d))for d in zip(*l)]     # The first expression, X.
[                                ]     # Start a list comprehension, that:
                 for d in              # ... Iterates using a variable d on:
                          zip(*l)      # ... The "input", l, transposed.
         zip(*d)                       # ... And for each d, transpose it...
 map(sum,       )                      # ... And compute the sum of its rows.
                                       # The last two steps sum the columns of d.

f(zip(*l[0][::-1]),*l)     # The second expression, Y. This is where the magic happens.
f(                   )     # Call the function, f with the following arguments:
  zip(*          )         # ... The transpose of:
       l[0][::-1]          # ...... The first element of l (the first arg.), reversed.
                  ,        # And:
                   *l      # ... l splatted. Basically turns each element of l
                           # into a separate argument to the function.

2番目のプログラムの場合:

l=input()                                # Take input and assign it to a variable l.
                                         # Note that input is taken as a singleton list.

exec"l+=zip(*l[-1][::-1]),;"*3           # Part 1. Create the list of rotations.
exec"                     ;"*3           # Execute (Do) the following 3 times:
     l+=                 ,               # ... Append to l the singleton tuple:
        zip(*           )                # ...... The transpose of:
             l[-1][::-1]                 # ......... The last element of l, reversed.

print[map(sum,zip(*d))for d in zip(*l)]  # Part 2. Generate the matrix of sums.
print                                    # Output the result of this expression:
     [                for d in        ]  # Create a list comprehension, that iterates
                                         # with a variable called "d" over:
                               zip(*l)   # ... The transpose of l.
      map(sum,       )                   # ... And computes the sum:
              zip(*d)                    # ... Of each row in d's transpose.
                                         # The last 2 steps generate the column sums.

TL; DR:入力を90度ずつ3回回転し、結果を収集することにより、必要なマトリックスのリストを生成します。次に、結果の転置の各行列の列の合計を取得します。


f=lambda*l:l[3:]and[map(sum,zip(*d))for d in zip(*l)]or f(zip(*l[0][::-1]),*l)「通常の」入力で2バイトを節約します。オンラインでお試しください!
デニス

@Dennisありがとうございます!lambda*l何らかの理由でPython 2では不可能だと思いました。
Xcoder氏

x,*y=1,2,3Python 2.7や[*x]Python 3.4ではできませんが、Python 1.6でも関数の引数にスター付きの式を使用できます。オンラインでお試しください!
デニス


5

クリーン、110バイト

import StdEnv,StdLib
r=reverse
t=transpose
z=zipWith(+)
$m=[z(z(r b)a)(z(r c)d)\\a<-m&b<-r m&c<-t m&d<-r(t m)]

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

行列から:

  • X = transpose(reverse M):90度回転
  • Y = reverse(map reverse M):180度回転
  • Z = reverse(transpose M):270度回転

これは、上加算演算子ジッパーMX、同様YZし、その後結果オーバー。



5

ジュリア0.6、29バイト

x*y=rotr90(y,x)
!x=x+1x+2x+3x

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

LukeSのソリューションを理解できませんでした

しかし、試してみると、これを思いついたのですが、それはちょっとかわいいと思います。

まず、乗算を回転操作に再定義します。ここで、最初は回転する回数です。したがって、ジュリアは並置によって乗算するため、次の1xようrotr90(x,1)3xなりrotr90(x,3)ます

次に、合計を書きます。


5

ジュリア0.628の、24バイト

~A=sum(rotr90.([A],0:3))

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

~A=sum(rotr90.([A],0:3)) #
~                        # redefine unary operator ~
 A                       # function argument
               [A]       # put input matrix A into a list with one element
                   0:3   # integer range from 0 to 3
       rotr90.(   ,   )  # apply function rotr90 elementwise, expand singleton dimensions
       rotr90.([A],0:3)  # yields list of rotated matrices:
                         # [rotr90(A,0), rotr90(A,1), rotr90(A,2), rotr90(A,3)]
  sum(                )  # sum

1
これは、julia 0.6で1x1マトリックスが宣言される方法であるため、この[1]例を実行する必要があることに注意してください~reshape([1], (1,1))
リンドンホワイト


4

MATL、9バイト

i3:"G@X!+

MATL Online試しください

説明

i       # Explicitly grab the input matrix
3:"     # Loop through the values [1, 2, 3], and for each value, N:
  G     # Grab the input again
  @X!   # Rotate the value by 90 degrees N times
  +     # Add it to the previous value on the stack
        # Implicitly end the for loop and display the resulting matrix




3

MATL、7バイト

,t@QX!+

MATL Online試しください

説明

オクターブ回答のポート。

,        % Do twice
  t      %   Duplicate. Takes input (implicit) the first time
  @Q     %   Push 1 in the first iteration, and 2 in the second
  X!     %   Rotate by that many 90-degree steps
  +      %   Add
         % End (implicit). Display (implicit)

3

R69 64バイト

function(x,a=function(y)apply(y,1,rev))x+a(x)+a(a(x))+a(a(a(x)))

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


codegolfで3番目の試み。ジュゼッペのおかげで69から64バイトまで!


a関数の引数に移動すると{}、関数本体の周りを取り除くことができるため、バイトが節約されます。また、Luis MendoのOctaveアプローチを移植すると、バイトがいくらか節約される可能性がありますか?最後に、私は100%確信していませんが、とt(apply(x,2,rev))同等apply(x,1,rev)です?
ジュゼッペ

おかげで、私はヒント#1と#3で改善することができました。しかし、引数nを追加しa()て操作を繰り返すことでバイトを保存することに成功しませんでした。
フロリアン




2

JavaScript(ES6)、77バイト

a=>a.map((b,i)=>b.map((c,j)=>c+a[j][c=l+~i]+a[c][c=l+~j]+a[c][i]),l=a.length)

2

ゼリー、7バイト

ṚZ$3СS

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

Erik the Outgolferのおかげで1バイト節約されました(バグを修正する提案もあります)。

どうやって?

ṚZ$3СS|| フルプログラム(モナド)。

   3С|| これを3回行い、結果をリストに収集します
  $ || –>最後の2つのリンクをモナドとして適用する
Ṛ|| –––>逆、
 Z || –––>トランスポーズ。
      S || まとめ。


2

APL(Dyalog Classic)、17バイト

{⍵+⌽∘⍉⍵+⌽∘⊖⍵+⍉⌽⍵}

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

APL NARS 34バイト21 17文字

{⍵+⌽∘⍉⍵+⌽∘⊖⍵+⍉⌽⍵}

-ngnのおかげで2文字

-2文字。演算子複合precedenceは+に優先権があるようです。

seemsaは90°から回転、⌽⊖aは180°から回転、⌽⍉⌽⊖aは270°から回転

存在する場合、演算子pは次のようになります。

r←(g p)n;a;i;k
   a←⌽,nr←⍬⋄i0k←⍴a⋄→C
A: B×⍳r≡⍬⋄rg¨r
B: rr,⊂ia
C: A×⍳ki+←1
   r←⌽r

上記の演算子pは、gが1引数関数(単項式?)の場合、次のようになります。

"g f a a a a" is "a ga gga ggga"

解決策は、15文字のフェラップです

  g←{⊃+/⌽∘⍉ p 4⍴⊂⍵}
  a2 21 3 2 4
  g a
10 10 
10 10 
  g 1
4

しかし、「3 df w」がf(f(f(w)))であるような1つの演算子「composed n time」dの方が良いかもしれません。

今、私は何かを書いたが、型チェックを必要とせずにあまりにも壊れやすいです。

しかし、引数mでfの構成を繰り返す演算子qの方が好きです(型のエラーケースが記述されていないため完全ではありません)

r←(n q f)m;i;k;l
   r←⍬⋄k←⍴,n⋄→A×⍳k1i0⋄→D
C: rr,⊂(in)q f m
D: C×⍳ki+←1
   0
A: lnrm⋄→0×⍳n0
B: l-←1rf r⋄→B×⍳l1

解決策は17文字ですが、私はそれを好む

  g←{⊃+/(0..3)q(⌽⍉)⍵}
  fmt g a
2─────┐
2 10 10
 10 10
└~─────┘
  fmt g 1
4
~

270がちょうどで⍉⌽あり、すべてが列車に
-ngn

gfwwwwがw gw ggw gggwであるようなfが存在する場合、答えは+ /⌽⍉f4 / rho w
RosLuP

という意味+/⌽∘⍉f 4⍴⊂⍵ですか?の4つのコピーを取得するには、最初にで囲む必要があります。の⌽⍉オペランドとして使用するにはf、次のように単一の関数に構成する必要があります⌽∘⍉。不思議なのfはスキャン(バックスラッシュ)かもしれませんが、他にも注意すべき詳細があります- ⌽∘⍉左引数を取得するので、無視する必要があります:+/{⌽⍉⍵}\4⍴⊂⍵または+/⊢∘⌽∘⍉\4⍴⊂⍵
NGN

私の最初のコメントでは、この列車を提案していました:⊢ + ⌽∘⍉ + ⌽∘⊖ + ⍉∘⌽。スクイーグルを巧みに再配置し、列車をうまく利用すれば、さらに短いソリューションにつながります。
NGN

@ngn単純な{⍵+⍺} \ 1 2 3 4でもドメインエラーを返す
RosLuP

2

K4 / K(oK)23 8バイト

溶液:

+/(|+:)\

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

例:

+/(|+:)\5 5#14 2 5 10 2 18 9 12 1 9 3 1 5 11 14 13 20 7 19 12 2 1 9 5 6
24 29 31 41 24
41 49 31 49 29
31 31 20 31 31
29 49 31 49 41
24 41 31 29 24

説明:

簡略化された変換手法を提供してくれたngnに感謝します。

+/(|+:)\ / the solution
       \ / converge
  (   )  / function to converge
    +:   / flip
   |     / reverse
+/       / sum over the result

追加:

Qでは、これは

sum (reverse flip @) scan


変換を適用するより良い方法があること知っていました!
ストリートスター

+ /(| +:)\ tio.run/##y9bNz/7/X1tfo0bbSjPGWMFY2UjBVMFCwVjB0AhImQGhocH//wAは悲しいことに同じカウントです... Gahはモバイルでマークアップを把握できません。
ストリートスター

コメントのマークアップには、モバイルだけでなくバグがあるようです。スペースを挿入して回避しました。
ngn

2

ルビー74 72 66バイト

->a{r=0...a.size;r.map{|i|r.map{|j|(0..3).sum{i,j=j,~i;a[i][j]}}}}

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

これは要素ごとに機能し、配列を回転させる代わりに、関連する要素を数学的に見つけます。重要な部分はi,j=j,~i、時計回りに90度回転する(i、j)です。

-Mr. Xcoderのおかげで2バイト

-6バイトのため sum



1

Ruby 89 79バイト

Unihedronのおかげで-10バイト

->m{n=m;3.times{n=n.zip(m=m.transpose.reverse).map{|i,j|i.zip(j).map &:sum}};n}

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


1
私はかなり確信して、置き換えることができるんだ.map &:dup*1文字の多くを遮断します。array*length新しい配列を作成し、浅いクローンを作成する便利な方法です。
ユニヘドロン

実際にn=*mは、さらに短くなります。
単面体

@Unihedronが問題です。クローンを深くする必要があります
Asone Tuhid

それは出力に影響しないように思えます。私はあなたの「オンラインそれを試してみてください」リンクでそれをいじっと出力がその変化に正しいままに見える
Unihedron

あなたが実際にあなたも浅いクローンを必要としない、正しい、transposeそれの世話をする
Asone Tuhid



1

、9バイト

F‡+↑4¡(↔T

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

説明

F‡+↑4¡(↔T)  -- implicit input M, for example: [[1,0,1],[2,3,4],[0,0,2]]
     ¡(  )  -- repeat infinitely times starting with M  
        T   -- | transpose: [[1,2,0],[0,3,0],[1,4,2]]
       ↔    -- | reverse: [[1,4,2],[0,3,0],[1,2,0]]
            -- : [[[1,0,1],[2,3,4],[0,0,2]],[[1,4,2],[0,3,0],[1,2,0]],[[2,0,0],[4,3,2],[1,0,1]],[[0,2,1],[0,3,0],[2,4,1]],[[1,0,1],[2,3,4],[0,0,2]],…
   ↑4       -- take 4: [[[1,0,1],[2,3,4],[0,0,2]],[[1,4,2],[0,3,0],[1,2,0]],[[2,0,0],[4,3,2],[1,0,1]],[[0,2,1],[0,3,0],[2,4,1]]]
F           -- fold (reduce) the elements (example with [[1,0,1],[2,3,4],[0,0,2]] [[1,4,2],[0,3,0],[1,2,0]])
 ‡+         -- | deep-zip addition (elementwise addition): [[2,4,3],[2,6,4],[1,2,2]]
            -- : [[4,6,4],[6,12,6],[4,6,4]]

1

tinylisp、132バイト

最近追加したライブラリ関数transposeを試してみましょう!

(load library
(d T transpose
(d R(q((m #)(i #(c m(R(reverse(T m))(dec #)))(
(q((m)(foldl(q(p(map(q((r)(map sum(T r))))(T p))))(R m 4

最後の行は、回転の合計を実行する名前のないラムダ関数です。実際に使用dするには、名前にバインドする必要があります。オンラインでお試しください!

Ungolfed、コメント付き

(load library) (comment Get functions from the standard library)

(comment Rotating a matrix by 90 degrees is just transpose + reverse)
(def rotate
 (lambda (matrix)
  (reverse (transpose matrix))))

(comment This function recursively generates a list of (count) successive rotations
          of (matrix))
(def rotations
 (lambda (matrix count)
  (if count
   (cons matrix
    (rotations (rotate matrix) (dec count)))
   nil)))

(comment To add two matrices, we zip them together and add the pairs of rows)
(def matrix-add
 (lambda two-matrices
  (map row-sum (transpose two-matrices))))

(comment To add two rows of a matrix, we zip them together and add the pairs of numbers)
(def row-sum
 (lambda (two-rows)
  (map sum (transpose two-rows))))

(comment Our final function: generate a list containing four rotations of the argument
          and fold them using matrix-add)
(def rotated-sum
 (lambda (matrix)
  (foldl matrix-add (rotations matrix 4))))

1

アタッシュ、20バイト

Sum@MatrixRotate&0:3

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

説明

Sum@MatrixRotate&0:3

MatrixRotate&0:3入力と、に拡大しxMatrixRotate[x, 0:3]ターンexapnds中へ[MatrixRotate[x, 0], MatrixRotate[x, 1], MatrixRotate[x, 2], MatrixRotate[x, 3]]。つまり、RHSを介してベクトル化します。次に、Sumこれらすべての行列の合計を1レベルずつ取ります。これにより、望ましい結果が得られます。


1

Java 8、135 133バイト

a->{int l=a.length,r[][]=new int[l][l],i=0,j;for(;i<l;i++)for(j=0;j<l;)r[i][j]=a[i][j]+a[j][l+~i]+a[l+~i][l-++j]+a[l-j][i];return r;}

@ceilingcatのおかげで-2バイト。

説明:

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

a->{                        // Method with integer-matrix as both parameter and return-type
  int l=a.length,           //  Dimensions of the input-matrix
      r[][]=new int[l][l],  //  Result-matrix of same size
      i=0,j;                //  Index-integers
  for(;i<l;i++)             //  Loop over the rows
    for(j=0;j<l;)           //   Loop over the columns
      r[i][j]=              //    Set the cell of the result-matrix to:
              a[i][j]+a[j][l+~i]+a[l+~i][l-++j]+a[l-j][i];
                            //     The four linked cells of the input-matrix
  return r;}                //  Return the result-matrix
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.