배열의 반복 횟수


20

배열을 수신하고 두 번 이상 발생하는 정수 수를 리턴해야합니다.

[234, 2, 12, 234, 5, 10, 1000, 2, 99, 234]

이것은 각각의 이후, 2를 반환 234하고 2두 번 이상 나타납니다.

[234, 2, 12, 234]
[2, 12, 234, 5, 10, 1000, 2]

목록의 길이는 100k 정수를 초과하지 않으며 목록 내의 정수는 항상 -100k와 100k 사이입니다.

정수는 두 번 이상 발생하면 계산되어야하므로 정수가 3 번 발생하면 여전히 하나의 반복 정수로만 계산됩니다.

테스트 사례

[1, 10, 16, 4, 8, 10, 9, 19, 2, 15, 18, 19, 10, 9, 17, 15, 19, 5, 13, 20]  = 4
[11, 8, 6, 15, 9, 19, 2, 2, 4, 19, 14, 19, 13, 12, 16, 13, 0, 5, 0, 8]     = 5
[9, 7, 8, 16, 3, 9, 20, 19, 15, 6, 8, 4, 18, 14, 19, 12, 12, 16, 11, 19]   = 5
[10, 17, 17, 7, 2, 18, 7, 13, 3, 10, 1, 5, 15, 4, 6, 0, 19, 4, 17, 0]      = 5
[12, 7, 17, 13, 5, 3, 4, 15, 20, 15, 5, 18, 18, 18, 4, 8, 15, 13, 11, 13]  = 5
[0, 3, 6, 1, 5, 2, 16, 1, 6, 3, 12, 1, 16, 5, 4, 5, 6, 17, 4, 8]           = 6
[11, 19, 2, 3, 11, 15, 19, 8, 2, 12, 12, 20, 13, 18, 1, 11, 19, 7, 11, 2]  = 4
[6, 4, 11, 14, 17, 3, 17, 11, 2, 16, 14, 1, 2, 1, 15, 15, 12, 10, 11, 13]  = 6
[0, 19, 2, 0, 10, 10, 16, 9, 19, 9, 15, 0, 10, 18, 0, 17, 18, 18, 0, 9]    = 5
[1, 19, 17, 17, 0, 2, 14, 10, 10, 12, 5, 14, 16, 7, 15, 15, 18, 11, 17, 7] = 5

무슨 뜻 Once it counts the repetition, don't count again인가요? 또한 특정 정수의 반복을 찾으려면 주어진 정수가 없으면 어떤 정수를 검색해야하는지 어떻게 알 수 있습니까? 마지막으로 테스트 사례는 약간 혼란 스럽다. 어느 것이 출력되고 어떤 것이 입력됩니까?
무지의 구현

4
좀 더 명확하게하기 위해 이것을 편집했습니다. 이것이 당신이 의도 한 것입니까? 또한 해당 테스트 사례에 대한 답변을 입력하십시오.
Rɪᴋᴇʀ

1
테스트 사례에 대한 답변을 추가했습니다. 잘못 입력하면 죄송합니다.
MickyT

1
본인이 의도 한 내용임을 확인할 때까지이 질문을 닫기로 투표했습니다.
Rɪᴋᴇʀ

4
관련 (독특하지 않은 항목의 양 대신 고유하지 않은 항목을 출력)
Kevin Cruijssen

답변:


15

R , 20 바이트

이것이 당신이 무엇을하고 있습니까? tablescan입력 값 의 발생 횟수를 계산하는 데 사용 합니다. count가 1보다 큰지 테스트하고 true를 합산합니다.

sum(table(scan())>1)

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


내 마음이 duplicated먼저 갔다 -겸손 table은 골프에 너무 유용합니다!
주세페

@giuseppe 테이블은 지금 좋아하는 것입니다 :)
MickyT




6

C (연타) 175 (117) 95 바이트

c(*a,*b){return*a-*b;}r(*l,m){qsort(l,m,4,c);return((!m||l[1]-*l)&l[-1]==*l)+(m?r(l+1,m-1):0);}

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

이 중 하나를 제출 한 것은 이번이 처음이므로 서식 또는 기타 문제가있는 경우 알려주십시오.

의견에서 업데이트 :

  • Jo King에서 -58 ~ 117 바이트
  • ASCII 전용에서 -80 ~ 95 바이트

최초 제출


5
환영합니다. 저는 C 개인이 아니지만 골프 C 페이지 를위한 링크입니다 .
MickyT

