최대 막심!


11

이 질문에서 영감을 얻어 Luis Mendo가 개선했습니다 .

도전

정수의 2D 행렬이 주어지면 각 행에는 최대 값이 있습니다. 각 행의 하나 이상의 요소는 해당 행의 최대 값과 같습니다. 목표는 열마다 발견 된 행별 최대 값뿐만 아니라 각 행의 최대 값과 동일한 항목을 포함하는 열을 결정하는 것입니다.

입력

  • 입력은 선택한 언어에 적합한 형식 으로 비어 있지 않은 Mx N행렬 ( M> 0 및 N> 0)이됩니다.

산출

  • 프로그램은 최대 행 단위 최대 수 (별도의 값 또는 목록)를 포함하는 각 열의 색인 을 리턴해야합니다 . 0 또는 1 기반 색인을 사용할 수 있습니다 (설명에 지정).
  • 또한 프로그램은이 열에 존재하는 최대 값 (단일 숫자)을 반환해야합니다.
  • 출력 순서 / 형식은 유연하지만 답변과 함께 제공되는 텍스트로 설명해야합니다.

추가 정보

  • 입력 행렬의 모든 항목은 양의 정수입니다.
  • 행의 최대 값이 해당 행의 여러 요소에 의해 공유되면 해당 값의 모든 항목이 해당 열의 총계로 계산됩니다.
  • 여러 열에 동일한 수의 최대 값 이 포함 된 경우이 수의 최대 값을 가진 모든 열 목록을 반환해야합니다 .

입력 고려

 7  93
69  35
77  30     

1 행에는 최대 2, 즉 2 열에서 발생하는 최대 93이 있습니다. 2 행 : 1 열에서 발생합니다. 따라서 출력은입니다 [1] [2]. 입력을 다음으로 변경하면

 7  93
69  35
77  77

[1 2] [2]두 열의 최대 값이 2이므로 출력은 입니다.

테스트 사례

input                 =>    output ( [1-based index array], [nMaxima] )
----------------------------------------------
 7  93
69  35                =>    [1], [2]
77  30

 7  93
69  35                =>    [1 2], [2]
77  77     

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

16   2   3  13
 5  11  10   8        =>    [1  2  4], [1]
 9   7   6  12    

 1   1   1   1        =>    [1  2  3  4], [1]

25   6  13  25        =>    [1  4], [1]

1
2
3                     =>    [1], [4] 
4

100                   =>    [1], [1]

채점

이것은 바이트 단위의 가장 짧은 코드가 승리하는 입니다. Tiebreaker는 이전 답변으로갑니다.

리더 보드

아래는 모든 항목을 분석하기위한 스택 스 니펫입니다.


7
재미있는 사실; 네덜란드 여왕은 Maxima라고 불리므로 기술적으로 우리는 1 Maxima 만 가질 수 있습니다.
Bassdrop Cumberwubwubwub

1
재미있는 사실; Maxima 라는 오픈 소스 CAS도 있습니다 .
flawr

답변:


3

젤리 , 9 바이트

="Ṁ€SµM,Ṁ

입력은 2D 목록이고 출력은 한 쌍입니다. 1부터 시작하는 인덱스 목록과 최대 최대 값입니다.

온라인으로 사용해보십시오! 또는 모든 테스트 사례를 확인하십시오 .

작동 원리

="Ṁ€SµM,Ṁ  Main link. Argument: M (matrix)

  Ṁ€       Apply maximum to each row.
="         Zipwith equal; compare the entries of the nth row with its maxmium.
    S      Sum; reduce across columns to count the maxima in each row.
     µ     Begin a new, monadic link. Argument: A (list of maxima)
      M    Yield all indices with maximal value.
        Ṁ  Yield the maximum of A.
       ,   Pair the results to both sides.

3

J, 27 바이트

((I.@:=;])>./)@(+/@:=>./"1)

이것은 두 번째 예의 경우 다음과 같이 사용되는 모나 딕 동사입니다.

   f =: ((I.@:=;])>./)@(+/@:=>./"1)
   m =: 3 2 $ 7 93 69 35 77 77
   f m
+---+-+
|0 1|1|
+---+-+

출력은 두 개의 상자로 구성되며 0 기반 색인을 사용합니다. 여기 사용해보십시오!

설명

((I.@:=;])>./)@(+/@:=>./"1)  Input is m.
(            )@(          )  Composition: apply right hand side, then left hand side.
                     >./"1   Take maximum of each row of m.
                    =        Replace row maxima by 1 and other values by 0,
                +/@:         then take sum (number of maxima) on each column.
                             The result is the array of number of row maxima in each column.
          >./                Compute the maximum of this array
 (     ;])                   and put it in a box with
  I.@:=                      the indices of those entries that are equal to it.

3

MATL, 17 바이트

