Matrisimin deltalarını topla


17

Arka fon

Bir tamsayı dizisinin deltaları birbirini izleyen elemanların farklarını alarak oluşan dizidir. Örneğin, [1, 2, 4, 7, 3, 9, 6]aşağıdaki deltalar vardır: [1, 2, 3, -4, 6, -3].

Şimdi bir tamsayı matrisinin deltalarını her satırın ve içerdiği her sütunun deltası olarak tanımlayacağız.

Örnek olarak:

Row deltas:

1 2 3 4 │ => [1, 1, 1]
4 5 6 7 │ => [1, 1, 1]
7 1 8 2 │ => [-6, 7, -6]

Column deltas (the matrix' columns have been rotated into rows for simplicity):

1 4 7 │ => [3, 3] 
2 5 1 │ => [3, -4]
3 6 8 │ => [3, 2]
4 7 2 │ => [3, -5]

Bu bize aşağıdaki matris deltalarının listesini verir:

[[1, 1, 1], [1, 1, 1], [-6, 7, -6], [3, 3], [3, -4], [3, 2], [3, -5]]

Yuvalanmalarını istemediğimiz için bu listeyi düzleştiriyoruz:

[1, 1, 1, 1, 1, 1, -6, 7, -6, 3, 3, 3, -4, 3, 2, 3, -5]

Görev

Göreviniz girdi olarak verilen bir matrisin tüm deltalarını toplamaktır . Matrisin yalnızca negatif olmayan tamsayılardan oluşacağını unutmayın.

kurallar

  • Tüm standart kurallar geçerlidir.

  • Matrisin her satır ve sütunda en az iki değer içerdiğini varsayabilirsiniz, böylece minimum boyut 2x2 olacaktır .

  • Matrisi, belirttiğiniz sürece herhangi bir makul biçimde alabilirsiniz.

  • Sen olmayabilir matris kare olduğunu varsayalım.

  • Bayt sayınızı azaltmanıza yardımcı olabilirse, isteğe bağlı olarak satır sayısını ve giriş olarak sütun sayısını da alabilirsiniz (Size bakıyorsunuz C!).

  • Bu kod golf, bu yüzden her dilde en kısa kod (bayt cinsinden) kazanır!

Test Durumları

Giriş => Çıkış

[[1, 2], [1, 2]] => 2
[[8, 7, 1], [4, 1, 3], [5, 5, 5]] => -9
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] => 24
[[9, 9, 9, 9, 9], [9, 9, 9, 9, 9]] => 0
[[1, 3, 14], [56, 89, 20], [99, 99, 99]] => 256
[[1, 2, 3, 4], [4, 5, 6, 7], [7, 1, 8, 2]] => 9
[[13, 19, 478], [0, 12, 4], [45, 3, 6], [1, 2, 3]] => -72

Yanıtlar:


12

Python 2 , 42 bayt

lambda m:sum(r[-1]-r[0]for r in m+zip(*m))

Liste listesini alan mve elde edilen sayıyı döndüren isimsiz bir işlev .

Çevrimiçi deneyin!

Nasıl?

Bir listenin deltalarının toplamı son eleman eksi birincidir, diğer her şey iptal eder:
(r [n] -r [n-1]) + (r [n-1] -r [n-2]) + ... + (r [2] -r [1]) = r [n] -r [1]

zip(*m)Kullanımları açma ( *arasında) msatırlarını geçmek miçin ayrı bağımsız değişken olarak zip(yaprak) ve bu nedenle, matris aktarır. Python 2'de bu bir liste verir (tuples, ancak bu iyidir), böylece onu ( msatırlarla ) ekleyebilir (birleştirebilir) , tüm satırlarımıza ve sütunlarımıza adım ratabilir, her biri için yukarıdaki numarayı yapabiliriz ve sadece sonuçları toplayabiliriz ( sum(...)).



8

Oktav , 33 bayt

