Las preguntas eliminadas en Stack Overflow a veces son un excelente material de golf.
Escriba una función que tome un entero no negativo como entrada y devuelva verdadero si todos los dígitos en la representación de base 10 de ese número son únicos. Ejemplo:
48778584 -> false
17308459 -> true
El recuento de caracteres incluye solo la función.
Si elige responder en C o C ++: sin macros, sin comportamiento indefinido; El comportamiento definido por la implementación y las advertencias del compilador están bien.
Respuestas:
Golfscript,
87 caracteres:`
- stringify el argumento..
- clonar dos veces&
- intersectarse consigo mismo (eliminar duplicados)=
- Verificar la igualdad.si la función necesita ser nombrada (
109 caracteres ):si un programa es suficiente (
5 54 caracteres ):fuente
Pitón 2 (28)
(32)Los backticks toman la representación de cadena. La conversión a un conjunto elimina duplicados, y verificamos si esto disminuye la longitud en comparación con 10 ^ d, que es más grande que todos los números de dígitos d pero sin números de dígitos (d + 1).
Código antiguo
fuente
n
withi
f=lambda _:len(`_`)==len(set(`_`))
lambda n:max(map('n'.count,'n'))<2
(the single quotes are backticks), but it's two chars longer.APL (6)
One of the few times where tacit style is shorter in APL too.
It's 8 characters to give it a name,
but that's not necessary to use it:
fuente
Perl, 19 characters
fuente
<>!~/(\d).*\1/
.\d
to.
.Rebmμ (10 characters)
Rebmu's "mushing" trick is that it's case-insensitive, so characters are run together. Whenever a case transition is hit, that splits to the next token. By using transitions instead of a CamelCase kind of thing, the unique choice to start with a capital run means a "set-word" is made. (While set-words can be used for other purposes in symbolic programming, they are evaluated as assignments by default).
So this "unmushes" to:
The space is needed because once you've begun a series of runs of alternating cases, you can't use that trick to get a set-word after the first unless you begin a new run. So
e?AtsAuqA
would have gotten youe? a ts a uq a
...no assignment.(Note: For what may be no particularly good reason, I tend to prefer rethinking solutions so that there are no spaces, if character counts are equal. Since brackets, parentheses, and strings implicitly end a symbol...there are often a fair number of opportunities for this.)
In any case, when mapped to the Rebol that it abbreviates:
Throwing in some parentheses to help get the gist of the evaluation order:
So the prefix equality operator is applied to two arguments--the first the result of assigning to
a
of the string version of itself, and the second the result ofunique
being run against that string. It so happens that unique will give you back the elements in the same order you passed them...so unique of "31214" is "3124" for instance.Run it with:
There's also some stats and debug information:
If the requirement is that one must define a named/reusable function you can make an "A-function" which implicitly takes a parameter named a with
a|
. (A B-function would be created withb|
and take a parameter named A then one named B). So that would add five more characters...let's say you call the function "f""You laugh! They laughed at Einstein! Or wait...did they? I...don't know."
fuente
Reb moo
, but now I'm not sure if it's supposed to beRebum mew
orReb mew
or something else.Fa|[e? AtsAugA]
asFalse? SomeGibberish
s
really decay to[
in Nethack?REBmu
is probably better. Either way, the beard is tight..it pinches. Guess you get what you pay for.FRACTRAN -
5338 fractionsUses division to count the number of occurrences of each digit. Call by putting n in register 2 and setting register 5 to 1, gives output in register 3 (0 if false, 1 if true). Also, make sure the rest of your program uses only registers > 71.
Edit 25/12/14: It's been 7 months and we've since gotten Stack Snippets, so here's one to test the code (using my could-be-better interpreter here).
Replace
142857
with another number. Output should be3^1
if true,1 = 3^0
if false. Takes a while for larger numbers (well, this is FRACTRAN...).fuente
JavaScript - 23 Characters
As a function (ECMAScript 6):
Or taking input from a prompt (25 characters)
fuente
C#
736059First golfing for me ...
Could strip another character by convertingHere we go ...uint
toint
, but I rather take the task too literally than the other way around.fuente
i => (i + "").Distinct().SequenceEqual(i + "");
+""
callingToString()
under the hood.Ruby (24 bytes)
Use a regular expression to match "some character, followed by zero or more characters, then the same character".
If truthy or falsy values are accepted, rather than literal
true
orfalse
, then we get 20 characters:fuente
C (87)
Since I can't win, I'll go for efficiency.
Function code:
fuente
Mathematica,
3525 characters(27 if the function needs a name.)
EDIT: Saved 8 characters thanks to belisarius!
fuente
Unequal @@ IntegerDigits@# &
could do, I think≠
would compare non-adjacent elements). Thanks, that shortens this a lot!Unequal@@IntegerDigits@#&
is 25 characters.R,
53514834 BytesTry it online!
Convert to a string and split. Convert to a table of counts minus 1, sum and negateInspired by Most common number answer by Alex and suggestion by Hugh.A couple saved, thanks to @plannapus One more from @Gregor And a couple from making it an anonymous function
Now with wonderful regex goodness thanks to @J.Doe. This looks for any single char in the number that matches itself else where in the string. The
grepl
command returns a logical that is then returned. Perl style regexes is set to True.fuente
paste0
instead oftoString
and save 2 characters.paste
instead ofpaste0
to save one more character.J (9)
Assumes the value to be tested is in variable
b
(I know this can be made into a function, but don't have a clue on how. J is confusing. Any help on this is appreciated)Thanks Marinus!Checks if the lenght of the string rep of the number with all the duplicates removed is the same as the lenght of the regular string rep.
fuente
(-:~.)@":
.R (
70,60,53, 52)Thank you all for the useful comments! Your comments are incorporated in the answer.
fuente
strsplit
why not coercing x to a character usingc(x,"")
?f=function(x)all(table(strsplit(c(x,""),"")[[1]])<2)
is 1 character shorter :)Mathematica (
2019)(
2221 if function needs a name)or
where | ist entered as [Esc]divides[Esc]
fuente
Brachylog, 1 byte
Try it online!
fuente
C99, 59 chars
fuente
Groovy (36 chars)
Tested it using:
fuente
0>1
is shorter.!1
instead.Haskell:
fuente
Data.List
anyway I'd suggestnub
, which removes duplicates from a List.(\x->nub x==x).show
main = interact $ show . ap (==) nub . show
J (8)
Competely sepertae from my previous answer.
fuente
R,
6665 charactersSeparate the digits using integer division and modulo, then check if they are duplicates.
Usage:
Or, as @MickyT suggested, for 63 characters:
fuente
anyDuplicated
rather thansum
andduplicated
for 2 moreC, 58 bytes
Can keep a tally of up to 7 identical digits before rolling over.
in test program (it's easier to see how it works with the constant in octal)
If you happen to have a large power of 2 handy the constant can be calculated like
f&(1<<30)/7*6
fuente
int main(int)
in your answer...Haskell, 34 bytes
Try it online!
fuente
Javascript 73 chars
fuente
Befunge 98, 17 bytes
This is a non-competing answer because Befunge does not have functions.
Prints a
1
if the number's digits are all unique; otherwise, it just ends.This works by accessing a cell in the Funge space whose
x
coordinate is the ASCII value of the character inputted (takes input character by character) and whosey
coordinate is1
. If the digit has not been seen before, the value of the cell is32
(space character). If that is so, I set the value to 1.As a bonus, this works for non-numbers as well.
fuente
PowerShell - 26
fuente
Perl 6 (19 bytes)
.comb
splits a string into characters (for example,42.comb
gives"4", "2"
)..uniq
removes all non-unique characters..comb
characters in string (originally I used.chars
, but.comb
is shorter).==
converts lists into number of elements in it, and compares the numbers. When.
is used without object before,$_
which is default function parameter is assumed.{}
are function literals.fuente
C, 76
This is no where near winning, but I'll post it anyway just to show an alternative approach.
Prints a new line if false, prints nothing if true.
fuente
int main(int, char **)
orint main(void)
.int main(int)
is not valid.main()
is ok then?main(void)
(when used in definition, in declaration it declares a function with unknown parameter list).POSIX sh and egrep (
47,43, 40)!
instead of-z
withtest
- Thanks DigitalTrauma`CODE`
instead of$(CODE)
- Thanks DigitalTraumafold -1
instead ofgrep -o .
1 - Thanks DigitalTrauma.If POSIX compliance is not important
echo PARAM |
can be replaced by<<<PARAM
, reducing the functions length to 37:Usage:
1 The
fold -N
notation is deprecated in some versions offold
.fuente
f()(! [ `fold -1<<<$1|sort|uniq -d` ])
down to 38 by my counttest
croaks on it whenuniq -d
returns more than one line. So the shortest non-POSIX version is 40 characters. I know about the[ !
notation, but I am suprised that! [
also works, do you know why that is?Java (
1315957)57 characters:
removed ^ and $ as @n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ suggested
59 characters (works also with negative numbers!):
7978 characters (thanks @n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ ):Use for loop to save a few charachers and use int as a boolean array.
Use & instead of && to save 1 character (It turns out that java allows it).
131 characters (returns true for negative numbers):
with comments:
And answer that is technically correct (character count includes only the function, not global variables), but I think it's cheating, 29 characters:
m[] is boolean array that contains correct answers for all 32-bit integers.
fuente
"^.*(.).*\\1.*$"
You can drop^
and$
. They are implied bymatches()
return!
in the shortest answer, you can get to 56 bytes.