g | x | w | all
Bytes Lang Time Link
016APLNARS250212T094736ZRosario
006Japt x240824T092859ZShaggy
050Haskell240825T152301Zmatteo_c
007Jelly240825T142645ZUnrelate
071Scala 3240825T003642Z138 Aspe
012Uiua240824T154539Znyxbird
007Vyxal240824T213729Zemanresu
011Uiua240824T202318ZjanMakos
057Python 2 60160719T145834ZJeremy
038Ruby rmatrix240824T162421ZJordan
037Wolfram Language Mathematica191113T022113Zatt
015Brachylog191111T102203ZUnrelate
024k4160723T022554ZAaron Da
048Matlab/Octave160720T145050ZSpamBot
021Actually160720T101159Zuser4594
010MATL160719T122926ZLuis Men
024R160720T074956Zplannapu
063Ruby160720T040535ZDavid Lj
059PHP160719T172040ZTitus
070Lua160719T154957ZLeaky Nu
012APL160719T151653ZLeaky Nu
043PowerShell v2+160719T151815ZAdmBorkB
010Jelly160719T144156ZLeaky Nu
014Pyth160719T142432ZLeaky Nu
020CJam160719T124809ZMartin E
046Retina160719T132314ZMartin E
046JavaScript160719T124213ZNeil
015J160719T125702Zmiles

APL(NARS), 16 chars

{+/⍵[⍸⍵=+/¨⍳⍴⍵]}

One possible solution a little differnt of othars use . The problem can be seen for all tensors, where case 2 dimensional matrix is a particular case...

This 18 chars solution is near the solution Iverson wrote

{+/(,⍵=+/¨⍳⍴⍵)/,⍵}

This below was a precedent try, 39 chars.

{0=×/a←⍴z←⍵:0⋄+/{z[⊂⍵]=k←+/⍵:k⋄0}¨,⍳a}

⍳a was the matrix of all the index of the matrix in right input of above function.

test:

  f←{+/⍵[⍸⍵=+/¨⍳⍴⍵]}
  f 0 0⍴ 1 2 3
0
  f 0 1⍴ 1 2 3
0
  f 2
0
  f ,1
1
  f 1 1 1⍴ 3 5 9 7
3
  f 3 3⍴1 5 2 9 4 2 5 9 6
10
  f 4 4⍴0 3 0 4 0 4 1 4 4 3 1 2 ¯2 4 ¯2 ¯1
11
  f 2 3⍴ 3 ¯1 3 3 3 ¯1 3 1
3

Japt -x, 7 6 bytes

0-indexed

ËfȶE°

Try it

ËfȶE°     :Implicit input of 2D-array
Ë          :Map each array at index E
 f         :  Filter by
  È        :  Passing each number through the following function
   ¶       :    Is equal to
    E°     :    Posfix incremented E
           :Implicit output of sum of resulting array

Haskell, 50 bytes

f x=sum[e|(i,r)<-z x,(j,e)<-z r,i+j==e];z=zip[0..]

Attempt This Online!

Jelly, 7 bytes

ŒJ§ḋ=¥Ẏ

Try it online!

ŒJ         All multidimensional indices in the input, in flat order.
  §        Sum them.
   ḋ       Dot product the sums with
    =¥     whether or not they equal corresponding elements of
      Ẏ    the input flattened.

Jelly, 7 bytes

ŒĖ§f/€S

Try it online!

ŒĖ         Multidimensional enumerate: list all [index, element] pairs.
  §        Vectorizing sum (sums the indices, but not the elements!).
    /€     For each pair,
   f       filter the index sum by equality to the element.
      S    Sum.

Scala 3, 71 bytes

m=>(for{i<-m.indices;j<-m(i).indices;if i+j==m(i)(j)}yield m(i)(j)).sum

Attempt This Online!

Uiua, 12 bytes

/+⊡⊚=≡≡/+°⊡.

