연대기 목록을 생성 2


11

회전식 2

"로니 톰 (Rotonym)"은 ROT13이 같은 단어로 다른 단어로 번역하는 단어입니다.

이 과제를 위해, 우리는 대체 정의를 사용할 것입니다 : "Rotonym"은 원형이 다른 단어 (동일한 언어로) 로 이동 / 회전하는 단어입니다 .

예를 들면 다음과 같습니다.

'stable' < 'tables' < 'ablest'
'abort' > 'tabor'
'tada' >> 'data'

도전

사전 / 단어 목록을 허용하고 완전한 반동 어 목록을 인쇄하거나 반환하는 프로그램 또는 함수를 작성하십시오.

  1. 순서는 중요하지 않습니다.
  2. 비교는 대소 문자를 구분하지 않으므로 입력이 소문자 전용 사전으로 전달된다고 가정 할 수 있습니다.
  3. 결과는 단일 단어 (쌍이 아님)로 표현되어야하며 중복이 포함되어 있지 않으므로 입력에 중복이 없다고 가정 할 수 있습니다.
  4. 이것은 입니다.

주어진

ablest
abort
green
irk
stable
tables
tabor
tata
terra
vex
you

반환

ablest
abort
stable
tables
tabor

실제 테스트

주어진

a aa aal aalii aam aani aardvark aardwolf aaron aaronic aaronical aaronite aaronitic aaru ab aba ababdeh ababua abac abaca abacate abacay abacinate abacination abaciscus abacist aback abactinal abactinally abaction abactor abaculus abacus abadite abaff abaft abaisance abaiser abaissed abalienate abalienation abalone abama abampere abandon abandonable abandoned abandonedly abandonee abandoner abandonment abanic abantes abaptiston abarambo abaris abarthrosis abarticular abarticulation abas abase abased abasedly abasedness abasement abaser abasgi abash abashed abashedly abashedness abashless abashlessly abashment abasia abasic abask abassin abastardize abatable abate abatement abater abatis abatised abaton abator abattoir abatua abature abave abaxial abaxile abaze abb abba abbacomes abbacy abbadide abbas abbasi abbassi abbasside abbatial abbatical abbess abbey abbeystede abbie abbot abbotcy abbotnullius abbotship abbreviate abbreviately abbreviation abbreviator abbreviatory abbreviature abby abcoulomb abdal abdat abderian abderite abdest abdicable abdicant abdicate abdication abdicative abdicator abdiel abditive abditory abdomen abdominal abdominales abdominalian abdominally abdominoanterior abdominocardiac abdominocentesis abdominocystic abdominogenital abdominohysterectomy abdominohysterotomy abdominoposterior abdominoscope abdominoscopy abdominothoracic abdominous abdominovaginal abdominovesical abduce abducens abducent abduct abduction abductor abe abeam abear abearance abecedarian abecedarium abecedary abed abeigh abel abele abelia abelian abelicea abelite abelmoschus abelmosk abelonian abeltree abencerrages abenteric abepithymia aberdeen aberdevine aberdonian aberia aberrance aberrancy aberrant aberrate aberration aberrational aberrator aberrometer aberroscope aberuncator abet abetment ablest abort abut ach ache acher achete achill achor acor acre acyl ad adad adat add addlings adet ala ama baa bafta balonea batea beta caba cha chilla cora crea da dad dada data each lacy orach rache saddling stable tables tabor tabu tade teache zoquean zoraptera zorgite zoril zorilla zorillinae zorillo zoroastrian zoroastrianism zoroastrism zorotypus zorrillo zorro zosma zoster zostera zosteraceae zosteriform zosteropinae zosterops zouave zounds zowie zoysia zubeneschamali zuccarino zucchetto zucchini zudda zugtierlast zugtierlaster zuisin zuleika zulhijjah zulinde zulkadah zulu zuludom zuluize zumatic zumbooruk zuni zunian zunyite zupanate zutugil zuurveldt zuza zwanziger zwieback zwinglian zwinglianism zwinglianist zwitter zwitterion zwitterionic zyga zygadenine zygadenus zygaena zygaenid zygaenidae zygal zygantra zygantrum zygapophyseal zygapophysis zygion zygite zygnema zygnemaceae zygnemales zygnemataceae zygnemataceous zygnematales zygobranch zygobranchia zygobranchiata zygobranchiate zygocactus zygodactyl zygodactylae zygodactyli zygodactylic zygodactylism zygodactylous zygodont zygolabialis zygoma zygomata zygomatic zygomaticoauricular zygomaticoauricularis zygomaticofacial zygomaticofrontal zygomaticomaxillary zygomaticoorbital zygomaticosphenoid zygomaticotemporal zygomaticum zygomaticus zygomaxillare zygomaxillary zygomorphic zygomorphism zygomorphous zygomycete zygomycetes zygomycetous zygon zygoneure zygophore zygophoric zygophyceae zygophyceous zygophyllaceae zygophyllaceous zygophyllum zygophyte zygopleural zygoptera zygopteraceae zygopteran zygopterid zygopterides zygopteris zygopteron zygopterous zygosaccharomyces zygose zygosis zygosperm zygosphenal zygosphene zygosphere zygosporange zygosporangium zygospore zygosporic zygosporophore zygostyle zygotactic zygotaxis zygote zygotene zygotic zygotoblast zygotoid zygotomere zygous zygozoospore zymase zyme zymic zymin zymite zymogen zymogene zymogenesis zymogenic zymogenous zymoid zymologic zymological zymologist zymology zymolyis zymolysis zymolytic zymome zymometer zymomin zymophore zymophoric zymophosphate zymophyte zymoplastic zymoscope zymosimeter zymosis zymosterol zymosthenic zymotechnic zymotechnical zymotechnics zymotechny zymotic zymotically zymotize zymotoxic zymurgy zyrenian zyrian zyryan zythem zythia zythum zyzomys zyzzogeton

