Determine if all decimal digits are unique

38

0

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.

Thomas

Posted 2014-05-21T19:20:18.720

Reputation: 579

1Why no C or C++ macros or undefined behavior? That's oddly limiting to just two languages. – dfeuer – 2019-04-14T02:05:57.200

I'd still be interested in other C or C++ solutions as per the question that inspired this one. – Thomas – 2014-05-21T19:59:58.443

Answers

31

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):

..&=

John Dvorak

Posted 2014-05-21T19:20:18.720

Reputation: 9 048

The $ is unnecessary, as .& preserves the order of the array elements. – Ilmari Karonen – 2014-05-21T20:27:15.447

@IlmariKaronen good catch, thanks – John Dvorak – 2014-05-21T20:29:27.723

5The hard part about challenges like this is being the first to see it. – primo – 2014-05-22T02:11:32.620

1@primo yet, somehow, they still get +6 score within half a day. – John Dvorak – 2014-05-22T07:16:57.333

1@JanDvorak Parkinson's law of triviality at work – Claudiu – 2014-05-22T20:43:51.130

2@Claudiu You can understand the law. Realise you're being subjected to it. Then upvote the answer anyway. – Cruncher – 2014-05-23T17:16:31.253

Golfscript 'answers' are officially not funny any more. – Nathan Chere – 2014-11-25T11:41:05.603

1

@NathanChere what do you mean? the last (and only) time that loophole was suggested it dropped to -3 before getting deleted by the suggester the next morning. If you don't like golfscript answers, don't upvote them.

– John Dvorak – 2014-11-25T11:49:29.040

24

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`)

xnor

Posted 2014-05-21T19:20:18.720

Reputation: 115 687

1Ha I had this exact same answer ready, just replace n with i – Claudiu – 2014-05-21T19:57:33.857

1@Claudiu so did I. f=lambda _:len(\`)==len(set(``))` – Oberon – 2014-05-21T19:59:18.360

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 – 2014-05-21T20:49:45.243

16

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

marinus

Posted 2014-05-21T19:20:18.720

Reputation: 30 224

1I think the second jot can be removed to make it 5. It would still be a valid function by itself (though it would require grouping parens to use it with each operator in the last example). – user46915 – 2015-11-09T09:44:31.830

11

Perl, 19 characters

print<>!~/(\d).*\1/

Tal

Posted 2014-05-21T19:20:18.720

Reputation: 1 358

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. – John Dvorak – 2014-05-21T19:45:34.360

@JanDvorak Sounds about right. I'll fix that. – Tal – 2014-05-21T19:48:24.513

Not-match operator: <>!~/(\d).*\1/. – primo – 2014-05-22T04:17:39.213

@primo Thanks! So much to learn :) – Tal – 2014-05-22T04:25:34.200

3The 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 – 2014-05-22T07:06:46.577

9

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

HostileFork says dont trust SE

Posted 2014-05-21T19:20:18.720

Reputation: 2 292

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. – Justin – 2014-05-23T01:48:50.253

2After playing Nethack, I read Fa|[e? AtsAugA] as False? SomeGibberish – Justin – 2014-05-23T01:49:42.410

