37
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ I'd still be interested in other C or C++ solutions as per the question that inspired this one. \$\endgroup\$ – Thomas May 21 '14 at 19:59
  • 1
    \$\begingroup\$ Why no C or C++ macros or undefined behavior? That's oddly limiting to just two languages. \$\endgroup\$ – dfeuer Apr 14 at 2:05

71 Answers 71

1
\$\begingroup\$

Python 2.7 114 106 bytes

First golf, and this is no way going to win :P

def d(a):
    f=[];
    for i in str(a):
        if i in f:return False
        f.append(i)
    return True

Kinda want to see how other people would improve this :)

EDIT: With ProgramFOX's comments:

def d(a):
    f=[];
    for i in str(a):
        if i in f:return 1<0
        f+=[i];
    return 0<1
\$\endgroup\$
  • \$\begingroup\$ return True can be shortened to something like 0<1. And f.append(i) can be shortened to f+=[i]. \$\endgroup\$ – ProgramFOX Dec 21 '14 at 15:40
  • \$\begingroup\$ You're welcome! Also, you can save one more character by dropping the ; after f+=[i]. It is not necessary there. \$\endgroup\$ – ProgramFOX Dec 21 '14 at 19:03
  • \$\begingroup\$ Ugh... Too much php :) \$\endgroup\$ – JamJar00 Dec 21 '14 at 19:04
1
\$\begingroup\$

Python, 40

f=lambda x:len(str(x))==len(set(str(x)))

The built-in set removes the duplicates, so if the length of a thing and the length of his set are equal, the thing does not have repeated elements.

\$\endgroup\$
1
\$\begingroup\$

Burlesque, 2 bytes

Using the Unique built-in:

blsq ) 17308459U_
1
blsq ) 48778584U_
0
\$\endgroup\$
1
\$\begingroup\$

Go, 138 bytes

Bad language choice.

run it like uniqchars 112345678

package main
import(."fmt"
."os"
."strings")
func main(){s:=Args[1]
f:=true
for _,e:=range s{if Count(s,string(e))>1{f=false}}
Println(f)}
\$\endgroup\$
  • \$\begingroup\$ This is post 65536 on the site! That's 2^16. \$\endgroup\$ – wizzwizz4 Jan 11 '16 at 21:11
1
\$\begingroup\$

J, 8 bytes

-:~.&.":

Explanation:

         ": - converts the integer to a string
       &.   - "under" conjuction - uses the result from ": as operand to ~.
               then applies the inverse to the result, so converts the string back to integer
    ~.      - removes duplicates
  -:        - matches the operands

So, it first converts the number to a string, removes the duplicates and converts the resulting string to a number. Then the original number is matched against the transformed one. In fact it is a hook of two verbs: -: and ~.&.":

┌──┬──────────┐
│-:│┌──┬──┬──┐│
│  ││~.│&.│":││
│  │└──┴──┴──┘│
└──┴──────────┘

Try it online!

\$\endgroup\$
1
\$\begingroup\$

PARI/GP, 26 bytes

n->d=digits(n);#d==#Set(d)

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Perl 6, 12 bytes

{!/(.).*$0/}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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;
}
\$\endgroup\$
0
\$\begingroup\$

C# 72 characters

var a=i.ToString().ToCharArray();
return a.Distinct().Count()==a.Count();
\$\endgroup\$
  • \$\begingroup\$ ".ToCharArray()" is unnecessary since there's String.Distinct. \$\endgroup\$ – Helix Quar May 22 '14 at 1:37
  • \$\begingroup\$ 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. \$\endgroup\$ – hvd May 22 '14 at 7:13
  • \$\begingroup\$ you could also do i+"" instead of i.ToString(). But this question is asking for a function, you just gave 2 lines of code \$\endgroup\$ – jzm May 26 '14 at 0:25
0
\$\begingroup\$

Julia, 44

f(n)=(d=digits(n);length(Set(d))==length(d))
\$\endgroup\$
  • \$\begingroup\$ 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? \$\endgroup\$ – Glen O May 22 '14 at 16:11
  • \$\begingroup\$ 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. \$\endgroup\$ – gggg May 22 '14 at 16:27
  • \$\begingroup\$ That might make a difference - I'm running 0.2.1. I get length(Set(1,2))=2, but length(Set([1,2]))=1. \$\endgroup\$ – Glen O May 22 '14 at 16:36
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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!
\$\endgroup\$
0
\$\begingroup\$

Ruby(47 characters)

->(x){x.to_s.chars.sort.uniq.size==x.to_s.size}

Example usage

