가장 짧은 Pangrammatic 창


15

팬 그램은 이 코드 골프 챌린지 에서 설명하는 것처럼 알파벳의 26 자 모두를 포함하는 문장 또는 발췌입니다 . 그러나 Pangrammatic 은 일부 텍스트 세그먼트 형태의 Pangram으로 , 더 큰 작업 내에서 발견 된 단어의 중간 지점에서 끝나거나 시작될 수 있습니다. 이것은 자연스럽게 모든 곳에서 발생하며, 진정한 팬 그램의 적절한 부분 집합이므로, 무언가가 pangrammatic window를 포함하고 있는지 확인하는 것은 지루하고 이전에 수행 된 것입니다.

따라서 문자 길이에 따라 주어진 텍스트에있는 가장 작은 것을 찾는 데 관심이 있습니다! 물론 가장 짧은 코드에서 바이트 단위로 테마에 맞 춥니 다.

규칙 및 지침

  • 입력으로 문자열을 수신하고 입력에서 가장 작은 pangrammatic window의 문자열을 반환합니다 (있는 경우). 없는 경우 부울 False 또는 빈 문자열을 반환하십시오.
  • 문자열이 Pangrammatic Window인지 아닌지는 대소 문자를 구분하지 않으며 문장 부호 나 숫자 또는 기타 홀수 기호가 아닌 26 자만 의존합니다.
  • 비슷하게, pangrammatic window의 글자 길이글자 의 숫자가 아니라 글자 자체에서 나타나는 글자 의 총 개수입니다 . 반환 된 값은이 개수를 기준으로 가장 작아야합니다. 우리는 결국 프로그래머가 아닌 언어 학자입니다.
  • 그러나 Pangrammatic Window의 출력은 동일한 대문자 및 구두점 등을 포함하는 입력의 정확한 하위 문자열이어야합니다.
  • 글자 길이가 같은 가장 짧은 창문 창이 여러 개 있으면 그 중 하나를 반환하십시오.

테스트 사례

'This isn't a pangram.'
==> False

'Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).'
==> 'Quick-Brown-Fox (the one who jumped over some lazy ig'

'"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.'
==> 'ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ'

1
마지막 테스트 사례에서 왜 The five boxing wizards jump quickly반환 되지 않습니까?
Blue

1
두 번째 경우 Q? 앞에 공백이 허용 됩니까? 문자 수에 추가되지 않습니다.
Neil

2
예상 출력은 26있다 반면이, 31 편지를 가지고 있기 때문에 @muddyfish
마틴 청산

4
좋은 첫 질문!
Rɪᴋᴇʀ

2
네. 그럴 필요가 없습니다. "진정한"최소값을 취하는 것은 문제 의 정신 에 있지만 필수는 아닙니다.
Reecer6

답변:


6

Pyth, 20 16 14 바이트

hol@GNf!-GrT0.:

설명:

             .: - substrings of input()
      f!-GrT0   - filter to ones which contain the alphabet
 ol@GN          - sort by number of alphabetical chars
h               - ^[0]

      f!-GrT0   - filter(lambda T:V, substrings)
          rT0   -    T.lower()
        -G      -   alphabet-^
       !        -  not ^

 o              - sort(^, lambda N:V)
   @GN          -   filter_presence(alphabet, N)
  l             -  len(^)

여기 사용해보십시오!

올바른 솔루션이 없으면 프로그램은 stdout으로 출력하지 않고 오류와 함께 종료됩니다.


첫 번째 코드 블록에서 코드를 업데이트하지 않은 것 같습니다. 또한 !-GrT0필터 조건이 더 짧습니다. 또한 l정렬이 제대로 작동하기 위해 필요하다고 생각합니다 .
FryAmTheEggman

오, 내가 틀렸어, 나는 링크를 의미했다. 귀하의 링크에는 여전히가 있으며 l, 그것 없이는 다른 결과를 얻습니다 . 나는 문제가 반복되는 편지라고 생각하지만 100 % 확신 할 수는 없습니다.
FryAmTheEggman

따라서 중요합니다-최적화에 감사드립니다!
Blue