@Quincunx does s really decay to [ in Nethack? – John Dvorak – 2014-05-25T11:08:00.900

@JanDvorak I've seen some letters do decay into [ after some time – Justin – 2014-05-28T04:18:31.463

@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. – HostileFork says dont trust SE – 2014-05-28T05:05:34.757

7

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.


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

var ITERS_PER_SEC=1E5;var TIMEOUT_MILLISECS=5E3;var ERROR_INPUT="Invalid input";var ERROR_PARSE="Parse error: ";var ERROR_TIMEOUT="Timeout";var ERROR_INTERRUPT="Interrupted by user";var running,instructions,registers,timeout,start_time,iterations;function clear_output(){document.getElementById("output").value="";document.getElementById("stderr").innerHTML=""};function stop(){running=false;document.getElementById("run").disabled=false;document.getElementById("stop").disabled=true;document.getElementById("clear").disabled=false}function interrupt(){error(ERROR_INTERRUPT)}function error(msg){document.getElementById("stderr").innerHTML=msg;stop()}function factorise(n){var factorisation={};var divisor=2;while(n>1){if(n%divisor==0){var power=0;while(n%divisor==0){n/=divisor;power+=1}if(power!=0)factorisation[divisor]=power}divisor+=1}return factorisation};function fact_accumulate(fact1,fact2){for(var reg in fact2)if(reg in fact1)fact1[reg]+=fact2[reg];else fact1[reg]=fact2[reg];return fact1};function exp_to_fact(expression){expression=expression.trim().split(/\s*\*\s*/);var factorisation={};for(var i=0;i<expression.length;++i){var term=expression[i].trim().split(/\s*\^\s*/);if(term.length>2)throw"error";term[0]=parseInt(term[0]);if(isNaN(term[0]))throw"error";if(term.length==2){term[1]=parseInt(term[1]);if(isNaN(term[1]))throw"error";}if(term[0]<=1)continue;var fact_term=factorise(term[0]);if(term.length==2)for(var reg in fact_term)fact_term[reg]*=term[1];factorisation=fact_accumulate(factorisation,fact_term)}return factorisation}function to_instruction(n,d){instruction=[];divisor=2;while(n>1||d>1){if(n%divisor==0||d%divisor==0){reg_offset=0;while(n%divisor==0){reg_offset+=1;n/=divisor}while(d%divisor==0){reg_offset-=1;d/=divisor}if(reg_offset!=0)instruction.push(Array(divisor,reg_offset))}divisor+=1}return instruction};function run(){clear_output();document.getElementById("run").disabled=true;document.getElementById("stop").disabled=false;document.getElementById("clear").disabled=true;timeout=document.getElementById("timeout").checked;var code=document.getElementById("code").value;var input=document.getElementById("input").value;instructions=[];code=code.trim().split(/[\s,]+/);for(i=0;i<code.length;++i){fraction=code[i];split_fraction=fraction.split("/");if(split_fraction.length!=2){error(ERROR_PARSE+fraction);return}numerator=parseInt(split_fraction[0]);denominator=parseInt(split_fraction[1]);if(isNaN(numerator)||isNaN(denominator)){error(ERROR_PARSE+fraction);return}instructions.push(to_instruction(numerator,denominator))}try{registers=exp_to_fact(input)}catch(err){error(ERROR_INPUT);return}running=true;iterations=0;start_time=Date.now();fractran_iter(1)};function regs_to_string(regs){reg_list=Object.keys(regs);reg_list.sort(function(a,b){return a-b});out_str=[];for(var i=0;i<reg_list.length;++i)if(regs[reg_list[i]]!=0)out_str.push(reg_list[i]+"^"+regs[reg_list[i]]);out_str=out_str.join(" * ");if(out_str=="")out_str="1";return out_str};function fractran_iter(niters){if(!running){stop();return}var iter_start_time=Date.now();for(var i=0;i<niters;++i){program_complete=true;for(var instr_ptr=0;instr_ptr<instructions.length;++instr_ptr){instruction=instructions[instr_ptr];perform_instr=true;for(var j=0;j<instruction.length;++j){var reg=instruction[j][0];var offset=instruction[j][1];if(registers[reg]==undefined)registers[reg]=0;if(offset<0&&registers[reg]<-offset){perform_instr=false;break}}if(perform_instr){for(var j=0;j<instruction.length;++j){var reg=instruction[j][0];var offset=instruction[j][1];registers[reg]+=offset}program_complete=false;break}}if(program_complete){document.getElementById("output").value+=regs_to_string(registers);stop();return}iterations++;if(timeout&&Date.now()-start_time>TIMEOUT_MILLISECS){error(ERROR_TIMEOUT);return}}setTimeout(function(){fractran_iter(ITERS_PER_SEC*(Date.now()-iter_start_time)/1E3)},0)};
<div style="font-size:12px;font-family:Verdana, Geneva, sans-serif;"><div style="float:left; width:50%;">Code:<br><textarea id="code" rows="4" style="overflow:scroll;overflow-x:hidden;width:90%;">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</textarea><br>Input:<br><textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden;width:90%;">2^142857 * 5</textarea><p>Timeout:<input id="timeout" type="checkbox" checked="true"></input></p></div><div style="float:left; width:50%;">Output:<br><textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea><p><input id="run" type="button" value="Run" onclick="run()"></input><input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="true"></input><input id="clear" type="button" value="Clear" onclick="clear_output()"></input>&nbsp;<span id="stderr" style="color:red"></span></p></div></div>

Replace 142857 with another number. Output should be 3^1 if true, 1 = 3^0 if false. Takes a while for larger numbers (well, this is FRACTRAN...).

Sp3000

Posted 2014-05-21T19:20:18.720

Reputation: 58 729

6

JavaScript - 23 Characters

As a function (ECMAScript 6):

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

Or taking input from a prompt (25 characters)

!/(.).*\1/.test(prompt())

MT0

Posted 2014-05-21T19:20:18.720

Reputation: 3 373

6

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

Num Lock

Posted 2014-05-21T19:20:18.720

Reputation: 211

Use C# 6 and you can use: bool f(int i)=>(i+"").Distinct().SequenceEqual(i+""); (53 bytes) – Stephan Schinkel – 2015-12-02T11:23:21.943

Some people claim you must count the characters in using System.Linq; as well. – Jeppe Stig Nielsen – 2017-11-03T21:30:10.013

@JeppeStigNielsen Some, yes. Common practice on CG.SE seems to be that usings can be omitted. – Num Lock – 2017-12-04T11:53:17.747

1Some options: i => (i + "").Distinct().SequenceEqual(i + ""); – NPSF3000 – 2014-05-22T10:14:47.717

@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 – 2014-05-22T10:46:28.283

A more literal interpretation of "nonnegative integer" suggests that a signed integer will be passed in, but it will never be negative. – Shaz – 2014-05-22T14:49:37.727

Well, I guess it will be ok then ... – Num Lock – 2014-05-23T04:46:58.880

5

Mathematica, 35 25 characters

(27 if the function needs a name.)

Unequal@@IntegerDigits@#&

EDIT: Saved 8 characters thanks to belisarius!

Martin Ender

Posted 2014-05-21T19:20:18.720

Reputation: 184 808

Unequal @@ IntegerDigits@# & could do, I think – Dr. belisarius – 2014-05-21T21:23:34.173

@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 Ender – 2014-05-21T22:20:17.010

You don't have to give it a name, right? Unequal@@IntegerDigits@#& is 25 characters. – akater – 2014-05-23T21:39:19.413

@Akater true, I can't see a requirement for the name in the challenge. Thanks! – Martin Ender – 2014-05-23T21:44:07.650

5

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/}