Try it!

/+⊡⊚=≡≡/+°⊡.
           °⊡  # create an array with the indices for each element
       ≡≡/+    # sum each pair of indices
  ⊡⊚=       . # pick-where-equal
/+             # sum

Vyxal, 7 bytes

⁽∑€=*f∑

Try it Online!

  €     # Place at each position
⁽∑      # The sum of its coordinates
   =*   # Keep only those that are equal
     f∑ # Flatten and sum

Uiua, 11 bytes

⧻⊚×⊸=/+°⍉°⊡

Try it online!

Explanation

⧻⊚×⊸=/+°⍉°⊡

         °⊡ # matrix indices
     /+°⍉ # sum along final axis (i+j)
  ×⊸= # set non-equal elements to zero (boolean multiply)
⧻⊚ # positive-only matrix sum

Python 2 - 60 57 bytes

It's a code snippet, so it would be a few more bytes if I actually returned the value, I guess. e=enumerate;sum(i*(x+y==i)for x,r in e(a)for y,i in e(r))

Thanks for the help Leaky Nun :-)

Quick explanation. a is an array holding numbers. Simply iterate through indexes and sum up all values where the value equals the sum of the index.

Ruby -rmatrix, 38 bytes

Takes a Matrix object as input (m). (Alas, The space after _1 is required.)

m.each_with_index.sum{_2+_3==_1 ?_1:0}

Attempt This Online!

Wolfram Language (Mathematica), 42 37 bytes