2
117 바이트 => d,i;c(*a,*b){return*a-*b;}r(l[],m){qsort(l,m,4,c);for(i=d=0;++i<m;)d+=((l[i+1]-l[i]||i>m-2)&&l[i-1]==l[i]);return d;}. include
Jo King

2
@JoKing 100 :d;c(*a,*b){return*a-*b;}r(*l,m){qsort(l,m,4,c);for(d=0;~m--;)d+=(!m||l[1]-*l)&l[-1]==*l++;return d;}
ASCII 전용

1
@CollinPhillips 예. 내가 게시 한 링크에서 볼 수 있듯이
ASCII

2
95 :c(*a,*b){return*a-*b;}r(*l,m){qsort(l,m,4,c);return((!m||l[1]-*l)&l[-1]==*l)+(m?r(l+1,m-1):0);}
ASCII 전용

5

C # (Visual C # 대화식 컴파일러) , 40 바이트

n=>n.GroupBy(c=>c).Count(c=>c.Count()>1)

사양의 첫 번째 초안은 명확하지 않았으며 두 번 이상 나타나는 모든 요소를 ​​반환한다는 의미라고 생각했습니다. 이것은 업데이트 된 버전입니다.

어떻게 든 내 코드가 한 번 나타난 요소 수를 반환한다는 것을 알지 못했습니다. 그것을 잡은 Paul Karam에게 감사합니다!

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


1
출력이 잘못되었습니다. 발생 횟수가 2 이상인 요소를 계산해야합니다. 이어야합니다 n=>n.GroupBy(c=>c).Count(c=>c.Count()>=2). OP는이 목록의 답이 2라고 말합니다. 코드는 5를 반환합니다. 변경 한 내용은 2를 반환합니다.
Paul Karam

1
또는 >140 바이트를 유지하기 위해
Paul Karam 7:25에

@PaulKaram 감사합니다!
무지의 구현


4

J , 11 9 바이트

Jonah 덕분에 -2 바이트!

1#.1<1#.=

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

독창적 인 솔루션 :

1#.(1<#)/.~

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

설명:

        /.~   group the list by itself
   (   )      for each group
    1<#       is the length greater than 1
1#.           sum by base-1 conversion

헤이 갈렌 1#.1<1#.=9 바이트 + 좋은 ol '자가 분류 재미.
요나

1
@Jonah 감사합니다! 솔직히, 나는 이것을 몰랐다.
Galen Ivanov

1
@ 조나 니스!
Adám

@ Adám과 나는 J를 APL과 연결하게되어 기뻤습니다. 다시 oil :)
요나



3

젤리 , 4 바이트

ĠITL

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

...또는 ĠIƇL

방법?

ĠITL - Link: list of integers   e.g. [234, 2, 12, 234, 5, 10, 1000, 2, 99, 234]
Ġ    - group indices by value        [[2,8],5,6,3,9,[1,4,10],7]
 I   - incremental differences       [[6],[],[],[],[],[3,6],[]]
  T  - truthy indices                [1,6]
   L - length                        2

원하는 길이를 가진 I( [[6],[3,6]]) 의 진실한 결과 만 유지하도록 필터링합니다 .




3

자바 8, 74 73 바이트

L->L.stream().filter(i->L.indexOf(i)<L.lastIndexOf(i)).distinct().count()

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

설명:

L->                      // Method with ArrayList parameter and integer return-type
  L.stream()             //  Create a stream of the input-list
   .filter(i->           //  Filter it by:
     L.indexOf(i)        //   Where the first index of a value
     <L.lastIndexOf(i))  //   is smaller than the last index of a value
   .distinct()           //  Deduplicate this filtered list
   .count()              //  And return the count of the remaining values



3

하스켈, 41 바이트

f[]=0
f(a:s)=sum[1|filter(==a)s==[a]]+f s

이 솔루션은 기본적으로 동일한 요소가 목록에서 정확히 한 번 표시되는 목록의 요소 수를 계산합니다.


2

하스켈 , 47 바이트

f[]=0
f(a:b)|x<-filter(/=a)b,x/=b=1+f x|1>0=f b

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

이것은 순진한 접근 방식입니다. 이를 개선하기 위해 수행 할 수있는 작업이있을 수 있습니다.

f[]=0

0빈 목록으로 돌아갑니다

f(a:b)

비어 있지 않은 목록의 경우 aand로 시작 b합니다.