->(x){x.to_s.chars.sort.uniq.size==x.to_s.size}[10]
=> true
\$\endgroup\$
0
\$\begingroup\$

C# (44 - 64)

Func

As a lambda (44):

y=>!(y+"").GroupBy(x=>x).Any(x=>x.Count()>1)

alt lambda (also 44):

y=>(y+"").GroupBy(x=>x).All(x=>x.Count()==1)

As a Func (63):

Func<int, bool> f=y=>(y+"").GroupBy(x=>x).All(x=>x.Count()==1);

As a method (64):

bool f(int y){return (y+"").GroupBy(x=>x).All(x=>x.Count()==1);}
\$\endgroup\$
0
\$\begingroup\$

Extended BrainFuck: 100

not included the unnecessary linefeed.

{a>[>>]}>>,10-[38-[-&a+[<<]>]&a>[[-]3<[-<<]<+2>&a>]
+3<[-<<]>,10-]<+<([-]>-|"false"[-])>(-|"true"[-])

Usage:

%> beef ebf.bf < unqiue.ebf > unqiue.bf
%> echo 48778584 | beef unique.bf 
-> false
%> echo 17308459 | beef unique.bf 
-> true
\$\endgroup\$
0
\$\begingroup\$

VBA (145)

Function jkl(f As String) As Boolean
For i = 1 To Len(f)
jkl = InStr(1, f, Left(Mid(f, i), 1)) <> i
If jkl = True Then Exit Function
Next
End Function

Calling the function and output with opposite of the result:

Sub jj()
Dim f As String
f = "1234256789"
MsgBox Not (jkl(f))
End Sub
\$\endgroup\$
0
\$\begingroup\$

PHP 74 Chars

<?php $a=str_split($argv[1]);var_dump(count($a)==count(array_unique($a)));
\$\endgroup\$
0
\$\begingroup\$

VB.NET - 189 184

Function U(I As Integer) As Boolean
    U = True
    Dim D(9)
    Dim S = I.ToString
    For Each E As Char In S
        If IsNumeric(E) Then If D(Val(E)) + 1 > 1 Then U = False Else D(Val(E)) += 1
    Next
End Function

First code-golf attempt. I'm aware it's an unsuitable language and poor result, but I wanted to try.

\$\endgroup\$
  • \$\begingroup\$ I counted 189 characters even without necessary whitespace. Please be aware that, unless explicitly stated in the question, we usually count necessary whitespaces in answers. However, you can reduce your source size by removing unnecessary whitespaces (spaces around assignment operators, indentations etc) and using one-character identifier names, e.g. U instead of Unique, i instead of IA etc. Also, I cannot test it now but I think you can skip the type definitions of your variables/function (i.e. using only Dim D(9),i()=I.ToString.ToCharArray) \$\endgroup\$ – ace May 24 '14 at 15:17
  • \$\begingroup\$ So your first line may become something like Function U(I). Your function can then return integers 0 and 1 instead of false/true. Then your second line can be changed to U=1 and your Return False can be changed to U=0. Finally, I'm not sure whether it works but perhaps making IA a string instead of a char array can save you a lot of bytes. \$\endgroup\$ – ace May 24 '14 at 15:22
  • \$\begingroup\$ I used an online tool out of laziness, I may have to write a character-counting function instead. Do you count line returns and tabs as characters? \$\endgroup\$ – Lou May 24 '14 at 15:23
  • \$\begingroup\$ Visual Studio 2012 religiously enforces spacing and indentation, even correcting it before beginning a debug - I don't see a way I can cut them out. \$\endgroup\$ – Lou May 24 '14 at 15:24
  • \$\begingroup\$ Also, how do I count bytes in code? Sorry, I looked in Meta and the Help Centre but I couldn't find an answer. \$\endgroup\$ – Lou May 24 '14 at 15:27
0
\$\begingroup\$

Clojure - (42 - 52)

As a named function (52):

(defn f[i](let[s(str i)](=(count s)(count(set s)))))

As an anonymous function (42):

#(let[s(str %)](=(count s)(count(set s))))
\$\endgroup\$
0
\$\begingroup\$

Scala

Cheating with library functions (29/12 characters):

def t(i:String)=i==i.distinct

Scala version of the GolfScript version (36/19 characters):

def t(i:String)=i.intersect(i).size>0

Doing the counting work manually (91/74 characters):

def t(i:String)=(Map.empty[Char,Int]/:i)((m,c)=>m+(c->(m.getOrElse(c,0)+1))).forall(_._2<2)
\$\endgroup\$
0
\$\begingroup\$

PHP - 44 33

