Pandigital 배가


14

CMC에서 영감을 얻은

양수가 0보다 큰 경우 다음 작업을 수행하십시오.

  • 10 개의 단일 숫자 ( 1234567890)가 모두 한 번 이상 숫자 인 경우 카운트를 출력하고 프로그램을 종료
  • 그렇지 않으면 숫자를 두 배로 늘리고 반복하여 카운트를 증가시킵니다.

카운트는 0에서 시작하며 입력이 두 배가 된 횟수입니다. 예를 들어, 입력이 617283945 인 경우 1234567890에 10 자리가 모두 있으므로 두 번 입력해야합니다.

이것은 이므로 가장 짧은 코드가 승리합니다. 원하는 경우 입력을 문자열로 사용할 수 있습니다.

테스트 사례

input => output

617283945 => 1
2 => 67
66833 => 44
1234567890 => 0
100 => 51
42 => 55

입력을 문자열로 할 수 있습니까?
Stephen

@Stephen은 문자열로 입력을받을 수 있습니다.
caird coinheringaahing

3
그것은 어떤을 위해 그것을 보장 n어떤 존재 k그러한 nkpandigital이다는? 증거를보고 싶습니다.
shooqie

1
@bfontaine 채팅 미니 챌린지
caird coinheringaahing

3
@shooqie Proof! 10에 coprime 인 n의 경우 10 ^ 10에도 coprime이므로 nk가 1 mod 10 ^ 10이되는 k가 있습니다. 그런 다음 1234567890 * nk = 1234567890 mod 10 ^ 10이므로 각 숫자는 반드시 한 번 이상 나타납니다. 그렇지 않은 경우, 0이 아닌 마지막 코 프라임을 10으로 만들기 위해 필요에 따라 2, 5 또는 25를 곱하고 위의 증거의 변형이 작동합니다 (공식적으로 n = 10 ^ m * p, 여기서 p는 위의 조건을 충족 함). 위와 같이 1234567890 * p * k는 pandigital이므로 1234567890 * p * k * 10 ^ m = 1234567890 * k * n은)입니다. :)
B. Mehta

답변:



4

J , 24 23 바이트

(]1&(+$:)2**)10>#@~.@":

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

설명

(]1&(+$:)2**)10>#@~.@":  Input: integer n
                     ":  Format as string
                  ~.@    Unique
                #@       Length
             10>         Less than 10
           *             Multiply, gives n if previous was true, else 0
         2*              Multiply by 2
 ]                       Get the previous condition
  1&(   )                Execute this if true on 2n, else return 0
      $:                   Recurse
  1  +                     Add 1

좋은. 나는 결과를 수집하는 데 붙어 있었고, 그 유형의 재귀 함수를 사용하는 것에 대해서는 생각하지 않았습니다.
코너 오브라이언

4

05AB1E , 11 10 바이트

scottinet 덕분에 -1 바이트