John Feminella

Posted 2014-05-21T19:20:18.720

Reputation: 151

5

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;}

DreamWarrior

Posted 2014-05-21T19:20:18.720

Reputation: 571

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 – 2014-05-22T23:08:55.137

5

R, 53 51 48 34 Bytes

function(n)!grepl("(.).*\\1",n,,T)

Try it online!

Convert to a string and split. Convert to a table of counts minus 1, sum and negate

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

MickyT

Posted 2014-05-21T19:20:18.720

Reputation: 11 735

You can also convert to string using paste0 instead of toString and save 2 characters. – plannapus – 2014-12-24T17:11:46.363

You can use paste instead of paste0 to save one more character. – Gregor Thomas – 2017-11-02T18:57:30.653

45 bytes using utf8ToInt – digEmAll – 2018-09-04T13:35:34.110

@J.Doe: even better ! :) – digEmAll – 2018-09-04T14:44:28.307

Used a different approach. 35 bytes with regex.

– J.Doe – 2018-09-04T15:36:03.140

4

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.

ɐɔıʇǝɥʇuʎs

Posted 2014-05-21T19:20:18.720

Reputation: 4 449

HI, I found and posted a shorter J solution: -:~.&.": – Galen Ivanov – 2017-11-02T17:25:24.120

For a function you can do (-:~.)@":. – marinus – 2014-05-21T20:22:04.560

