하나의 숫자로 구성 할 수있는 영숫자 수를 찾으십시오


23

영숫자 문자에는 ASCII 값이 있습니다.

0-9  ->  48-57
A-Z  ->  65-90
a-z  ->  97-122

문제는 정수를 입력으로 사용하고 해당 숫자의 연속 숫자를 사용하여 만들 수있는 문자 수를 출력하는 것입니다. 문자 코드가 겹칠 수 있습니다. 두 번 있기 때문에 666결과가 나타납니다 .266

테스트 사례 :

Input: 5698
Possible characters: '8' (56), 'E' (69), 'b' (98)
Output: 3

Input: 564693
Possible characters: '8' (56), 'E' (69)
Output: 2

Input: 530923864209124521
Possible characters: '5' (53), 'V' (86), '4' (52)  
Output: 3

Input: 1111111
Possible characters: 'ooooo' (5*111)
Output: 5

Input: 5115643141276343
Possible characters: '3' (51), '8' (56), 'L' (76), 's' (115)
Output: 4

Input: 56789
Possible characters: '8' (56), 'C' (67), 'N' (78), 'Y' (89)
Output: 4

Input: 94
Possible characters: ''
Output: 0

Input: 1
Output: 0

입력 및 출력 형식은 선택 사항입니다 (예, 정수를 문자열로 사용할 수 있음).

답변:


11

05AB1E , 8 7 바이트

žKÇIŒÃg

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

설명

žK       # push [a-zA-Z0-9]
  Ç      # convert to list of ascii codes
   IŒ    # push all substrings of input
     Ã   # keep only the subtrings which exist in the list of acsii codes
      g  # push length of resulting list

ŒžKÇÃg작동하지 않습니까?
— Magic Octopus Urn

@carusocomputing : 불행히도 1111111테스트 사례에 실패했습니다 .
— Emigna

Ã, 그것은 내가하고있는 일을 읽었으므로 훨씬 더 의미가 있습니다.
— Magic Octopus Urn

7

Brachylog , 22 바이트

∧Ạụ:Ạ:Ịcạ:?{tT&h∋~sT}ᶜ

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

설명

       c                 Concatenate together:
∧Ạụ:                       "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Ạ:                     "abcdefghijklmnopqrstuvwxyz"
      Ị                    "0123456789"
        ạ                Get the list of ASCII codes of that string
         :?{        }ᶜ   Count the number of results, for input [list of codes, Input], of:
            tT             Call the Input T
              &h∋          Take one ASCII code
                 ~sT       It is a substring of T

불행히도 나를 위해, 다행히도 당신을 위해, 나는 지금 컴퓨터에 액세스 할 수 없습니다;)
— Leaky Nun

@LeakyNun 나는 버그로 인해 실패하는 짧은 방법을 생각했습니다.
— Fatalize

두 사람을 합칠 수 있습니까 T?
— Leaky Nun

1
이 버그의 원인은 무엇입니까?
— Leaky Nun

1
@LeakyNun 예를 들어 정수 13의 경우 무한히 많은 목록과 13을 포함하는 무한정의 많은 정수가 있으며 어떤 순서로 나열해야하는지 명확하지 않습니다.
— Fatalize

7

MATL , 17 13 바이트

8Y2"G@oVXf]vn

온라인으로 사용해보십시오! 또는 모든 테스트 사례를 확인하십시오 .

설명

8Y2     % Predefined literal: string with all letters, uppercase and lowercase,
        % and digits
"       % For each character in that string
  G     %   Push input, for example the string '5115643141276343'
  @     %   Push current character, such as 'A'
  o     %   Convert to its ASCII code, such as 65
  V     %   String representation, such as '65'
  Xf    %   Find string '65' within string '5115643141276343'. This gives a vector
        %   (possibly empty) with indices of occurrences
]       % End
v       % Concatenate all stack contents vertically
n       % Number of entries. Implicitly display

6

자바 7, 204 197 195 바이트

int c(String n){int r=0,i=0,e=n.length()-1,t;for(;i<e;r+=((t=new Byte(n.substring(i,i+2)))>47&t<57)|(t>64&t<91)|(t>96&t<100)|((t=new Short(n.substring(i,i++>e-2?i:i+2)))>99&t<123)?1:0);return r;}

설명:

int c(String n){       // Method with String parameter and integer return-type
  int r=0,             //  Result
      i=0,             //  Index
      e=n.length()-1,  //  Length of String -1
      t;               //  Temp integer
  for(;i<e;            //  Loop over the String using the index
    r+=                //   Append the result-sum with:
      ((t=new Byte(n.substring(i,i+2)))>47&t<57)|(t>64&t<91)|(t>96&t<100)
                       //    If two adjacent digits are a digit or letter
      |                //    or
      ((t=new Short(n.substring(i,i++>e-2?i:i+2)))>99&t<123)?
                       //    if three adjacent digits are a letter
       1               //     Raise the sum by 1
      :                //    Else:
       0               //     Keep the sum the same (by adding 0)
  );                   //  End of loop (implicit / no body)
  return r;            //  Return result
}                      // End of method

테스트 코드 :

여기에서 시도하십시오.

class M{
  static int c(String n){int r=0,i=0,e=n.length()-1,t;for(;i<e;r+=((t=new Byte(n.substring(i,i+2)))>47&t<57)|(t>64&t<91)|(t>96&t<100)|((t=new Short(n.substring(i,i++>e-2?i:i+2)))>99&t<123)?1:0);return r;}

  public static void main(String[] a){
    System.out.println(c("5698"));
    System.out.println(c("564693"));
    System.out.println(c("530923864209124521"));
    System.out.println(c("1111111"));
    System.out.println(c("5115643141276343"));
    System.out.println(c("56789"));
    System.out.println(c("94"));
    System.out.println(c("1"));
  }
}

지금 컴퓨터에 액세스 할 수 없으므로 확인할 수 없지만 다음 두 가지 제안이 있습니다. 1. 초기화를 for 루프에 넣습니다. 2. 문자열 조작 대신 산술을 사용하십시오 (정수 나누기를 사용하여 숫자를 반복하고 모듈로를 사용하여 마지막 2 또는 3 자리를 추출하십시오).
— Leaky Nun

@LeakyNun 제안 해 주셔서 감사합니다. 첫 번째 경우 정수 초기화가 for 루프 외부에있는 이유는 결과 ( r) 를 반환해야하기 때문 입니다. 그러나, 나는 하나의 삼항으로 for 루프 안에 다른 모든 것을 넣음으로써 7 바이트를 골프 수있었습니다. 나중에 두 번째 제안을 할 수 있는지 살펴 보겠습니다. 점심 시간이 다시 끝나서 다시 일을해야합니다. 명심하십시오.
— Kevin Cruijssen

5

자바 스크립트 (ES6), 71 70 바이트

f=([a,...b])=>a?(a&(a+=b[0])+b[1]<123|a>47&a<58|a>64&a<91|a>96)+f(b):0

테스트 사례


4

펄 5 , 47 바이트

46 바이트의 코드 + -p플래그

$"="|";$_=()=/(?=@{[48..57,65..90,97..122]})/g

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

