İlk satır ve sütun toplamı, ardından ikinci satır ve sütun toplamı…


31

Giriş olarak pozitif tam sayıları içeren boş olmayan bir matris / sayısal dizi alın. Bu sırayla, ilk satırın ve sütunun, ardından ikinci satırın ve sütunun toplamını döndürün ve daha fazla satır ya da sütun bulunmayana kadar devam edin.

Diyelim ki giriş:

2   10   10    2    4
9    7    7    2    9
1    7    6    2    4
7    1    4    8    9

O zaman çıktı şöyle olmalı:

45, 33, 16, 17

Çünkü: 2+9+1+7+10+10+2+4=45, 7+7+1+7+2+9=33, 6+4+2+4=16, 8+9=17.

Test durumları:

Test durumları aşağıdaki biçimdedir:

Input
---
Output

5
---
5
..........

1  4
----
5
..........

7
2
---
9
..........

 8    3    7   10    3    7   10    1
10    7    5    8    4    3    3    1
 1    6    4    1    3    6   10    1
 2    3    8    2    8    3    4    1
---
62   40   33   18
..........

30    39    48     1    10    19    28
38    47     7     9    18    27    29
46     6     8    17    26    35    37
 5    14    16    25    34    36    45
13    15    24    33    42    44     4
21    23    32    41    43     3    12
22    31    40    49     2    11    20
---
320  226   235   263   135    26    20
..........

7   10    1
4    4    2
6    3    4
1    4   10
5    7    6
---
34   20   20

Diziler olarak:

[[5]]
[[1,4]]
[[7],[2]]
[[8,3,7,10,3,7,10,1],[10,7,5,8,4,3,3,1],[1,6,4,1,3,6,10,1],[2,3,8,2,8,3,4,1]]
[[30,39,48,1,10,19,28],[38,47,7,9,18,27,29],[46,6,8,17,26,35,37],[5,14,16,25,34,36,45],[13,15,24,33,42,44,4],[21,23,32,41,43,3,12],[22,31,40,49,2,11,20]]
[[7,10,1],[4,4,2],[6,3,4],[1,4,10],[5,7,6]]

Bu olduğundan her dilde en kısa çözüm kazanır.


2
@ JonathanAllan, sonsuza kadar sıfır basmak biraz gergin, bu yüzden buna hayır demeliyim.
Stewie Griffin

1
Güzel örneklerden Python dizilerine dönüştürmek için Retina programı .
mbomb007

1
Örneklere bakmak. Görev tanımı yanlış. İlk örnekte ikinci sütun 10,7,7,1, ikinci satır 9,7,7,2,9ve toplamdır 59. Ve böylece
edc65

1
@ edc65 Örneklere bakıldığında, önceki hesaplamalarda kullanılan sayıların tekrar kullanılmadığı anlaşılmaktadır. Ya da, nth satırını düşünürken, sadece nth sütunundaki değerleri kullanın ve 1 ila n-1 arasındaki sütunları dikkate almayın.
Brian J

1
@ Arc676 Standart io kuralları. İşlev argümanları kabul edilen giriş yöntemlerinden biridir.
Stewie Griffin

Yanıtlar:


10

MATL , 16 bayt

&n:w:!XlX:GX:1XQ

Çevrimiçi deneyin! Veya tüm test durumlarını doğrulayın .

açıklama

Örnek olarak, girişi düşünün

2   10   10    2    4
9    7    7    2    9
1    7    6    2    4
7    1    4    8    9

Kod &n:w:!Xl, sütun vektörünü [1; 2; 3; 4]ve satır vektörünü oluşturur [1 2 3 4 5]. Sonra Xlasgari eleman bilgisini yayınlayarak yayınlar, matrisi verir

1 1 1 1 1
1 2 2 2 2
1 2 3 3 3
1 2 3 4 4

X:Bu matrisi (ana sütun sırasına göre) sütun vektörüne doğrusallaştırır [1; 1; 1; 1; 1; 2; 2; ... ; 4]. Bu vektör ve doğrusallaştırılmış giriş matrisi, olarak işleve GX:girdi olarak iletilir accumarray(... @sum)veya 1XQ. Bu, ilk girişin değerlerine göre gruplandırılmış ikinci girişin toplamını hesaplar.



5

CJam , 23 18 bayt