반환

aal aam aba abac abaft abalone abate abet ablest abort abut ach ache acher achete achill achor acor acre acyl ad adad adat add addlings adet ala ama baa bafta balonea batea beta caba cha chilla cora crea da dad dada data each lacy orach rache saddling stable tables tabor tabu tade teache

입력 단어가 고유하다고 가정 할 수 있습니까?
ngn

예, 시스템 사전을 실행할 때 고유 한 필터를 통해 입력을 미리 평가합니다.
우산

나는 일부 답변이 예제에서는 효과가 있지만 완전한 사전에는 효과가 없다는 것을 알았습니다. 나는 사소한 예제를 통과하는 일부 답변에 실패하는 단어를 포함하기에 충분히 큰 사전의 하위 집합 인 더 큰 테스트 세트를 추가했습니다.
Umbrella

@Umbrella 당신은 사용자가 자신의 답변을 수정 / 삭제할 수 있도록 잘못된 답변에 대해 언급해야합니다.
H.PWiz

abdominovaginal거기에 이상한 단어가 있습니다.
Magic Octopus Urn

답변:


5

젤리 , 8 바이트

ṙ1$ƬfḊɗƇ

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

대체 버전, 7 바이트

ṙƬ1fḊʋƇ

Dyadic Ƭ는 이상한 일을 했으므로 도전이 게시되었을 때 작동하지 않았습니다.

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

작동 원리

ṙƬ1fḊʋƇ  Main link. Argument: A (array of strings)

     ʋ   Vier; combine the 4 preceding links into a dyadic chain.
      Ƈ  Comb; for each string s in A, call the chain with left argument s and
         right argument A. Keep s iff the chain returned a truthy value.
 Ƭ           'Til; keep calling the link to the left, until the results are no
             longer unique. Return the array of unique results.
ṙ 1          Rotate the previous result (initially s) one unit to the left.
   f         Filter; keep only rotations that belong to A.
             s is a rotonym iff there are at least two rotations of s in A.
    Ḋ        Deque; remove the first string (s) of the result.
             The resulting array is non-empty / truthy iff s is a rotonym.

