Bu sayı bir repdigit mi?


33

Meydan okuma

Bir repdigit olan basamak tüm eşit olmayan bir pozitif bir tamsayıdır.

Giriş numarası tek bir tamsayı alan ve giriş numarası 10 tabanındaki bir repdigit ve aksi takdirde sahte değerse, bir gerçek değer veren bir işlev veya tam bir program oluşturun.

Giriş, pozitif bir tamsayı olarak garanti edilir .

Girdiyi, üs 10'da cezasız olarak bir dize temsili olarak alabilir ve kullanabilirsiniz.

Test durumları

Bunların hepsi 1000'in altındaki haydutlar.

1
2
3
4
5
6
7
8
9
11
22
33
44
55
66
77
88
99
111
222
333
444
555
666
777
888
999

OEIS'te daha büyük bir liste bulunabilir .

Kazanan

Bayt cinsinden en kısa kod kazanır. Bu, ayrıntılı dillerdeki zekice cevapların kabul edilmeyeceği anlamına gelmez.



@ AidanF.Pierce Girişin en büyük sayısı kaçtır?
stevefestl

Yanıtlar:



19

C (GCC) , 33 30 29 bayt

f(n){n=n%100%11?9/n:f(n/10);}

Çevrimiçi deneyin!


Bunun yerine özyineleme ve ödev ile çok güzel bir numara return(Sanırım cevabım için ikincisini çalacağımı düşünüyorum :)).
Doorknob

@Doorknob Devam et. :) Yine de bir derleyici belirtmeniz gerekecek; Bunun sadece gcc / tcc olmasını bekliyorum.
Dennis

Birlikte gcc olduğunu önceden biliyor muydunuz -O0için nihai sonucu yazacak ntam olarak gelen eaxbu dönüş değeri yapmak için çok gibi? İşe yarayacağını neden bildiğin konusunda mantığı açıklayabilir misin?
Ruslan

@Ruslan, gcc'nin neden böyle davrandığından emin değilim , ancak bir işlev içindeki son değişken ataması eax'takinden çok daha fazla donuyor . Tahmin etmek zorunda olsaydım, bunun return nbir "nop" olmasına izin verdiği için ve sonucun geri dönmeyecekseniz, bir fonksiyonun sonunda yerel bir değişkene atamak için bir neden bulunmadığını söylerdim .
Dennis,

9

COBOL , 139 BYTES

COBOL'un kod golfünde hiç sevilmediğini hissediyorum (muhtemelen kazanması mümkün olmadığı için) ama işte:

IF A = ALL '1' OR ALL '2' OR ALL '3' OR ALL '4' OR ALL '5' OR
ALL '6' OR ALL '7' OR ALL '8' OR ALL '9' DISPLAY "TRUE" ELSE   
DISPLAY "FALSE".

A, PIC 9 (4) olarak tanımlanmıştır.


2
Değiştirerek yapabilirsiniz golf bu TRUEve FALSEsırasıyla 1 ve 0
coinheringaahing Caird


6

Python 3, 25, 24 19 bayt.

len({*input()})>1>t

Bir stdin => hata kodu değişkeni.

Eğer bir repdigit - veya bir hata durumunda bir hata kodu 0 döndürür.

Yorumlarda bana yardım ettiği için Dennis'e teşekkür ederim.


Çıkış kodu 0 başarıyı gösterdiğinden, test etmek >1yerine test etmelisiniz <2. Gerçek bir hatayı exitarttırmak btw kullanmaktan daha kısa olacaktır .
Dennis

Bunu merak ediyordum. Mücadelede "gerçek bir değer" yazıyor. Bir hatayı düzeltmek için değiştireceğim.
Shadow

1
Evet, if python3 repdigit.py; then echo truthy; else echo falsy; fitanımlamaya göre çalışmak zorunda, yani 0 gerçek değil ve her şey sahte.
Dennis

Bu mantıklı. Tamam, ben de bu değişikliği yapacağım.
Gölge

2
@ Arc676 Unary yinelenebilir *bir ambalajı açar. Örneğin {*'123'}, seti oluşturur {'1','2','3'}.
Dennis,

6

Mathematica, 27 bayt

