문자열에서 가장 많이 발생하는 문자를 찾는 프로그램 작성


20

프로그램은 가장 쌍을 이루는 문자를 출력해야합니다. 예를 들어, 프로그램에 다음 문자열이 제공된 경우 :

"Sally's friend Bobby searched for seashells."

두 번 발생 L하기 때문에 출력해야 "ll"하며 이는 다른 쌍보다 더 자주 발생합니다 "bb".

규칙 :

  • 둘 이상의 문자가 1 번째로 발생하는 경우 알파벳 순서로 "Sally's friends Jimmy and Bobby rummaged for seashells."모두 출력하십시오 (예 : LAND와 M[또는 원하는 "LM"경우]는 모두 다른 쌍보다 더 자주 발생하므로 모두 출력해야 합니다).
  • 3 배, 4 배 등의 문자는 한 쌍 으로 계산됩니다 (예 : "lll"in "willless"은 한 쌍으로 만 계산됩니다 L).
  • 문자 쌍은 한 단어로되어 있어야합니다 (예 : 보다 많은 어커런스가 있음에도 불구하고 공백으로 구분 되므로 "Sally's sociable friends Sammy and Bobby searched for fabulous seashells."출력 L되지 않아야 함 ).S"ss""ll"
  • 영어 알파벳 글자 만 센다
  • 케이스 (예 : 중요하지 않습니다 "Ss"과 동일 "SS"하거나 "ss", 모두가 한 쌍으로 계산됩니다 S.)

당신이 원하는 곳에서 입력을 읽을 수 있습니다. 가장 짧은 코드가 승리합니다.


2
문자 만 쌍으로 발생하거나 입력에 이중 공백이나 이중 '등이 포함될 수 있다고 가정 할 수 있습니까 ?
— Martin Ender

1
하나 이상의 문자가 두 번 나타나는 것으로 가정 할 수 있습니까?
— 마틴 엔더

@ MartinBüttner 네, 적어도 하나의 문자 쌍이 발생한다고 가정 할 수 있습니다. 그러나 다른 문자도 쌍으로 나타날 수 있습니다. 글자 만 세십시오.
— ayane

한 쌍만 있어도 여전히 같은 목록으로 인쇄 할 수 ['l']있습니까?
— Maltysen

@ Maltysen 네, 그렇게 할 수 있습니다.
— ayane

답변:


6

Pyth, 26 25 24 16 15 바이트

.M/sfthTrrz08ZG

온라인으로 사용해보십시오 : 데모

설명:

.M/sfthTrrz08ZG   implicit: z = input string
         rz0      convert z to lower-char
        r   8     run-length-encoding (into tuples [count, char])
    f             filter for tuples T, which satisfy:
     thT            T[0]-1 != 0 (count > 1)
   s              join to a string
.M            G   find the elements Z of "abcd...z", which produce the highest value:
  /...........Z       count of Z in ...

1
eC-> s1 바이트를 저장합니다.
— isaacg

Pyth를 배우기 위해 사용할 수있는 좋은 자료가 있습니까?
— Beta Decay

당신은 Pyth에 대한 자습서를 찾을 수 있습니다 @BetaDecay pyth.readthedocs.org 그것은 모든 기능과 트릭을 포함하지 않습니다, 그러나 그것은 좋은 시작이다. 질문이 있으시면 채팅으로 문의하십시오 .
— Jakube

7

배쉬 + GNU 코어 유틸리티, 133

grep -Eo '([A-Z])\1+'<<<"${1^^}"|cut -c1|sort|uniq -c|sort -rn|while read n l
do((a-n&&a-0))&&exit||echo $l&&a=$n
done|sort|tr -d \\n

테스트 케이스 :

$ for t in "Sally's friend Bobby searched for seashells." \
> "Sally's friends Jimmy and Bobby rummaged for seashells." \
> "willless" \
> "Sally's sociable friends Sammy and Bobby searched for fabulous seashells." \
> "11ss11aa"
> do
> ./mostpaired.sh "$t"
> echo
> done
L
LM
LS
L
AS
$ 

글자 만 세나요? (testcase : 11ss11aa-> SA)
— edc65

@ edc65 나는 그것을 고쳤다 ;-). 실제로 11ss11aa-> AS :)
— Digital Trauma

나는 당신이 10 개 이상의 짝을 이룬 편지라면 당신 의 sort -r필요가 있다고 생각합니다 sort -rn.
— Toby Speight

