¿Es este número un digito?


33

Reto

Un repdigit es un número entero no negativo cuyos dígitos son todos iguales.

Cree una función o un programa completo que tome un entero entero como entrada y genere un valor verdadero si el número de entrada es un repdigit en la base 10 y un valor falso de lo contrario.

Se garantiza que la entrada sea un número entero positivo .

Puede tomar y usar input como una representación de cadena en la base 10 con impunidad.

Casos de prueba

Todos estos son dígitos por debajo de 1000.

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

Se puede encontrar una lista más grande en OEIS .

Victorioso

El código más corto en bytes gana. Eso no quiere decir que las respuestas inteligentes en idiomas detallados no serán bienvenidas.



@ AidanF.Pierce ¿Cuál es el mayor número de entrada?
stevefestl

Respuestas:



19

C (gcc) , 33 30 29 bytes

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

Pruébalo en línea!


Very nice trick with the recursion and assignment instead of return (think I'm going to steal the latter for my answer :) ).
Doorknob

@Doorknob Go ahead. :) You'll have to specify a compiler though; I expect this to be pretty much gcc/tcc only.
Dennis

Did you know beforehand that gcc with -O0 will write final result to n from exactly eax, so as to make it the return value? Could you elaborate on the logic why you knew it would work?
Ruslan

@Ruslan I'm not sure why gcc behaves like this, but the last variable assignment inside a function winds up in eax more often than not. If I had to guess, I'd say it's because it allows return n to be a nop, and there's no reason to assign to a local variable at the end of a function if you're not going to return the result.
Dennis

9

COBOL, 139 BYTES

I feel like COBOL doesn't get any love in code golfing (probably because there is no way it could win) but here goes:

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 is defined as a PIC 9(4).


2
You can golf this by changing TRUE and FALSE to 1 and 0 respectively
caird coinheringaahing


6

Python 3, 25, 24 19 bytes.

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

A stdin => error code variant.

Returns error code 0 if it's a repdigit - or an error on failure.

Thanks to Dennis for helping me in the comments.


Since exit code 0 indicates success, I think you should test >1 rather than <2. Raising an actual error would be shorter than using exit btw.
Dennis

I was wondering about that. The challenge says "a truthy value". I'll change it to raise an error.
Shadow

1
Yes, if python3 repdigit.py; then echo truthy; else echo falsy; fi has to work according to out definition, so 0 is truthy and everything else is falsy.
Dennis

That makes sense. Ok I'll make that change too.
Shadow

2
@Arc676 Unary * unpacks an iterable. For example, {*'123'} generates the set {'1','2','3'}.
Dennis

6

Mathematica, 27 bytes

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

It doesn't beat Equal@@IntegerDigits@#&, but it beats the other arithmetic-based Mathematica solution.

Repdigits are of the form n = d (10m-1) / 9 where m is the number of digits and d is the repeated digit. We can recover d from n by taking it modulo 10 (because if it's a rep digit, it's last digit will be d). So we can just rearrange this as m = log10(9 n / (n % 10) + 1) and check whether m is an integer.


5

Haskell, 15 bytes

all=<<(==).head

Try it online! Takes string input.

Equivalent to \s->all(==head s)s. Narrowly beats out alternatives:

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) is a very interesting idea, I wasn't aware of this behaviour of <*before.
Laikoni

5

C (gcc), 41 bytes

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

This is a function that takes input as a string and returns 1 if it is a repdigit and 0 otherwise.

It does this by making use of the strspn function, which takes two strings and returns the length of the longest prefix of the first string consisting of only characters from the second string. Here, the first string is the input, and the second string is the last digit of the input, obtained by passing a pointer to the last character of the input string.

Iff the input is a repdigit, then the result of the call to strspn will be strlen(s). Then, indexing into s will return a null byte if this is the case (str[strlen(str)] is always \0) or the first digit that doesn't match the last digit otherwise. Negating this with ! results in whether s represents a repdigit.

Try it online!

Thanks to @Dennis for indirectly reminding me of the assign-instead-of-return trick via his insanely impressive answer, saving 4 bytes!


You can shorten this a bit further by avoiding strlen and creating a new string from *s: c;f(char*s){c=*s;c=!s[strspn(s,&c)];} for 37.
hvd

5

PHP, 25 28 25

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

remove all chars from the right that are equal to the first and print 1 if all chars were removed.


5

R, 31 bytes

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

This functions works with string inputs and uses a regular expression to determine whether the input is a repdigit.

Example

> 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

28 bytes by switching from function(x) to using scan(,'') tio.run/##K/r/P70otSBHQylOQ08zJsZQS0VJpzg5MU9DR11dU/O/paXlfwA
Sumner18

5

///, 110 bytes

/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

Try it online!

The /// language doesn't have any concept of truthy and falsey, so this outputs "T" if the input is a repdigit, and does not output any characters if the input is not a repdigit.



4

Octave, 11 bytes

@(s)s==s(1)

Try it online!

Takes the input as a string.

It checks all characters for equality with the first characters. If all are equal, the result will be a vector with only 1 (true in Octave), otherwise there will be at least one 0 (false in Octave). Here's a proof.


Wouldn't you need to wrap it in all(...) to get a truthy/falsy value output?
Tom Carpenter

Did you test the proof? That's piece of code is the definition (meta consensus) of true/false on ppcg.
Stewie Griffin

4

grep, 17 bytes

grep -xP '(.)\1*'

Matches any string that's a repetition of its first character.


4

C#, 42 33 28 bytes

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

i has to be a string.

Shaved down a lot thanks to @LethalCoder


2
i[0].ToString() can be shortened to i[0]+"", <1 is shorter than ==0.
TheLethalCoder

1
Also .Length<1 can just be ==""
TheLethalCoder

3

Braingolf, 6 bytes

iul1-n

Try it online!

Unfortunately, Braingolf's implicit input from commandline args can't accept an all-digits input as a string, it will always cast it to a number, so instead the solution is to pass it via STDIN, which adds 1 byte for reading STDIN (i)

Explanation:

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

After u, the length of the stack equals the number of unique characters in the input, subtracting 1 means it will be 0 if and only if there is exactly 1 unique character in the input, 0 is the only falsey number in Python, so n will replace 0 with 1, and everything else with 0.



3

JavaScript (ES6), 23 21 bytes

Saved 2 bytes thanks to Neil

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.

Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.