Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Deleted questions on Stack Overflow sometimes make for great golf material.

Write a function that takes a nonnegative integer as input, and returns true if all the digits in the base 10 representation of that number are unique. Example:

48778584 -> false
17308459 -> true

Character count includes only the function.

If you choose to answer in C or C++: no macros, no undefined behaviour; implementation-defined behaviour and compiler warnings are fine.

share|improve this question
    
I'd still be interested in other C or C++ solutions as per the question that inspired this one. –  Thomas May 21 at 19:59
    
Does this have to work for negative numbers? –  xnor May 21 at 20:07
    
No. Edited..... –  Thomas May 21 at 20:08

48 Answers 48

Golfscript, 8 7 characters:

{`..&=}
  • ` - stringify the argument
  • .. - clone twice
  • & - intersect with itself (remove duplicates)
  • = - check for equality.

if the function needs to be named (10 9 characters):

{`..&=}:a

if a program suffices (5 4 characters):

..&=
share|improve this answer
    
The $ is unnecessary, as .& preserves the order of the array elements. –  Ilmari Karonen May 21 at 20:27
5  
The hard part about challenges like this is being the first to see it. –  primo May 22 at 2:11
1  
@primo yet, somehow, they still get +6 score within half a day. –  Jan Dvorak May 22 at 7:16
1  
@JanDvorak Parkinson's law of triviality at work –  Claudiu May 22 at 20:43
2  
@Claudiu You can understand the law. Realise you're being subjected to it. Then upvote the answer anyway. –  Cruncher May 23 at 17:16

Python 2 (28) (32)

lambda n:10**len(set(`n`))>n

The backticks take the string representation. Converting to a set removes duplicates, and we check whether this decreases the length by comparing to 10^d, which is bigger than all d-digit number but no (d+1)-digit numbers.

Old code:

lambda n:len(set(`n`))==len(`n`)
share|improve this answer
    
Ha I had this exact same answer ready, just replace n with i –  Claudiu May 21 at 19:57
1  
@Claudiu so did I. f=lambda _:len(`_`)==len(set(`_`)) –  Oberon May 21 at 19:59
    
Yeah, with these bite-size challenges, everyone is going to converge on pretty much the same thing. I was also trying lambda n:max(map('n'.count,'n'))<2 (the single quotes are backticks), but it's two chars longer. –  xnor May 21 at 20:49

APL (6)

≡∘∪⍨∘⍕

One of the few times where tacit style is shorter in APL too.

It's 8 characters to give it a name,

f←≡∘∪⍨∘⍕

but that's not necessary to use it:

      ≡∘∪⍨∘⍕ 199
0
      ≡∘∪⍨∘⍕ 198
1
      f←≡∘∪⍨∘⍕
      f¨ 198 199 200 201
1 0 0 1
      ≡∘∪⍨∘⍕¨ 198 199 200 201
1 0 0 1
share|improve this answer

Perl, 19 characters

print<>!~/(\d).*\1/
share|improve this answer
    
assuming output can be treated as true and no-output can be treated as false, your logic is reversed. You should return true if there's no repetition. –  Jan Dvorak May 21 at 19:45
    
@JanDvorak Sounds about right. I'll fix that. –  Tal May 21 at 19:48
    
Not-match operator: <>!~/(\d).*\1/. –  primo May 22 at 4:17
    
@primo Thanks! So much to learn :) –  Tal May 22 at 4:25
2  
The input is specified as being a non-negative integer, so I don't think you need to verify that. If you indeed don't, you can change \d to .. –  hvd May 22 at 7:06

Rebmμ (10 characters)

e? AtsAuqA

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:

e? a: ts a uq a

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 you e? 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:

equal? a: to-string a unique a

Throwing in some parentheses to help get the gist of the evaluation order:

equal? (a: (to-string a)) (unique a)

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 of unique 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:

>> rebmu/args "e? AtsAuqA" 17308459             
== true

There's also some stats and debug information:

>> rebmu/args/stats/debug "e? AtsAuqA" 48778584 
Original Rebmu string was: 10 characters.
Rebmu as mushed Rebol block molds to: 10 characters.
Unmushed Rebmu molds to: 15 characters.
Executing: [e? a: ts a uq a]
== false

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 with b| 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"

Fa|[e? AtsAugA]

"You laugh! They laughed at Einstein! Or wait...did they? I...don't know."

share|improve this answer
    
I used to think the language was pronounced like Reb moo, but now I'm not sure if it's supposed to be Rebum mew or Reb mew or something else. –  Quincunx May 23 at 1:48
2  
After playing Nethack, I read Fa|[e? AtsAugA] as False? SomeGibberish –  Quincunx May 23 at 1:49
    
@Quincunx does s really decay to [ in Nethack? –  Jan Dvorak May 25 at 11:08
    
@JanDvorak I've seen some letters do decay into [ after some time –  Quincunx May 28 at 4:18
    
@Quincunx Just playing with the logo. I think REBmu is probably better. Either way, the beard is tight..it pinches. Guess you get what you pay for. –  Dr. Rebmu May 28 at 5:05

JavaScript - 23 Characters

As a function (ECMAScript 6):

f=x=>!/(.).*\1/.test(x)

Or taking input from a prompt (25 characters)

!/(.).*\1/.test(prompt())
share|improve this answer

C (87)

Since I can't win, I'll go for efficiency.

Function code:

int u(uint32_t d){short s=0,f;while(d){f=1<<d%10;if(s&f)return 0;s|=f;d/=10;}return 1;}
share|improve this answer
    
Oh, and since I still can't comment on other people's posts -- I'd like to say that this was a neat solution, even if inaccurate when it "overflows". –  DreamWarrior May 22 at 23:08

C# 73 60 59

First golfing for me ...

Write a function that takes a nonnegative integer as input

bool f(int i){return(i+"").Distinct().SequenceEqual(i+"");}

Could strip another character by converting uint to int, but I rather take the task too literally than the other way around. Here we go ...

share|improve this answer
1  
Some options: i => (i + "").Distinct().SequenceEqual(i + ""); –  NPSF3000 May 22 at 10:14
    
@NPSF3000 Thanks! Edited my answer. I had something like this on my mind, but oh well ... I totally forgot about +"" calling ToString() under the hood. –  Num Lock May 22 at 10:46
    
A more literal interpretation of "nonnegative integer" suggests that a signed integer will be passed in, but it will never be negative. –  Ryan May 22 at 14:49
    
Well, I guess it will be ok then ... –  Num Lock May 23 at 4:46

Mathematica, 35 25 characters

(27 if the function needs a name.)

Unequal@@IntegerDigits@#&

EDIT: Saved 8 characters thanks to belisarius!

share|improve this answer
    
Unequal @@ IntegerDigits@# & could do, I think –  belisarius May 21 at 21:23
    
@belisarius oh nice, I was looking for something like that but couldn't find it (and didn't think that chained would compare non-adjacent elements). Thanks, that shortens this a lot! –  Martin Büttner May 21 at 22:20
    
You don't have to give it a name, right? Unequal@@IntegerDigits@#& is 25 characters. –  Akater May 23 at 21:39
    
@Akater true, I can't see a requirement for the name in the challenge. Thanks! –  Martin Büttner May 23 at 21:44

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.

share|improve this answer
    
For a function you can do (-:~.)@":. –  marinus May 21 at 20:22
    
@marinus Oh wow, that's even shorter than I thought. Thanks! –  ɐɔıʇǝɥʇuʎs May 21 at 20:24

FRACTRAN - 53 38 fractions

47/10 3/5 106/47 3599/54272 53/61 2881/27136 2479/13568 2077/6784 1943/3392 1541/1696 1273/848 1139/424 871/212 737/106 469/53 142/3953 67/71 5/67 1/147 1/363 1/507 1/867 1/1083 1/1587 1/2523 1/2883 1/4107 1/5547 1/7 1/11 1/13 1/17 1/19 1/23 1/29 1/31 1/37 1/43

Uses 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.

share|improve this answer

Ruby (24 bytes)

Use a regular expression to match "some character, followed by zero or more characters, then the same character".

->(s){!!(s !~/(.).*\1/)}

If truthy or falsy values are accepted, rather than literal true or false, then we get 20 characters:

->(s){s !~/(.).*\1/}
share|improve this answer

C99, 59 chars

a(x){int r=1,f[10]={};for(;x;x/=10)r&=!f[x%10]++;return r;}
share|improve this answer
    
C99 doesn't have implicit int, technically. –  PatrickB May 21 at 20:55
1  
Not just "technically", it was specifically and intentionally removed. This is a syntax error in C99, and aside from a required diagnostic, syntax errors are in the same category as undefined behaviour (explicitly disallowed in the question): if an implementation accepts this, the standard makes no requirements whatsoever about the program's behaviour. –  hvd May 22 at 7:09

Groovy (36 chars)

f={s="$it" as List;s==s.unique(!1)}

Tested it using:

println f(args[0].toInteger())
share|improve this answer
    
'false' can be golfed via '1==0' or possibly something more clever. Good answer –  Michael Easter May 22 at 1:57
    
@MichaelEaster 0>1 is shorter. –  ace May 22 at 10:14
1  
@ace Yes, though !1 works too... –  Michael Easter May 22 at 10:16
    
@ace, MichaelEaster, thx for the help :-) –  Will P May 22 at 12:06
    
@WillP as suggested by MichaelEaster, use !1 instead. –  ace May 22 at 12:14

Haskell:

 import Data.List

 all ((== 1) . length) . group . sort . show
share|improve this answer
    
A little late to the party, but since you're importing Data.List anyway I'd suggest nub, which removes duplicates from a List. (\x->nub x==x).show –  Flonk May 30 at 18:07
    
You didnt use pl... main = interact $ show . ap (==) nub . show –  kazagistar Jun 15 at 20:26

Mathematica (20 19)

(22 21 if function needs a name)

Max@DigitCount@#<2&

or

Max@DigitCount@#|1&

where | ist entered as [Esc]divides[Esc]

share|improve this answer

C, 53 chars in function(uses global constant)

If you consider using a global constant cheating, I would point out that OP did say he wanted to see different ways of doing it in C.) It can keep a tally of up to 7 identical digits before rolling over.

r;s=06666666666;

a(x){int f=0;for(;x;x/=10)f+=1<<x%10*3;return!(f&s);}

main(){
scanf("%d",&r);
printf("%o\n",a(r));}

C, 62 (or 60) chars in function(no global constant required)

The same as before, but I calculate the constant, which is more legitimate. The calculated constant (1<<30)/7*6 is 11 chars, exactly the same as the literal 06666666666 octal, but if you happen to have a large power of 2 in your program, you can take advantage to shorten it. The decimal version of the constant, 920350134 is 9 chars for a total of 60.

a(x){int f=0;for(;x;x/=10)f+=1<<x%10*3;return!(f&(1<<30)/7*6);}
share|improve this answer
    
I think the comment by @xfix was intended for my post instead of yours? You didn't actually used int main(int) in your answer... –  ace May 22 at 13:25

Javascript 73 chars

function f(n){return !~(n+'').split('').sort().join('').search(/(\d)\1/)}
share|improve this answer

Befunge 98, 17 bytes

This is a non-competing answer because Befunge does not have functions.

~:1g1`j@1\1p3j@.1

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 whose y coordinate is 1. If the digit has not been seen before, the value of the cell is 32 (space character). If that is so, I set the value to 1.

As a bonus, this works for non-numbers as well.

share|improve this answer

C, 76

This is no where near winning, but I'll post it anyway just to show an alternative approach.

c;i;a[99];main(){while(~(c=getchar()))a[c]++;for(;i<99;)a[i++]>1&&puts("");}

Prints a new line if false, prints nothing if true.

share|improve this answer
    
This program has an undefined behavior. The correct signatures for main are int main(int, char **) or int main(void). int main(int) is not valid. –  xfix May 22 at 13:11
    
@xfix I assume main() is ok then? –  ace May 22 at 13:22
    
Yes, it's fine. It means the same thing as main(void) (when used in definition, in declaration it declares a function with unknown parameter list). –  xfix May 22 at 13:22

R (70, 60, 53, 52)

Thank you all for the useful comments! Your comments are incorporated in the answer.

### Version 70 chars
f=function(x)!any(duplicated(strsplit(as.character(x),split="")[[1]]))

### Version 60 chars
f=function(x)all(table(strsplit(as.character(x),"")[[1]])<2)

### Version 53 chars
f=function(x)all(table(strsplit(paste(x),"")[[1]])<2)

### Version 52 chars
f=function(x)all(table(strsplit(c(x,""),"")[[1]])<2)

f(48778584)
f(17308459)
share|improve this answer
1  
wouldn't f=function(x)!any(duplicated(strsplit(as.character(x),split="")[[1]])) be enough? –  plannapus May 22 at 11:18
    
@plannapus, you are right. I got confused about "base 10 representation". –  djhurio May 22 at 11:33
1  
Using table and comparing against 0 instead of duplicated might save some characters –  Dason May 22 at 21:26
1  
And I think you could leave the split parameter unnamed. I'm just on my phone so can't check easily but I believe it is the second parameter of strsplit so you could use positional instead of named arguments to save characters –  Dason May 22 at 21:29
1  
And since you already take the first element of the result of strsplit why not coercing x to a character using c(x,"")? f=function(x)all(table(strsplit(c(x,""),"")[[1]])<2) is 1 character shorter :) –  plannapus May 23 at 8:38

POSIX sh and egrep (47, 43, 40)

f()([ ! `echo $1|egrep '([0-9]).*\1'` ])
  • [-1 char]: Use ! instead of -z with test - Thanks DigitalTrauma
  • [-1 char]: Use `CODE` instead of $(CODE) - Thanks DigitalTrauma
  • [-2 chars]: Use fold -1 instead of grep -o .1 - Thanks DigitalTrauma.
  • [-3 chars]: Check for repeated digits with a backreferenced regular expression.

If POSIX compliance is not important echo PARAM | can be replaced by <<<PARAM, reducing the functions length to 37:

f()([ ! `egrep '([0-9]).*\1'<<<$1` ])

Usage:

$ if f 48778584; then echo true; else echo false; fi
false
$ if f 17308459; then echo true; else echo false; fi
true

1 The fold -N notation is deprecated in some versions of fold.

share|improve this answer
    
f()(! [ `fold -1<<<$1|sort|uniq -d` ]) down to 38 by my count –  DigitalTrauma May 29 at 23:39
    
@DigitalTrauma: Good stuff thanks for sharing. I find that the tested command must be quoted, otherwise test croaks on it when uniq -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? –  Thor May 30 at 19:40
    
Ah I was using bash. So I guess its longer if you want POSIX conformance. –  DigitalTrauma May 30 at 19:42

C 151

Bytes = 181 or 151 without newline chars. Program keeps a tally of digits and exits if greater than 1.

#include <stdio.h>
int i,j[10],r;
int main()
{
scanf("%d",&i);
do{
r=i%10;
j[r]++;
if(j[r]>1){printf("false");return 0;}
i/=10;
}while(i);
printf("true");
return 0;
}
share|improve this answer

C# 72 characters

var a=i.ToString().ToCharArray();
return a.Distinct().Count()==a.Count();
share|improve this answer
    
".ToCharArray()" is unnecessary since there's String.Distinct. –  helix May 22 at 1:37
    
I think that not including the required using System.Linq; in your character count is cheating a bit. @helix That's Enumerable.Distinct, not String.Distinct. MSDN is a bit confusing by showing extension methods too. But indeed, ToCharArray() is not necessary. –  hvd May 22 at 7:13
    
you could also do i+"" instead of i.ToString(). But this question is asking for a function, you just gave 2 lines of code –  malik May 26 at 0:25

Julia, 44

f(n)=(d=digits(n);length(Set(d))==length(d))
share|improve this answer
    
This doesn't work - it only returns true if n is one digit long, as length(Set(d))=1 for any integer. For the same approach idea, perhaps use unique(d)==d? –  Glen O May 22 at 16:11
    
julia> f(123456) true julia> f(1234566) false It seems to work. julia> length(Set(1,2)) 2 Perhaps the definition of length(x::Set) changed recently? I'm running 0.3 prerelease. –  gggg May 22 at 16:27
    
That might make a difference - I'm running 0.2.1. I get length(Set(1,2))=2, but length(Set([1,2]))=1. –  Glen O May 22 at 16:36

k4 (8)

  {x=.?$x}48778584
0b
  {x=.?$x}17308459
1b

inspired by a combination of the J and Golfscript answers

share|improve this answer

Cobra - 109

def f(n) as bool
    l=0
    m=n.toString
    for i in m,for j in m,if i==j,l+=1
    return if(l>m.length,false,true)

Makes me wish that LINQ would work properly in Cobra.

share|improve this answer

Perl, 63ish

$ echo 48778584| perl -F// -alpe '$"="";$_= 0<"@{[map {$a{$_}++} @F]}"?"false":"true"'
false
$ echo 17308459| perl -F// -alpe '$"="";$_= 0<"@{[map {$a{$_}++} @F]}"?"false":"true"'
true
share|improve this answer

R, 66 65 characters

f=function(x)!sum(duplicated((x%%10^(i<-1:nchar(x)))%/%10^(i-1)))

Separate the digits using integer division and modulo, then check if they are duplicates.

Usage:

> f(48778584)
[1] FALSE
> f(17308459)
[1] TRUE
share|improve this answer

C# 72 69 67 characters (no libraries needed)

for(;d>0;d/=10)for(int f=d/10;f>0;f/=10)if(d%10==f%10) return true;

Ungolfed:

for (; d > 0; d /= 10)
    for (int f = d / 10; f > 0; f /= 10) 
        if (d % 10 == f % 10) 
            return true;

I'm just using simple maths here.(i.e. number 1231):

  • Take the last digit (1)
  • Iterate through the quotient (123)
  • If the number is equal to our digit (1), then return true
  • 3 == 1, 2 == 1, 1 == 1 - found it!
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.