2

루비, 100 바이트

창이 없으면 nil을 반환합니다.

->s{r=0..s.size
(r.map{|i|s[i,r.find{|j|(?a..?z).all?{|c|s[i,j]=~/#{c}/i}}||0]}-['']).min_by &:size}

2

자바 스크립트 (ES6), 139 (138) 136 바이트

s=>[r=l="",...s].map((_,b,a)=>a.map((c,i)=>i>b&&(t+=c,z=parseInt(c,36))>9&&(v++,n+=!m[z],m[z]=n<26||l&&v>l||(r=t,l=v)),t=m=[],v=n=0))&&r

@Neil 덕분에 2 바이트를 절약했습니다!

들여 쓰기

var solution =

s=>
  [r=l="",...s].map((_,b,a)=> // b = index of start of window to check
    a.map((c,i)=>
      i>b&&(
        t+=c,
        z=parseInt(c,36)
      )>9&&(
        v++,
        n+=!m[z],
        m[z]=
          n<26||
          v>l&&l||(
            r=t,
            l=v
          )
      ),
      t=m=[],
      v=n=0
    )
  )
  &&r
<textarea cols="70" rows="6" id="input">Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).</textarea><br /><button onclick="result.textContent=solution(input.value)">Go</button><pre id="result"></pre>


사용할 수 없습니까 [r=l="",...s].map((_,b,a)=>?
Neil

@ Neil 고마워, 나는 항상 map함수 의 세 번째 매개 변수를 잊어 버렸습니다 .
user81655

@ edc65 가이를 이길 수 있다고 생각합니다. 폭발 된 하위 문자열 코드를 팬 그램 테스터 코드와 병합하고 134 바이트 함수로 끝났습니다.
Neil

내 최고는 지금까지 142
edc65

슬프게도 나는 그것을 저장하려고 생각하지 않았고 내 PC가 추락하여 이제 내가 가진 것을 알지 못합니다. 내가 지금 할 수있는 최선은 138 바이트입니다.
Neil

2

PowerShell v2 +, 218 바이트

param($a)$z=@{};(0..($b=$a.length-1)|%{($i=$_)..$b|%{-join$a[$i..$_]}})|%{$y=$_;$j=1;65..90|%{$j*=$y.ToUpper().IndexOf([char]$_)+1};if($j){$z[($y-replace'[^A-Za-z]').Length]=$y}}
($z.GetEnumerator()|sort Name)[0].Value

예, 하위 문자열 조작 (내장되어 있지 않음)은 실제로 PowerShell의 강력한 소송이 아닙니다 ...

입력을 받아서 param($a)새로운 빈 해시 테이블을 설정합니다 $z. 이것은 후보 pangrammatic substring을 저장하는 것입니다.

Exploded Substrings 에서 내 코드를 약간 수정 하여 입력의 모든 하위 문자열을 구성 합니다 . 한 문자 문장 부호 전용 하위 문자열조차도 가능합니다. 이것은 아닌 입니다. ;-)

이러한 모든 하위 문자열은 parens로 캡슐화되고을 사용하여 다른 루프로 파이프됩니다 |%{...}. 우리는 일시적으로 $y현재 하위 문자열로 설정하고 도우미 카운터를 설정하고 대문자의 ASCII 문자 코드를 통해 편리하게 $j다른 루프를 시작 65..90|%{...}합니다. 각각의 내부 루프는 $y모두 대문자로 만들고 .IndexOf특정 문자를 가져옵니다 . 이 값을 -1찾지 못하면 반환되므로에 +1곱하기 전에 결과를 얻습니다 $j. 이렇게하면 하나의 문자를 찾지 못하면 $j0이됩니다.

정확히 무엇에 if관한 것입니다. $j0이 아닌 경우 모든 문자가 하위 문자열에서 적어도 한 번 발견 $y되었으므로 후보 풀에 추가해야합니다. 우리는 복용에 의해 그렇게 $y하고 -replace우리에게 그 문자열의 문자 길이를 가져옵니다 아무것도 아닌 모든 문자를 보내고. 우리는 이것을 해시 테이블에 대한 색인으로 사용하고 해당 색인에 $z저장 $y합니다. 이것은 원래 문자열에서 "가장 먼"것과 동일한 문자 길이의 하위 문자열을 덮어 쓰는 까다로운 문제가 있지만 문자 길이에만 관심이 있기 때문에 규칙에서 허용됩니다.

마지막으로, 우리는 정렬 $z하고 가장 작은 것을 뽑아야합니다. 우리는 사용해야 .GetEnumerator상의 정렬하기 위해 호출 객체 내부 $z 다음 sort에 이들을 Name선택 용, (위에서 즉, 길이 인덱스) [0](즉, 최단) 번째 하나를, 그것의 출력 .Value(즉, 문자열)를. 이러한 하위 문자열에 맞지 않으면 Cannot index into a null array인덱싱을 시도 할 때 오류 ( )가 발생하고 $z아무 것도 출력하지 않습니다. 이는 PowerShell에서 잘못된 것입니다. (아래 세 번째 테스트 사례 [bool]에는이를 보여주기 위한 명시 적 캐스트가 있습니다 )

테스트 사례

PS C:\Tools\Scripts> .\golfing\shortest-pangrammatic-window.ps1 '"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.'
ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" 

PS C:\Tools\Scripts> .\golfing\shortest-pangrammatic-window.ps1 'Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).'
Quick-Brown-Fox (the one who jumped over some lazy ig

PS C:\Tools\Scripts> [bool](.\golfing\shortest-pangrammatic-window.ps1 "This isn't a pangram.")
Cannot index into a null array.
At C:\Tools\Scripts\golfing\shortest-pangrammatic-window.ps1:2 char:1
+ ($z.GetEnumerator()|sort Name)[0].Value
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

False

2

하스켈, 180 바이트

이것은 힘들었지 만 수입이 없으면 정말 재미있었습니다.

l=['a'..'z']
u=['A'..'Z']
f&[]=[];f&x=x:f&f x
g#h=(.g).h.g
f x|v<-[y|y<-(tail&)=<<(init&x),and$zipWith((`elem`y)#(||))l u]=last$[]:[z|z<-v,all((length.filter(`elem`l++u))#(<=)$z)v]

훨씬 덜 골프 :

lowerCase = ['a'..'z']
upperCase = ['A'..'Z']

f & x = takeWhile (not . null) $ iterate f x

(#) = flip on

subStrings x = (tail &) =<< (init & x)

pangram p = and $ zipWith ((`elem` p) # (||)) lowerCase upperCase

leqLetters x y = (length . filter (`elem` lowerCase ++ upperCase)) # (<=)

fewestLetters xs = [ x | x <- xs, all (leqLetters x) xs]

safeHead [] = ""
safeHead xs = head xs

f x = safeHead . fewestLetters . filter pangram . subStrings

놀랍고 놀랍습니다. 정말 느립니다.


2

Oracle SQL 11.2, 461 바이트

WITH s AS (SELECT SUBSTR(:1,LEVEL,1)c,LEVEL p FROM DUAL CONNECT BY LEVEL<=LENGTH(:1)),v(s,f,l)AS(SELECT c,p,p FROM s UNION ALL SELECT s||c,f,p FROM v,s WHERE p=l+1),c AS(SELECT CHR(96+LEVEL)c FROM DUAL CONNECT BY LEVEL<27),a AS(SELECT LISTAGG(c)WITHIN GROUP(ORDER BY 1) a FROM c)SELECT MIN(s)KEEP(DENSE_RANK FIRST ORDER BY LENGTH(s)-NVL(LENGTH(TRANSLATE(LOWER(s),' '||a,' ')),0))FROM(SELECT s,f,SUM(SIGN(INSTR(LOWER(s),c)))x FROM v,c GROUP BY s,f),a WHERE x=26;

언 골프

WITH s AS (SELECT SUBSTR(:1,LEVEL,1)c,LEVEL p FROM DUAL CONNECT BY LEVEL<=LENGTH(:1))
,v(s,f,l) AS
(
  SELECT c,p,p FROM s
  UNION ALL
  SELECT s||c,f,p FROM v,s WHERE p=l+1 
)
,c AS(SELECT CHR(96+LEVEL)c FROM DUAL CONNECT BY LEVEL<27)
,a AS(SELECT LISTAGG(c)WITHIN GROUP(ORDER BY 1) a FROM c)
SELECT MIN(s)KEEP(DENSE_RANK FIRST ORDER BY LENGTH(s)-NVL(LENGTH(TRANSLATE(LOWER(s),' '||a,' ')),0))
FROM(SELECT s,f,SUM(SIGN(INSTR(LOWER(s),c)))x FROM v,c GROUP BY s,f),a
WHERE x=26

s보기는 문자 입력을 분할하고 각 문자의 위치를 반환합니다.

재귀 뷰 v는 입력
의 모든 하위 문자열을 반환합니다. s 하위 문자열
f 하위 문자열 의 첫 번째 문자
위치 l 현재 하위 문자열에 추가 된 마지막 문자의 위치

c보기는 한 번에 알파벳, 하나 개의 문자를 반환

a보기는 하나의 문자열로 연결된 알파벳을 반환

SELECT s,f,SUM(SIGN(INSTR(LOWER(s),c))
각 하위 문자열에 대해 고유 문자 수를
INSTR반환하고 하위 문자열에있는 문자의 위치를 ​​반환합니다. 존재하지 않으면 0
SIGN은 pos> 0이면 1, pos = 0이면 0을 반환합니다

WHERE x=26
전체 알파벳을 포함하는 부분 문자열을 필터링합니다.

TRANSLATE(LOWER(s),' '||a,' ')
부분 문자열에서 모든 문자를 삭제합니다

LENGTH(s)-NVL(LENGTH(TRANSLATE(LOWER(s),' '||a,' ')
문자 길이는 문자가없는 부분 문자열의 길이에서 부분 문자열의 길이를 뺀 값입니다.

SELECT MIN(s)KEEP(DENSE_RANK FIRST ORDER BY LENGTH(s)-NVL(LENGTH(TRANSLATE(LOWER(s),' '||a,' ')),0))
문자 수가 적은 부분 ​​문자열 만 유지합니다.
둘 이상이 있으면 문자열 오름차순으로 정렬 된 첫 번째 문자열이 유지됩니다.


2

Python 3, 171, 167, 163, 157 , 149 바이트

DSM 덕분에 4 바이트를 절약했습니다.
RootTwo 덕분에 8 바이트가 절약되었습니다.

lambda x,r=range:min([x[i:j]for i in r(len(x))for j in r(len(x))if{*map(chr,r(65,91))}<={*x[i:j].upper()}]or' ',key=lambda y:sum(map(str.isalpha,y)))

글자 수를 기준으로 정렬 해야하는 것은 나를 죽입니다.

테스트 사례 :

assert f("This isn't a pangram.") == ' '
assert f("Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).") == ' Quick-Brown-Fox (the one who jumped over some lazy ig', f("Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).")
assert f('"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.') == '. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ', f('"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.')

.upper()핵심 기능에 필요 하다고 생각하지 마십시오 .
RootTwo

@RootTwo 죄송합니다. 맞습니다. 감사.
Morgan Thrapp

1

PowerShell (v4), 198 156 바이트

param($s)
-join(@(1..($y=$s.Length)|%{$w=$_
0..$y|%{(,@($s[$_..($_+$w)]))}}|?{($_-match'[a-z]'|sort -U).Count-eq26}|sort -Pr {($_-match'[a-z]').count})[0])


# Previous 198 byte golf
$a,$b,$c=@(1..($s="$args").Length|%{$w=$_
0..($s.Length-$w)|%{if((($t=$s[$_..($_+$w)]-match'[a-z]')|sort -u).Count-eq26){(,@($t.Length,$_,$w))}}}|sort -pr{$_[0]})[0]
(-join($s[$b..($b+$c)]),'')[!$a]

테스트 사례

PS C:\> .\PangramWindow.ps1 "This isn't a pangram."


PS C:\> .\PangramWindow.ps1 'Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).'
Quick-Brown-Fox (the one who jumped over some lazy ig

PS C:\> .\PangramWindow.ps1 '"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.'
ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!

원본에 대한 설명없이

모든 크기의 슬라이딩 윈도우를 만드는 무차별 강제 중첩 루프입니다.

.SubString(0, 1) -> slide window over the string
.SubString(0, 2) -> slide window over the string
..
.SubString(0, string.Length) -> slide window over the string

각 창에 대해 문자 만 필터링하고 (기본적으로 대소 문자를 구분하지 않는 정규식 일치) 고유 한 필터를 통해 나머지 문자를 실행하고 팬 그램 테스트로 26 개의 고유 한 문자가 있는지 확인합니다.

팬 그램이있는 모든 창은 (두피를 포함한 문자 수, 시작 색인, 문장 부호를 포함한 창 길이)의 삼중으로 바뀝니다.이 문자 는 전체 문자 수로 가장 짧은 것을 찾기 위해 정렬되고 첫 번째 문자가 선택 되고 그로부터 작성된 출력 문자열 .

문자열의 경계 외부에는 많은 인덱싱이 있으며 PowerShell은 예외를 throw하는 대신 $ null을 반환하는 데 유용합니다.

NB. 새로운 156 바이트 1은 동일한 접근 방식이지만 파이프 라인을 훨씬 더 많이 사용하도록 다시 작성되었습니다.

$string = "$args"

# increasing window widths, outer loop
$allPangramWindows =  foreach ($windowWidth in 1..$string.Length) {

    # sliding windows over string, inner loop
    0..($string.Length - $windowWidth) | ForEach {

        # slice window out of string, returns a char array
        $tmp = $string[$_..($_+$windowWidth)]

        # filter the char array to drop not-letters
        $tmp = $tmp -match '[a-z]'

        # Drop duplicate letters
        $tmpNoDupes = $tmp | sort -Unique

        # If we're left with a 26 character array, this is a pangrammatic window. Output
        # a PowerShell-style tuple of count of letters, start index, width.
        if($tmpNoDupes.Count -eq 26){
            (,@($tmp.Length,$_,$windowWidth))
        }
    }
}

# Force the result into an array (to handle no-results), sort it
# by the first element (num of letters in the window, total)
$allPangramWindows = @( $allPangramWindows | sort -Property {$_[0]} )

# take element 0, a window with the fewest letters
$windowCharCount, $windowStart, $WindowEnd = $allPangramWindows[0]

# uses the results to find the original string with punctuation and whitespace
if ($windowLen) {
    $string[$windowStart..($windowStart + $windowLen)] -join ''
}

NB. ungolfed 버전이 작동하는지 확실하지 않습니다. 필자가 골프를 쓰지 않았기 때문에 박람회 용입니다.


0

하스켈, 123 바이트

import Data.Lists
import Data.Char
h x=take 1$sortOn((1<$).filter isAlpha)[e|e<-powerslice x,['a'..'z']\\map toLower e==""]

hpangrammatic 창이 없거나 최소 창이 하나 인 요소 목록이없는 경우 빈 목록을 반환 하는 function을 정의합니다 . 사용 예 :

*Main>  h "'The five boxing wizards jump quickly.' stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. 'ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!' he shouted to the heavens."
[". 'ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ"]

작동 방식 :

          [e|e<-powerslice x                  ]  -- for all continuous subsequences
                                                 -- e of the input  
                ,['a'..'z']\\map toLower e==""   -- keep those where the list
                                                 -- difference with all letters is
                                                 -- empty, i.e. every letter appears
                                                 -- at least once
    sortOn((1<$).filter isAlpha)                 -- sort all remaining lists on
                                                 -- their length after removing all
                                                 -- non-letters -> (1<$) see below
take 1                                           -- take the first, i.e. the minimum


calculating the length of a list: we're not interested in the length itself, but
in the relative order of the length. (1<$) replaces each element in a list with
the number 1, e.g. "abc" -> "111", "abcd" -> "1111", etc. Such '1'-strings have
the same order as the length of the original list. One byte saved!
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.