|x<-filter(/=a)b,x/=b=1+f x

필터링하면 a아웃 b다르다 b(즉 a이다 b) 후 잠시 후 1 이상 f에 적용 b(가)로 a여과 s는.

|1>0=f b

필터링 a이 변경되지 않으면 나머지 부분 b만 실행 f합니다.

Here is another similar approach that has the same length:

f[]=0
f(a:b)|elem a b=1+f(filter(/=a)b)|1>0=f b

Try it online!



2

Wolfram Language 34 bytes

 Length@DeleteCases[Gather@#,{x_}]&

Gather groups identical integers into lists. DeleteCases[...{x_}] eliminates lists containing a single number. Length returns the number of remaining lists (each containing two or more identical integers.


1
Count[{_,__}]@*Gather
alephalpha


2

Pyth, 6 bytes

l{.-Q{

Try it here

Explanation

l{.-Q{
     {Q   Deduplicate the (implicit) input.
  .-Q     Remove the first instance of each from the input.
l{        Count unique.

2

Brachylog, 7 bytes

ọzt;1xl

Try it online!

Explanation:

ọ          For every unique element E of the input, [E, how many times E occurs]
 zt        The last elements of the previous value.
   ;1x     With every 1 removed,
      l    how many there are.

2

PHP, 39 bytes

a nice occasion to use variable variables:

foreach($argv as$v)$r+=++$$v==2;echo$r;

takes input from command line arguments. Run with -nr or try it online.


$argv[0] is - and that appears only once in the arguments, so it does not affect the result.


1

Element, 40 bytes

_(#'{"2:0+4:'~1+";~2=[''1+""]$2+'[(#]'}`

Try it online!

This requires input to be in a precise format like [234, 2, 1000, 2, 99, 234] (enclosed with [] with a comma and space between integers).

Explanation:

_                                        input
 (#                                      delete the [ at start of input
   '{"                               '}  WHILE the string is non-empty
   '{"2:                             '}    duplicate it
   '{"  0+                           '}    add 0 to coerce to integer (gets next number in array)
   '{"    4:                         '}    make 3 additional copies
   '{"      '                        '}    temporarily move 1 copy to control stack
   '{"       ~                       '}    fetch the current map value for given integer
   '{"        1+                     '}    increment map value
   '{"          "                    '}    retrieve temporary copy of integer (the key for the map)
   '{"           ;                   '}    store updated map value
   '{"            ~                  '}    fetch map value again (1 if 1st instance, 2 if 2nd, etc.)
   '{"             2=                '}    test for map value = 2, this is the first duplication
   '{"               [      ]        '}    IF
   '{"               [''    ]        '}      move stuff from main stack to control stack
   '{"               [  1+  ]        '}      increment the counter of duplicate (bottom of stack)
   '{"               [    ""]        '}      move stuff back to main stack
   '{"                       $       '}    take length of current integer
   '{"                        2+     '}    add 2 (for the comma and space)
   '{"                          '[  ]'}    FOR loop with that number
   '{"                          '[(#]'}      trim those many characters from front of input string
                                       ` output result

1

Retina 0.8.2, 19 bytes

O`.+
m`^(.+)(¶\1)+$

Try it online! Link includes test suite which splits each line on commas. Explanation:

O`.+

Sort equal values together.

m`^(.+)(¶\1)+$

Count the number of runs of at least two values.


1

Clean, 59 54 bytes

import StdEnv,StdLib
$l=sum[1\\[_,_:_]<-group(sort l)]

Try it online!

Sorts the list, groups adjacent equal elements, and counts the number with more than 1 item.


1

Rust, 126 bytes

let f=|v:Vec<i32>|{let mut u=v.clone();u.sort();u.dedup();u.iter().filter(|i|v.iter().filter(|n|**n==**i).count()>1).count()};

I give up. This is basically the same as Ruby. There is "another way" creating an array and indexing into it using the values in the input vector, +100000, however the type conversions (as usize / as i32) take up too much space.



1

k, 8 bytes

+/1<#:'=

reads as: sum (length each group) > 1

+/ is sum (plus over)

#:' is length each

= is group (ex. =1 2 1 6 7 2 generates 1 2 6 7!(0 2;1 5;,3;,4) (dictionary of unique value and its positions)

Use example (first test case)

+/1<#:'=1 10 16 4 8 10 9 19 2 15 18 19 10 9 17 15 19 5 13 20

writes 4

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.