vH3$X>G=XstX>tb=f

첫 번째 출력은 최대 최대 값 수이고 두 번째 출력은 이것이 발생한 열입니다 (1 기반 색인 생성).

온라인으로 사용해보십시오!

설명

v       % Vertically concatenate everything on the stack (nothing), yields []
        % Implicitly grab the input
H       % Push the number 2 to the stack
3$X>    % Compute the maximum value of each row (along the second dimension)
G       % Explicitly grab input again
=       % Compare each row of the input to the row-wise max (automatically broadcasts). 
Xs      % Sum the number of matches in each column
t       % Duplicate the array
X>      % Determine the max number of maxima in all columns
t       % Duplicate this value
b=f     % Find the index of the columns which had the maximum number of maxima
        % Implicitly display stack contents

3

MATL , 17 바이트

!tvX>!G=5#fFTT#XM

입력은 행을 세미콜론으로 구분하여 2D 배열입니다. 테스트 케이스의 입력은

[7 93; 69 35; 77  30]
[7 93; 69 35; 77  77]
[1 2 3 4; 5 6 7 8]
[16 2 3 13; 5 11 10 8; 9 7 6 12]
[1 1 1 1]
[25 6 13 25]
[1; 2; 3; 4]
[100]

출력은 다음과 같습니다. 먼저 최대 최대량을 계산 한 다음 하나 이상의 열 인덱스를 표시합니다.

온라인으로 사용해보십시오!

설명

이것은 Suever의 답변 과 다른 접근법을 사용합니다 .

먼저 논리 값 ( truefalse) 의 행렬 이 계산되며 여기서 true행 최대 값이 있음을 나타냅니다. 그런 다음 true값 의 열 인덱스가 벡터로 추출됩니다. 마지막으로, 가장 빈번한 모든 값 (원하는 열 인덱스)과 함께 해당 벡터의 모드가 계산됩니다 (최대 값의 최대 값).

!        % Implicit input. Transpose
tv       % Duplicate. Concatenate vertically. This forces next function (max)
         % to work along columns even if input is a row vector
X>       % Maximum of each column (gives row vector)
!        % Transpose into column vector
G        % Push input again
=        % Test for equality, with broadcast. Gives matrix of true and false
5#f      % Column indices of true values, as a column vector
FTT#XM   % Mode of that vector, and all values that occur maximum number of times
         % Implicit display

3

Pyth, 20 19 17 바이트

@Suever 덕분에 1 바이트 .

@Jakube 덕분에 1 바이트 .

{MC.MhZrSsxLeSdQ8

테스트 스위트.

출력은 0 인덱스입니다.

주문이 취소되었습니다.

모든 입력

[[7,93],[69,35],[77,30]]
[[7,93],[69,35],[77,77]]
[[1,2,3,4],[5,6,7,8]]
[[16,2,3,13],[5,11,10,8],[9,7,6,12]]
[[1,1,1,1]]
[[25,6,13,25]]
[[1],[2],[3],[4]]
[[100]]

모든 출력

[[2], [0]]

[[2], [0, 1]]

[[2], [3]]

[[1], [0, 1, 3]]

[[1], [0, 1, 2, 3]]

[[1], [0, 3]]

[[4], [0]]

[[1], [0]]

작동 원리

{MC.MhZrSsxLeSdQ8

               Q   Yield input.
           L       For each array in input (as d):
            eSd      Yield maximum of d.
          x          Yield the 0-indexed indices of the maximum in d.
         s          Flatten.
        S           Sort.
       r         8  Run-length encoding.
                    Now the array is:
                      [number of maxima in column, index of column]
                      for all the columns
   .MhZ             Yield the sub-arrays whose first element is maximum.
                     The first element of each sub-array
                     is "number of maxima in column".
                     Now the array is:
                       [number of maxima in column, index of column]
                       for all the required columns
  C                 Transpose.
                    Now the array is:
                      [[number of maxima in each column],
                       [index of each required column]]
                    Note that every element in the
                    first sub-array is the same.
{M                  Deduplicate each.

3

CJam , 38 35 31 바이트

@quartata의 도움으로 @FryAmTheEggMan 덕분에 2 바이트가 줄었습니다. 4 바이트를 더 제거 한 @Dennis에게도 감사드립니다.

q~_::e>.f=:.+_:e>_@f{=U):Ua*~}p

입력은 형식입니다

[[7 93] [69 35] [77 77]]

출력은 1 기반 열 인덱스와 숫자의 배열입니다.

온라인으로 사용해보십시오!


q~_::e>.f=:.+_:e>_@f{=U):Ua*~}p몇 바이트를 절약합니다. 코드 블록으로 바꾸면 1이 더 절약됩니다.
Dennis

@Dennis 감사합니다! 이제 무엇을 이해해야 {=U):Ua*~}합니까?
Luis Mendo