[D9ÝåË#·]N

온라인으로 사용해보십시오! 또는 테스트 스위트

[          // Start infinity loop
 D         // Duplicate current value (or input)
  9Ý       // Push [0,1,2,3,4,5,6,7,8,9]
    å      // Does each exist in the current value
     Ë#    // Break if all equal (if every digit exists)
       ·   // Else double the current value
        ]N // End loop and print the number of times through the loop


@ scottinet 감사합니다! 어떻게 그리웠는지 모르겠습니다.
라일리

@riley는 말할 use x것이지만 10도 있습니다 ... 좋은 답변. 생각 x은 제거 D되지만 같은 생각입니다.
Magic Octopus Urn

3

펄 6 ,31 28 바이트 (27 자)

@Joshua 덕분에 -3 바이트

{($_,2×*...*.comb.Set>9)-1}

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

설명 : 목록을 반복적으로 생성하는 동일한 구성입니다. 첫 번째 요소는 주어진 수 (있다 $_, 다음의 각 요소)은 2 시간 이전 ( 2×*- 2 바이트 문자 있지만, 여전히 1 바이트보다 저렴, 때문에 우리가, × 사용 2 * *), 그리고 우리가 최종 상태까지이를 *.comb.unique>9만족 즉, 숫자에 9 개 이상의 고유 문자가있는 경우. (기술적으로, 우리는 문자로 목록까지 문자열을 깰 .comb와 세트로 강제로 .Set) 물론, 설정 한 번만 각 요소를 포함 (, 9, 비교하는 힘 차례로주는 수치 컨텍스트로 설정, 요소 수)

마지막으로이 목록에서 1을 뺍니다. 다시 말하지만, 목록은 숫자 컨텍스트로 강제 적용되므로 반환되는 것은 해당 목록의 길이보다 1이 짧습니다.


.Set대신 .unique3 바이트를 절약 할 수 있습니다 .
Joshua

@Joshua, 좋은 지적입니다! 감사합니다. 나는 이것을 전혀 생각하지 않았다.
Ramillies

3

자바 스크립트 (ES6) + big.js , 84 74 73 70 바이트

bignumber.js 대신 big.js 를 제안하여 10 바이트를 절약 해 준 @ ConorO'Brien 에게
감사합니다. -1 바이트에 대한 @Rick Hitchcock
덕분 에 -3 바이트에 대한 @Shaggy 덕분에

f=n=>[..."4"+2**29].every(d=>RegExp(d).test(c=Big(n)))?0:1+f(c.mul(2))

입력을 문자열로 취합니다. 약 2까지 지원 69 의한 자동 표기법 변환은 포인트 이상 발생.

테스트 스 니펫

f=n=>[..."4"+2**29].every(d=>RegExp(d).test(c=Big(n)))?0:1+f(c.mul(2))

;[617283945, 2, 66833, 1234567890, 100, 42].forEach(t=>console.log(`f(${t}) = `+f(t)))
<script src="https://cdn.rawgit.com/MikeMcl/big.js/c6fadd08/big.min.js"></script>

무한 범위, 106 88 87 84 바이트

숫자를 문자열로 변환 할 때 과학 표기법을 효과적으로 비활성화하기 위해 config 옵션을 사용하면 거의 무한한 범위를 가질 수 있습니다.


big.jsBigNumber 를 사용하여 비트를 줄일 수 있습니까?
코너 오브라이언

@ ConorO'Brien 특히 도움이 될 것 new입니다. 감사합니다!
저스틴 마리너

로 1 바이트를 저장하십시오 f=n=>[..."0123456789"].every(d=>RegExp(d).test(c=Big(n)))?0:1+f(c.mul(2)).
Rick Hitchcock

큰 정수를 처리 할 필요가 없으므로 원하는 경우 big.js를 삭제하여 61 바이트로 줄일 수 있습니다. 그리고 당신과 함께 숫자의 문자열을 대체하여 3 바이트를 저장할 수 있습니다 "4"+2**29: tio.run/##BcGxDkAwEADQb2GQO41LNBZDbX7AKgbhKkSu0jZSX1/...
얽히고 설킨

2

젤리 , 12 , 11 바이트

QLn⁵
ḤÇпL’

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

빨리 가야 해!

설명:

        # Helper link, takes one argument 'z'
Q       # The unique digits of 'z'
 L      # Length
  n     # Does not equal
   ⁵    # 10
        #
        # Main link
  п    # While <condition> is true, run <body> and return all intermediate results
        # Condition:
 Ç      #   The helper link
        # Body:
Ḥ       #   Double the input
        # Now we have a list of all the 'z's that we passed to the helper link
    L   # Return it's length
     ’  # minus one




2

하스켈, 44 바이트

until(\c->all(`elem`show(n*2^c))['0'..'9'])(+1)0

2

클로저, 115 89 82 바이트

문자열을 사용하여 문자 목록을 나타내는 -26 바이트 (duh, 회고) 및 재귀 사용에서로 변경하여 loop몇 가지 최적화를 수행 할 수있었습니다.

에 대한 호출을 제거하여 -7 바이트 bigint . 분명히 오버플로를 일으키지 않는 입력 만 처리하면됩니다.

#(loop[n % c 0](if(empty?(remove(set(str n))"1234567890"))c(recur(* 2 n)(inc c))))

사전 골프 :

(defn pan [num]
  (loop [n num
         cnt 0]

    ; Remove all the characters from the stringified input
    ;  that are numeric. If the result is an empty list, all
    ;  the numbers were present.
    (if (empty? (remove (set (str n)) "1234567890"))
      cnt
      (recur (* 2 n) (inc cnt)))))

every?대신 다음을 사용하여 7 바이트를 절약 할 수 있습니다 empty? (remove ….#(loop[n % c 0](if(every?(set(str n))"1234567890")c(recur(* 2 n)(inc c)))))
bfontaine

@bfontaine 아, 맞아요! 감사. 나중에 고칠 게요. 감사.
Carcigenicate

2

망막 , 85 바이트

^\d*
$&¶$&
D`.(?=.*¶)
\d{10}¶\d+|\d*¶

[5-9]
#$&
T`d`EE
T`_d#`d_`\d#
#
1
}`\d\b
$&@
@

온라인으로 사용해보십시오!링크에는 테스트 사례가 포함됩니다. 런타임에 약간 최적화되었습니다. 설명:

^\d*
$&¶$&

입력 번호를 복제하십시오.

D`.(?=.*¶)

첫 번째 사본의 숫자를 중복 제거하십시오.

\d{10}¶\d+|\d*¶

10 자리가 남아 있으면 두 숫자를 모두 삭제하십시오. 그렇지 않으면 첫 번째 사본 만 삭제하십시오. 두 숫자를 모두 삭제하면 나머지 루프가 작동하지 않습니다.

[5-9]
#$&

장소 #큰 자릿수 앞에 를 배치하십시오.

T`d`EE

각 자리수를 두 배로 늘리십시오.

T`_d#`d_`\d#

캐리에 추가하십시오.

#
1

최고의 캐리를 다루십시오.

}`\d\b
$&@

추가 @10 자리가 모두 발견 될 때까지 및 루프를 .

@

@추가 된 수를 인쇄하십시오 .


2

APL (Dyalog Unicode) , 19 + 2 = 21 바이트

0∘{∧/⎕D∊⍕⍵:⍺⋄⍺+12×⍵}

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

이것은 이항이다 Dfn( D irect F unctio N 의 인수 왼쪽 및 오른쪽과 같은 정수로서 0 복용). 입력은 정수로만 가정되므로 인수에 2 바이트를 추가했습니다.0∘ 되므로 바이트 수에 에 .

f← 바이트 수에 포함되지 않습니다. 필요 않습니다 . 테스트 사례를보다 쉽게 ​​구축 할 수 있습니다.

작동 방식 :

헤더 : APL 룸에서 채팅 한 후 바이트 수에서 제거했습니다. 기능이 수행해야 할 작업을 수행하고 APL의 REPL의 기본 설정으로 인해 결과가 올바르지 않기 때문입니다.

⎕FR←1287세트 F loat의 R의 128 비트 소수에 epresentation를 (7 APL의 REPL에서 소수점 코드입니다). ⎕PP←34세트 P의 RINT의 P의 34 자리 recision합니다. 큰 숫자에 대한 APL의 기본 표현은 그것들을 과학적 표기법 (예 : 3.14159265359E15)으로 변환하여 코드를 크게 엉망으로 만들기 때문에 둘 다 필요합니다.

0∘{∧/⎕D∊⍕⍵:⍺⋄⍺+12×⍵}  Dyadic Dfn
0                      Fixes 0 as the left argument  
          :             If
     D                 String representation of all digits [0, 9]
                       "is in"
        ⍕⍵              String representation of the input
   ∧/                   AND-reduction. Yields 1 (true) iff all digits are in the right argument.
                       return the left argument
                       Else
                 2×⍵    Double the right arg
             ⍺+1        increment the left arg
                       Recursively call this function with the new arguments.

2

자바 8 132 110 87 74 바이트

n->{int c=0;for(;(n+"").chars().distinct().count()!=10;n*=2)c++;return c;}

@ OlivierGrégoire 덕분에 -57 바이트 .

설명:

여기에서 시도하십시오. (참고 : 테스트 케이스 2는 2 68 에서 중지해야하므로 사용할 수 없지만 크기는 long2 63-1 로 제한됩니다 .)

n->          // Method with long parameter and integer return-type
  int c=0;   //  Count-integer, starting at 0
  for(;(n+"").chars().distinct().count()!=10;
             //  Loop (1) as long as the unique amount of digits in the number are not 10
    n*=2)    //    After every iteration: multiply the input by 2
   c++;      //   Increase the count by 1
             //  End of loop (1) (implicit / single-line body)
  return c;  //  Return the counter
}            // End of method