var_dump(max(count_chars($n))<2);

Or Proper function 42 Characters

function(){return max(count_chars($n))<2;}

UPDATE : Thanks for @scrblnrd3 pointed out for shorter solution.

\$\endgroup\$
  • \$\begingroup\$ You could cut out a few chars by doing <2 instead of the ternary operator \$\endgroup\$ – scrblnrd3 May 23 '14 at 19:49
  • \$\begingroup\$ <2 in PHP, DO you have some reference page, how it used in php as I never seen this. \$\endgroup\$ – kuldeep.kamboj May 26 '14 at 5:20
  • 1
    \$\begingroup\$ I mean you could use var_dump(max(count_chars($n))<2); instead \$\endgroup\$ – scrblnrd3 May 26 '14 at 13:19
  • \$\begingroup\$ <?=max(count_chars($argn))<2); 30+1 bytes: run as pipe with -F, prints 1 for true, nothing for false \$\endgroup\$ – Titus Nov 2 '17 at 20:58
0
\$\begingroup\$

Haskell (41)

import Data.List
f x=show x==nub(show x)

About 23 characters shorter than the other Haskell answer and a fair bit more intuitive I think. Basically the same process but using Haskell's built-in list functions is much easier and shorter.

\$\endgroup\$
  • \$\begingroup\$ I don't think you're required to count the last newline. \$\endgroup\$ – seequ Jun 3 '14 at 17:42
0
\$\begingroup\$

C - 62

int m[10];f(int a){while(m[a%10]++?0:a/=10);return m[a%10]<2;}

I've included the count of the globally declared array (which ensures initialisation to 0).

As a bonus, here is a much shorter technically correct answer:

f(int a){return 1}

The question does not state that non-unique digits should return false. Therefore I claim the current lead for C code with 18 characters, although I expect to be beaten by a scripting language with an answer like:

1
\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to Programming Puzzles and Code Golf. I think the OP states quite clearly that a number with duplicate digits should return false. Perhaps you could explain why you think differently? And explain how an undefined function performs the requested task, and how a singly character can do so in any scripting language. \$\endgroup\$ – David Wilkins May 23 '14 at 17:24
  • 1
    \$\begingroup\$ @David Wilkins One of the examples returns false; the actual OP just states that unique digits should return true, which the C program I added in jest certainly does. \$\endgroup\$ – Alchymist May 27 '14 at 7:40
  • \$\begingroup\$ Also, if I knew golfscript, for example, I would have written a function returning true in that rather than describing an unspecified "scripting language" \$\endgroup\$ – Alchymist May 27 '14 at 7:59
0
\$\begingroup\$

Julia - 29 28

f(n)=unique("$n")=="$n".data

Old version:

f(n)=join(unique("$n"))=="$n"
\$\endgroup\$
0
\$\begingroup\$

F# - 82

let f i =
    let s = i.ToString() 
    s |> Set.ofSeq|> Seq.length = s.Length;;
\$\endgroup\$
0
\$\begingroup\$

COBOL 66 with Object Cobol extensions

Microfocus Cobol (721 659 592)

       method-id u.
       local-storage section.
       77  i pic s9(9) comp.
       77  c pic 9 occurs 10 value 0.
       77  g pic 9.
       01  s pic 9(9).
       01  t redefines s pic 9 occurs 9.
       linkage section.
       77  n pic s9(9) comp.
       77  d pic x.
       88  f value is 'y'.
       procedure division using by value n returning d.
           move n to s. move 'n' to d. perform p varying i from 1 by 1 until i greater than 9 or f. goback.
       p.  move t (i) to g. if c (g) is not zero then move 'y' to d. add 1 to c (g).
       end method.

Hmmm, I think I should go back to pitch & putt :(

EDIT: OMGZ I CAN USE LOWER CASE!!!

\$\endgroup\$
0
\$\begingroup\$

C++ 82

this code is at least legitimate

int a(uint32_t i,uint32_t r=0,uint32_t h=0)
{return i?r&h?0:a(i/10,r|h,1<<i%10):1;}        // thanks to DreamWarrior

C 47

this works if you compile it in debug mode or provide two more arguments set to 0

a(i,r,h){return i?r&h?0:a(i/10,r|h,1<<i%10):1;}
\$\endgroup\$
0
\$\begingroup\$

k4 (8)

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

inspired by a combination of the J and Golfscript answers

\$\endgroup\$
0
\$\begingroup\$

Regular Expression 17 bytes

^(?:(.)(?!.*\1))*$

Original expression taken from https://stackoverflow.com/a/12870549.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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