새로운 퀵 캐릭터? 흠 (나는 그들이 있었다 다시보다 2 byters을 사용할 수 있도록 지금 같은 일이지만 1 byters을) ... 지금 사람들을 사용할 때 학습 해
HyperNeutrino

와 같습니다 ṙ1$ÐĿfḊɗÐf.
Dennis

4

APL (Dyalog) , 20 바이트

필요 ⎕io←0

⊂∩¨(,/(1↓∘∪⍳∘≢⌽¨⊂)¨)

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

(1↓∘∪⍳∘≢⌽¨⊂)¨ 사전에있는 각 문자열의 고유 한 회전 (문자열 자체 제외)을 가져옵니다.

벡터의 길이를 취함

⍳∘≢ 0에서 길이까지의 범위를 만듭니다.

벡터를 몇 번 회전시킵니다. 예 : 2⌽'abort '->'ortab '

⍳∘≢⌽¨⊂ 그런 다음 벡터의 모든 회전을 제공합니다

중복을 제거합니다

1↓ 첫 번째 요소 (원래 문자열)를 제거합니다

,/ 모든 회전을 하나의 목록으로 평탄화

⊂∩¨ 사전과 회전의 교차점을 취합니다.


당신의 결과는 동봉 나오고 있지만, 나는 괜찮을, 아담이 훔칠 수 @해야 추측 ⊂∩¨추가 -1에 대한 트릭 (또는 반대의 반대를)
NGN

4

APL (Dyalog Unicode) , 25 23 22 17 16 바이트 SBCS

ngn의 ngn / k 솔루션 에서 아이디어를 차용 합니다 . 그리고 그에게 -6 감사합니다. 또한 H.PWiz와 같이 닫힌 목록 을 반환 하여 -1합니다 .

익명의 암묵적 접두사 기능.

⊂∩¨1,.↓(∪≢,/,⍨)¨

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