@(x)sum([diff(x)(:);diff(x')(:)])

Çevrimiçi deneyin!

Açıklama:

Bu xgiriş olarak anonim bir işlevdir . Tüm sütunlar arasındaki farkı alır ve aktarılan sütunlar arasındaki farkla birleştirir.x . Daha sonra bu vektörü ikinci boyut boyunca toplar.



5

JavaScript (ES6), 68 67 bayt

m=>m.map(r=>s+=[...l=r].pop()-r[0],s=0)|m[0].map(v=>s+=l.pop()-v)|s

Biçimlendirilmiş ve yorumlanmış

m =>                              // given a matrix m
  m.map(r =>                      // for each row r of m
    s += [...l = r].pop() - r[0], //   add to s: last value of r - first value of r
    s = 0                         //   starting with s = 0
  ) |                             //
  m[0].map(v =>                   // for each value v in the first row of m:
    s += l.pop() - v              //   add to s: last value of last row of m - v
  ) |                             //
  s                               // return s

Giriş matrisinin minimum boyutu 2x2 olduğundan m.map(...)|m[0].map(...), zorlanması garanti edilir 0. Bu yüzden nihai sonucu geri getirmek güvenlidir |s.

Test senaryoları


5

MATL , 7 bayt

dG!dhss

Çevrimiçi deneyin!

Açıklama:

Girişin

[8 7 1; 4 1 3; 5 5 5]

d        % Difference between rows of input
         % Stack:
         % [-4 -6  2; 1  4  2]
 G       % Grab the input again. Stack:
         % [-4 -6  2; 1  4  2]
         % [8 7 1; 4 1 3; 5 5 5]]
  !      % Transpose the bottom element. Stack:
         % [-4 -6  2; 1  4  2]
         % [8 4 5; 7 1 5; 1 3 5]
   d     % Difference between rows. Stack:
         % [-4 -6  2; 1  4  2]
         % [-1 -3  0; -6  2  0]
    h    % Concatenate horizontally. Stack:
         % [-4 -6  2 -1 -3  0; 1  4  2 -6  2  0]
     ss  % Sum each column, then sum all column sums. Stack:
         % -9


4

J , 14 bayt

+/@,&({:-{.)|:

Çevrimiçi deneyin!

açıklama

+/@,&({:-{.)|:  Input: matrix M
            |:  Transpose
     (     )    Operate on M and M'
      {:          Tail
        -         Minus
         {.       Head
   ,&           Join
+/@             Reduce by addition

3

Kabuk , 7 bayt

ΣṁẊ-S+T

Çevrimiçi deneyin!

-1 sayesinde Sn Xcoder uzak benim odak alarak Sve ¤ve doğru m(ki olmalıydı ṁ).
-1 Zgarb kötüye kullanımı sayesinde S.

Açıklama:

ΣṁẊ-S+T 3-function composition
    S   (x -> y -> z) (f) -> (x -> y) (g) -> x (x) (implicit): f x g x
     +    f: [x] (x) -> [x] (y) -> [x]: concatenate two lists
      T   g: [[x]] (x) -> [[x]]: transpose x
 ṁ      (x -> [y]) (f) -> [x] (x) -> [y]: map f on x and concatenate
  Ẋ       f: (x -> y -> z) (f) -> [x] (x) -> [z]: map f on splat overlapping pairs of x
   -        f: TNum (x) -> TNum (y) -> TNum: y - x
Σ       [TNum] (x) -> TNum: sum x

Evet, 8 bayt kullanarak ṁ.
— Bay Xcoder

Bunun yerine yaklaşımınızı kullanarak 8 bayt .
— Bay Xcoder

@ Mr.Xcoder vay canına unuttum
— Outgolfer Erik


3

Haskell , 60 bayt

e=[]:e
z=zipWith
f s=sum$(z(-)=<<tail)=<<(s++foldr(z(:))e s)

Çevrimiçi deneyin! Kısa devri kullanırBir süre önce bulduğum .

açıklama

eboş listelerin sonsuz bir listesidir ve aktarma için kullanılır. işlevi ziçin bir kısayoldur zipWith, çünkü iki kez kullanılır.

f s=                                        -- input s is a list of lists
                            foldr(z(:))e s  -- transpose s
                         s++                -- append the result to the original list s
                     =<<(                 ) -- map the following function over the list and concatenate the results
        (z(-)=<<tail)                       -- compute the delta of each list by element-wise subtracting its tail
    sum$                                    -- compute the sum of the resulting list

3

Brachylog , 13 bayt

@ sundar'ın tasarımına dayalı olarak

⟨≡⟨t-h⟩ᵐ²\⟩c+ 

açıklama

⟨≡      \⟩          #   Take the original matrix and it's transpose 
      ᵐ             #       and execute the following on both
       ²            #           map for each row (this is now a double map "ᵐ²")
  ⟨t h⟩             #               take head and tail
   -                #               and subtract them from each other (sum of deltas in a row)
         c+         #       and add all the values 
                    #           (we have two arrays of arrays so we concat them and sum them)

⟨⟩üzgün, biçimlendirme kadar uğraşıyorsun

Çevrimiçi deneyin!


2

Pyth, 7 bayt

ss.+M+C

Burada deneyin.

Golf dilinde ilk cevabım! @EriktheOutgolfer sayesinde for -1 byte!

açıklama

ss.+M+C    ~ This is a full program with implicit input (used twice, in fact)

      C    ~ Matrix transpose. Push all the columns;
     +     ~ Concatenate with the rows;
  .+M      ~ For each list;
  .+       ~ Get the deltas;
 s         ~ Flatten the list of deltas;
s          ~ Get the sum;
           ~ Print Implicitly;

.tC-1 için olabilir .
— Outgolfer Erik

@EriktheOutgolfer Oh wow, thanks!

2

Brachylog, 22 16 bytes

⟨≡{s₂ᶠc+ᵐ-}ᵐ\⟩+ṅ

Try it online!

(-6 bytes inspired by @Kroppeb's suggestions.)

?⟨≡{s₂ᶠc+ᵐ-}ᵐ\⟩+ṅ.       Full code (? and . are implicit input and output)
?⟨≡{       }ᵐ\⟩          Apply this on both the input and its transpose:
    s₂ᶠ                  Get pairs of successive rows, [[row1, row2], [row2, row3], ...]
       c                 Flatten that: [row1, row2, row2, row3, row3, row4, ...]
        +ᵐ               Sum the elements within each row [sum1, sum2, sum2, sum3, ...]
          -              Get the difference between even-indexed elements (starting index 0)
                         and odd-indexed elements, i.e. sum1+sum2+sum3+... - (sum2+sum3+sum4+...)
                         This gets the negative of the usual difference i.e. a-b instead of b-a
                         for each pair of rows
               +         Add the results for the input and its transpose
                ṅ        Negate that to get the sign correct
                 .       That is the output

The sum of the deltas is equal to the last element-the first one ⟨t-h⟩ does the trick. Resulting in {⟨t-h⟩ᵐ+}R&\↰₁;R+ which is 5 bytes shorter. Try it online!
— Kroppeb

using ⟨≡{...}ᵐ\⟩+ instead of {...}R&\↰₁;R+ saves 2 bytes. Resulting in ⟨≡{⟨t-h⟩ᵐ+}ᵐ\⟩+ Try it online!
— Kroppeb

Changing the mapping of a map in a double map and concatenating and somming at the and removes an additional 2 bytes ⟨≡⟨t-h⟩ᵐ²\⟩c+. Try it online!
— Kroppeb

@Kroppeb That's different enough and big enough of an improvement, that you should post it as a new answer yourself. Seeing your suggestions gave me an idea for a 16-byte solution using a different method ⟨≡{s₂ᶠc+ᵐ-}ᵐ\⟩+ṅ Try it online!, so I'll update this answer with that version instead.
— sundar - Reinstate Monica

2

Japt -x, 11 10 9 bytes

cUy)®än x

Try it


Explanation

c             :Concatenate
 U            :  Input array
  y           :  Transpose
   )          :End concatenation
    ®         :Map
     än       :  Deltas
        x     :  Reduce by addition
              :Implicitly reduce by addition and output

1

SOGL V0.12, 9 bytes

:⌡-≤H⌡-¹∑

Try it Here! (→ added because this takes input on the stack)

Explanation:

:          duplicate ToS
 ⌡         for each do
  -          get deltas
   ≤       get the duplicate ontop
    H      rotate it anti-clockwise
     ⌡     for each do
      -      get deltas
       ¹   wrap all of that in an array
        ∑  sum

1
→ added because this takes input on the stack - I've been meaning to ask this for a long time: Is input pushed automatically to the stack? If it is not, and expects input to be already present in the stack, shouldn't you add → in your byte count as well? Not sure how these situations are handled. Or is it like a function?
— Mr. Xcoder

@Mr.Xcoder hmm.. I thought that was allowed by the default inputs, but I guess there's only this for functions.. Then again, I could call this an unnamed function used as this (in SOGL a "function"s definition is functionNameSingleChar\n)
— dzaima

Oh, alright. It is perfectly valid then.
— Mr. Xcoder

1

Mathematica, 45 bytes

Tr@Flatten[Differences/@#&/@{#,Transpose@#}]&

Input

[{{13, 19, 478}, {0, 12, 4}, {45, 3, 6}, {1, 2, 3}}]


Would it be shorter to subtract the first from the last for each array in {#,Transpose@#} (like my Python answer)?
— Jonathan Allan

Total[Differences/@{#,Thread@#},3]&
— alephalpha

1

CJam, 19 bytes

0q~_z+2few:::-:+:+-

Input is a list of lists of numbers. Try it online!

Explanation

0       e# Push 0
q~      e# Evaluated input. 
_       e# Duplicate
z       e# Zip (transpose)
+       e# Concatenate. This gives a lists of lists of numbers, where the
        e# inner lists are the original rows and the columns
2few    e# Replace each inner list of numbers by a list of overlapping
        e# slices of size 2. We not have three-level list nesting
:::-    e# Compute difference for each of those size-two slices. We now
        e# have the deltas for each row and column
:+      e# Concatenate all second-level lists (de-nest one level)
:+      e# Sum all values
-       e# Subtract from 0, to change sign. Implicitly display

4
This answer needs more colons. There are 2few colons.
— Esolanging Fruit

0

MY, 9 bytes

ωΔω⍉Δ ḟΣ↵

Try it online!

Since I cannot ping Dennis in chat to pull MY (due to a suspension), this will currently not work. (Δ previously didn't vecify when subtracting) Thanks to whomever got Dennis to pull MY!

How?

  • ωΔ, increments of the first command line argument
  • ω⍉Δ, increments of the transpose of the first command line argument
  • , in a single list
  • ḟ, flatten
  • Σ, sum
  • ↵, output


0

Pyt, 11 bytes

Đ⊤ʁ-⇹ʁ-áƑƩ~

Explanation:

          Implicit input (as a matrix)
Đ         Duplicate the matrix
⊤         Transpose the matrix
ʁ-        Get row deltas of transposed matrix
⇹         Swap top two elements on the stack
ʁ-        Get row deltas of original matrix
á         Push the stack into an array
Ƒ         Flatten the array
Ʃ         Sum the array
~         Flip the sign (because the deltas are negative, as subtraction was performed to obtain them)
          Implicit output
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.