{[{(:+\z}h;]2/::+}

Anonim blok argümandaki değişkeni bekliyor ve sonucu yığında bırakıyor.

Çevrimiçi deneyin!

açıklama

[      e# Begin working in an array.
 {     e#  Do:
  (:+  e#   Remove the first row of the matrix and sum it.
  \z   e#   Bring the matrix back to the top and transpose it.
 }h    e#  While the matrix is non-empty.
 ;     e#  Discard the remaining empty matrix.
]      e# Close the array.
2/     e# Split it into consecutive pairs of elements (possibly with a singleton on the end).
::+    e# Sum each pair.

Bu biraz "aldatma" değil mi? Yani, bayt sayısında giriş ve çıkış kodunu saymıyorsunuz. Hem giriş hem de çıkış ile sadece 1 byte daha uzundur:q~[{(:+\z}h;]2/::+p
FrodCube

@FrodCube Meta konsensüs tarafından izin verilir .
Business Cat

2
Aslında, teknik olarak, açılıştan çıkabileceğim için tam bir programla aynı uzunluktaydı [. Ancak bir blok olarak ihtiyacım olduğunu düşünüyorum çünkü altındaki tüm yığını da yakalamaması gerekiyor.
Business Cat

5

05AB1E , 14 11 bayt

[ćOˆøŽ]¯2ôO

Çevrimiçi deneyin!

açıklama

[   Ž ]       # loop until stack is empty
 ć            # extract the head
  Oˆ          # sum and add to global list
     ø        # transpose
       ¯      # push global list
        2ô    # split into pairs
          O   # sum each pair

4

JavaScript (ES6), 60 bayt

a=>a.map((b,y)=>b.map((c,x)=>r[x=x<y?x:y]=~~r[x]+c),r=[])&&r

Naif çözelti, daha iyi bir yol olabilir.


4

Mathematica, 60 bayt

Esinlenerek Luis Mendo en Matl cevap .

Pick[#,Min~Array~d,n]~Total~2~Table~{n,Min[d=Dimensions@#]}&

Açıklama: Min~Array~Dimensions@#aşağıdakine benzer bir matris oluşturur:

1 1 1 1 1
1 2 2 2 2
1 2 3 3 3
1 2 3 4 4

Daha sonra yukarıdaki garip matristeki Pick[#,...,n]~Total~2sayıya karşılık gelen giriş matrisinin girişlerini seçer ve bunları toplar n. Sonunda ...~Table~{n,Min[d=Dimensions@#]}tekrar eder n.

Bu, naif yaklaşımdan 1 bayt daha kısadır:

{#[[n,n;;]],#[[n+1;;,n]]}~Total~2~Table~{n,Min@Dimensions@#}&

4

Haskell, 50 49 bayt

f(a@(_:_):b)=sum(a++map(!!0)b):f(tail<$>b)
f _=[]

Çevrimiçi deneyin!

En az bir elemente sahip en az bir satır varsa, sonuç, ilk satırın toplamı ve diğer tüm satırların kafalarının ardından gelen tüm diğer satırların kuyrukları ile özyinelemeli bir çağrıdır. Diğer tüm durumlarda, sonuç boş listedir.

Düzenleme: Ørjan Johansen bir bayt kaydetti. Teşekkürler!


4

Octave , 64 52 bayt

1 byte tasarrufu için @StewieGriffin'e teşekkürler!

@(x)accumarray(min((1:size(x))',1:rows(x'))(:),x(:))

Bu isimsiz bir işlevi tanımlar.

Çevrimiçi deneyin!

açıklama

Kod benim MATL cevabımı benzer (see explanation there).

Two bytes have been saved using 1:size(x) instead of 1:size(x,1), exploiting the fact that 1:[a b] behaves the same as 1:a. Also, one byte has been saved using 1:rows(x') instead of 1:size(x,2), thanks to Stewie.


3

k, 19 bytes

|1_-':|+//'(1_+1_)\

Try it online!

Explanation:

           (1_+1_)   /a function that strips the top and leftmost rows of a matrix
                  \  /apply this function as many times as possible,
                     /    saving each result as one element of a list
       +//'          /for each result, get the sum of all numbers
|  -':|              /subtract every right value from every left value
 1_                  /remove the extra 0

3

05AB1E, 16 bytes

[ćOsø.g<NQ#])2ôO

Try it online! or Try all tests

[                # Start loop
 ć               # Extract first element
  O              # Sum
   sø            # Transpose the input array (without the first N rows and columns)
     .g<NQ       # Push if (stack height - 1 == loop count)
          #]     # If they were equal break
            )2ô  # Break stack into chunks of 2
               O # Sum the chunks

3

Octave, 63 60 bytes

@(A)(@(L)sum(triu(A,1)')(L)+sum(tril(A))(L))(1:min(size(A)))

Try it online!

The answer for this matrix:

2   10   10    2    4
9    7    7    2    9
1    7    6    2    4
7    1    4    8    9

is the vector of row sums of its upper triangular part:

0   10   10    2    4
0    0    7    2    9
0    0    0    2    4
0    0    0    0    9

plus the vector of column sums of its lower triangular part:

2    0    0    0    0
9    7    0    0    0
1    7    6    0    0
7    1    4    8    0

which is precisely what my answer is computing.


2

Julia, 62 bytes

f=x->1∈size(x)?sum(x):(n=f(x[2:end,2:end]);[sum(x)-sum(n);n])

Works recursively by summing up the whole matrix and then subtracting off the sum of the next block. Probably not the most effective approach, but nicely intuitive.


2

Java 7, 248 bytes

String c(int[][]a){int l=a.length,L=a[0].length,b[][]=new int[l][L],i,j,x=1,s;for(;x<(l>L?l:L);x++)for(i=l;i-->x;)for(j=L;j-->x;b[i][j]=x);String r="";for(;x-->0;r=s>0?s+" "+r:r)for(s=0,i=0;i<l;i++)for(j=0;j<L;j++)s+=b[i][j]==x?a[i][j]:0;return r;}

Try it here.

General explanation:

Let's say the input array has dimensions of 4x6. The first part of the code will create a temp matrix and fills it as follows:

// 1. Fill the entire array with 0:
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

// 2. Overwrite the inner part with 1 (excluding the first row & column):
0 0 0 0 0 0
0 1 1 1 1 1
0 1 1 1 1 1
0 1 1 1 1 1

// #. Etc. until we are left with this:
0 0 0 0 0 0
0 1 1 1 1 1
0 1 2 2 2 2
0 1 2 3 3 3

And in the second part of the code it will loop over this temp matrix, and sums all values of the input-matrix for each of the distinct numbers in the temp matrix.

Explanation of the code:

String c(int[][]a){               // Method with int-matrix parameter and String return-type
  int l=a.length,                 //  Amount of rows
      L=a[0].length,              //  Amount of columns
      b[][]=new int[l][L],        //  New temp matrix to fill as explained above
      i,j,x=1,s;                  //  Some temp integers

                                  //This is the first part of the code mentioned above:
  for(;x<(l>L?l:L);x++)           //  Loop (1) over the rows or columns (whichever is highest)
    for(i=l;i-->x;)               //   Inner loop (2) over the rows
      for(j=L;j-->x;              //    Inner loop (3) over the columns
        b[i][j]=x);               //     Set the current `x`-number
                                  //    End of loop (3) (implicit / no body)
                                  //   End of loop (2) (implicit / single-line body)
                                  //  End of loop (1) (implicit / single-line body)

                                  //This is the second part of the code mentioned above:
  String r="";                    //  Result-String
  for(;x-->0;                     //  Loop (4) over the unique numbers in the temp matrix
             r=s>0?s+" "+r:r)     //   After every iteration, append the sum to the result (if it's larger than 0)
    for(s=0,i=0;i<l;i++)          //   Inner loop (5) over the rows (and reset the sum to 0)
      for(j=0;j<L;j++)            //    Inner loop (6) over the columns
        s+=b[i][j]==x?a[i][j]:0;  //     Add to the sum if its position equals the current `x` in the temp matrix
                                  //    End of loop (6) (implicit / single-line body)
                                  //   End of loop (5) (implicit / single-line body)
                                  //  End of loop (4) (implicit / single-line body)
  return r;                       //  Return the result-String
}                                 // End of method

2

Perl 6, 63 55 bytes

{($_ Z [Z] $_).kv.map(->\a,\b{b.flatmap(*[a..*]).sum -b[0;a]})}

{($_ Z [Z] .skip).kv.map({$^b.flatmap(*[$^a..*]).sum})}
  • $_ is the matrix input to the anonymous function
  • .skip is the input matrix with its first row removed
  • [Z] .skip is the transpose of the input matrix with its first row removed; that is, the transpose without its first column
  • $_ Z [Z] .skip zips the input matrix with its transpose-sans-first-column, producing a list ((first-row, first-column-sans-first-element), (second-row, second-column-sans-first-element), ...)
  • .kv prefixes each pair with its index
  • map({...}) maps over the the pairs, using a function which takes its first argument (the index) in $^a and its second (the row/column pair) in $^b
  • $^b.flatmap(*[$^a..*]).sum strips off the first $^a elements of each row/column pair, then sums all the remaining elements

After some thought I realized that stripping off the first column of the transpose before zipping was equivalent to subtracting the doubly-contributing diagonal elements, as in my first solution. That let me delete that subtraction, and using each argument to the mapping function only once made the {...$^a...$^b...} method of passing arguments to an anonymous function more efficient than the original -> \a, \b {...a...b...}.


1

Vim, 66, 52 bytes

qq^f j<C-v>}dkV}Jo<esc>p@qq@q:%s/\v> +</+/g|%norm C<C-v><C-r>=<C-v><C-r>"<C-v><cr><cr>

Try it online!

The wrong tool for the job...


1

Jelly, 10 bytes

Ḣ;Ḣ€SṄȧßS¿

A full program that prints the values

Try it online!

How?

Ḣ;Ḣ€SṄȧßF¿ - Main link: list of lists a
Ḣ          - head a (pop the first row and yield it, modifying a)
  Ḣ€       - head €ach (do the same for each of the remaining rows)
 ;         - concatenate
    S      - sum (adds up the list that contains the top row and left column)
     Ṅ     - print that plus a linefeed and yield the result
         ¿ - while:
           - ... condition:
        F  -   flatten (a list of empty lists flattens to an empty list which is falsey) 
           - ... body:
       ß   -   call this link with the same arity (as a monad) i.e. Main(modified a)
      ȧ    - logical and (when the sum is non-zero gets the modified a to feed back in)

1

Python + NumPy, 75 bytes

Input is a 2D numpy array.

lambda L:[sum(L[i,i:])+sum(L[i+1:,i])for i in range(min(len(L),len(L[0])))]

Try it online



1

Pyth, 16 15 bytes

.es+>b+1k>@CQkk

Takes a python-style array of arrays of numbers, returns an array of sums.

Try it!

Explanation

.es+>b+1k>@CQkk 
.e             Q  # Enumerated map over the implicit input (Q); indices k, rows b
           CQ     # Take the transpose
          @  k    # The kth column
         >    k   # cut off the first k elements
    >b+1k         # cut off the first k+1 elements of the rows, so (k,k) isn't counted twice
  s+              # add the row and column together and sum

1

GNU APL 1.7, 123 bytes

Solution requires two functions: one creates a global array and the calls the second, which recursively appends the sums to that array.

∇f N
R←⍬
g N
R
∇
∇g N
→2+2×0∈⍴N
R←R,(+/N[1;])+(+/N[;1])-N[1;1]
g N[1↓⍳1⊃⍴N;1↓⍳2⊃⍴N]
∇

begins and ends the function. Both f and g take tables as arguments (essentially 2D arrays). These can be created with X←rows cols ⍴ 1 2 3 4....

R←⍬ assigns an empty vector to global variable R.

g N calls the second function with the same argument given to the first.

⍴N gives the dimensions of N; when one of the dimensions is zero, there are no more rows/columns to add up. 0∈⍴N returns 1 if there is a zero in the dimensions. →2+2×0∈⍴N branches to line number 2 plus 2 times the return value of the function: if there is no zero, returns 0 and the function branches to line 2 (the next line). If there is a zero, returns 1 and the function branches to line 4 (the end of the function, so return essentially).

/ is the reduce operator. It applies the left argument, which is an operator (+) to every element in the list given as the right argument. N[1;] gives the entire first row of the table and N[;1] gives the first column. (+/N[1;])+(+/N[;1])-N[1;1] sums the first row and column and subtracts the value in the upper left corner because it gets added both in the column sum and the row sum. R←R,... appends the newly calculated value to the global vector R.

The function then calls itself (recurse until no more rows or columns). The pick operator obtains the specified element from the list. 1⊃⍴N gives the number of rows, 2⊃⍴N the number of columns. gives all numbers from 1 to the specified number. The drop operator removes elements from the beginning of the list. If you give multiple indices when accessing elements from a table or vector (e.g. N[1 2 3]), APL accesses each one. Therefore, 1↓⍳1⊃⍴N gives the indices of each row excluding the first one (2, 3, 4, ..., N) and 1↓⍳2⊃⍴N gives a similar vector but for the columns. g N[1↓⍳1⊃⍴N;1↓⍳2⊃⍴N] calls the function again but without the first row or column.



0

Mathematica, 116 bytes

l=Length;If[l@#==1||l@#[[1]]==1,Total@Flatten@#,Total/@Flatten/@Table[{#[[i]][[i;;]],#[[All,i]][[i+1;;]]},{i,l@#}]]&

Input form

[{{5}}], [{{1},{4}}], [{{7,2}}] or [{{....},{....}...{....}}]


0

Clojure, 98 bytes

#(vals(apply merge-with +(sorted-map)(mapcat(fn[i r](map(fn[j v]{(min i j)v})(range)r))(range)%)))

Iterates over the input with row and column indexes (in a very verbose manner), creates a hash-map with the minimum of i and j as the key, merges hash-maps with + into a sorted-map, returns values.


0

R, 102 bytes

function(x)`for`(i,1:min(r<-nrow(x),k<-ncol(x)),{dput(sum(x[,1],x[1,-1]));x=matrix(x[-1,-1],r-i,k-i)})

returns an anonymous function; prints the results to the console, with a trailing newline. I probably need a different approach.

Iterates over the minimum of the rows and columns; prints the sum of x[,1] (the first column) and x[1,-1] the first row except for the first entry, then sets x to be a matrix equal to x[-1,-1] (i.e., x excluding its first row and column). Unfortunately, simply setting x=x[-1,-1] causes it to fail in the case of a square matrix, because when x is 2x2, the subsetting returns a vector rather than a matrix.

Try it online!


0

Java 7, 280 276 bytes

import java.util.*;String d(ArrayList l){String r="";for(;l.size()>0&&((List)l.get(0)).size()>0;l.remove(0))r+=s(l)+" ";return r;}int s(List<ArrayList<Integer>>l){int s=0,L=l.size(),i=1;for(;l.get(0).size()>0;s+=l.get(0).remove(0));for(;i<L;s+=l.get(i++).remove(0));return s;}

Try it here.

Alternative approach compared to my previous answer with arrays, which is still shorter than this one in the end (so I kinda wasted time trying this alternative approach).

General explanation:

Inspiration from @Riley's amazing 05AB1E answer
This answer uses a List and after every sum is calculated it removes the first column and first row from the List-matrix, like this:

// Starting matrix:
7 10 1
4 4  2
6 3  4
1 4  10
5 7  6

// After first iteration (result so far: "34 "):
4  2
3  4
4  10
7  6

// After second iteration (result so far: "34 20 "):
4
10
6

// After last iteration, result: "34 20 20 "

Explanation of the code:

import java.util.*;                // Required import for List and ArrayList

String d(ArrayList l){             //  Method with ArrayList parameter and String return-type
  String r="";                     //  Return-String
  for(;l.size()>0&&((List)l.get(0)).size()>0; 
                                   //  Loop as long as the list still contains anything
       l.remove(0))                //  And remove the first row after every iteration
    r+=s(l)+" ";                   //   Append the sum to the result-String
                                   //  End of loop (implicit / single-line body)
  return r;                        //  Return result-String
}                                  // End of method

int s(List<ArrayList<Integer>>l){  // Separate method with List-matrix parameter and integer return-type
  int s=0,                         //  The sum
      L=l.size(),                  //  The size of the input list
      i=1;                         //  Temp integer
  for(;l.get(0).size()>0;          //  Loop (1) over the items of the first row
    s+=l.get(0).                   //   Add the number to the sum
                remove(0)          //   And remove it from the list afterwards
  );                               //  End of loop (1)
  for(;i<L;                        //  Loop (2) over the rows
    s+=l.get(i++).                 //   Add the first number of the row to the sum
                  remove(0)        //   And remove it from the list afterwards
  );                               //  End of loop (2)
  return s;                        //  Return sum
}                                  // End of separate method

0

Python, 93 bytes

Similar to mbomb007's answer, but without NumPy

f=lambda m:[sum(m[k][k:])+sum(list(zip(*m))[k][k+1:])for k in range(min(len(m),len(m[0])))]
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.