Tr[Pick[#2,Tr@#,#2]&@@@ArrayRules@#]&

Try it online!

1-indexed.

                       ArrayRules@#     get (position->value)s
   Pick[#2,Tr@#,#2]&@@@                 keep values equal to sum(position)
Tr[                                ]    sum

Brachylog, 15 bytes

{iiʰI-ʰ=∧Ihh}ᶠ+

Try it online!

              +    The output is the sum of
{           }ᶠ     all possible results of
 i                 taking a row from the input with its index,
  i                taking an element with its index
   ʰ               from that row,
    I    Ihh       and outputting the element
       =∧          so long as the index of the row is equal to
     -ʰ            the value of the element minus its index within the row.

k4, 24 bytes

Assumes the matrix is stored in m.

+//7h$m*m=(!#m)+/:\:!#*m

This is one of those puzzles where the simplifications involved in designing k from APL (and J) really hurt—k’s ! is the equivalent of APL’s but only works on vectors, so I have to assemble the matrix of indices myself; inner product is one character in APL but five in k; and I lose three characters to handling the empty matrix properly because k doesn’t have strongly-typed matrices.

Matlab/Octave, 48 bytes

1-indexed.

Will not handle the first test case because [1:0] has size 1x0 for some reason

sum(sum(M.*(M-[1:size(M,1)]'-[1:size(M,2)]==0)))

Tested in Octave 3.

Full program:

M = [2]
sum(sum(M.*(M-[1:size(M,1)]'-[1:size(M,2)]==0)))
M = [1 5 2; 9 4 2; 5 9 6]
sum(sum(M.*(M-[1:size(M,1)]'-[1:size(M,2)]==0)))
M = [ 0 3  0  4; 0 4  1  4; 4 3  1  2;-2 4 -2 -1]
sum(sum(M.*(M-[1:size(M,1)]'-[1:size(M,2)]==0)))
M = [ 3 -1 3 3; 3 -1 3 1]
sum(sum(M.*(M-[1:size(M,1)]'-[1:size(M,2)]==0)))

Actually, 21 bytes

ñ`i╗ñ"i╜+@;(=*"£Mi`MΣ

Try it online!

Thanks to Leaky Nun for making me stop being lazy and finally write this.

This uses 0-indexed matrices, and takes input as a nested list.

Explanation:

ñ`i╗ñ"i╜+@;(=*"£Mi`MΣ
ñ                      enumerate input
 `i╗ñ"i╜+@;(=*"£Mi`M   for each (i, row) pair:
  i╗                     flatten, store i in register 0
    ñ                    enumerate the row
     "i╜+@;(=*"£M        for each (j, val) pair:
      i╜+                  flatten, add i to j
         @;(               make an extra copy of val, bring i+j back to top
            =              compare equality of i+j and val
             *             multiply (0 if not equal, val if they are)
                 i       flatten the resulting list
                    Σ  sum the values

MATL, 15 14 10 bytes

3#fbb+y=*s

The input has rows separated by ;. For example: [1 5 2; 9 4 2; 5 9 6]. 1-based indexing is used.

Try it online! Or verify all test cases.

Explanation

I'll use the example with input [3 -1 3 3; 3 -1 3 1] in the explanation.

3#f    % Three-output find: for all nonzero values of implicit input matrix, pushes
       % three column vectors with row indices, column indices, and values
       %   Stack contains: [1;2;1;2;1;2;1;2], [1;1;2;2;3;3;4;4], [3;3;-1;-1;3;3;3;1]
bb     % Bubble up twice: move vectors of row and column indices to top
       %   Stack contains: [3;3;-1;-1;3;3;3;1], [1;2;1;2;1;2;1;2], [1;1;2;2;3;3;4;4]
+      % Element-wise sum of top two arrays
       %   Stack contains: [3;3;-1;-1;3;3;3;1], [2;3;3;4;4;5;5;6]
y      % Duplicate the vector of nonzero values onto the top of the stack
       %   Stack contains: [3;3;-1;-1;3;3;3;1], [2;3;3;4;4;5;5;6], [3;3;-1;-1;3;3;3;1] 
=      % Element-wise equality test of top two arrays
       %   Stack contains: [3;3;-1;-1;3;3;3;1], [0;1;0;0;0;0;0;0]
*      % Element-wise multiply of top two arrays
       %   Stack contains: [0;3;0;0;0;0;0;0]
s      % Sum of array
       %   Stack contains: 3

R, 24 bytes

sum(M[M==row(M)+col(M)])

1-based.
Test cases:

> M<-matrix(nrow=0,ncol=0)
> M
<0 x 0 matrix>
> sum(M[M==row(M)+col(M)])
[1] 0
> M<-matrix(2,nrow=1,ncol=1)
> M
     [,1]
[1,]    2
> sum(M[M==row(M)+col(M)])
[1] 2
> M<-matrix(c(1,9,5,5,4,9,2,2,6),nrow=3)
> M
     [,1] [,2] [,3]
[1,]    1    5    2
[2,]    9    4    2
[3,]    5    9    6
> sum(M[M==row(M)+col(M)])
[1] 10
> M<-matrix(c(0,0,4,-2,3,4,3,4,0,1,1,-2,4,4,2,-1),nrow=4)
> M
     [,1] [,2] [,3] [,4]
[1,]    0    3    0    4
[2,]    0    4    1    4
[3,]    4    3    1    2
[4,]   -2    4   -2   -1
> sum(M[M==row(M)+col(M)])
[1] 11
> M<-matrix(c(3,3,-1,-1,3,3,3,1),nrow=2)
> M
     [,1] [,2] [,3] [,4]
[1,]    3   -1    3    3
[2,]    3   -1    3    1
> sum(M[M==row(M)+col(M)])
[1] 3

Ruby, 63 bytes

With z as a two-dimensional array of numbers:

s=0;z.each_index{|i|z[i].each_index{|j|s+=i+j if z[i][j]==i+j}}

Not terribly exciting at all.

If z is a flattened array with x and y having the sizes of the arrays, such as:

x=z.size
y=z[0].size
z=z.flatten

Then we have this monstrousity - perhaps more ruby-ish with it's fancy products and zips, but actually larger:

(1..x).to_a.product((1..y).to_a).zip(z).inject(0){|s,n|s+(n[0][0]+n[0][1]==n[1]+2?n[1]:0)}

PHP, 59 bytes

foreach($a as$y=>$r)foreach($r as$x=>$v)$s+=($v==$x+$y)*$v;

expects array $a defined; must be empty or 2-dimensional, 0-indexed.
calculates sum to $s (previously 0 or undefined - 0 equals NULL)
insert +2 before final ) for 1-indexed behaviour

Happy Birthday APL!

functions and test suite

function f0($a) { foreach($a as$y=>$r)foreach($r as$x=>$v)$s+=($v==$x+$y)*$v;return $s|0; }
function f1($a) { foreach($a as$y=>$r)foreach($r as$x=>$v)$s+=($v==$x+$y+2)*$v;return $s|0;}
$samples = [
    [], 0, 0,
    [[2]], 0, 2,
    [[1,5,2],[9,4,2],[5,9,6]], 2, 10,
    [[0,3,0,4],[0,4,1,4],[4,3,1,2],[-2,4,-2,-1]],11,11,
    [[3,-1,3,3],[3,-1,3,1]],6,3
];
function test($x,$e,$y){static $h='<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';echo"$h<tr><td>",out($x),'</td><td>',out($y),'</td><td>',out($e),'</td><td>',cmp($e,$y)?'N':'Y',"</td></tr>";$h='';}
while($samples)
{
    $a=array_shift($samples);
    test($a,'B0:'.array_shift($samples),'B0:'.f0($a));
    test($a,'B1:'.array_shift($samples),'B1:'.f1($a));
}

Lua, 70 bytes

1-indexed.

s=0 for i=1,#a do for j=1,#a[i]do s=i+j==a[i][j]and s+i+j or s end end

Bonus: it works for ragged arrays!

Input stored in a, output stored in s.

Full program:

function Dijkstras_Challenge(a)
    s=0 for i=1,#a do for j=1,#a[i]do s=i+j==a[i][j]and s+i+j or s end end
    print(s)
end

Dijkstras_Challenge({})
Dijkstras_Challenge({{2}})
Dijkstras_Challenge({{1,5,2},{9,4,2},{5,9,6}})
Dijkstras_Challenge({{0,3,0,4},{0,4,1,4},{4,3,1,2},{-2,4,-2,-1}})
Dijkstras_Challenge({{3,-1,3,3},{3,-1,3,1}})

APL, 13 12 bytes

1 byte thanks to @jimmy23013.

1-indexed.

The array is stored in the variable m.

+/,m×m=+/¨⍳⍴m
+/∊m∩¨+/¨⍳⍴m

Try it online!

Based on the answer in J, which is a language based on APL.

In TryAPL, to key in: +/m`em`c`1+/`1`i`rm

With the array: +/m`em`c`1+/`1`i`rm `[ 2 4 `r 3 `21 3 3 3 `21 3 1

Explanation

+/∊m∩¨+/¨⍳⍴m
           m    temp ← variable
          ⍴     temp ← shape of temp
         ⍳      temp ← a 2D array where each element is
                       the corresponding index. for the
                       example, this gives:
                       ┌───┬───┬───┬───┐
                       │1 1│1 2│1 3│1 4│
                       ├───┼───┼───┼───┤
                       │2 1│2 2│2 3│2 4│
                       └───┴───┴───┴───┘
      +/¨       each element in temp ← its sum
   m∩¨          temp ← intersect each element in temp with the variable
+/              temp ← sum of temp

PowerShell v2+, 43 bytes

%{$j=0;$_|%{$o+=$_*($_-eq$i+$j++)};$i++};$o

As a snippet. Usage is to explicitly pipe the matrix to this (see examples below). Assumes that $i, and $o are either null or zero at the start (I've explicitly set them as such in the examples below), and utilizes 0-index.

Does a foreach loop on each row of the matrix. We set $j to 0, and then go through each element of the row in another loop $_|%{...}. Each inner loop, we increment $o by the current element multiplied by a Boolean ($_-eq$i+$j++), meaning if that Boolean is $TRUE, it'll be 1, otherwise 0. Then we exit the inner loop, increment $i, and start the next row. Finally, we leave $o on the pipeline at the end.

Examples

PS C:\Tools\Scripts\golfing> $o=0;$i=0;$j=0;@(@(3,-1,3,3),@(3,-1,3,1))|%{$j=0;$_|%{$o+=$_*($_-eq$i+$j++)};$i++};$o
6

PS C:\Tools\Scripts\golfing> $o=0;$i=0;$j=0;@(@(0,3,0,4),@(0,4,1,4),@(4,3,1,2),@(-2,4,-2,-1))|%{$j=0;$_|%{$o+=$_*($_-eq$i+$j++)};$i++};$o
11

Jelly, 15 14 10 bytes

4 bytes thanks to Adnan.

1-indexed.

L€R€+"LR$=³×³FS
L€R€+"LR$=׳FS
J€+"J=×⁸FS

Try it online!

Verify all testcases at once. (Slightly modified.)

Pyth, 14 bytes

0-indexed.

ss.e.e*ZqZ+kYb

Test suite.

CJam, 23 21 20 bytes

Thanks to Peter Taylor for saving 3 bytes.

ee{~_@f-_,,.=.*~}%1b

Expects the matrix to be on the stack and leaves the sum instead. Indices are zero-based in either case.

Test it here.

Retina, 46 bytes

Byte count assumes ISO 8859-1 encoding.

\d+
$*
M!`(?<=(\S* |.*¶)*)(?<-1>1)+\b(?(1)1)
1

Input uses space and linefeed separators to represent the matrix. Indices are 0-based.

Try it online!

Explanation

Not quite the kind of challenge Retina was made for, but it's doing surprisingly well... :)

Stage 1: Substitution

\d+
$*

This simply expands all the integers in the string as unary numbers using 1 as the unary digit. Negative numbers like -3 will simply become things like -111.

Stage 2: Match

M!`(?<=(\S* |.*¶)*)(?<-1>1)+\b(?(1)1)

Due to the ! option, this prints all the matches of the given regex. Said regex uses balancing groups to check whether the current number is the same as the sum of its indices.

To do that, we first determine the sum of indices with the lookbehind (?<=(\S* |.*¶)*). This adds one capture for each number in front of the current one on the same line (via \S* ) as well as one capture for each line in front of the current one (via .*¶) to group 1. Hence, we get the zero-based sum of indices as a result.

Then we try to match the entire next number while removing captures from this stack with (?<-1>1)+\b. And then we make the match fail if any captures are left on group 1 with (?(1)1) to ensure equality.

Note that negative numbers are never matched, because the lookbehind cannot get past the - in front of list of 1s and the (?<-1>1)+ can't match it either.

This gives us a list of all the unary numbers which equal the sum of their indices.

Stage 3: Match

1

We end with another match stage, but without the ! option, this just counts the number of matches, which both sums all the unary numbers from the previous result and also converts that sum back to decimal.

JavaScript, 49 46 bytes

a.map((b,i)=>b.map((c,j)=>r+=c==i+j&&c),r=0)|r

Edit: Saved 3 bytes thanks to @MartinEnder pointing out that snippets are allowed.

J, 15 bytes

+/,M*M=+/&i./$M

Uses zero-based indexing and assumes the matrix is already stored in variable M.

Explanation

+/,M*M=+/&i./$M
             $a  Get the shape of M
            /    Insert between the shape
         &i.     Create a range from 0 to each end exclusive
       +/        Forms a table which is the sum of each row and column index
     M=          1 if the element is equal to its index sum else 0
   M*            Multiply by their values
  ,              Flatten
+/               Reduce using addition to get the sum