@marinus Oh wow, that's even shorter than I thought. Thanks! – ɐɔıʇǝɥʇuʎs – 2014-05-21T20:24:11.647

4

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)

djhurio

Posted 2014-05-21T19:20:18.720

Reputation: 1 113

@plannapus, you are right. I got confused about "base 10 representation". – djhurio – 2014-05-22T11:33:10.730

1Using table and comparing against 0 instead of duplicated might save some characters – Dason – 2014-05-22T21:26:55.527

1And 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 – 2014-05-22T21:29:14.540

1And 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 – 2014-05-23T08:38:44.733

3

Erik the Outgolfer

Posted 2014-05-21T19:20:18.720

Reputation: 38 134

3

Mathematica (20 19)

(22 21 if function needs a name)

Max@DigitCount@#<2&

or

Max@DigitCount@#|1&

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

branislav

Posted 2014-05-21T19:20:18.720

Reputation: 51

Nice. I forgot DigitCount existed, and wrote a solution based on conversion to strings. Yours is much better. – Michael Stern – 2014-12-25T17:24:56.840

2

Haskell, 34 bytes

import Data.List
((==)=<<nub).show

Try it online!

ovs

Posted 2014-05-21T19:20:18.720

Reputation: 21 408

2

C99, 59 chars

a(x){int r=1,f[10]={};for(;x;x/=10)r&=!f[x%10]++;return r;}

Thomas

Posted 2014-05-21T19:20:18.720

Reputation: 579

C99 doesn't have implicit int, technically. – PatrickB – 2014-05-21T20:55:44.543

1Not 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 – 2014-05-22T07:09:56.583

2

Groovy (36 chars)

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

Tested it using:

println f(args[0].toInteger())

Will Lp

Posted 2014-05-21T19:20:18.720

Reputation: 797

'false' can be golfed via '1==0' or possibly something more clever. Good answer – Michael Easter – 2014-05-22T01:57:07.480

@MichaelEaster 0>1 is shorter. – user12205 – 2014-05-22T10:14:10.713

1@ace Yes, though !1 works too... – Michael Easter – 2014-05-22T10:16:49.130

@ace, MichaelEaster, thx for the help :-) – Will Lp – 2014-05-22T12:06:40.620

@WillP as suggested by MichaelEaster, use !1 instead. – user12205 – 2014-05-22T12:14:11.530

@ace, my mistake, thanks again, you both! – Will Lp – 2014-05-22T12:16:53.887

2

C, 58 bytes

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

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)

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

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

If you happen to have a large power of 2 handy the constant can be calculated like f&(1<<30)/7*6

Level River St

Posted 2014-05-21T19:20:18.720

Reputation: 22 049

Having external information that doesn't count towards the code byte/char count is obviously not allowed. I suggest you remove the first version (53 bytes). – 2501 – 2017-04-27T12:13:43.213

Please see my comment in the edit summary. – 2501 – 2017-04-27T12:24:34.287

I voted to reject the edit, but I agree that the counts look wrong. I make them 67 and 63 (61). – Peter Taylor – 2017-04-27T12:39:12.970

My edit was rejected by other users. Please re-evaluate it. – 2501 – 2017-04-27T13:09:36.437

@2501 Back in 2014 we were still thrashing out the rules here and cheeky answers were common. You're right my original answer wouldn't be acceptable now, so I've accepted your version of the code. I have however kept the info about how it works - this site has always been about sharing ideas and I think code should always come with an explanation (not just a score.) I see what you were trying to do but I also agree with the rejection. I'd forgotten this answer - thanks for highlighting. But it would have been better to leave a comment. See https://codegolf.meta.stackexchange.com/q/1615/15599