이전 132 바이트String입력과 정규식을 사용하여 응답합니다 .

n->f(n,0)int f(String n,int c){String t="";for(int i=0;i<10;t+="(?=.*"+i+++")");return n.matches(t+".*")?c:f(new Long(n)*2+"",c+1);}

여기에서 시도하십시오. (참고 : 테스트 케이스 2는 재귀가 너무 많기 때문에 StackOverflowException이 발생하므로 비활성화됩니다.)

문자열에 9 자리가 모두 포함되어 있는지 확인하기위한 총 정규 표현식 ^(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9).*$은이되어 전체 문자열에 대해 양의 미리보기를 사용합니다.


1
111 바이트 (넵, 바이트 카운트는 "단방향 디지털"; - 인
올리비에 그레

우리 2^68는 첫 번째 pandigital 숫자로 기대하기 때문에 2는 작동하지 않지만 Java의 long은으로 제한됩니다 2^63-1.
Olivier Grégoire

1
87 바이트 . 감사합니다 reduce\ o /
Olivier Grégoire

1
74 바이트 . 여기서 멈추는 ;-)
Olivier Grégoire

1
@KevinCruijssen 나는 당신이 당신의 오래된 방법을 말살했다는 것을 알고 있지만, 다음 정규식을 사용하여 모든 10 자리를 일치시킬 수 있음을 지적하고 싶습니다.(?:.*?(\d)(?!.*\1)){10}
jaytea

