28
\$\begingroup\$

This is a simple one: Take a matrix of integers as input, and output the index of the row with the most non-zero elements. You may assume that there will only be one row with the most non-zero elements.

Test cases:

These are 1-indexed, you may choose if you want 0 or 1-indexed.

1
0
row = 1
---
0  -1
0   0
row = 1
---
1   1   0   0   0
0   0   5   0   0
2   3   0   0   0
0   5   6   2   2
row = 4
---
0   4   1   0
0   0  -6   0
0   1   4  -3
2   0   0   8
0   0   0   0
row = 3
\$\endgroup\$
0

35 Answers 35

1
2
1
\$\begingroup\$

Python 2, 51 bytes

def f(x,i=0):print i;x[i].remove(0);f(x,-~i%len(x))

Try it online!

This version removes 0s progressively through the arrays, printing the current index, and crashes when there are no more zeros to remove. Last printed index is the answer.

Python 2, 57 bytes

lambda x,i=0:0in x[i]>x[i].remove(0)and f(x,-~i%len(x))|i

Try it online!

Wanted to try a different approach from what's already here. So here I recursively iterate over the array removing one 0 at a time until the current array no longer has any zeroes - and then output the index of that array.

\$\endgroup\$
1
\$\begingroup\$

Japt, 7 bytes

0-indexed. Takes input as an array of arrays.

mè
bUrw

Test it


Explanation

Implicit input of array U.
[[0,4,1,0],[0,0,-6,0],[0,1,4,-3],[2,0,0,8],[0,0,0,0]]

Map (m) over U returning the count of truthy (non-zero) elements in each sub-array. Implicitly assign this new array to U.
[2,1,3,2,0]

Urw

Reduce (r) array U by getting the greater of the current value and the current element.
3

b

Get the first index in U where the element equals that value and implicitly output the result.
2

\$\endgroup\$
1
\$\begingroup\$

Vyxal, 34 bitsv2, 4.25 bytes

vT@ÞM

Try it Online!

Bitstring:

1000101100100011101101110100011000

optimally encoded solution

\$\endgroup\$
0
\$\begingroup\$

Uiua, 7 bytes

⊢⍖/+≠0⍉

Try it!

⊢⍖/+≠0⍉
      ⍉  # transpose
    ≠0   # where is it not equal to zero?
  /+     # sum columns
⊢⍖       # index of maximum
\$\endgroup\$
0
\$\begingroup\$

Perl 5 -pa, 25 bytes

$;[grep$_,@F]=$.}{$\=pop@

Try it online!

\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.