– Level River St – 2017-04-27T23:12:14.350

I agree. If the random generator generates more than 7 identical digits in a row it produces a false positive? – 2501 – 2017-04-27T23:41:23.397

@2501 yes, if there are eight 1's it will roll over and be indistinguishable from one 2. There's only so much info that can be stored in a single int. With larger variables you could use the constant (1<<40)/15*14 instead of (1<<30)/7*6 for up to 15 identical digits, or(1<<50)/31*30. for upto 31 identical digits. It's a fault of the question that it doesn't say what the largest input you can expect is. – Level River St – 2017-04-27T23:57:11.823

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... – user12205 – 2014-05-22T13:25:22.633

2

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

Or, as @MickyT suggested, for 63 characters:

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

plannapus

Posted 2014-05-21T19:20:18.720

Reputation: 8 610

1You could use anyDuplicated rather than sum and duplicated for 2 more – MickyT – 2014-12-21T19:54:45.333

2

Haskell:

 import Data.List

 all ((== 1) . length) . group . sort . show

Paul Johnson

Posted 2014-05-21T19:20:18.720

Reputation: 121

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 – 2014-05-30T18:07:25.793

You didnt use pl... main = interact $ show . ap (==) nub . show – kazagistar – 2014-06-15T20:26:33.253

2

Java ( 131 59 57)

57 characters:

removed ^ and $ as @n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ suggested

boolean u(int n){return !(n+"").matches(".*(.).*\\1.*");}

59 characters (works also with negative numbers!):

boolean u(int n){return !(n+"").matches("^.*(.).*\\1.*$");}

79 78 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).

boolean u(int n){for(int x=0;n>0&(x>>n%10&1)==0;n/=10)x|=1<<n%10;return n==0;}

131 characters (returns true for negative numbers):

boolean u(int n){int[] p=new int[]{2,3,5,7,11,13,17,19,32,29};double a=9001312320D;while(n>0){a/=p[n%10];n/=10;}return (long)a==a;}

with comments:

boolean unique(int n){
    int[] p=new int[]{2,3,5,7,11,13,17,19,32,29};//list of 10 first primes
    double a=9001312320D;//10 first primes multiplied
    while(n>0){
        a/=p[n%10];//divide by (n%10+1)th prime
        n/=10;//divide n by 10, next digit
    }
    return (long)a==a;//if a is integer then n has all digits unique
}

And answer that is technically correct (character count includes only the function, not global variables), but I think it's cheating, 29 characters:

boolean u(int i){return m[i];}

m[] is boolean array that contains correct answers for all 32-bit integers.

barteks2x

Posted 2014-05-21T19:20:18.720

Reputation: 281

I know it's been three years, but if you remove the space between return! in the shortest answer, you can get to 56 bytes. – Kevin Cruijssen – 2017-11-03T14:20:39.517

"^.*(.).*\\1.*$" You can drop ^ and $. They are implied by matches() – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-06-15T13:34:12.303

The 2nd approach can be done by using 10 bits in an int as a boolean array, which will eliminate the need for the prime table. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2014-06-15T13:39:15.933

2

J (8)

Competely sepertae from my previous answer.

*/@~:@":

ɐɔıʇǝɥʇuʎs

Posted 2014-05-21T19:20:18.720

Reputation: 4 449

1

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!

Galen Ivanov

Posted 2014-05-21T19:20:18.720

Reputation: 13 815

1

PARI/GP, 26 bytes

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

Try it online!

Jeppe Stig Nielsen

Posted 2014-05-21T19:20:18.720

Reputation: 602

1

Perl 6, 12 bytes

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

Try it online!

Phil H

Posted 2014-05-21T19:20:18.720

Reputation: 1 376

1

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.

user12205

Posted 2014-05-21T19:20:18.720