1

껍질 , 10 바이트

←Vö>9Lud¡D

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

설명

        ¡D    Repeatedly double the input, collecting results in a list
 V            Return the first index where the following is true
     L          The length of
       d        the digits
      u         with duplicates removed
  ö>9           is greater than 9
←             Decrement (as Husk uses 1-indexing)

1

매스 매 티카, 59 48 47 46 38 바이트

Jenny_mathy 덕분에 -9 바이트.

If[!FreeQ[DigitCount@#,0],#0[2#]+1,0]&

Mathics를 사용하여 온라인으로 사용해보십시오!


2
46 바이트 : If [Tr [1 ^ Union @ IntegerDigits @ #] <10, # 0 [2 #] + 1,0] &
J42161217

Mathematica는 익명의 재귀 함수를 허용합니다. 고마워!
완전히 인간적인

2
38 바이트 : If [! FreeQ [DigitCount @ #, 0], # 0 [2 #] + 1,0] &
J42161217

오 감사! BTW,``는 코드에 사용될 수 있지만 선행 공백은 허용되지 않습니다. a작동하지만`a`는 작동하지 않습니다.
완전히 인간적인

! 확인 BTW 당신은 TIO이 바닥 글 사용할 수 있습니다 Print/@f/@{617283945,2,66833,1234567890,100,42}
J42161217

1

R , 74 바이트

function(x){while(!all(0:9%in%el(strsplit(c(x,""),"")))){F=F+1;x=2*x};F*1}

온라인으로 사용해보십시오! R은 f(2)언어가 큰 정수를 저장하는 방법의 제한으로 인해 잘못된 답변을 제공합니다 .

설명 : pandigitality 테스트의 경우 입력은 빈 문자열과 결합하여 문자 벡터로 강제 변환 된 다음 개별 숫자로 분할됩니다. 그런 다음 결과 벡터에 0 : 9가 모두 있는지 확인합니다. 그렇지 않으면 카운터를 증가시키고 입력을 두 배로 늘리고 반복합니다.

카운터는 FALSE로 초기화되는 F를 사용합니다. 숫자로 강제 변환하기 위해 반환하기 전에 1을 곱합니다.


사용 c(x,"")은 깔끔한 트릭입니다el(strsplit(...))
Giuseppe

1

PowerShell , 70 69 바이트

for($n=[bigint]$args[0];([char[]]"$n"|group).count-le9;$n*=2){$i++}$i

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

(Python 답변 :-\ 길이의 거의 두 배)

입력 $args[0]을 받아 a로 캐스트하여 [bigint]저장합니다 $n. 입력합니다 for루프. 우리가 여부에 대해 확인 각 반복 $n암갈색가에 다음 문자열로 변환 char할 때 -array은 Group-Object'함께 거라고하는이 .count -l나보다 더 ESS eQUAL에를 9. 즉, 10과 같은 유일한 방법은 모든 숫자 중 하나 이상의 숫자 1234567890가 존재하는 것입니다. 그렇다면 루프를 종료하십시오. 그렇지 않다면, 우리는 $n*=2계속합니다. 루프 내부의 각 반복은 단순히 증가하고 $i있습니다. 루프를 종료하면 간단히 출력 $i합니다.

1234567890모든 숫자가 이미 설명 된 위치 와 같은 입력의 경우 PowerShell에서 잘못된 값이며 0로 캐스트 될 때 와 같은 값이 출력되지 않습니다 [int]. 그것이 좋지 않으면, 우리는 단순히 +출력 앞에 $i정수를 캐스트하기 위해 출력 앞에 넣을 수 있습니다 .

롤랜드 히스 덕분에 바이트를 절약했습니다.


ne10 대신 le9를 사용할 수 있습니까? powershell에 익숙하지 않지만 바이트를 절약 할 수 있습니다.
롤랜드 히스

@RolandHeath Indeed; good call. Thanks!
AdmBorkBork



0

Perl, 43 + 1 bytes

for$x(0..9){$_*=2,++$\,redo LINE if!/$x/}}{

Using the -p flag. This builds on the solution provided by Xcali above.


0

Swift 4, 111 bytes

func p(_ x:Int,_ c:Int=0)->Int{if !(String(Set(String(x)).sorted())=="0123456789"){return p(x*2,c+1)};return c}

Note: Won't work for x = 2, because of overflow.

Explanation - Input x is first typecasted to string. Then Set() removes the repeating characters. Then it is sorted to match the result. If it doesn't match, x is doubles and counter is incremented.


1
it doesn't wok because the var is 64 bits. There a lot of other answers with same problem.
Naresh


If you think that this should be allowed bring it up with the OP. It may be common practice but the OP has not specifically allowed it and the testcases seem to suggest you need to support 2.
Post Rock Garf Hunter

1
@FunkyComputerMan actually, I did allow answers that can't handle numbers outside the bounds of the language, but Shaggy seems to have deleted the comment asking about that. This answer is fine.
caird coinheringaahing

0

Ruby, 46 45 39 38 bytes

def f n;n.digits.uniq[9]?0:1+f(n*2)end

Try it online!

Updates:

  1. -1 by using def f n; instead of def f(n);.
  2. -6 by using …[9] instead of ….size==10
  3. -1 by removing a semicolon

0

Japt, 15 bytes

LÆ*2pXÃbì_â Ê¥A

Try it


Explanation

Implicit input of integer U.

LÆ    Ã

Create an array of integers from 0 to 99 and pass each through a function where X is the current element.

*2pX

U multiplied by 2 raised to the power of X.

b

Get the index of the first element thay returns true when passed through the following function.

ì_â

Split to an array of digits and remove the duplicates.

Ê¥A

Get the length of the array and check for equality with 10.


Alternative, 15 bytes

@*2pX)ìâ sÊ¥A}a

Try it


Explanation

Implicit input of integer U.

@            }a

Starting with 0, return the first number that returns true when passed through the following function, with X being the current number.

*2pX)

As above, multiply U by 2 to the power of X.

ìâ

Split to an array of digits, remove duplicates and rejoin to an integer.

Convert to a string, get the length and convert back to an integer.

¥A

Check for equality with 10.


0

QBIC, 48 bytes, nc

{q=1[z|q=q*instr(!:$,!a-1$)]~q>0|_Xp\p=p+1┘b=b*2

This should work, in theory. However, in practice this fails because QBasic casts ten-digit numbers (at least needed to get all digits) to scientific notation... I've marked it as non-competing because of that.

Explanation

{             DO ad infinitum
q=1           set q to 1
[z|           FOR a = 1 to 10
q=q*instr     multiply q by the position
(!:$             - in 'b' (read from cmd line at start) cast to string (! ... $)
,!a-1$)          - of the number a-1 [0-9] cast to string
]             NEXT
~q>0          IF any character was not found, instr gave a 0. If q != 0 all digits were present
|_Xp          THEN quit, printing  p (is 0 at start)
\p=p+1        ELSE increase step counter p
┘b=b*2        and double 'b'

0

GNU dc, 61 bytes

Input is copied from top of stack (which must be otherwise empty); output is pushed to top of stack.

[I~1r:ad0<s]ss[d1+r;a1=p]sp[d2*lfx]sh[0Sadlsxlpx11!=h]dsfxz1-

Explanation

We use the array variable a, storing a 1 in a[d] if digit d is present, otherwise falling back to 0 there. We use the GNU extension ~ to obtain quotient and remainder in a single command.

# populate a[0-9] from the digits
[I~1r:ad0<s]ss

# check pandigit
# return 1 more than lowest unset element of a[]
# start with stack=0
[d1+r;a1=p]sp

# Test for pandigit; double and repeat if needed
[dd+lfx]sh
[0Sadlsxlpx11!=h]dsfx

# We left one value on the stack for each doubling, plus the original
z1-

As a bonus, this will work in arbitrary number bases (not only decimal): simply set the input radix as required (the constant 11 in the definition of f will be read using that number base, so is automatically correct).

Test

for i in 617283945 2 66833 1234567890 100 42
do
    printf '%s => ' $i
    dc -e $i \
       -e '[I~1r:ad0<s]ss[d1+r;a1=p]sp[dd+lfx]sh[0Sadlsxlpx11!=h]dsfxz1-' \
       -e p
done
617283945 => 1
2 => 67
66833 => 44
1234567890 => 0
100 => 51
42 => 55

0

REXX, 57 bytes

arg n
do b=0 while verify(0123456789,n)>0
  n=n*2
  end
say b

0

q/kdb+, 33 bytes

Solution:

(#)1_{x*2 1 min!:[10]in 10 vs x}\

Examples:

q)(#)1_{x*2 1 min!:[10]in 10 vs x}\[100]
51
q)(#)1_{x*2 1 min!:[10]in 10 vs x}\[1234567890]
0
q)(#)1_{x*2 1 min!:[10]in 10 vs x}\[42]
55

Explanation:

All the bytes are in the equality, might be able to golf this one down a little further. Utilises q's scan adverb:

count 1_{x*2 1 min til[10] in 10 vs x}\ / ungolfed solution
        {                            }\ / scan over this lambda until it yields same result
                              10 vs x   / convert to base 10
                           in           / left list in right list, returns boolean list
                   til[10]              / range 0..9
               min                      / return the minimum of the list, 0 or 1
           2 1                          / list (2;1) indexed into with 0 or 1
         x*                             / return x multiplied by either 2 or 1
      1_                                / 1 drop, drop one element from front of list
count                                   / count the length of the list

Notes:

If we drop to the k prompt then we can have a 25 byte solution. Converts the number to a list of characters:

q)\
  #1_{x*2 1@&/($!10)in$$x}\[100]
51
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.