최대 편차 찾기


20

이 문제는 Quora (코드 골프는 아님)에 대해 처음에 제기 된 질문에서 "영감"됩니다 . 나는 당신들 (그리고 나의 첫 번째 문제 제출)에게 도전하기를 원합니다.

정수 요소의 배열 v과 정수 d(d가 배열의 길이와 같거나 같다고 가정)를 가정하면 배열에서 d연속 요소 의 모든 시퀀스를 고려하십시오 . 각 시퀀스에 대해 해당 시퀀스에있는 요소의 최대 값과 최소값의 차이를 계산하고 편차의 이름을 지정합니다.

당신의 임무는 위에서 고려한 모든 시퀀스의 모든 편차 중에서 최대 값을 계산하는 프로그램이나 함수를 작성하고 그 값을 반환하거나 출력하는 것입니다.

실습 예제 :

v: (6,9,4,7,4,1)
d: 3

The sequences of length 3 are:
6,9,4 with deviation 5
9,4,7 with deviation 5
4,7,4 with deviation 3
7,4,1 with deviation 6

Thus the maximal deviation is 6, so the output is 6.

이것은 코드 골프이므로 바이트 단위의 최단 답변이 이깁니다.

답변:


14

Dyalog APL, 7 바이트

⌈/⌈/-⌊/

TryAPL에서 테스트하십시오 .

작동 원리

⌈/⌈/-⌊/  Dyadic chain. Left argument: d. Right argument: v

     ⌊/  Reduce v by d-wise minimum, yielding the minima of all slices of length d.
  ⌈/     Reduce v by d-wise maximum, yielding the maxima of all slices of length d.
    -    Subtract, yielding the ranges of all slices of length d.
⌈/       Take the maximum.

5

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

with(Math)(v,d)=>max(...v.map((a,i)=>max(...a=v.slice(i,i+d))-min(...a)))

with전체 람다 함수에서 사용할 수있는 TIL +1
Bassdrop Cumberwubwubwub

실제로 Uncaught SyntaxError: Unexpected token with. 작동하는 스 니펫을 게시 할 수 있습니까?
Bassdrop Cumberwubwubwub

@BassdropCumberwubwubwub 람다의 이름을 지정하려면 할당 뒤에을 입력하거나을 with(Math)사용해야 f=eval("with(Math)(v,d)=>max(...a)))")합니다.
Neil

4

파이썬, 60 바이트

Neil 덕분에 5 바이트 절약

f=lambda v,d:v and max(max(v[:d])-min(v[:d]),f(v[1:],d))or 0

내 첫 재귀 람다!

용법:

print f([6,9,4,7,4,1], 3)

1
나는 당신이 그냥 사용할 수 있다고 생각합니다 v and; 요소를 제거해도 범위가 올라가지 않습니다.
Neil

4

펄, 48 바이트

에 +5 포함 -0pi

-i옵션 뒤에 너비를 지정하고 STDIN에서 요소를 별도의 선으로 제공하십시오.

perl -0pi3 -e '/(^.*\n){1,$^I}(?{\$F[abs$1-$&]})\A/m;$_=$#F'
6
9
4
7
4
1
^D

코드 만 :

/(^.*\n){1,$^I}(?{\$F[abs$1-$&]})\A/m;$_=$#F

( \n클레임 된 점수에 리터럴 사용 )


정규식을 본 다음 길을 잃습니다. 0.0 무슨 일이야?
애디슨 크럼

@VTCAKAVSMoACE 기본적으로 나는 1에서 너비의 연속적인 줄을 찾습니다. $&산술 컨텍스트에서 첫 번째 숫자로 평가되는 전체 일치를 포함합니다. $1마지막 숫자를 포함합니다. 그런 다음와 함께 정규 표현식을 강제로 실패합니다 \A. 따라서 모든 시작 위치와 길이를 최대 너비까지 시도합니다. 차이의 절대 값을 배열 인덱스로 사용하고 배열이 얼마나 커지는 지 확인합니다. 펄은 내장이 없어서 max즉흥적으로해야합니다
Ton Hospel

그것은 매우 영리합니다. 당신은 넣을 수 있습니다 어떤 방법 -0pi3 -e으로 -0pi3e? 가능한 감소에 대한 가정, 나는 perl을 사용하지 않습니다 (따라서 내 질문).
애디슨 크럼

@VTCAKAVSMoACE 불행히도. -i어떤 포함한 값으로 그 이후에 먹는 모든 것을e
톤 Hospel

그리고 나는 그것이 -e코드 바로 전에 가야 한다고 가정하고 있습니까? 버머.
애디슨 크럼

4

R, 63 62 56 바이트