Reputation: 8 752

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. – Konrad Borowski – 2014-05-22T13:11:09.647

@xfix I assume main() is ok then? – user12205 – 2014-05-22T13:22:06.700

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). – Konrad Borowski – 2014-05-22T13:22:32.947

1

Javascript 73 chars

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

pllee

Posted 2014-05-21T19:20:18.720

Reputation: 151

1

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.

Justin

Posted 2014-05-21T19:20:18.720

Reputation: 19 757

1

PowerShell - 26

!($args|sls '(.)(?=.*\1)')

Rynant

Posted 2014-05-21T19:20:18.720

Reputation: 2 353

1

Perl 6 (19 bytes)

{.comb.uniq==.comb}

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

Konrad Borowski

Posted 2014-05-21T19:20:18.720

Reputation: 11 185

1

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.

Thor

Posted 2014-05-21T19:20:18.720

Reputation: 2 526

f()(! [ \fold -1<<<$1|sort|uniq -d` ])` down to 38 by my count – Digital Trauma – 2014-05-29T23:39:32.713

@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 – 2014-05-30T19:40:21.200

Ah I was using bash. So I guess its longer if you want POSIX conformance. – Digital Trauma – 2014-05-30T19:42:37.063

1

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

JamJar00

Posted 2014-05-21T19:20:18.720

Reputation: 209

return True can be shortened to something like 0<1. And f.append(i) can be shortened to f+=[i]. – ProgramFOX – 2014-12-21T15:40:19.617

You're welcome! Also, you can save one more character by dropping the ; after f+=[i]. It is not necessary there. – ProgramFOX – 2014-12-21T19:03:52.880

Ugh... Too much php :) – JamJar00 – 2014-12-21T19:04:18.533

1

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.

Caridorc

Posted 2014-05-21T19:20:18.720

Reputation: 2 254

1

Burlesque, 2 bytes

Using the Unique built-in:

blsq ) 17308459U_
1
blsq ) 48778584U_
0

mroman

Posted 2014-05-21T19:20:18.720

Reputation: 1 382

1

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)}

cat

Posted 2014-05-21T19:20:18.720

Reputation: 4 989

This is post 65536 on the site! That's 2^16. – wizzwizz4 – 2016-01-11T21:11:48.390

0

05AB1E, 2 bytes

ÙQ

Try it online!

-1 thanks to Kaldo


{   # Sort.
 ¥  # Consecutive differences.
  P # Product.

Works on negatives, though OP never specified...

Magic Octopus Urn

Posted 2014-05-21T19:20:18.720

Reputation: 19 422

ÙQ for 2 bytes. – Kaldo – 2018-04-05T15:25:08.903

0

Add++, 7 bytes

L,BDdq=

Try it online!

caird coinheringaahing

Posted 2014-05-21T19:20:18.720

Reputation: 13 702

0

Japt, 5 3 bytes

¶ìâ

Try it here

Shaggy

Posted 2014-05-21T19:20:18.720

Reputation: 24 623

0

Python 3, 29 bytes

lambda x:10**len({*str(x)})>x

Inspired on this answer in Python 2; for Python 3 to only lag behind 2 by one byte is pretty rare :)

ArBo

Posted 2014-05-21T19:20:18.720

Reputation: 1 416

0

C# (Visual C# Interactive Compiler), 28 bytes

i=>(i+"").ToDictionary(c=>c)

Try it online!

This lambda uses presence or absence of an exception to determine whether a number has unique digits. If a digit occurs more than once, a duplicate key exception will be thrown when converting the string to a dictionary.

dana

Posted 2014-05-21T19:20:18.720

Reputation: 2 541

0

Braingolf, 12 bytes

dlMulMve1:0|

Try it online!

Explanation

dlMulMve1:0|  Implicit input from args

d             Split into digits
 lM           Push length of stack to next stack
   u          Keep only first occurrence of each unique digit
    lM        Push length of stack to next stack
      v       Switch to next stack
       e      If top 2 items are equal
        1      - Push 1
         :    Else
          0    - Push 0
           |  EndIf

              Implicit output of top of stack