( 다음의 암묵적 기능을 각 단어에 적용하십시오.

,⍨ 단어를 스스로 연결하다

≢,/ 모든 단어 길이 하위 문자열 (예 : 모든 회전)

 회전의 고유 한 요소 (단어가 tata두 번 나타나는 것과 같은 단어를 방지하기 위해 )

1,.↓ 각리스트의 드롭 퍼스트 (원래 단어)의 연결

⊂∩¨ 그 내용과 전체 단어 목록의 교차


오래된 솔루션

ngn 덕분에 -2입니다.

익명 접두사 람다.

{⍵/⍨2≤+/⍵∊⍨↑(∪≢,/,⍨)¨⍵}

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

{… 단어 목록이있는 } 곳의 기능 :

( 다음의 암묵적 기능을 각 단어에 적용하십시오.

  ,⍨ 단어를 스스로 연결하다

  ≢,/ 모든 단어 길이 하위 문자열 (예 : 모든 회전)

   회전의 고유 한 요소 (단어가 tata두 번 나타나는 것과 같은 단어를 방지하기 위해 )

 리스트의리스트를 단일 행렬로 혼합 (전 공간 문자열이있는 패드)

⍵∊⍨ 행렬의 어떤 요소가 원래 목록의 구성원인지 표시

+/ 행을 합산합니다 (원래 단어 각각의 발생 횟수를 계산합니다)

2≤ 중복이있는 항목을 나타냅니다 (예 : 원본으로 회전하지 않은 경우 발생)

⍵/⍨ 그것을 사용하여 원래 목록을 필터링하십시오.


{∪⌽∘⍵¨⍳≢⍵}-> (∪≢,/,⍨); 귀하의 사용 은 영리합니다
ngn

@ngn 감사합니다. 나는 Morten으로부터 트릭을 배웠다.
Adám

그 기차는 내 뇌를 아프게합니다 ... dfn처럼 간단합니다 :{⍵∩⊃,/1↓¨(∪≢,/,⍨)¨⍵}
ngn

@ngn 즉 기차로 및 회전을위한 트릭 않고 있지만 내가 가진 무엇
H.PWiz

1
죄송합니다, 마지막 마음의 변화 :⊢∩∘⊃1,.↓(∪≢,/,⍨)¨
ngn

4

Brachylog , 26 바이트

g;?z{tWl⟧₆∋I;W↺₍R;W≠&h∋R}ˢ

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

g;?z                          % Zip the whole input with each word in it respectively
    {                   }ˢ    % Apply this predicate to each pair in the zip
                              %   and select the successful values
     tW                       % Let the current word be W
       l⟧₆∋I                  % There exists a number I from 1 to length(W)-1
            ;W↺₍R             % And R is the result of circularly shifting the 
                              %   current word I times 
                 ;W≠          % And R is not the current word itself (needed for words like "tata")
                    &h∋R      % And R is one of the input dictionary words
                              % (R is implicitly the output of the predicate, and 
                              %  successful R values are collected and output by the ˢ)


3

K (ngn / k) , 23 바이트

{x^x^,/1_'(,/|0 1_)\'x}

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

{ } 인수가있는 함수입니다 x

0 1_인덱스 0과 1에서 문자열을 자릅니다. 예 : "abcd"->(,"a";"bcd")

| 두 조각을 뒤집습니다. ("bcd";,"a")

,/ 그들과 합류 : "bcda"

(,/|0 1_)\ 문자열의 모든 회전을 반환

(,/|0 1_)\'x 각 문자열의 회전 x

1_' 각각의 첫 번째 "회전", 즉 각각의 사소한 정체성 회전을 떨어 뜨립니다.

,/ 붙다

x^y목록의 x요소가없는 목록입니다.y

x^x^y이다의 교회법 xy


영리한. 교차 부분을 사용하여 다른 바이트를 저장할 수있었습니다.
Adám

2

05AB1E , 14 바이트

εDvDÀ})ÙåO<Ā}Ï

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

설명

ε           }    # apply to each word in the input
 Dv  }           # for each letter in the word
   DÀ            # copy the previous word and rotate it left
      )Ù         # wrap the rotations in a list and remove duplicates
        å        # check each rotation for presence in the input
         O       # sum presences
          <Ā     # decrement the sum and truthify it (check if 1 or greater)
             Ï   # filter, keep words in input that are true in the resulting list

2

PynTree , 44 바이트

§y:f#x0€[x/|Ḟz&⁻xzėzḞw+#x`wLx#x`0wRLxy]y#\x1

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

이것은 PynTree가 변수를 할당하는 표현식을 사용할 수 있도록 변수를 할당하는 함수를 사용하기 때문에 목록 이해를 구성하는 방식에 중대한 결함을 드러내는 것으로 밝혀졌습니다. 메인 블록이 평가되었습니다. 이것은 쉽게 고칠 수있는 것처럼 보이지만 일찍이 알지 못했기 때문에이 대답은 엄청나게 길다.

실제로 내가 고쳐도 여전히 너무 길다고 생각합니다.


2

펄 6 , 65 바이트

{@^a.grep:{@aany(($/=[.comb]).rotate,*.rotate...^*eq$/).join}}

시도 해봐

넓히는:

{  # bare block lambda with placeholder parameter @a

  @^a     # declare and use placeholder parameter
  .grep:  # find the values that match
  {

    @a
                # Set contains operator

    any(         # create a junction of the following

      # generate a sequence
      (
        $/ =     # store into $/ (no declaration needed for this variable)
        [        # turn into an array instead of a one-time sequence
          .comb  # the input split into characters
        ]
      ).rotate,  # start the sequence on the first rotation

      *.rotate   # use this to generate the rest of the values in the sequence

      ...^       # keep generating values until: (and throw out last value)

      * eq $/    # one of them matches the cached array of the input

    ).join       # for each array in the junction join the strings (no spaces)
  }
}