Billywob은 이미 기본 기능만을 사용하여 훌륭한 R 답변을 제공했습니다 . 그러나 R의 광범위한 패키지를 사용하여 대체 방법이 가능한지 알고 싶었습니다. 패키지에는 배열의 롤링 창에 함수를 적용하도록 설계된 멋진 기능 rollapplyzoo있으므로 목적에 잘 맞습니다. 우리 는 각 창 rollapply을 찾기 위해 max사용하고 다시 min각 창 을 찾기 위해 사용합니다 . 그런 다음 최대 값과 최소값의 차이를 취하여 각 창에 대한 편차를 얻은 다음 그 값을 반환합니다 max.

function(v,d)max((r=zoo::rollapply)(v,d,max)-r(v,d,min))

1
좋아요, 하위 시퀀스를 생성하는 기능이 있지만 그것을 찾을 수 없다는 것을 알았습니다. 또한 직장에서 프록시 뒤에 있으므로 외부 패키지를 사용할 수 없습니다.
Billywob

1
일부 인터넷 검색은 나에게도 있음을 알려주지 gtools::rolling만 바이트가 하나 더 있고 익숙하지 않습니다. 나는 기본 패키지가 아닌 패키지를 사용하는 것에 대해 항상 두 가지 생각을하고있다. 반면에 패키지와 커뮤니티는 언어로서 R의 강점 중 하나라고 생각합니다.
rturnbull

3

R, 80 77 바이트 바이트

편집 : @rturnbull 덕분에 3 바이트가 절약되었습니다.

function(s,d)max(sapply(d:sum(1|s)-d+1,function(i)diff(range(s[i:(i+d-1)]))))

1
당신은 대체 할 수 있습니다 1:(length(s)-d+1)d:sum(1|s)-d+1.
rturnbull

@rturnbull 멋진 캐치!
Billywob

2

PowerShell v2 +, 68 바이트

param($v,$d)($v|%{($x=$v[$i..($i+++$d-1)]|sort)[-1]-$x[0]}|sort)[-1]

반복 솔루션. 반복 $v하지만 실제로는 실제로 값을 통과하기보다는 카운터로 사용합니다. 반복 할 때마다, 우리는 슬라이스있어 $v$i..($i+++$d-1), $i기본값 0. 우리는 |sort그 요소들을 가지고 결과를에 저장합니다 $x. 그리고 우리는 가장 큰 취할 [-1]가장 작은을 뺍니다 [0]. 그런 다음 |sort그 결과를 최대한 활용합니다 [-1]. 이 숫자는 파이프 라인에 남아 있고 출력은 암시 적입니다.

PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(6,9,4,7,4,1) 3
6

PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(1,2,3,4,5,6) 3
2

PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(7,2,3,4,5,6) 3
5

2

05AB1E , 12 10 바이트

CP-1252 인코딩을 사용합니다 .

Œù€{øÀ`-ÄZ

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

설명

Π             # sublists of v
 ù             # of length d
  €{           # sort each
    ø          # zip
     À         # rotate left (last 2 lists will be largest and smallest)
      `        # flatten (lists with smallest and largest item will be on top)
       -       # subtract largest from smallest
        Ä      # take absolute value (as we will have negatives after the previous step)
         Z     # take the largest

2

자바 (8), 140 (128)

VTCAKAVSMoACE 덕분에 무리를 깎았습니다.

int l(int[]a,int d){int x=0,i=0,f,j,k;for(;i<=a.length-d;i++)for(j=i;j<i+d;j++)for(k=i;k<i+d;)x=(f=a[j]-a[k++])>x?f:x;return x;}

언 골프

int l(int[]a,int d){
    int x=0,i=0,f,j,k;
    for(;i<=a.length-d;i++)
        for(j=i;j<i+d;j++)
            for(k=i;k<i+d;)
                x=(f=a[j]-a[k++])>x?f:x;
    return x;
}

엔드 브래킷이 없습니다. ;)
Addison Crump

