Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

Return to Answer

added 689 characters in body
Source Link
Luis Mendo
  • 106.7k
  • 10
  • 139
  • 382

MATL, 9 bytes

tQ!=&f-|s

Try it online! Or verify all test cases.

How it works

Consider input [2 9 3 6 8 1] as an example.

tQ % Implicit input. Duplicate, add 1; element-wise
 % STACK: [2 9 3 6 8 1], [3 10 4 7 9 2]
! % Transpose
 % STACK: [2 9 3 6 8 1], [3; 10; 4; 7; 9; 2]
= % Test for equality (element-wise with broadcast)
 % STACK: [0 0 1 0 0 0;
 0 0 0 0 0 0;
 0 0 0 0 0 0;
 0 0 0 0 0 0;
 0 1 0 0 0 0;
 1 0 0 0 0 0]
&f % Two-output find: row and column indices of nonzeros
 % STACK: [6; 5; 1], [1; 2; 3]
-| % Minus, absolute value (element-wise)
 % STACK: [5; 3; 2]
s % Sum. Implicit display
 % STACK: 10

MATL, 9 bytes

tQ!=&f-|s

Try it online! Or verify all test cases.

MATL, 9 bytes

tQ!=&f-|s

Try it online! Or verify all test cases.

How it works

Consider input [2 9 3 6 8 1] as an example.

tQ % Implicit input. Duplicate, add 1; element-wise
 % STACK: [2 9 3 6 8 1], [3 10 4 7 9 2]
! % Transpose
 % STACK: [2 9 3 6 8 1], [3; 10; 4; 7; 9; 2]
= % Test for equality (element-wise with broadcast)
 % STACK: [0 0 1 0 0 0;
 0 0 0 0 0 0;
 0 0 0 0 0 0;
 0 0 0 0 0 0;
 0 1 0 0 0 0;
 1 0 0 0 0 0]
&f % Two-output find: row and column indices of nonzeros
 % STACK: [6; 5; 1], [1; 2; 3]
-| % Minus, absolute value (element-wise)
 % STACK: [5; 3; 2]
s % Sum. Implicit display
 % STACK: 10
Source Link
Luis Mendo
  • 106.7k
  • 10
  • 139
  • 382

MATL, 9 bytes

tQ!=&f-|s

Try it online! Or verify all test cases.

AltStyle によって変換されたページ (->オリジナル) /