Skidsdev

Posted 2014-05-21T19:20:18.720

Reputation: 9 656

0

8086 machine code, 9 bytes

51 AC 8B FE F2 AE 59 E0 F7

Unassembled listing:

    DU  MACRO
    SEARCH: 
51      PUSH CX             ; save loop counter 
AC      LODSB               ; load next digit from SI into AL, advance SI 
8B FE   MOV  DI, SI         ; DI is offset of next digit 
F2/ AE  REPNZ SCASB         ; search until match, ZF=1 if found 
59      POP  CX             ; restore loop counter 
E0 F7   LOOPNZ SEARCH       ; loop until match found or CX is 0
        ENDM

Implemented as a MACRO (most similar to function). Input is SI, length in CX. Output is ZF=0 if unique, ZF=1 if not unique. Also returned in CX is position from lowest order digit where first duplicate was found and SI the duplicated digit.

Below is a test program in IBM PC DOS that reads input from command line args, displays T or F:

enter image description here

Download and test DU.COM.

640KB

Posted 2014-05-21T19:20:18.720

Reputation: 7 149

0

JavaScript, 22 bytes

s=>!s[new Set(s).size]

Try it online

Shaggy

Posted 2014-05-21T19:20:18.720

Reputation: 24 623

0

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;
}

bacchusbeale

Posted 2014-05-21T19:20:18.720

Reputation: 1 235

0

C# 72 characters

var a=i.ToString().ToCharArray();
return a.Distinct().Count()==a.Count();

Paul Richards

Posted 2014-05-21T19:20:18.720

Reputation: 101

".ToCharArray()" is unnecessary since there's String.Distinct.

– Helix Quar – 2014-05-22T01:37:55.833

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 – 2014-05-22T07:13:24.087

you could also do i+"" instead of i.ToString(). But this question is asking for a function, you just gave 2 lines of code – jzm – 2014-05-26T00:25:29.020

0

Julia, 44

f(n)=(d=digits(n);length(Set(d))==length(d))

gggg

Posted 2014-05-21T19:20:18.720

Reputation: 1 715

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 – 2014-05-22T16:11:16.057

e>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 – 2014-05-22T16:27:54.193

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 – 2014-05-22T16:36:18.187

0

k4 (8)

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

inspired by a combination of the J and Golfscript answers

Aaron Davies

Posted 2014-05-21T19:20:18.720

Reputation: 881

0

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.

Οurous

Posted 2014-05-21T19:20:18.720

Reputation: 7 916

0

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

Thorbjørn Ravn Andersen

Posted 2014-05-21T19:20:18.720

Reputation: 95

0

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.

kuldeep.kamboj

Posted 2014-05-21T19:20:18.720

Reputation: 625

<?=max(count_chars($argn))<2); 30+1 bytes: run as pipe with -F, prints 1 for true, nothing for false – Titus – 2017-11-02T20:58:27.837

You could cut out a few chars by doing <2 instead of the ternary operator – scrblnrd3 – 2014-05-23T19:49:09.067

<2 in PHP, DO you have some reference page, how it used in php as I never seen this. – kuldeep.kamboj – 2014-05-26T05:20:09.883

1I mean you could use var_dump(max(count_chars($n))<2); instead – scrblnrd3 – 2014-05-26T13:19:24.670

0

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!

mai

Posted 2014-05-21T19:20:18.720

Reputation: 191

0

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

bsd

Posted 2014-05-21T19:20:18.720

Reputation: 141

0

Julia - 29 28

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

Old version:

f(n)=join(unique("$n"))=="$n"

Glen O

Posted 2014-05-21T19:20:18.720

Reputation: 2 548

0

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);}

DLeh

Posted 2014-05-21T19:20:18.720

Reputation: 1 111

0

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!!!

ClickRick

Posted 2014-05-21T19:20:18.720

Reputation: 245

0

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