AtomQ@Log10[9#/#~Mod~10+1]&

Dövmez Equal@@IntegerDigits@#& , ancak diğer aritmetik tabanlı Mathematica çözümünü yener.

Repdigitler n = d (10 m -1) / 9 biçimindedir , burada m rakamların sayısıdır ve d tekrarlanan rakamdır. Biz kurtarabilirsiniz d den n (It is a temsilcisi basamaklı ise, 's son basamak olacak çünkü 10 modulo alarak d ). Böylece bunu m = log 10 (9 n / (n% 10) + 1) olarak yeniden düzenleyebilir ve m'nin bir tamsayı olup olmadığını kontrol edebiliriz .


5

Haskell , 15 bayt

all=<<(==).head

Çevrimiçi deneyin! Dize girişi alır.

Eşdeğer \s->all(==head s)s. Dar alternatifleri yener:

f s=all(==s!!0)s
f s=s==(s!!0<$s)
f(h:t)=all(==h)t
f(h:t)=(h<$t)==t
f s=(s<*s)==(s*>s)
f(h:t)=h:t==t++[h]

f s=(s<*s)==(s*>s)çok ilginç bir fikir, daha <*önce bu davranışların farkında değildim .
Laikoni

5

C (gcc), 41 bayt

f(char*s){s=!s[strspn(s,s+strlen(s)-1)];}

Bu, bir dize olarak girdi alan ve 1bir repdigit ise ve 0aksi takdirde döndüren bir işlevdir .

Bunu kullanarak yapar strspn iki dizgeyi alan ve ilk dizginin en uzun önekinin uzunluğunu döndüren, ikinci dizgiden sadece karakterlerden oluşan işlevi kullanarak yapar. Burada, ilk dize girdidir ve ikinci dize girdiyi en son karaktere bir gösterici geçirerek elde edilen son dizedir.

Giriş bir repdigit ise, aramanın sonucu strspnolacaktır strlen(s). Ardından, sbu durumda ( str[strlen(str)]her zaman \0) veya aksi takdirde son rakamla eşleşmeyen ilk rakamsa , indeksleme boş bir bayt döndürür. Bunu olumsuzlamak, bir repdigit !olup olmadığını sgösterir.

Çevrimiçi deneyin!

Bana dolaylı olarak delicesine etkileyici cevabı ile 4 yerine geri dönmek yerine atamak yerine hileci hatırlattığımız için @Dennis sayesinde !


strlen*sc;f(char*s){c=*s;c=!s[strspn(s,&c)];}
Şundan

5

PHP, 25 28 25

<?=!chop($argn,$argn[0]);

sağdaki ilk 1karaktere eşit olan tüm karakterleri kaldırın ve tüm karakterlerin kaldırılması durumunda yazdırın .


5

R, 31 bayt

function(x)grepl("^(.)\\1*$",x)

Bu işlev dizge girişleriyle çalışır ve girişin repdigit olup olmadığını belirlemek için normal bir ifade kullanır.

Örnek

> f <- function(x)grepl("^(.)\\1*$",x)
> x <- c("1", "2", "11", "12", "100", "121", "333")
> f(x)
[1]  TRUE  TRUE  TRUE FALSE FALSE FALSE  TRUE

(X) işlevinden tarama işlevine geçmek için 28 bayt (, '') tio.run/##K/r/P70otSBHQylOQ08zJsZQS0VJpzg5MU9DR11dU/O/paXlfwA
Sumner18

5

/// , 110 bayt

/11/1//22/2//33/3//44/4//55/5//66/6//77/7//88/8//99/9//1/.//2/.//3/.//4/.//5/.//6/.//7/.//8/.//9/.//T..///.//T

Çevrimiçi deneyin!

/// dilinde herhangi bir gerçek ve falsey kavramı yoktur, bu nedenle giriş bir repdigit ise "T", giriş bir repdigit değilse, herhangi bir karakter çıkarmaz.



4

Oktav , 11 bayt

@(s)s==s(1)

Çevrimiçi deneyin!

Girdiyi dizge olarak alır.

Tüm karakterleri ilk karakterlerle eşitlik için kontrol eder. Hepsi eşitse, sonuç yalnızca 1(Octave'de gerçek) olan bir vektör olacak, aksi halde en az bir 0(Octave'de yanlış) olacaktır. İşte bir kanıtı .


all(...)Gerçek / sahte bir değer çıktısı elde etmek için onu sarmanız gerekmez mi ?
Tom Carpenter,

İspatı test ettin mi? Bu kod parçası ppcg üzerinde true / false tanımıdır (meta konsensüs).
Stewie Griffin

4

grep, 17 bayt

grep -xP '(.)\1*'

İlk karakterinin tekrarı olan herhangi bir dizeyle eşleşir.


4

C #, 42 33 28 bayt

i=>i.Replace(i[0]+"","")==""

i bir dize olmalı.

@LethalCoder sayesinde çok tıraş olun


2
i[0].ToString()için kısaltılabilir i[0]+"", <1daha kısadır ==0.
TheLethalCoder,

1
Ayrıca .Length<1sadece olabilir==""
TheLethalCoder 8:17

3

Braingolf , 6 bayt

iul1-n

Çevrimiçi deneyin!

Ne yazık ki, Braingolf'un komut satırı argümanlarından gelen örtük girişi dize olarak tüm basamaklar girişini kabul edemez, her zaman bir sayıya çevrilir, bu nedenle çözüm STDIN ( i) değerini okumak için 1 bayt ekleyen STDIN üzerinden geçirmektir.

Açıklama:

iul1-n
i       Read from STDIN as string, push each codepoint to stack
 u      Remove duplicates from stack
  l     Push length of stack
   1-   Subtract 1
     n  Boolean negate, replace each item on stack with 1 if it is a python falsey value
        replace each item on stack with 0 if it is a python truthy value
        Implicit output of last item on stack

Sonra u, yığının uzunluğu olacak 1 aracı çıkarılarak, giriş benzersiz karakter sayısına eşittir 0orada, girişte tam 1 benzersiz bir karakter ancak ve ancak 0böylece, Python sadece Falsey sayıdır nyerini alacak 0olan 1, ve diğer her şey 0.



3

JavaScript (ES6), 23 21 bayt

Neil sayesinde 2 bayt kaydedildi

Takes input as either an integer or a string. Returns a boolean.

n=>/^(.)\1*$/.test(n)

Demo


Doesn't usingtest instead of !!exec save 2 bytes?
Neil

(Although, for a string-only input, porting the PHP answer is even shorter.)
Neil

@Neil I don't know what I was thinking. Thanks!
Arnauld

3

Ohm, 4 bytes

Ul2<

Try it online!

Explanation

 Ul2<
 U    # Push uniquified input
  l   # Length
   2< # Is it smaller than 2?

I think Ul≤should work.
Christoph

@Christoph Yee I had that but I wasn't sure if 0 counts as a truthy value. (Quite new to this codegolf thing ^^)
Datboi

Ah damn 0 is falsey and every other number is truthy. I just noticed that we need exactly the opposite for this challenge (often we're allowed to swap as long as we declare which case is truthy and which is falsey). Truthy is defined by "would take a brench".
Christoph

Ul1E should also work (though I don't know Ohm) because it doesn't need to handle 0.
Esolanging Fruit

3

APL, 5 bytes

2 bytes saved thanks to @KritixiLithos

⍕≡1⌽⍕

Try it online!


You can golf the 7-byte solution to 5 bytes by using a train ⊢≡1⌽⊢.
Kritixi Lithos

@KritixiLithos thanks!
Uriel

Replace with to handle both strings and numbers.
Adám

@Adám thanks! I didn't think of formatting as a way of getting array of digits.
Uriel

3

Java, 21 bytes:

l->l.toSet().size()<2

l is a MutableList<Character> from eclipse collections.


1
l could also be a CharAdapter.
Donald Raab

@DonaldRaab oooh, I've never seen that class. Nice find.
Nathan Merrill

There is CodePointAdapter and CodePointList as well.
Donald Raab

1
@DonaldRaab I use eclipse collections quite a bit, but I always struggle to find anything outside of the standard List/Map/Set collections. Is your knowledge based off of development of the libraries, or is there somewhere (other than the javadoc) I can find a better reference for everything EC provides?
Nathan Merrill

Glad to hear it. I am a committer for the framework... I wrote these particular String related classes a year or so ago. There is a Reference Guide which many folks don't know about. There is a mind-map I recently put together to help folks learn and navigate through the the plethora of features in the library. It's the last link in the TOC of the Ref. Guide. github.com/eclipse/eclipse-collections/blob/master/docs/…
Donald Raab

3

Kotlin, 28 19 bytes

{it.toSet().size<2}

Try it online!

Takes input as a String because

You may take and use input as a string representation in base 10 with impunity.

Explanation

{
    it.toSet()     // create a Set (collection with only unique entries)
                   // out of the characters of this string
        .size < 2  // not a repdigit if the set only has one entry
}

If you don't like the fact it takes a String, you can have one that takes an Int for 24 bytes.

{(""+it).toSet().size<2}

3

Regex (ECMAScript), 31 bytes

^(x{0,9})((x+)\3{8}(?=\3$)\1)*$

Try it online!

Takes input in unary, as usual for math regexes (note that the problem is trivial with decimal input: just ^(.)\1*$).

Explanation:

^(x{0,9})           # \1 = candidate digit, N -= \1
(                   # Loop the following:
  (x+)\3{8}(?=\3$)  # N /= 10 (fails and backtracks if N isn’t a multiple of 10)
  \1                # N -= \1
)* $                # End loop, assert N = 0


@Deadcode Whoops I forgot to put that in, thanks!
Grimmy


2

Neim, 1 byte

𝐐

Simply checks that all elements are equal.

Without builtin, 2 bytes:

𝐮𝐥

Explanation:

𝐮     Calculate unique digits
 𝐥    Get the length

This works because only 1 is considered truthy in Neim, and everything else is falsy.

Alternatively, for 4 bytes:

𝐮𝐣μ𝕃

Explanation:

𝐮      Calculate unique digits
 𝐣      Join list into an integer
   𝕃   Check that is is less than
  μ    Ten.

Try it!


2

C, 38 bytes

f(char*s){return*s^s[1]?!s[1]:f(s+1);}

Recursively walks a string. If the first two characters differ (*s^s[1]) then we succeed only if we're at the end of the string (!s[1]) otherwise we repeat the test at the next position (f(s+1)).

Test program

#include <stdio.h>
int main(int argc, char **argv)
{
    while (*++argv)
        printf("%s: %s\n", *argv, f(*argv)?"yes":"no");
}

2

Java, 38 33 23 bytes

n->n.matches("(.)\\1*")

n is a String, naturally.

Note that there is no need for ^...$ in the regex since it's automatically used for exact matching (such as the match method), compared to finding in the string.

Try it!

Saves

  • -5 bytes: used String since "You may take and use input as a string with impunity."
  • -10 bytes: regex is apparently a good fit.

Was about to post this exact solution, including the explanation about the matches not requiring ^$ because it matches the entire String. So a definite +1 from me. ;)
Kevin Cruijssen

2

R, 25 bytes

grepl("^(.)\\1*$",scan())

Try it online

Best non-regex solution I could come up with was 36 bytes:

is.na(unique(el(strsplit(x,"")))[2])

1
for another option on the non-regex rle(charToRaw(scan(,'')))$v[2]<1
MickyT

2

Cubix, 15 bytes

uOn@ii?-?;.$@<_

Try it online!

    u O
    n @
i i ? - ? ; . $
@ < _ . . . . .
    . .
    . .

Watch It Run

Outputs 1 for truthy and nothing for falsey

Very simply read reads in the input one character at a time. It takes the current character away from the previous. If a non zero result then it halts immediately. Otherwise it continues inputting and comparing until the EOI. On EOI (-1), negate and exit


2

QBasic 4.5, 55 bytes

INPUT a
FOR x=1TO LEN(STR$(a))
c=c*10+1
NEXT
?a MOD c=0

I've mathed it! The FOR-loop checks the number of digits in the input, then creates c, which is a series of 1's of length equal to the input. A number then is repdigit if it modulo the one-string == 0.

Try it online! Note that the online interpreter is a bit quirky and I had to write out a couple of statements that the DOS-based QBasic IDE would expand automatically.

Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.