나는 그것을 쓸 수있는 짧은 방법을 찾을 수 없습니다 48..57,65..90,97..122: map{ord}0..9,a..z,A..Z(문자의 아스키 값을 받고) 한 바이트 이상을. 그리고 for$c(0..122){$\+=chr($c)=~/\pl|\d/ for/(?=$c)/g}}{(모든 숫자를 찾고 문자 ( \pl) 또는 숫자 ( \d) 의 ASCII 값에 해당하는 숫자 만 유지하면 5 바이트가 길어집니다 ( 후자는 밑줄도 포함하므로 \pl|\d바꿀 수 없습니다 \w)) .


이전 접근 방식 (49 바이트) :

for$@(48..57,65..90,97..122){$\+=()=/(?=$@)/g}}{


1

자바 스크립트 (ES) 165 161 156 154 153 바이트

네, RegEx는 확실히이 일에 적합한 도구가 아니 었습니다!

n=>[/\d{2}/g,/\d{3}/g].map(e=>eval("while(x=e.exec(n)){a.push(m=x[0]);e.lastIndex-=m.length-1}"),a=[])|a.filter(x=>x>47&x<58|x>64&x<91|x>96&x<123).length

시도 해봐

f=

n=>[/\d{2}/g,/\d{3}/g].map(e=>eval("while(x=e.exec(n)){a.push(m=x[0]);e.lastIndex-=m.length-1}"),a=[])|a.filter(x=>x>47&x<58|x>64&x<91|x>96&x<123).length

console.log(f(5698))//3
console.log(f(564693))//2
console.log(f(530923864209124521))//3
console.log(f(1111111))//5
console.log(f(5115643141276343))//4
console.log(f(56789))//4
console.log(f(94))//0
console.log(f(1))//0


정규 표현식은 그렇게 나쁘지 않습니다. 내 Retina 답변의 포트는 78 바이트였습니다.
— Neil



1

하스켈, 161 (157) 138 (129) 126 바이트

import Data.List
f x=sum[1|y<-nub$concat$words.concat<$>mapM(\c->[[c],c:" "])x,any(elem$read y)[[48..57],[65..90],[97..122]]]

Nub를 위해 Data.List를 가져 오는 것보다 목록의 중복을 제거하는 더 좋은 방법이 있는지 궁금합니다.


1
Data.Lists대신에 가져 오는 경우 다음을 Data.List사용할 수 있습니다 y<-tail$powerslice x..
— nimi

@nimi 비표준 모듈을 다운로드하여 설치해야한다면 골프 규칙에 위배됩니까? Data.Lists가 GHC의 표준이라고 생각하지 않습니다.
— maple_shaft

내가 아는 한 우리는 여전히 표준 모듈로 간주되는 것에 대한 합의가 없습니다. 여기에는 몇 가지 Haskell 답변이 있습니다 Data.Lists. Haskell 의 골프 팁 에서도 언급되었습니다 . 지금까지 아무도 불평하지 않았습니다.
— nimi

@nimi 솔직히 cabal에서 패키지를 다운로드 할 수 있다면 문제를 해결하는 함수를 작성하고 업로드 한 다음 솔루션에서 모듈을 가져올 수 있다고 생각합니다. 기술적으로 나는 속일 수있었습니다. 그러나 특정 도전 과제는 암호와 같은 기본 GHC로 수행 할 수 없으므로 알 수 없습니다.
— maple_shaft

1
팁 골프로 돌아 가기 : or $ f <$> list이다 any f list: any(elem$read y)[...].
— nimi

0

Pyth, 19 17 14 바이트

l@jGUTmr0Csd.:

문자열을 가져옵니다.

@LeakyNun 덕분에 -3 바이트

시도 해봐!

설명

l@jGUTmr0Csd.:
    UT                # the list of digits [0,1,2,...,9]
  jG                  # join that on the lowercase alphabet (repetition doesn't matter)
              Q       # implicit input
            .:        # all substrings of the input
      m               # for each of those substrings
          sd          # Convert the string to a base 10 integer
         C            # convert that integer to the character with that number
       r0             # make that character lowercase
l@                    # length of the intersection of those two list of chars we generated

을 사용하는 대신을 사용할 idT수 있습니다 sd.
— Leaky Nun

또한 l@jGUTmr0Csd.:더 짧을 수도 있습니다 (작동하는지 확실하지 않음).
— Leaky Nun

@LeakyNun 감사합니다,이 작동합니다!
— KarlKastor

0

젤리 , 8 바이트

ØBODf@ẆL

입력은 숫자 배열입니다.

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

작동 원리

ØBODf@ẆL  Main link. Argument: A (digit array)

ØB        Base 62; yield all alphanumeric ASCII characters.
  O       Ordinal; get their code points.
   D      Decimal; convert the code points into digit arrays.
      Ẇ   Window; yield all contiguous subarrays of A.
    f@    Filter swapped; keep all elements of the result to the right that appear
          in the result to the left.
       L  Length; count the matches.

0

루비, 50 바이트

p (0..~/$/).any?{|n|$_[n,2].to_i.chr=~/\p{Alnum}/}

표준 입력에서 읽습니다. Ruby 인터프리터를 -n옵션 (암시 적 while gets루프) 으로 호출해야합니다 .

밑줄과 일치하도록 허용 된 경우 43 바이트로 줄일 수 있습니다.

p (0..~/$/).any?{|n|$_[n,2].to_i.chr=~/\w/}

문자가 표시되는 횟수는 반환하지 않습니다. 또한에 실패 하지만 111반환해야 1하지만을 돌려드립니다 0.
— Value Ink

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