Sylwester

Posted 2014-05-21T19:20:18.720

Reputation: 3 678

0

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

Alex

Posted 2014-05-21T19:20:18.720

Reputation: 369

0

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

Alchymist

Posted 2014-05-21T19:20:18.720

Reputation: 544

1Welcome 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. – David Wilkins – 2014-05-23T17:24:00.073

1@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. – Alchymist – 2014-05-27T07:40:49.703

Also, if I knew golfscript, for example, I would have written a function returning true in that rather than describing an unspecified "scripting language" – Alchymist – 2014-05-27T07:59:16.843

0

PHP 74 Chars

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

Sammitch

Posted 2014-05-21T19:20:18.720

Reputation: 509

0

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.

Lou

Posted 2014-05-21T19:20:18.720

Reputation: 105

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) – user12205 – 2014-05-24T15:17:53.280

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. – user12205 – 2014-05-24T15:22:37.393

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? – Lou – 2014-05-24T15:23:07.603

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. – Lou – 2014-05-24T15:24:45.713

Also, how do I count bytes in code? Sorry, I looked in Meta and the Help Centre but I couldn't find an answer. – Lou – 2014-05-24T15:27:39.403

Online tools should be sufficient, and this seems to be giving a correct count. As for automatic spacing and indentation, Visual Studio should have some settings that allows you to turn it off (see here). Line returns and tabs all count as one each.

– user12205 – 2014-05-24T15:32:50.533

Thank you for the character counter link, though the tool calculates 219 characters for the current code, which is off your initial count. Do line returns and tabs make up one byte, or character? – Lou – 2014-05-24T15:34:35.143

@Ace, what did you use to highlight the syntax? – Lou – 2014-05-25T09:47:27.413

Click on "edit" to see what I've done. – user12205 – 2014-05-25T09:52:04.447

0

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))))

user100464

Posted 2014-05-21T19:20:18.720

Reputation: 101

0

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)

DCKing

Posted 2014-05-21T19:20:18.720

Reputation: 101

0

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.

Zaphod65

Posted 2014-05-21T19:20:18.720

Reputation: 31

I don't think you're required to count the last newline. – seequ – 2014-06-03T17:42:03.473

0

F# - 82

let f i =
    let s = i.ToString() 
    s |> Set.ofSeq|> Seq.length = s.Length;;

Alexan

Posted 2014-05-21T19:20:18.720

Reputation: 101

0

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;}

bebe

Posted 2014-05-21T19:20:18.720

Reputation: 3 916

0

Regular Expression 17 bytes

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

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

hetzi

Posted 2014-05-21T19:20:18.720

Reputation: 131

0

Clojure, 23

#(=(distinct x)(seq x))

Usage: (#(=(distinct x)(seq x)) "23563462464543")

user20637

Posted 2014-05-21T19:20:18.720

Reputation:

0

Candy, 13 bytes

This is a late post, but...

(k&{1k1.|0})0

Invokation with -I , which is actually for string parameters.

The long form:

while    # while we are still consuming characters from the stack
  setSP  # pop the next stack-id from the stack.  It's the ord of the digit
  stackSz  # test for empty stack
  if
    digit1 setSP  # goto stack #1, and push the true indicator on
    digit1
    retSub        # and halt
  else
    digit0    # mark the stack as having been visited
  endif
endwhile
digit0    # push the false indicator if we got this far

Dale Johnson

Posted 2014-05-21T19:20:18.720

Reputation: 509

0

Prolog, 49 bytes

Code:

p(N):-number_codes(N,L),sort(L,S),msort(L,T),S=T.

Explained:

p(N):-number_codes(N,L), % Convert int to list (of charcodes)
      sort(L,S),         % Sort list and remove duplicates
      msort(L,T),        % Sort list and keep duplicates
      S=T.               % Check if lists are equal

Example:

p(48778584).
false

p(17308459).
true

Emigna

Posted 2014-05-21T19:20:18.720

Reputation: 50 798