@TobySpeight. 예. 결정된.
— 디지털 외상

awk '! n {n = $ 1}; n == $ 1'| grep -o. $
— Nik O'Lai

5

CJam, 29 27 바이트

leue`{2a>},s_el-$e`$z~\)-,>

2 바이트를 사용하지 않는 @Optimizer 덕분에!

CJam 통역사 에서 온라인으로 사용해보십시오 .

작동 원리

leu    e# Read a line from STDIN and covert to uppercase.
e`     e# Perform run-length encoding.
       e# Example: "AABBBC!!" -> [[2 'A] [3 'B] [1 'C] [2 '!]]
{2a>}, e# Filter out all pairs that are less of equal to [2].
s      e# Stringify.
       e# Example: [[2 'A] [3 'B] [2 '!]] -> "2A3B2!"
_el    e# Push a copy of the string and convert to lowercase.
       e# Example: "2A3B2!" -> "2a3b2!"
-      e# Remove all character from the second string from the first.
       e# Example: "2A3B2!" "2a3b2!" - -> "AB"
$e`$   e# Sort, perform run-length encoding and sort again.
       e# Example: "ABACABDBC" -> "AAABBBCCD"
       e#                      -> [[3 'A] [3 'B] [2 'C] [1 'D]]
                               -> [[1 'D] [2 'C] [3 'A] [3 'B]]
z~     e# Zip and dump.
       e# Example: [[1 'D] [2 'C] [3 'A] [3 'B]] -> [1 2 3 3] ['D 'C 'A 'B]
\)     e# Pop out the last element from the first array.
       e# Example: [1 2 3 3] -> [1 2 3] 3
-      e# Remove all occurrences of the popped element from the array.
       e# Example: [1 2 3] 3 -> [1 2]
,      e# Compute the length of the remainder.
>      e# Skip that many elements from the character array.

z~\)-,>내가 볼 수있는 한 작동해야합니다.
— Optimizer

@Optimizer : 더 짧고 직관적입니다. 감사!
— Dennis

4

Pyth- 23 22 21 20 바이트

regexp 대체를 사용하여 두 개 이상의 알파벳을 모두 임시 값으로 .M바꾸고 aximal을 사용 하여 가장 높은 발생률을 갖습니다. 정렬 및 바이트 저장의 중복성을 지적한 @Jakube에게 감사드립니다.

.M/:rz0+Z"{2,}"KC0KG

stdin에서 입력을 가져오고 ['l', 'm']stdout 과 같은 출력을 가져옵니다 .

.M        G         Values which yield maximal amount over lowercase alphabet
 /                  Count
  :                 Regexp substitution
   rz0              Lowercased input
   +Z               String concatenate current loop var         
    "{2,}"          Regexp 2 or more of previous group
   KCZ              Inline assign null byte to K and use value
  K                 Count K which is null byte

여기에서 온라인으로 사용해보십시오 .


4

C, 155

정규 표현식이 아닌 다른 것.

m=1,i=1,n[91];
main(c,a)char**a;
{
  char*t=a[1];
  for(;c=*t++;)(c&=95)>64&&c<91&&(c-(*t&95)?i=1:(c=(n[c]+=i),i=0,m=m<c?c:m));
  for(c=0;++c<91;)n[c]-m||putchar(c);
}

3

파이썬 2 132 143 바이트

def f(x):import re;x=re.findall(r'(.)\1+',x.upper());s={l:x.count(l)for l in x};print "".join(sorted([l for l in s if s[l]==max(s.values())]))

예제 실행 :

f("Sally's friends Jimmy and Bobby rummaged for seashells.")
LM

1
아마도 "3 배, 4 배 등의 문자는 한 쌍으로 계산됩니다"
— Ginden

네가 옳아! 나는 그것을 고치려고 노력했다. 지적 해 주셔서 감사합니다 :)
— heo

2

CJam, 37 바이트

leue`{~_el-\(e&},1f=$e`$_W=0=f-{,1=},

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

정규 표현식 지원이 없으면 Pyth와 경쟁하기가 까다로워집니다. 이것이 첫 패스에서 생각 해낸 최고입니다.

설명:

l     Get input.
eu    Convert it to upper case, since case does not matter.
e`    Run length encoding, to split into groups of same characters.
{     Start of block for filtering.
  ~     Unpack the length/letter pair.
  _     Copy the letter.
  el    Change copy to lower case.
  -     Subtract to compare. If result is non-zero, this is a letter.
  \     Swap count to top.
  (     Decrement to get truthy value for count > 1.
  e&    Logical and: It's a letter, and count is > 1.
},    End of filter.
1f=   Don't need the counts anymore, filter out the letters only from the RLE pairs.
$     Sort them, so that multiples of the same letter are sequential.
e`    RLE again, to count how many multiples of each letter we had.
$     And sort again, to get the count/letter pairs in order of incrementing count.
_     Copy list.
W=0=  Pick out count of last element, which is the highest count.
f-    Remove count from pairs that have the highest count. This leaves them
      as one member lists with letter only, while others still have count/letter.
{     Start block for filter.
  ,1=   Check for list length one.
},    End filter.

2

Q (66)

부팅하기 상대적으로 읽기 쉬운 :

{where g=max g:.Q.A#count each group y where not differ y:upper x}

2

R, 105 바이트

cat(substr(names(b<-table(regmatches(s<-toupper(readline()),gregexpr("([A-Z])\\1+",s))))[b==max(b)],1,1))

STDIN에서 한 줄의 텍스트를 읽고 가장 일반적으로 쌍을 이루는 문자의 공백으로 구분 된 목록을 STDOUT에 인쇄합니다.

언 골프 + 설명 :

# Read a string from STDIN, convert to uppercase
s <- toupper(readline())

# Get each match of the regex /([A-Z])\1+/
matches <- regmatches(s, gregexpr("([A-Z])\\1+", s))

# Compute the frequency of each match
freq <- table(matches)

# Get the matches with the highest frequency
highest <- names(freq)[freq == max(freq)]

# Each element of highest is the literal pair, so take the first character
first <- substr(highest, 1, 1)

# Print to STDOUT
cat(first)

예 :

> (code)
Sally's friends Jimmy and Bobby rummaged for seashells.
L M

> (code)
Sally's friend Bobby searched for seashells.
L

> (code)
Sally's sociable friends Sammy and Bobby searched for fabulous seashells.
L

> (code)
11ss11nn
N S

당신은 할 수 있습니다 온라인으로보십시오 !


toupper대소 문자를 무시하고에서 perl을 사용하면 아마도 제거 할 수 있습니다 gregexpr. 예 :cat(substr(names(b<-table(regmatches(s<-readline(),gregexpr("(\\w)\\1+",s,T,T))))[b==max(b)],1,1))
— MickyT

@MickyT : 그것에 대해 생각했지만 OP가 출력을 대문자로 원하는 것처럼 보이므로 toupper어쨌든 그것을 보장하기 위해 사용해야합니다.
— Alex A.

아쉬 메, 질문을 읽을 때보고 싶었습니다.
— MickyT

바이올린을 시험해 보았지만 파이어 폭스에서 outpuy없이 영원히 실행되는 것처럼 보입니다. 테스트 사례 : 11ss11nn?
— edc65

@ edc65 R-Fiddle의 문제입니다. 전혀 작동하지 않습니다. 문제를보고하기 위해 관리자에게 문의했습니다. 정규식을 수정하고 테스트가 예상대로 작동하지만 비용은 2 바이트입니다. 이 내용을 지적 해 주셔서 감사합니다. 감사합니다.
— Alex A.

2

루비, 60

f=->s{(?a..?z).group_by{|l|s.scan(/#{l*2}+/i).size}.max[1]}

p f["Sally's friends Jimmy and Bobby rummaged for seashells."]

group_by키가 블록의 출력이고 값이 각 키를 생성하는 문자 목록 인 해시 (사전) 구조를 만듭니다. 이 경우 키는 대소 문자를 구분하지 않고 문자의 2 + 실행 횟수입니다. max각 [key,value]튜플을 사전 식으로 비교 하므로 최대 키만 찾습니다. 그런 다음 [1]튜플의 값 목록 부분을 반환합니다.


2

파이썬 (2), 185 (159) 153

i=input().lower()
d=sorted({l:len(i.split(l+l))for l in map(chr,range(97,123))}.items(),None,lambda x:x[1],1)
print sorted(c for c,k in d if k==d[0][1])

인용 된 문자열로 입력을받습니다.


2

C # 160 바이트

s입력은 어디에 있습니까?

char? d(string s){s=s.ToUpper();return s.Select((x,i)=>new{y=x,z=i==0?(char?)null:s[i-1]}).Where(x=>x.y==x.z).GroupBy(x=>x.z).OrderBy(x=>x.Count()).Last().Key;}

1

rs, 146 바이트

[^A-Za-z]/
*(.)\1+/\1\1
*(.)(?!\1)/
$/#
+*(.)#(?!.*?\1)/#\1
+*(.)(.*)#(.*)\1/\2#\3\1\1
#/
*(.)(\1*)/\1(_)^^((^^\1\2))
([^_])(_+)(?!_)(?=.*\2_)/
_/

시도 해봐! 부디! 해당 페이지의 출력 상자에서도 버튼을 만드는 데 영원히 걸렸습니다 ...

글쎄, 이것은 상당히 ... 미쳤다. 여기의 논리는 이상합니다. 누군가가 묻는 경우에만 설명을 게시합니다. (물론, 나는 설명이 요청 된 INTERCAL 답변에 대해 ... 나는 결코 설명하지 않았다고 말했다.


인터프리터가 마음에 들지만 디버그 확인란을 버튼이나 같은 줄에 넣을 수도 있습니다. 좀 이상해 보이는데. 아직도 시원하다! +1
— Maltysen

그것을 시도 (오류 ...) i.stack.imgur.com/mTioT.png
— edc65

@ Maltysen 나는 그것을 고려할 것이다. 감사!
— kirbyfan64sos

@ edc65 젠장 ... 완전한 오류 메시지는 무엇입니까? PyPy.js 버그 일 수 있습니다. 아니면 파이어 폭스에서 이것을 테스트 한 적이 없다는 사실은 ...
— kirbyfan64sos

1

스크립트 (156) (153)

var x=prompt(),f={},a=0,o
x.toUpperCase().replace(/([A-Z])\1+/g,function(m,s){m=f[s]=-~f[s]
if(a==m)o.push(s)
if(a<m)a=m,o=[s]})
alert(o.sort().join(""))


f[s]?f[s]+1:1->-~f[s]
— edc65

비 레터로 실패 :Count only letters from the English alphabet
— edc65

감사합니다 @ edc65. 바로 가기와 AZ 검사를 추가했습니다.
— 울프 해머

1
정확한 코드, 유선형 및 ES6 : f=x=>{x.toUpperCase(f={},a=0,o).replace(/([A-Z])\1+/g,(m,s)=>a<(m=f[s]=-~f[s])?(a=m,o=[s]):a>m?0:o.push(s));alert(o.sort().join'')}(마지막 2 ''는 실제로 백틱입니다. & # 96
— edc65

1

Bash + textutils (grep, sed), 111 자

fold -1<<<$s|uniq -iD|sort -f|uniq -ic|sort -rn|grep -i [A-Z]|sed -n '1h;G;s/\(\s*\S\+\s\)\(.\)\n\1./\2/p'|sort

Bash + awk (sed 대신), 97 자

fold -1<<<$s|uniq -iD|sort -f|uniq -ic|sort -rn|grep -i [A-Z]|awk '!n{n=$1};n==$1{print $2}'|sort

테스트하려면 먼저 s를 할당하십시오.

s="Sally's friends Jimmy ää and Bobby rummaged ää for seashells."

0

R, 98 바이트

Alex의 솔루션과 매우 유사하지만 일치하는 문자 대신 대체 문자를 사용하여 연속 문자를 결정합니다. 스캔은 입력을 가져오고 대체 결과를 공백으로 분할하는 데 사용됩니다.

cat(names(a<-table(scan(,'',t=gsub('([A-z]?)(\\1?)[^A-z]*','\\U\\2 ',scan(,''),T,T))))[a==max(a)])

몇 가지 테스트

> cat(names(a<-table(scan(,'',t=gsub('([A-z]?)(\\1?)[^A-z]*','\\U\\2 ',scan(,''),T,T))))[a==max(a)])
1: 11 was a race horse, 22 was one too. 11 won one race and 22 one won too.
19: 
Read 18 items
Read 2 items
O
> cat(names(a<-table(scan(,'',t=gsub('([A-z]?)(\\1?)[^A-z]*','\\U\\2 ',scan(,''),T,T))))[a==max(a)])
1: Sally's friends Jimmy and Bobby rummaged for seashells.
9: 
Read 8 items
Read 5 items
L M
> cat(names(a<-table(scan(,'',t=gsub('([A-z]?)(\\1?)[^A-z]*','\\U\\2 ',scan(,''),T,T))))[a==max(a)])
1: 11ss11nn
2: 
Read 1 item
Read 2 items
N S
> 
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.