2

자바 스크립트 (Node.js), 105 99 바이트

f=l=>l.filter(w=>[...Array(k=w.length)].map((x,i)=>(w+w).substr(i,k)).some(r=>l.includes(r)&&r!=w))

언 골프 드 :

f = list =>
  list.filter( word =>
    // create a list of all rotonyms for the current word
    [ ...Array( len = word.length ) ]
      .map( (x,i) => 
         ( word+word ).substr(i, len)
      )
    // check if any of the rotonyms is in the initial dictionary/wordlist
     .some( rotonym =>
        list.includes( rotonym )
    // and is not the word itself
        && rotonym != word
     )

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


PPCG에 오신 것을 환영합니다! JavaScript에 익숙하지 않지만 JavaScript Tips 스레드를 확인하여 여기에 적용되는 것이 있는지 확인 하십시오.
AdmBorkBork

힌트 주셔서 감사합니다. JS와 ES6에 대한 답변을 읽었지만 이미 관련 팁을 모두 적용한 것 같습니다. 적어도 나에게 명백한 것.
bubens 2016 년

1

레티 나 0.8.2 , 71 62 바이트

^(\w)(\w*)
$2$1!¶$&
%+)s`^(.+)(!.*¶\1)$
$2
O`
!`\b(.+)(?=¶\1!)

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

%+)

각 단어마다 반복하십시오.

^(\w)(\w*)
$2$1!¶$&

단어의 다음 회전을 뒤에 붙 !입니다.

s`^(.+)(!.*¶\1)$
$2

그러나 이것이 원래 단어라면 다시 삭제하십시오.

O`

단어를 정렬하십시오.

!`\b(.+)(?=¶\1!)

중복을 찾으십시오.


1

파이썬 2 , 66 55 70 바이트

lambda d:{w for w in d for v in d if v not in w not in v in w*2in v*3}

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

체인 접근 방식 을 사용 하기 위해 Dennis 에 11 바이트 가 사용 x in y in z됩니다.

단어 집합을 취합니다 d. 회전의 집합을 반환합니다.


수표가 너무 약합니다. {ab, abab}이 통과 할 것입니다.
xnor

@ xnor : 그 가장자리 조건을 당황! 빠른 수정 사항 ...
Chas Brown


0

Japt , 17 바이트

매우 느리지 만 작동합니다. TIO가 시간 초과되었지만 언어 소스에서 반복 횟수를 수동으로 낮춰 작동한다는 것을 확인했습니다.

f@_XéZ ÀX©UøXéZ}a
f@                // Filter the input array by
  _            }a // generating up to 1e8 rotations of each string
   XéZ ÀX         // and checking if the rotation is different than the original,
         ©UøXéZ   // yet still exists in the input array.

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


왜 반복이 그렇게 많은가? 처음에는 문자열 길이에 대해 반복을 수행했지만 테스트를 통해 단어 당 10 개의 왼쪽 회전이 MacOS dict 파일에서 모든 사례를 찾기에 충분하다는 것을 깨달았습니다.
우산

@Umbrella 쓰기가 짧기 때문에. 문제는 가장 빠른 코드가 아니라 코드 골프입니다.
Nit

내가 참조. 나는 Japt에 익숙하지 않기 때문에 반복하는 데 더 많은 캐릭터가 필요하다는 것은 분명하지 않았습니다.
우산

0

자바 스크립트, 129 자

f=a=>{n={};r=w=>w.slice(1,w.length)+w[0];a.map(w=>{m=r(w);while(m!=w){if(-~a.indexOf(m))n[m]=1;m=r(m);}});return Object.keys(n);}

언 골프

f=a=>{
    n={};
    r=w=>w.slice(1,w.length)+w[0];
    a.map(w=>{
        m=r(w);
        while(m!=w){
            if(-~a.indexOf(m))n[m]=1;
            m=r(m);
        }
    });
    return Object.keys(n);
}

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



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