Визначте, чи всі десяткові цифри унікальні


37

Видалені питання щодо переповнення стека іноді створюють чудові матеріали для гольфу.

Напишіть функцію, яка приймає як вхідне невід’ємне ціле число, і повертає істину, якщо всі цифри в базовій частині 10 представлення цього числа є унікальними. Приклад:

48778584 -> false
17308459 -> true

Кількість символів включає лише функцію.

Якщо ви вирішите відповісти на С або С ++: немає макросів, не визначеної поведінки; Поведінка, визначена реалізацією та попередження компілятора, чудово.


Мені все ще цікавляться інші рішення C або C ++ відповідно до питання, яке надихнуло це.
— Томас

1
Чому немає макросів C або C ++ або невизначеної поведінки? Це дивно обмежує лише дві мови.
— dfeuer

Відповіді:


31

Гольфскрипт, 8 7 символів:

{`..&=}
  • ` - строфізуйте аргумент
  • .. - клонують двічі
  • & - перетинатися з собою (видалити дублікати)
  • = - перевірка рівності.

якщо функцію потрібно назвати (109 символів ):

{`..&=}:a

якщо програми достатньо (54 символи ):

..&=

5
Важкою частиною подібних проблем є вперше це побачити.
— примо

1
@primo все ще, якось, вони все-таки отримують +6 балів протягом пів дня.
— Джон Дворак

1
@JanDvorak Паркінсона закон тривіальності на роботі
— Клавдіу

2
@Claudiu Ви можете зрозуміти закон. Зрозумійте, що вам це піддають. Тоді будь-ласка підтвердіть відповідь.
— Cruncher

1
@NathanChere що ти маєш на увазі? в останній (і єдиний) раз, коли лазівку запропонували, вона знизилася до -3, перш ніж видалити пропозиціонер наступного ранку. Якщо вам не подобаються відповіді на гольфскрипт, не підтримуйте їх.
— Джон Дворак

24

Пітон 2 (28) (32)

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

На задній панелі приймаються рядкові подання. Перетворення в набір видаляє дублікати, і ми перевіряємо, чи зменшується це довжина порівняно з 10 ^ d, що більше, ніж усі d-розрядні числа, але не (d + 1) -значні числа.

Старий код:

lambda n:len(set(`n`))==len(`n`)


1
Ha У мене була готова ця точно така ж відповідь, просто замініть nнаi
— Клавдіу

1
@Claudiu так само зробив і яf=lambda _:len(`_`)==len(set(`_`))
— Оберон

Так, з цими проблемами розміру укусу всі збираються майже однакове. Я також намагався lambda n:max(map('n'.count,'n'))<2(одиничні цитати - це зворотній зв'язок), але це на дві символи довше.
— xnor

16

APL (6)

≡∘∪⍨∘⍕

Один з небагатьох випадків, коли мовчазний стиль коротший і в APL.

Це 8 символів, щоб дати йому ім'я,

f←≡∘∪⍨∘⍕

але використовувати це не обов’язково:

      ≡∘∪⍨∘⍕ 199
0
      ≡∘∪⍨∘⍕ 198
1
      f←≡∘∪⍨∘⍕
      f¨ 198 199 200 201
1 0 0 1
      ≡∘∪⍨∘⍕¨ 198 199 200 201
1 0 0 1

1
Я думаю, другий джот можна видалити, щоб зробити його 5. Він все одно буде дійсною функцією сама по собі (хоча для останнього прикладу потрібно буде згрупувати паролі для використання кожного оператора).
— user46915

11

Perl, 19 символів

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

якщо припустити, що вихід може трактуватися як істинний, а невідповідний не можна вважати помилковим, ваша логіка зворотна. Вам слід повернути істину, якщо повторення немає.
— Джон Дворак

@JanDvorak Звучить правильно. Я це виправлю.
— Тал

Оператор Not-матч: <>!~/(\d).*\1/.
— примо

@primo Дякую! Так багато, щоб дізнатися :)
— Тал

3
Вхід вказано як невід'ємне ціле число, тому я не думаю, що вам потрібно це перевірити. Якщо ви насправді цього не зробите, ви можете перейти \dна ..
— hvd

9

Rebmμ (10 символів)

e? AtsAuqA

Трюк Ребму "придуркою" полягає в тому, що він нечутливий до регістру, тому персонажі працюють разом. Щоразу, коли буде натиснутий перехід випадку, він переходить на наступний маркер. Використовуючи переходи замість речі CamelCase, унікальний вибір для початку з великої літери означає "задане слово". (Хоча набір слів може використовуватися для інших цілей у символічному програмуванні, вони оцінюються як завдання за замовчуванням).

Тож це "роздуття":

e? a: ts a uq a

Простір потрібен, оскільки після того, як ви розпочали серію запусків змінних випадків, ви не зможете скористатися цим трюком, щоб отримати слово-набір після першого, якщо ви не почнете новий запуск. Отож, e?AtsAuqAби тебе дісталиe? a ts a uq a ... жодного завдання.

(Примітка. Для того, що може бути не особливо вагомою причиною, я схильний віддавати перевагу переосмисленню рішень, щоб не було пробілів, якщо кількість символів однакова. Оскільки дужки, дужки та рядки неявно закінчуються символом ... часто є справедливі кількість можливостей для цього.)

У будь-якому випадку, коли вони відображаються на Rebol, він скорочує:

equal? a: to-string a unique a

Введення в круглі дужки, щоб отримати суть порядку замовлення:

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

Тож оператор рівності префікса застосовується до двох аргументів - перший результат присвоєння a самій рядковій версії, а другий результатunique запуску проти цього рядка. Так буває, що унікальний поверне вам елементи в тому ж порядку, коли ви їх передали ... так унікальним для "31214" є "3124", наприклад.

Запустити його:

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

Також є інформація про статистику та налагодження:

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

Якщо вимога полягає в тому, що потрібно визначити функцію з назвою / багаторазовим використанням, ви можете зробити "A-функцію", яка неявно приймає параметр з ім'ям a a|. (B-функція була б створена за допомогою b|та приймає параметр з назвою A, а потім - ім'ям B). Отже, це додало б ще п’ять символів ... скажімо, ви називаєте функцію "f"

Fa|[e? AtsAugA]

"Ви смієтесь! Вони сміялися з Ейнштейна! Або чекали ... чи не так? Я ... не знаю".


Раніше я думав , мова була оголошена як Reb moo, але тепер я не впевнений , що це повинно бути Rebum mewабо Reb mewабо що - то інше.
— Джастін

2
Після гри в Nethack я прочитав Fa|[e? AtsAugA]якFalse? SomeGibberish
— Джастін

@Quincunx sдійсно занепадає [в Nethack?
— Джон Дворак

@JanDvorak Я бачив, як деякі листи занепадають [через деякий час
— Джастін,

@Quincunx Просто граючи з логотипом. Я думаю, REBmuце, мабуть, краще. Так чи інакше, борода туга .. вона щипає. Здогадайтесь, ви отримаєте те, за що платите.
— Доктор Ребму

7

FRACTRAN - 53 38 фракцій

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

Використовує поділ для підрахунку кількості подій кожної цифри. Виклик, поклавши n у регістр 2 та встановивши регістр 5 на 1, дає вихід у регістр 3 (0, якщо помилковий, 1 якщо істинний). Також переконайтесь, що решта програми використовує лише регістри> 71.


Edit 25/12/14: Це було 7 місяців , і ми з тих пір отримав Stack Snippets, так ось один для перевірки коду ( з допомогою мого може-бути краще перекладача тут ).

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


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

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


1
Some options: i => (i + "").Distinct().SequenceEqual(i + "");
— NPSF3000

@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

A more literal interpretation of "nonnegative integer" suggests that a signed integer will be passed in, but it will never be negative.
— Shaz

Well, I guess it will be ok then ...
— Num Lock

Use C# 6 and you can use: bool f(int i)=>(i+"").Distinct().SequenceEqual(i+""); (53 bytes)
— Stephan Schinkel

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

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

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

5

Mathematica, 35 25 characters

(27 if the function needs a name.)

Unequal@@IntegerDigits@#&

EDIT: Saved 8 characters thanks to belisarius!


Unequal @@ IntegerDigits@# & could do, I think
— Dr. belisarius

@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

You don't have to give it a name, right? Unequal@@IntegerDigits@#& is 25 characters.
— akater

@Akater true, I can't see a requirement for the name in the challenge. Thanks!
— Martin Ender

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.


You can also convert to string using paste0 instead of toString and save 2 characters.
— plannapus

You can use paste instead of paste0 to save one more character.
— Gregor


@J.Doe: even better ! :)
— digEmAll

Used a different approach. 35 bytes with regex.
— J.Doe

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.


For a function you can do (-:~.)@":.
— marinus

@marinus Oh wow, that's even shorter than I thought. Thanks!
— ɐɔıʇǝɥʇuʎs

HI, I found and posted a shorter J solution: -:~.&.":
— Galen Ivanov

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)

@plannapus, you are right. I got confused about "base 10 representation".
— djhurio

1
Using table and comparing against 0 instead of duplicated might save some characters
— Dason

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

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

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]


Nice. I forgot DigitCount existed, and wrote a solution based on conversion to strings. Yours is much better.
— Michael Stern


2

C99, 59 chars

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

C99 doesn't have implicit int, technically.
— PatrickB

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


2

Haskell:

 import Data.List

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

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

You didnt use pl... main = interact $ show . ap (==) nub . show
— kazagistar


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

1
You could use anyDuplicated rather than sum and duplicated for 2 more
— MickyT

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


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...
— pastebin.com slash 0mr8spkT

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

Please see my comment in the edit summary.
— 2501

I voted to reject the edit, but I agree that the counts look wrong. I make them 67 and 63 (61).
— Peter Taylor

My edit was rejected by other users. Please re-evaluate it.
— 2501


1

Javascript 73 chars

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

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.



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.


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.


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

@xfix I assume main() is ok then?
— pastebin.com slash 0mr8spkT

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

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.


f()(! [ `fold -1<<<$1|sort|uniq -d` ]) down to 38 by my count
— Digital Trauma

@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

Ah I was using bash. So I guess its longer if you want POSIX conformance.
— Digital Trauma

1

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.


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

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̷̰̀ĥ̷̳

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
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.