Quel numero è un numero a due bit ™ ️?
Iniziamo definendo un numero a due bit ™ ️:
- È un numero intero positivo
- Quando espresso come stringa binaria, ha esattamente 2 bit veri OR
- Quando è espresso come un numero decimale, ha esattamente 2 del numero uno e tutti gli altri numeri sono zero.
O come frase
Un numero a due bit ™ ️ è un numero che contiene esattamente 2 del numero 1 e nessun altro numero oltre allo 0, se espresso come stringa decimale o numero binario.
Quindi qui sono tutti i Two Bit Numbers ™ ️ compresi tra 0 e 256
Dec Bin Type
3 00000011 Binary
5 00000101 Binary
6 00000110 Binary
9 00001001 Binary
10 00001010 Binary
11 00001011 Decimal
12 00001100 Binary
17 00010001 Binary
18 00010010 Binary
20 00010100 Binary
24 00011000 Binary
33 00100001 Binary
34 00100010 Binary
36 00100100 Binary
40 00101000 Binary
48 00110000 Binary
65 01000001 Binary
66 01000010 Binary
68 01000100 Binary
72 01001000 Binary
80 01010000 Binary
96 01100000 Binary
101 01100101 Decimal
110 01101110 Decimal
129 10000001 Binary
130 10000010 Binary
132 10000100 Binary
136 10001000 Binary
144 10010000 Binary
160 10100000 Binary
192 11000000 Binary
La sfida:
- Scrivi un codice che accetti un numero e restituisca vero o falso (o qualche indicatore di vero o falso) se si tratta di un numero a due bit ™ ️.
- L'input sarà sempre un numero intero, ma potrebbe non essere sempre positivo.
- Può essere in qualsiasi lingua tu voglia.
- È il golf in codice, quindi vince il minor numero di byte.
- Includere collegamenti a un interprete online per il codice (come tio.run).
Casi test
Numeri binari a due bit ™ ️:
- 3
- 9
- 18
- 192
- 288
- 520
- 524304
Numeri decimali a due bit ™ ️:
- 11
- 101
- 1001
- 1010
- 1100
- 1000001
- 1100000000
- 1000000010
Numeri non a due bit ™ ️:
- 0
- 1
- 112 (qualsiasi numero superiore a 1 impedisce che sia un binario
- 200
- 649
- -1
- -3
Curiosità: non sono riuscito a trovare alcun DecimalBinary Two Bit Numbers ™ ️ controllando fino a circa 14 miliardi, e ho un'ipotesi che tale numero non esista, ma non ho prove matematiche. Sarei interessato a sapere se riesci a trovarne uno.
Risposte
Python 3 , 68 62 48 byte
-6 byte grazie a xnor !
-14 byte grazie a Jitse !
lambda n:' 11 'in f' {n:b} {n} '.replace('0','')
Provalo online!
JavaScript (ES6), 38 byte
Restituisce 0 per vero o un numero intero diverso da zero per falso .
n=>(g=n=>!(n&=n-1)|n&n-1)(n)*g('0b'+n)
Provalo online!
Come?
La funzione di supporto g rimuove i due bit meno significativi impostati ncalcolando n & (n - 1)due volte. Se otteniamo 0 la prima volta, significa che nha al massimo un bit impostato, il che non è sufficiente. Se non otteniamo 0 la seconda volta, significa che nha più di 2 bit impostati, il che è troppo.
Per il test decimale, invochiamo g con '0b' + nper analizzarlo come valore binario. Se nè negativo, dà qualcosa come '0b-10100', che è NaN'ish e fallisce come previsto.
JavaScript (ES6), 40 39 byte
Restituisce un valore booleano che indica se l'ingresso non è un numero a due bit.
n=>[n,'0b'+n].every(n=>!(n&=n-1)|n&n-1)
Provalo online!
Haskell , 50 byte
f n=or[b^x+b^y==n|b<-[2,10],x<-[0..n],y<-[x+1..n]]
Provalo online!
Ricerca di forza bruta.
50 byte alternativi
b!0=0
b!x=rem x b^3+b!quot x b
f n=2!n==2||10!n==2
b!xcalcola una b"somma di cifre al cubo" in base x. Ad esempio, 10!123= \$1^3+2^3+3^3\$ = 36.
Controlliamo se uno di 2!no è 10!nuguale a 2.
quotè necessario per supportare l'input negativo. Arrotonda verso zero, mentre divarrotonda per difetto, il che significa che div (-1) 10 == (-1)causa un ciclo infinito.
APL (Dyalog Extended) , 18 byte
2∊+/↑(*3)2 10⊤¨0⌈⎕
Provalo online!
La soluzione a 18 byte di Jo King.
APL (Dyalog Extended) , 20 21 20 26 25 byte
{<⍵:2∊+/↑(⊂×⍨⍎¨⍕⍵)⍪⊂⊤⍵⋄0}
Provalo online!
+1 byte dopo aver corretto la risposta (ovs).
-1 byte dopo il suggerimento di ovs. (Yay!)
+7 byte dopo aver accettato correttamente casi di test negativi.
-1 byte da Adám.
Ispirato dalla soluzione J.
Spiegazione
{⍵>0:2∊+/↑(⊂2*⍨⍎¨⍕⍵)⍪⊂⊤⍵⋄0}
⍵>0: If number is positive
⊤⍵ Decode number to binary
×⍨⍎¨⍕⍵ square each digit
↑ ⊂ ⍪⊂ join into two rows
+/ sum each row
2∊ is two present in it?
⋄0 otherwise return 0
05AB1E , 8 7 byte
b‚€{11å
Provalo online o verifica tutti i casi di test .
Spiegazione:
b # Convert the (implicit) input-integer to a binary string
‚ # Pair it together with the (implicit) input-integer
€{ # Sort the digits in each string
11å # And check if this pair contains an 11 (which is truthy for "011","0011",etc.)
# (after which the result is output implicitly)
R , 50 49 48 46 byte
Modifica: -1 byte, quindi -1 byte in più e poi -2 byte in più, grazie a Robin Ryder
gsub(0,'',n<-scan())!=11&sum(n%/%2^(0:n)%%2)-2
Provalo online!
I test per i numeri decimali 2bit utilizzando manipolazione del testo per rimuovere ' 0' cifre e controllare se il risultato è non ' 11', e poi test per i numeri 2 bit binari calcolando le cifre binarie e controllando se non sommano a 2. Restituisce FALSE per i numeri a 2 bit e TRUE per i numeri non a 2 bit.
Sembra un po 'goffo fare due diversi tipi di test essenzialmente per la stessa funzione, ma in qualche modo risulta piuttosto breve ...
J , 25 byte
0&<*10&#.inv+&(2=1#.*~)#:
Provalo online!
Come funziona
0&<*10&#.inv+&(2=1#.*.~)#:
0&<* input is a positive number
10&#.inv list of digits base 10
#: list of digits base 2
+&( ) OR the result of both …
*.~ square each digit (x>=2 will be larger than 2)
1#. sum
2= is equal to two
Se è presente un numero DecimalBinary, +as OR potrebbe restituire 2, quindi è necessario un byte in più per +..
Brachylog , 9 byte
ℕ{ḃc|}o11
Provalo online!
Un po 'imbarazzato non ho pensato di tradurre prima gli approcci basati sull'ordinamento di altre soluzioni ...
Una soluzione più divertente:
Brachylog , 10 byte
ℕ{|ẹ~ḃ}ḃ+2
Provalo online!
ℕ The input is a whole number (necessary to exclude -3 etc.),
{| } which either unchanged or
ẹ with its decimal digits
~ḃ interpreted as binary (impossible if any ≥ 2),
ḃ has binary digits
+2 that sum to 2.
Brachylog , 12 11 byte
ℕ{ḃ|ẹ}<ᵛ²+2
Provalo online!
-1 byte grazie a xash
ℕ The input is a whole number,
{ | } and either
ḃ its binary digits
ẹ or its decimal digits
<ᵛ² are all less than 2
+2 and sum to 2.
Japt , 9 byte
Dev'esserci un modo per eliminare almeno un byte in più da questo.
ìͶBªB¥¢ñ
Provalo o esegui tutti i casi di test
ìͶBªB¥¢ñ :Implicit input of integer U
ì :Convert to digit array
Í :Sort (and implicitly convert back to integer)
¶ :Test for strict equality with
B :11
ª :Logical OR with
B¥ :Test 11 for equality with
¢ :Convert U to binary string
ñ :Sort
Raku , 25 byte
{$_|.base(2)~~/^10*10*$/}
Provalo online!
Controlla se l'input o la base 2 dell'input corrisponde alla regex ^10*10*$
Carboncino , 21 13 byte
№⟦⁻θ0⁻⍘N²0⟧11
Provalo online! Il collegamento è alla versione dettagliata del codice. Emette un booleano Charcoal, cioè -per un numero a due bit, niente in caso contrario. Port della risposta PHP di @ Kaddath. Spiegazione:
θ Input as a string
⁻ 0 Remove zeros
N Input as a number
⍘ ² Convert to base 2
⁻ 0 Remove zeros
⟦ ⟧ Make into a list
№ 11 Count occurances of literal string `11`
Python 3 , 67 byte
lambda n:n>2in{g(n,2),g(n,10)}
g=lambda x,b:x and(x%b)**2+g(x//b,b)
Provalo online!
Porto della mia risposta Haskell. (Ho preso il test harness dalla risposta Python di ovs. Grazie!)
R , 71 64 byte
-7 byte grazie a Dominic van Essen
`+`=function(n,k)sum((n%/%k^(0:n)%%k)^2)-2
n=scan();n<0|n+2&n+10
Provalo online!
L'uscita è invertita: fornisce FALSEse l'ingresso è un numero a due bit e TRUEse non lo è.
La funzione helper +converte un intero in un vettore di cifre in base k(abbiamo bisogno di k=2e k=10). Quindi somma il quadrato di queste cifre. Questa somma è uguale a 2 esattamente per un numero a due bit.
Non funzionerà a causa dei limiti di memoria per input di grandi dimensioni, nel qual caso è possibile utilizzare al 0:log2(n)posto di 0:ne ||invece di |: Provalo online! .
Fattore , 79 74 byte
: n ( n -- ? ) [ 10 >base ] [ >bin ] bi [ 48 swap remove "11" = ] bi@ or ;
Provalo online!
Gelatina , 8 byte
,BṢ€Ḍ11e
Provalo online!
Spiegazione
,BṢ€Ḍ11e Main Link
, Pair the integer with
B Convert the integer to binary
Ṣ€ Sort Each (sorts the digits of the integer implicitly)
Ḍ Convert from decimal to integer
11e Is 11 in this list?
Perl 5 -lp , 35 byte
$_=grep/^10*10*$/,$_,sprintf"%b",$_
Provalo online!
restituisce 1 o 2 (se un numero può essere decimale e un numero binario a due bit) per vero, 0 per falso.
Wolfram Language (Mathematica) , 46 byte
!FreeQ[Tr/@(#~IntegerDigits~{10,2}^2),2]&&#>0&
Provalo online!
-1 byte da @att
PCRE Regex, 100 95 byte
^(((?(2)\2\2|.))*.)(?!\1)((?(3)\3\3|.))*.$|^(((?(5)\5{10}|.{9}))*.)(?!\4)((?(6)\6{10}|.{9}))*.$
Supponiamo un input unario (nessun supporto per i numeri negativi).
Dovrebbe funzionare in versioni con supporto per regex condizionale e riferimento all'indietro dichiarato in avanti.
L'espressione regolare è composta da 2 parti simili, una verifica per binario e l'altra per decimale.
I marchi di codice utilizzare per somma di serie geometriche per abbinare 2 n e 10 n .
1 + (1 + 2 + 2 2 + ... + 2 n ) = 2 n + 1
1 + 9 * (1 + 10 + 10 2 + ... + 10 n ) = 10 n + 1Quindi prova a scomporre il numero nella somma di 2 n + 2 k (o 10 n + 10 k per i decimali) e verifica che 2 n ! = 2 k
Aggiornare:
- Elimina il gruppo di acquisizione inutilizzato
- Cade
$in(?!\1$)quanto va bene se rifiutiamo 2 n <2 k
regex101
Julia , 61 byte
utilizzando una regex sulla rappresentazione binaria e decimale del numero
x->any(match.([r"^0*10*10*$"],["$x",bitstring(x)]).!=nothing)
Provalo online!
Julia, 69 byte
ordinando i caratteri
x->any(endswith.(join.(sort.(collect.(["0$x",bitstring(x)]))),"011"))
Provalo online!
Ruby 2.7, 44 byte
->n{[2,10].any?{n.to_s(_1).tr(?0,'')=='11'}}
Spiegazione:
->n{ # a lambda with one argument
[2,10].any?{ # Return true if for either of 2 or 10...
n.to_s(_1) # input in that base
.tr(?0,'') # after removing all 0-s
=='11' # is exactly '11'
}
}
Equivalente in rubino <2,7, 46 byte
->n{[2,10].any?{|b|n.to_s(b).tr(?0,'')=='11'}}
Provalo
Retina 0.8.2 , 36 byte
^\d+
$*1¶$&
+`^(1+)\1
$+0 m`^10*10*$
Provalo online! Link include la maggior parte dei casi di test (quelli più grandi fanno sì che Retina esaurisca la memoria). Spiegazione:
^\d+
$*1¶$&
Se l'input non è negativo, anteponilo a una copia unaria.
+`^(1+)\1
$+0
Inizia a convertire la copia unaria in binario. A questo punto ci sono troppi zeri nel risultato, ma fortunatamente sono irrilevanti.
m`^10*10*$
Trova uno dei due numeri come un numero a due bit.
K (ngn / k) , 25 24 byte
-1 byte grazie a ngn
{("11"~($x)^$0)+2=+/2\x}
Provalo online!
PHP , 69 67 byte
echo($f=fn($s)=>str_replace(0,'',$s)==11)($argn)|$f(decbin($argn));
Provalo online!
Abbastanza semplice: tratta ogni input come una stringa, sostituisce tutti gli zeri con ''e verifica se è (vagamente) uguale 11o se il binario lo fa
EDIT: salvato 2 byte utilizzando 0invece di'0'
APL (Dyalog Extended) , 19 byte
2∊2 10(+.×⍨⊤)¨⊢×0<⊢
Provalo online!
Commentato:
0<⊢ ⍝ Is the (right) argument greater than 0
⊢× ⍝ Multiply this with the argument
⍝ results in 0 for negative inputs
2 10( )¨ ⍝ Call the next function with each of the bases 2 and 10
⍝ and the non-negative number as a right argument
⊤ ⍝ Convert number to base digits
+.×⍨ ⍝ The sum of squares of the digits
2∊ ⍝ Does this contain 2?
C (gcc) , 75 \$\cdots\$ 76 80 byte
Aggiunti 6 byte per correggere un bug.
d;r;c;f(n){for(c=2,r=__builtin_popcount(n)!=2|n<0;n>0;n/=10)d=n%10,c-=d*d;r*=c;}
Provalo online!
Restituisce un valore falso se \$n\$ è un Two Bit Number ™ ️ o altrimenti vero.
Pyth , 22 16 byte
-6 byte grazie a @FryAmTheEggman
}11,v-Q\0v-.BQ\0
Provalo online!
Python, 79 byte
lambda n:any(sum((ord(c)-48)**4 for c in f.format(n))==2for f in["{}","{0:b}"])
Spiegazione
Formatto il int sia come binario che decimale. Per ogni carattere, sottraggo il '0'carattere, quindi lo alzo alla potenza di 4. Questo viene mappato '0'a 0, '1'a 1, '2'a 16 e altre cifre e il '-'carattere a numeri maggiori di 16. Quindi, controllo se la somma è uguale a 2 .
Ottava , 67 64 byte
@(x,p=@(b,z=dec2base(x*(x>0),b)-48)all(z<2)&sum(z)==2)p(2)|p(10)
Provalo online!
In caso di dubbio, rendere il codice più complesso. In qualche modo questo tende a salvare byte ...
@(x, % Main anonymous function with 'x' as input
p= % Second input 'p' with default value (no second input is given when calling function) which
@(b, % consists of another anonymous function which takes base as input
z= % From which it creates a second input 'z' with default value
dec2base( ,b) % Which runs dec2base (convert from integer to string) using provided base
x % On the input to the main anonymous function
*(x>0) % Multiplied by (x>0) to return false for any negative integer passed in.
-48 % And converts from a string to an array of integers (one per digit)
)
all(z<2)& % Two-bit numbers must only contain 0 or 1, so need all elements in array of digits <2.
sum(z)==2 % Sum all digits. Two-digit number if sum is 2 (two 1's)
)
p(2))|| % Run two-bit number check in base 2
p(10) % Run two-bit number check in base 10
Primo tentativo,
@(x,p=@(z)all(z<50)&&sum(z-48)==2)x>0&&p(dec2bin(x))||p(num2str(x))
Provalo online!
@(x, % Main anonymous function with 'x' as input
p= % Second input 'p' with default value (no second input is given when calling function)
@(z) % Default value consists of another anonymous function to check if string is two-bit
all(z<50)&& % Two-bit numbers must only contain '0' or '1', so need all elements in string <'2'(50).
sum(z-48)==2 % Convert all characters from '0'/'1' to 0/1 and sum. Two-digit if sum is 2 (two 1's)
)
x>0&& % Short-circuit to return false for any negative integer passed in.
p(dec2bin(x))|| % Convert to binary string and check if two-digit, or...
p(num2str(x)) % Convert to decimal string and check if two-digit
T-SQL, 93 byte
Restituisce 1 per vero, 0 per falso
DECLARE @y INT=@,@x INT=9WHILE @>0SELECT
@x+=@%2,@/=2PRINT
IIF(11in(@x,replace(@y,0,'')),1,0)
Provalo online
Regex generica, 58 byte
^((((1+)(?=\4$))+|^)1){2}$|^((((1+)\8{8}(?=\8$))+|^)1){2}$
Provalo online! Il collegamento include il test harness scritto in Retina 0.8.2 sebbene la stessa regex dovrebbe funzionare nella maggior parte dei motori. Prende l'input in unario firmato cioè ^-?1*$. Spiegazione: Dato ke mpossiamo scrivere un test specifico per un numero che è la somma di kpotenze distinte di mdividendo ripetutamente me sottraendo 1 ktempi distinti lungo il percorso, prima di raggiungere infine lo zero:
^((((1+)\4{<m-2>}(?=\4$))+|^)1){<k>}$
dove <m-2>e <k>rappresentano sostituzioni per i valori specifici in fase di test (soggetti a riduzioni banali come \4{0}essere un no-op). Funziona come segue:
(1+) Find `i` such that
\4{<m-2>} `i+(m-2)i=(m-1)i` is equal to
(?=\4$) `n-i`, therefore `i=n/m`.
( )+ Divide `n` by `m` at least once
( |^) Except on the first loop
( 1){<k>} Decrement `k` distinct times
^ $ Consume entire input
Il problema si riduce quindi ad un'alternanza di due di tali prove.