@VTCAKAVSMoACE 죄송합니다. 복사하여 붙여 넣기 오류 :(
dpa97

1
5 바이트 감소 :int l(int[]a,int d){int x=0,i=0,f,j,k;for(;i<=a.length-d;i++)for(j=i;j<i+d;j++)for(k=j;k<i+d;)x=(f=a[j]-a[k++])<0?-f:f>x?f:x;return x;}
Addison Crump

@VTCAKAVSMoACE 나는 당신이 무엇을 할 것인지 잘못 믿습니다. 테스트 케이스에서 7과 1을 전환 해보십시오. 그러나 나는 그것을 사용하여 새로운 아이디어를 덜어 낼 수 있습니다!
dpa97

1
나는 또한 k에서 i를 시작하여 abs (물론 과정에서 알고를 훨씬 더 악화시키는)의 필요성을 제거했습니다. 같은 줄에 x = (f = ...)를 갖는 꽤 멋진 트릭입니다.
dpa97

2

Mathematica, 41 37 바이트

Max[MovingMap[MinMax,#,#2-1].{-1,1}]&

도트 제품을 사용 {-1,1}하여 Abs? 를 피할 수 없습니까?
마일

@ 마일 감사합니다! 수정 된 답변.
JungHwan Min

@JHM 1 바이트가로 저장되었습니다 Max[BlockMap[MinMax,#,#2,1].{-1,1}]&.

1

루비, 45 바이트

->a,d{a.each_cons(d).map{|b|b.max-b.min}.max}

나는 이것이 훨씬 나을 수 있다고 생각합니다.


1

통계 및 이미지 처리 도구 상자가 포함 된 MATLAB, 33 바이트

@(v,d)max(range(im2col(v,[1 d])))

이것은 익명 함수를 정의합니다. 사용 예 :

>> f = @(v,d)max(range(im2col(v,[1 d])));
>> f([6,9,4,7,4,1], 3)
ans =
     6

You can also try it on Octave at Ideone (but Octave, unlike Matlab, requires explicitly loading the image package).

Explanation

im2col(v,[1 d]))   % Takes overlapping blocks of size d from v, and arranges them as
                   % columns of a matrix
range(...)         % Maximum minus minimum of each column. Gives a row vector
max(...)           % Maximum of the above row vector

1

Scala, 48 bytes

(_:Seq[Int])sliding(_:Int)map(s=>s.max-s.min)max

Ungolfed:

(a:Seq[Int],d:Int)=>a.sliding(d).map(s=>s.max-s.min).max

Explanation:

(_:Seq[Int])   //define a function with a seq of ints as an argument
sliding(_:Int) //get the sequences with the length of an int argument
map(s=>        //map each sequence
  s.max-s.min    //to its deviation
)max           //and take the maximum value

1

MATL, 10 bytes

YCS5LY)dX>

Try it online!

Explanation

Consider inputs [6,9,4,7,4,1], 3 as an example.

       % Implicitly take the two inputs: v, d
       % STACK: [6,9,4,7,4,1], 3
YC     % Matrix of overlapping d-blocks of v
       % STACK: [6 9 4 7
                 9 4 7 4
                 4 7 4 1]
S      % Sort each column
       % STACK: [4 4 4 1
                 6 7 4 4
                 9 9 7 7]
5LY)   % Keep first and last rows
       % STACK: [4 4 4 1
                 9 9 7 7]
d      % Differences along each column
       % STACK: [5 5 3 6]
X>     % Maximum
       % STACK: 6
       % Implicitly display

1

Actually, 13 bytes

╗╜@V`;m@M-`MM

Try it online!

-6 bytes from the observation in nimi's Haskell answer, that slices shorter than d don't affect the maximum deviation.

Explanation:

╗╜@V`;m@M-`MM
╗              store d in register 0
 ╜@            push d, swap so v is on top
   V           push all slices of v whose length is in [1, d]
    `;m@M-`M   map (for each slice):
     ;m@M-       get minimum and maximum, subtract min from max
           M  get maximum of list of deviations

1

PHP, 89 87 bytes

for($i=1;$r=array_slice($argv,++$i,$argv[1]);$d=max($r)-min($r))$o=$d>$o?$d:$o;echo+$o;

Not particularly clever or pretty but it works. Use like:

php -r "for($i=1;$r=array_slice($argv,++$i,$argv[1]);$d=max($r)-min($r))$o=$d>$o?$d:$o;echo+$o;" 3 6 9 4 7 1

for v=6,9,4,7,4,1, d=3

Edit: 2 bytes saved thanks to Jörg Hülsermann


echo+$o; instead of echo$o?:0;
Jörg Hülsermann

0

CJam, 17 bytes

q~ew{$)\(\;-}%:e>

(Also q~ew:$z)\(\;.-:e>)

Try it online!

Explanation

q~                   e# Read the two inputs. Evaluate
  ew                 e# Overlapping blocks
    {       }%       e# For each block
     $               e# Sort
      )              e# Get last element (that is, maximum)
       \(            e# Swap, get first element (minimum)
         \;          e# Swap, delete rest of the block
           -         e# Subtract (maximum minus minimum)
              :e>    e# Maximum of array

0

Java 7,159 bytes

Java = expensive(i know it can be golfed much more)

int c(int[]a,int d){int[]b=new int[d];int i,j,s=0;for(i=-1;i<a.length-d;){for(j=++i;j<i+d;)b[i+d-1-j]=a[j++];Arrays.sort(b);s=(j=b[d-1]-b[0])>s?j:s;}return s;}

Ungolfed

static int c ( int []a , int d){
    int []b = new int[ d ];
    int i , j , s = 0 ;
    for ( i = -1 ; i < a.length - d ;) {
        for ( j = ++i ; j < i + d ;)
        b[ i + d - 1 - j ] = a[ j++ ] ;
        Arrays.sort( b ) ;
        s = ( j = b[ d - 1 ] - b[ 0 ] ) > s ? j : s ;
    }
    return s ;
    }

0

Haskell, 56 bytes

_#[]=0 
d#l|m<-take d l=max(maximum m-minimum m)$d#tail l

Usage example: 3 # [6,9,4,7,4,1] -> 6.

Considering ranges less than d doesn't change the overall maximum, so we can run take d down to the very end of the list (i.e. also include the ranges with the last d-1, d-2, ... 0 elements). The recursion stops with the empty list where we set the deviation to 0.



0

Racket 121 bytes

(let p((v v)(j 0))(let*((l(take v d))(k(-(apply max l)(apply min l)))
(j(if(> k j)k j)))(if(= d(length v))j(p(cdr v)j))))

Ungolfed:

(define (f d v)
  (let loop ((v v)
             (mxdev 0))                     ; start with max deviation as 0
    (let* ((l (take v d))                   ; take initial d elements in v
           (dev (- (apply max l)            ; find deviation
                    (apply min l)))
           (mxdev (if(> dev mxdev)          ; note max deviation
                   dev
                   mxdev)))
      (if (= d (length v)) mxdev            ; if all combinations tested, print max deviation
          (loop (rest v) mxdev))            ; else test again 
      )))                                   ; with first element of list removed

Testing:

(f 3 '(6 9 4 7 4 1))

Output:

6

0

q, 25 bytes

{max mmax[y;x]-mmin[y;x]}

mmax and mmin are sliding window maximum and minimum respectively

Example

q){max mmax[y;x]-mmin[y;x]}[6 9 4 7 4 1;3]
6

0

C#, 131 bytes

here is a verbose linq solution

int c(int[]a){var x=from j in Enumerable.Range(0,a.Length-2)let p=new[]{a[j],a[j+1],a[j+2]}select p.Max()-p.Min();return x.Max();}

0

C#, 163 bytes

Golfed:

int m(List<int> v,int d){var l=new List<List<int>>();for(int i=0;i<v.Count;i++){if(v.Count-i>=d)l.Add(v.GetRange(i,d));}return l.Select(o=>o.Max()-o.Min()).Max();}

Ungolfed:

public int m(List<int> v, int d)
{
  var l = new List<List<int>>();

  for (int i = 0; i < v.Count; i++)
  {
    if (v.Count - i >= d)
      l.Add(v.GetRange(i, d));
  }

  return l.Select(o => o.Max() - o.Min()).Max();
}

Test:

var maximumDeviation = new MaximumDeviation();
Console.WriteLine(maximumDeviation.f(new List<int> {6,9,4,7,4,1}, 3));

Output:

6

0

Pyth, 11 bytes

eSms.+Sd.:F

Explanation

eSms.+Sd.:FQ   Implicit input
          FQ   Unpack the input (v, d)
        .:     Get all subsequences of length d
  m   Sd       Sort each
   s.+         Take the sum of differences to get the deviation
eS             Get the maximum

0

Jelly, 8 bytes

ṡµṂ€ạṀ€Ṁ

Try it online!

Uses the same algorithm as Dyalog APL, but I figured this myself before looking at it.

Explanation:

ṡµṂ€ạṀ€Ṁ ḷ“Main link. Arguments: v d.”
ṡ        ḷ“Overlapping sublists of x of length y.”
 µ       ḷ“Start a new monadic chain.”
  Ṃ€ạṀ€  ḷ“Find the deviation of each of the elements of x.”
       Ṁ ḷ“Take the maximum of x.”

Note: x, y are left, right arguments respectively.


0

Perl 6, 44 bytes

{$^a.rotor($^b=>1-$^b).map({.max-.min}).max}

$^a and $^b are the two arguments to the function, called v and d respectively in the problem statement. The rotor method returns the sequence of subsequences of v of size d.


0

Clojure, 73 67 bytes

Edit: Using #(...) instead of (fn[...]) and for instead of map.

#(apply max(for[p(partition %2 1 %)](-(apply max p)(apply min p))))

0

Python 3, 80 bytes

lambda v,d:max(map(lambda g:max(g)-min(g),[v[i:i+d]for i in range(-~len(v)-d)]))

you can use (max(v[i:i+d])-min(v[i:i+d])for i in range(-~len(v)-d) instead of map(lambda g:max(g)-min(g),[v[i:i+d]for i in range(-~len(v)-d)])
Wheat Wizard
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.