2

파이썬 2, 106 바이트

x=map(sum,zip(*[map(max(r).__eq__,r)for r in input()]))
m=max(x);print[i for i,n in enumerate(x)if n==m],m

입력은 2D 부동 소수점 목록이고 출력은 쌍 (0 기반 색인 및 정수)의 쌍입니다.

Ideone에서 테스트하십시오 .



1

자바 스크립트 (ES6), 111 바이트

a=>[m=Math.max(...a=a[0].map((_,i)=>a.map(a=>c+=a[i]==Math.min(...a),c=0)|c)),[...a.keys()].filter(i=>a[i]==m)]

두 요소의 배열을 반환합니다. 첫 번째는 최대의 최대 개수이고, 두 번째는 해당 개수의 인덱스가없는 열의 배열입니다.


1

옥타브, 47 46 바이트

@(r){m=max(s=sum(r==max(r,0,2),1)),find(s==m)}

그러면 자동으로 자신을 할당하고을 ans사용하여 실행할 수 있는 익명 함수가 생성됩니다 ans([1 2 3; 4 5 6]). 첫 번째 요소는 최대 최대 수이고 두 번째 요소는 이러한 최대 값을 포함하는 열의 1 기반 인덱스입니다.

모든 테스트 사례


1

파이썬 3, 142 바이트

여기의 알고리즘은 기본적으로 각 행을 통과하고 해당 행의 최대 값을 갖는 열의 점수를 증가시킵니다. 그런 다음 최대 점수를 찾아 해당 최대 점수가있는 열을 찾아 반환하십시오. 열은 1- 인덱싱됩니다. 나는 이것을 람다로 한 줄로 시도했지만 열별로 점수를 생성하면 153 바이트였습니다.

def f(r):
    s=[0]*len(r[0]);e=enumerate
    for x in r:
        for i,j in e(x):
            s[i]+=(0,1)[j==max(x)]
    m=max(s);return[i+1for i,j in e(s)if j==m],m

테스트 사례

x=[[7, 93],
[69, 35],              
[77, 30]]

print(f(x)) #=>    [[1], 2]

x=[[ 7, 93],
[69, 35],             
[77, 77]]    

print(f(x)) #=>    [[1 2], 2]

x=[[1,  2,   3,  4],        
[5,  6,  7,  8]]

print(f(x)) #=>    [[4], 2]

x=[[16,  2,  3, 13],
 [5, 11, 10,  8],      
 [9,  7, 6, 12]]

print(f(x)) #=>    [[1  2  4], 1]

x=[[1,  1,  1,  1]]      

print(f(x)) #=>    [[1  2  3  4], 1]

x=[[25,   6,  13,  25]]        

print(f(x)) #=>    [[1  4], 1]

x=[[1],
[2],
[3],                   
[4]]

print(f(x)) #=>    [[1], 4] 

x=[[100]]                   

print(f(x)) #=>    [[1], 1]

1

클로저, 150 바이트

(fn[M](let[F(dissoc(frequencies(mapcat(fn[r](map-indexed #(if(=(apply max r)%2)%)r))M))nil)m(apply max(vals F))][(map first(filter #(#{m}(% 1))F))m]))

긴 사람, 나는 이것이 많이 단순화 될 수 있다고 생각했습니다. 적어도 올바른 출력을 생성합니다.

[(f [[ 7  93][69  35][77  30]])
 (f [[ 7  93][69  35][77  77]])
 (f [[16   2   3  13][5  11  10   8][9   7   6  12]])]

[[(0) 2] [(1 0) 2] [(0 1 3) 1]]

1

05AB1E , 14 (또는 12) 바이트

εZQ}øOZ©Qƶ0K®‚

형식의 출력 [[1-indexed columns-list], maxima] .

온라인으로 시도 하거나 모든 테스트 사례를 확인하십시오 .

품목이 허용 된 경우 0열 목록에 무시할 수있는 을 하는 경우 0K다음 을 제거하여 2 바이트를 줄일 수 있습니다 .

온라인으로 시도 하거나 모든 테스트 사례를 확인하십시오 .

설명:

ε               # Map each row in the (implicit) input-matrix:
 Z              #  Get the maximum of the row (without popping)
  Q             #  Check for each value in this row if its equal to the row-maximum
              # After the map: zip/transpose the matrix; swapping rows/columns
     O          # Take the sum of each inner list (the truthy/falsey values of the columns)
      Z         # Get the maximum column-sum (without popping)
       ©        # Store it in the register (without popping)
        Q       # Check for each column-sum if its equal to this maximum
         ƶ      # Multiply each truthy/falsey value in the list by its 1-based index
          0K    # Remove all 0s
            ®‚  # Pair the resulting list with the maximum we stored in the register
                # (and output the result implicitly)
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.