# Question
Title: Determine if all decimal digits are unique
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.

# Answer
## 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**):

```
..&=

```
> 31 votes

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

```
> 26 votes

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

```
> 17 votes

# Answer
# Perl, 19 characters

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

```
> 11 votes

# Answer
### 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."*
> 9 votes

# Answer
# 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)};
```

```

Code:
<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>
Input:
<textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden;width:90%;">2^142857 * 5</textarea>
Timeout:<input id="timeout" type="checkbox" checked="true"></input>

Output:
<textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea>
<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>

```

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

# Answer
# 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 votes

# Answer
# 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 ...
> 6 votes

# Answer
# Trilangle, 34 bytes

UB is only disallowed in C, huh?

```
'0.<".@|>i\re@..j..2'2#!>.(&,\,<.-

```

This works on x64, at least. Can't guarantee it'll work on other architectures.

Expects the number on STDIN, immediately followed by EOF (no trailing newline). Prints "0" (with trailing newline) iff the digits are unique.

Edit: there is now an online interpreter. This code seems to work in wasm, too (but I still haven’t tested native ARM or other processors).

## High-level Overview

Roughly equivalent to this C code:

```
#include <stdio.h>

int main() {
    // A bitfield of the seen numbers:
    // e.g. if "12" is input, this is 0b0000'0000'0000'0110;
    // if "3" is input, this is 0b0000'0000'0000'1000; etc.
    int seen = 0;

    while (1) {
        // Get a number in. If EOF is read,
        // we haven't encountered a duplicate, so indicate success.
        int i = getchar();
        if (i == EOF) {
            puts("0");
            break;
        }

        // Check if the digit has already been seen.
        // If so, exit without printing anything.
        // If not, add this digit to the bitfield.
        i = 1 << (i - '0');
        if (i & seen) break;
        seen = seen | i;
    }
}

```

## How does Trilangle work?

Trilangle is a 2-D programming language laid out in a triangular grid (hence the name). The IP can move in one of six directions; it starts heading southwest. If it walks off the edge of the grid, it continues one row or diagonal to its left.

The memory model is like a stack, but it's possible to index into it.

## Explanation of the Code

The interpreter unfolds that code into this triangular grid:

```
       '
      0 .
     < " .
    @ | > i
   \ r e @ .
  . j . . 2 '
 2 # ! > . ( &
, \ , < . - . .

```

I hope this explanation makes any sense. Here goes nothing.

Below is an image of the code, with the IP's paths highlighted in various colors.

The IP starts on the red path, where it hits the following instructions:

* `'0`: Push the number 0 to the stack
* `<`: Change the direction of control flow
* `i`: Get a character from STDIN and push it to the stack; pushes -1 on EOF
* `>`: Branch on the sign of the top of the stack

If the value is negative, EOF was read, and the IP continues on the green path:

* `e`: Pop from the stack, and push `1 << value`. This is the UB: `1 << -1` is undefined. At least on x64, it evaluates to 0.
* `.`: No-op
* `!`: Print the top of the stack as a decimal integer
* `,`: Pop from the stack
* `i`: Attempt to read from STDIN again (always sees EOF on this path)
* `@`: End program

The `,i` aren't strictly necessary on this code path, but they're harmless to leave in.

If a character was successfully read, control flow continues on the blue path:

* `"0`: Push the value of the character '0' (i.e. 48) to the stack
* `-`: Pop two values from the stack and push their difference
* `..`: No-ops
* `e`: Pop from the stack and push `1 << value`
* `|`: Redirect control flow
* `".,`: Push the value of the character '.' and immediately pop it, effectively a no-op
* `2`: Duplicate the top of the stack
* `.`: Another no-op
* `\`: Redirect control flow
* `'2`: Push the number 2 to the stack
* `..`: Even more no-ops
* `j`: The indexing function. After this, the stack contains `{ seen, i, i, seen }` (from the C code above), in that order.
* `.`: Yet another no-op
* `&`: Pop two values from the stack and push `a & b` (bitwise and)
* `(`: Decrement the top of the stack. If `seen & i` is 0, the top of the stack is now negative; otherwise, it's still positive
* `.`: Yep, still a no-op
* `>`: Branch

If `i` and `seen` have any bits in common, the IP follows the yellow path; otherwise, the IP follows the magenta path.

The yellow path contains a harmless `r` (bitwise or) instruction, before the IP hits `@` and the program ends.

On the magenta path, the IP continues as follows:

* `<`: Redirect control flow
* `,`: Pop from the stack
* `\`: Redirect control flow
* `#`: Ignore the next instruction (`j`)
* `r`: Pop two values from the stack and push `a | b` (bitwise or)
* `|`: Redirect control flow
* `<`: Redirect control flow, merging with the red path

From which it reads the next character from STDIN, and continues until it either reads the same character twice or reads EOF.

## Disassembly

I recently added a `--disassemble` flag to the interpreter. The output is fairly straightforward if you understand the syntax:

```
0.0:    PSI #0
0.2:    GTC
0.3:    BNG 2.0
1.0:    PSC '0' ; 0x30
1.1:    SUB
1.4:    EXP
1.6:    PSC '.' ; 0x2e
1.7:    POP
1.8:    DUP
1.11:   PSI #2
1.14:   IDX
1.16:   AND
1.17:   DEC
1.19:   BNG 4.0
        JMP 3.0
2.0:    EXP
2.2:    PTI
2.3:    POP
2.4:    GTC
2.5:    EXT
3.1:    IOR
3.2:    EXT
4.1:    POP
4.4:    IOR
4.7:    JMP 0.2

```
> 6 votes

# Answer
## Mathematica, ~~35~~ 25 characters

(27 if the function needs a name.)

```
Unequal@@IntegerDigits@#&

```

**EDIT:** Saved 8 characters thanks to belisarius!
> 5 votes

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

```
> 5 votes

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

```
> 5 votes

# Answer
## 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.
> 5 votes

# Answer
# 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.
> 4 votes

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

```
> 4 votes

# Answer
# FRACTRAN, 15 fractions, 83 (or 32) bytes

This beats Sp3000's 38-fraction solution.

$$\frac25,\frac{875}{88},\frac78,\frac{25{\cdot}17^c}{92},\frac14,\frac{15}{38},\frac{69}{2},\frac{23}{17},\frac{19}{3^b},\frac43,\frac{7}{23},\frac{26}{19},\frac{11}{7^c},\frac{1}{91},\frac{8}{11}$$

The initial state is \\$3^n\cdot 13\cdot 23\\$. It halts at \\$1\\$ if every digit in the base-\\$b\\$ representation of \\$n\\$ occurs fewer than \\$c\\$ times, and at some other value otherwise. Plug in \\$b=10, c=2\\$ to get the answer to the challenge as posed.

The final state is actually \\$13^{k - \mathrm{wt}\_c\left(\sum c^{d\_i}\right)}\\$, where \\$d\_1\cdots d\_k\\$ are the base-\\$b\\$ digits of \\$n\\$, and \\$\mathrm{wt}\_c\\$ is the base-\\$c\\$ digit sum. Adding a power of \\$c\\$ increases the digit sum by \\$1\\$ if there is no carry, and doesn't increase it if there is a carry, so the final state is \\$1\\$ iff each digit occurs fewer than \\$c\\$ times.

The length of the \\$b=10, c=2\\$ version is 83 bytes in the decimal coding (`2/5,875/88,`...) that seems to be standard here. With a more efficient coding (Elias δ), it's 32 bytes.

There's a fast online interpreter here. I see no way to encode a program in the URL, so you'll have to copy-paste this:

```
2%5 875%88 7%8 25*17^2%92 1%4 15%38 69%2 23%17 19%3^10 4%3 7%23 26%19 11%7^2 1%91 8%11

```

Then enter, e.g., `[3,48778584],[13,1],[23,1]` as the input.
> 4 votes

# Answer
# Mathematica (~~20~~ 19)

(~~22~~ 21 if function needs a name)

```
Max@DigitCount@#<2&

```

or

```
Max@DigitCount@#|1&

```

where | ist entered as \[Esc\]divides\[Esc\]
> 3 votes

# Answer
# Haskell, 34 bytes

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

```

Try it online!
> 3 votes

# Answer
# Brachylog, 1 byte

Try it online!
> 3 votes

# Answer
# JavaScript, 22 bytes

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

```

Try it online
> 3 votes

# Answer
# C99, 59 chars

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

```
> 2 votes

# Answer
## Groovy (36 chars)

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

```

Tested it using:

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

```
> 2 votes

# Answer
# 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`
> 2 votes

# 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

```

Or, as @MickyT suggested, for 63 characters:

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

```
> 2 votes

# Answer
## 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 .`<sup><sup><sub>1</sub></sup></sup> \- 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

```

---

<sup><sup><sub>1</sub></sup></sup> <sub><sup>The `fold -N` notation is deprecated in some versions of `fold`.</sup></sub>
> 2 votes

# Answer
**Haskell:**

```
 import Data.List

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

```
> 2 votes

# Answer
# Java ( ~~131~~ ~~59~~ 57)

## 57 characters:

removed ^ and $ as @n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ 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̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ ):

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

# Answer
# J (8)

Competely sepertae from my previous answer.

```
*/@~:@":

```
> 2 votes

# Answer
# , 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!
> 2 votes

# Answer
# Add++, 7 bytes

```
L,BDdq=

```

Try it online!
> 2 votes

# Answer
# Julia, 25 bytes

the best I could come up with was the same as one of the top voted answers

```
n->10^length(Set("$n"))>n

```

Try it online!
> 2 votes

# Answer
# Vyxal , 3 bytes

```
U∑=

```

Try it Online!
> 2 votes

# Answer
# Vyxal, 2 bytes

```
Þu

```

Try it Online!
> 2 votes

# Answer
# k4 (8)

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

```

inspired by a combination of the J and Golfscript answers
> 1 votes

# 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.
> 1 votes

# Answer
**Javascript 73 chars**

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

```
> 1 votes

# 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.
> 1 votes

# Answer
## PowerShell - 26

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

```
> 1 votes

# Answer
# 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 votes

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

```
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
## Burlesque, 2 bytes

Using the Unique built-in:

```
blsq ) 17308459U_
1
blsq ) 48778584U_
0

```
> 1 votes

# Answer
# 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)}
```
> 1 votes

# Answer
# PARI/GP, 26 bytes

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

```

Try it online!
> 1 votes

# Answer
# Japt v2.0a0, ~~5~~ ~~3~~ 2 bytes

Takes input as a string.

```
¶â

```

Try it
> 1 votes

# Answer
# 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 :)
> 1 votes

# Answer
# 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.
> 1 votes

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

```
> 1 votes

# Answer
# x86-16 machine code, 11 bytes

```
FC 51 AC 8B FE F2 AE 59 E0 F7 C3

```

Listing:

```
    SEARCH:
FC      CLD                 ; string direction forward
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
C3      RET                 ; return to caller
        ENDM

```

Callable function, input as digit array at `DS:SI`, length in `CX`. Output `ZF=0` if unique, `ZF=1` if not unique.

Test program in IBM PC DOS that reads input from command line args, displays `T` or `F`:
> 1 votes

# Answer
# Perl 6, 12 bytes

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

```

Try it online!
> 1 votes

# Answer
# Jelly, 3 bytes

```
DQƑ

```

Try it online!

## How it works

```
DQƑ - Main link. Takes n on the left
D   - Convert to digits
  Ƒ - Is it unchanged under:
 Q  -   Deduplication?

```
> 1 votes

# Answer
# Husk, 4 bytes

```
S=ud

```

Try it online!

```
S           # Hook: S fgx means f x(gx)
 =          # are they equal:
            # x (implied by S)
            # and
  u         # unique elements of x
   d        # when x is the decimal digits of the input

```
> 1 votes

# Answer
# Pyth, 2 bytes

```
q{

```

Try it online!
> 1 votes

# Answer
# Zsh, ~~28~~ 24 bytes

If output is 0, the digits are unique. Otherwise, there are dupes

```
<<<$[$#1-${#${(us::)1}}]

```

Try it Online! <sub>~~28 bytes~~</sub>
> 1 votes

# Answer
# Regex (ECMAScript<sub><sup> / Perl / PCRE / Python / .NET</sup></sub>), ~~66~~ 61 bytes

```
^(?!((?=(x{10})*(x*))(^|(?=(x*)(\5{9}x*))\6)+){2}\B\2*\3$)|^$

```

Takes its input in unary, as the length of a string of `x`s.

Try it online! \- ECMAScript
Try it online! \- Perl
Try it online! \- PCRE
Try it online! \- Python
Try it online! \- .NET

This regex apparently does not work in Java, Boost, or Ruby. The reasons are unknown as of yet.

```
^                          # tail = N = input number
(?!                        # Assert that there is no way for the below to match
    (
        (?=
            (x{10})*(x*)   # \2 = 10; \3 = tail % 10
        )
        (
            ^              # Allow the loop to iterate once without doing
                           # anything iff this is the first iteration of the
                           # main loop.
        |
            (?=
                (x*)       # \5 = floor(tail / 10)
                (\5{9}x*)  # \6 = tool to make tail = \5
            )\6            # tail = \5
        )+                 # Execute the above loop an arbitrary positive
                           # number of times.
    ){2}                   # Execute the above loop exactly twice, so that \3
                           # will contain the value it had at the beginning of
                           # the loop's second iteration.

    \B                     # Assert that we aren't at the beginning or end, or
                           # that N==0; the latter "or" part is undesirable,
                           # because it prevents this main algorithm from being
                           # able to match N==0, but even still, using "(?!^|$)"
                           # would be longer than "\B" and "|^$" combined.
    # Note that if (x{10})* repeated zero times, \2 will be a non-participating
    # capture group (unset). In ECMAScript this means it will behave as if \2=0.
    # In all other flavors, it means \2* will only be able to repeat zero times,
    # because \2 alone won't match anything. But this doesn't matter, since if
    # it was only able to match zero times before, it wouldn't be able to match
    # more than zero times now, anyway.
    \2*\3$                 # Assert tail % 10 != \3
)
|^$                        # Match N==0, which the main algorithm above can't.

```

See also my decimal regex answer. I feel that this unary version is more interesting, especially since unary is like a native integer data format for regex, whereas decimal is like passing an integer as a string, but it's definitely worth presenting decimal versions as well.
> 1 votes

# Answer
See also my unary regex answer. Although other posts have already used a regex that take decimal input, this post provides a unified presentation, and outgolfs some of the previous posts (including a language in which there wasn't previously any regex post).

# Regex (ECMAScript or better), 13 bytes

```
^(?!(.)+.*\1)

```

Takes its input in decimal. Returns a match for numbers with all-unique digits.

Try it online!

# Regex (ECMAScript or better), 7 bytes

```
(.).*\1

```

Takes its input in decimal. Returns a non-match for numbers with all-unique digits.

Try it online!

### \\$\large\textit{Anonymous functions}\\$

# v3.5.2, 29 bytes

```
pryr::f(!grepl('(.).*\\1',n))

```

Try it online!

Uses the same regex as MickyT's R answer, but `,,T` is unnecessary (the regex doesn't need to run in PCRE mode) and omitting it saves 3 bytes. Using `pryr`'s lambda syntax saves another 2 bytes.

# v4.1.0+, 24 bytes

```
\(n)!grepl('(.).*\\1',n)

```

Attempt This Online!

# PHP, 35 bytes

```
fn($n)=>!preg_match('/(.).*\1/',$n)

```

Try it online!

# Java, 33 bytes

```
n->!(n+"").matches("(.)+.*\\1.*")

```

Try it online!

This uses a regex 1 byte shorter than barteks2x's answer.

# Perl, 19 bytes

```
sub{pop!~/(.).*\1/}

```

Try it online!

# Ruby, 23 bytes

```
->n{n.to_s !~/(.).*\1/}

```

Takes an integer as input. Returns a native boolean, true if the digits are unique.

Try it online!

## Ruby, 18 bytes

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

```

Takes a string as input. Returns a native boolean, true if the digits are unique.

This is identical to John Feminella's 20 byte answer except for removing the unnecessary parentheses surrounding the function parameter, saving 2 bytes.

### \\$\large\textit{Full programs}\\$

# Retina, 12 bytes

```
A`(.).*\1
^.

```

Try it online!

# PHP, 37 bytes

```
<?=!preg_match('/(.).*\1/',$argv[1]);

```

Try it online!

# Perl, 16 bytes

```
say<>!~/(.).*\1/

```

Try it online!

This uses a regex 1 byte shorter than Tal's answer. Another 2 bytes are saved by using `say` (requiring Perl v5.010+) instead of `print`.
> 1 votes

# Answer
# Arturo, ~~27~~ ~~26~~ 21 bytes

```
$=>[=unique<=digits&]

```

Try it

-1 byte from abusing Arturo's hidden stack features. \>:)

-5 bytes from using a tacit function and using the dup operator over the function.

Checks whether the list of digits of the input number is equal to itself when uniquified.
> 1 votes

# Answer
# K (ngn/k), 13 bytes

```
{(#t)=#?t:$x}

```

Try it online!

I think there's a way this one could be a train...

Explanation:

```
{(#t)=#?t:$x}  Main function. x is input
          $x   Convert x to string
        t:     Assign it to variable t
       ?       Unique
      #        Length
     =         Equal to
 (#t)          The length of t

```
> 1 votes

# Answer
# Julia 1.0, ~~23~~ 18 bytes

```
~x=allunique("$x")

```

Try it online!

-5 bytes thanks to MarcMush: replace `digits(x)` with `"$x"`
> 1 votes

# Answer
# Thunno, \\$ 6 \log\_{256}(96) \approx \\$ 4.94 bytes

```
dDZUA=

```

Attempt This Online!

#### Explanation

```
dDZUA=  # Implicit input
dD      # Cast to digits and duplicate
  ZU    # Uniquify this list
    A=  # Are they equal?
        # Implicit output

```
> 1 votes

# Answer
# Excel, 47 bytes

```
=LET(a,ROW(1:10)-1,COUNT(SEARCH(a&"*"&a,A1))=0)

```

Input in cell `A1`.
> 1 votes

# Answer
# Haskell, 32 bytes

```
(\s->s==[x|x<-s,y<-s,x==y]).show

```

Try it online!

Repeats each character once per each character that equals it, and checks that this gives the original digits string.
> 1 votes

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

```
> 0 votes

# Answer
**C# 72 characters**

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

```
> 0 votes

# Answer
# Julia, 44

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

```
> 0 votes

# 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.
> 0 votes

# Answer
## 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.
> 0 votes

# 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!
> 0 votes

# Answer
**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

```
> 0 votes

# Answer
# Julia - ~~29~~ 28

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

```

Old version:

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

```
> 0 votes

# Answer
**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);}

```
> 0 votes

# Answer
~~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!!!
> 0 votes

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

```
> 0 votes

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

```
> 0 votes

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

```
> 0 votes

# Answer
# PHP 74 Chars

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

```
> 0 votes

# Answer
## 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.
> 0 votes

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

```
> 0 votes

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

```
> 0 votes

# Answer
# 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.
> 0 votes

# Answer
**F# - 82**

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

```
> 0 votes

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

```
> 0 votes

# Answer
**Regular Expression 17 bytes**

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

```

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

# Answer
# Clojure, 23

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

```

Usage: `(#(=(distinct x)(seq x)) "23563462464543")`
> 0 votes

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

```
> 0 votes

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

```
> 0 votes

# Answer
# 05AB1E, 2 bytes

```
ÙQ

```

Try it online!

-1 thanks to Kaldo

---

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

```

---

Works on negatives, though OP never specified...
> 0 votes

# Answer
# rSNBATWPL, 45 bytes

```
n~(d=1;rdc{norm{n}sort<}$a~b~(d=d*a!b;b);d)

```

A (probably golfable) approach, which looks for duplicate characters. Instead of a costly `cast.string`, I use `norm`, which applies Unicode normalization, which is a no-op here. I use `rdc` as an expensive hack to iterate over pairs. The most important part of the solution is `d=d*a!b` (I use `d=d*...` rather than `d*=...` since `*=` requires whitespace to prevent ambiguity), which multiplies `d` (initially `1`) by `a!b`, which after being cast to an int will be `1` only if `a` and `b` aren't equal.
> 0 votes

# Answer
# Thunno 2, 2 bytes

```
U=

```

Attempt This Online!

#### Explanation

```
U=  # Implicit input
U   # Uniquify the input
 =  # Does it equal the input?
    # Implicit output

```
> 0 votes

# Answer
## Pascal, 142 bytes

This `function` requires a processor compliant with Extended Pascal, ISO standard 10206. In particular the `card` function must be available.

```
function f(x:integer):Boolean;var d:set of 0..9;w:integer;begin d:=[];w:=0;repeat d:=d+[x mod 10];x:=x div 10;w:=w+1 until x=0;f:=w=card(d)end

```

Ungolfed:

```
    type
        { This will permit a proper `function` domain restriction. }
        integerNonNegative = 0..maxInt;

    { Returns `true` if `x` as decimal number contains no duplicate digits. }
    function hasUniqueDecimalDigits(x: integerNonNegative): Boolean;
        var
            { The decimal digits that appear in `x`. }
            digits: set of 0‥9 value [];
            { The total width of a decimal representation of `x`. }
            width:  integer    value 0;
        begin
            { If there are as many distinct decimal `digits` as
              the total `width` of the decimal number,
              we can tell that no digit appears twice. }
            repeat
            begin
                digits ≔ digits + [x mod 10];
                x      ≔ x div 10;
                width  ≔ width + 1;
            end
            until x = 0;
            { `card` returns the cardinalty of a set,
              that is the number of members in a set. }
            hasUniqueDecimalDigits ≔ card(digits) = width;
        end;

```
> 0 votes

# Answer
# convey, 355 bytes

```
          1-}  1-}  1-}  1-}  1-}  1-}  1-}  1-}  1-}  1-}
>>vv<">>~>>?;~>>?;~>>?;~>>?;~>>?;~>>?;~>>?;~>>?;~>>?;~>>?;}
^ ;<1@>]3 >>!3 >>!3 >>!3 >>!3 >>!3 >>!3 >>!3 >>!3 >>!3 >>!
,{>">"   >#v0 >#v0 >#v0 >#v0 >#v0 >#v0 >#v0 >#v0 >#v0 >#v0
.10|>#>>"@^>#"@^>#"@^>#"@^>#"@^>#"@^>#"@^>#"@^>#"@^>#"@^>#]
_<<<<%10>=0 1>=1 1>=2 1>=3 1>=4 1>=5 1>=6 1>=7 1>=8 1>=9 1

```

Try it online!

I don't believe that this was the more optimal solution in convey, but it's cool to see it running at least (You can watch all the process in the "Try it online" link):
> 0 votes

# 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

```
> -1 votes

---
Tags: code-golf, number, decision-problem
---


title: Jolly gerrymandering

text:
# Question
Title: Jolly gerrymandering
## Background

The United States has a unique love of gerrymandering––the deliberate manipulation of an electoral district to predict certain voting results. Just recently there was a gerrymandering case brought before the Supreme Court. Gerrymandering, especially when related to race, is ruled illegal and results in the requirement to redraw the district lines.

Given a rectangular map of a municipality (2d array), you will draw district lines to help your party get the most representation. That is, you will gerrymander. Every municipality has two parties, `0` and `1`. The map will be comprised of squares with either `0` or `1` on them. Here is an example map:

## Challenge

You will group the map into districts so that the `1` party will get at least the number of districts specified by the Input.

## Input

The input will consist of a map, the number of districts to draw, and the minimum number of districts the `1` party needs to win (the minimum score).

## Output

The output will be a map of the districts. Each district will be uniquely comprised of a capitalized letter of the alphabet. Yes, this means that there will not be more than 26 districts.

If there is no possible output where the inputted party wins enough districts, either:

1. Print “We tried...”
2. Fatally error because the party was irreparably injured by the election results
3. Or both

## Rules (also very important)

1. All districts must be contiguous
2. Districts may not have other districts in them
3. Each district must have at least four nodes in it. The input will be consistent with the rules, meaning that there will be at least `number_of_districts * 4` nodes in the map
4. The score of each party is the number of districts it has a majority in
5. If a district has the same number of `0`s and `1`s, then neither party benefits from it
6. Normal no-cheating rules
7. This is , so shortest code in bytes wins.

## Test cases

```
1. Input       1. Output       2. Input       2. Output     3. Input      3. Output
districts: 5   Image and map   districts: 3   Image below   districts: 3  fatal error
min wins: 3                    min wins: 3                  min wins: 3
map:                           map:                         map:
00000110000    AAAAAAAAAAA     101101                       101101
10000010000    AAAAAAAAAAA     100000                       100000
10010000011    AAAAAAAAAAA     011011                       011011
11001110000    BBBBBBBAAAA     111111                       100111
00111111000    BBBBBBBAAAA
01111111000    CCCCCDDDAAA
01111111001    CCCCCDDDAAA
01000111100    EEEEEDDDDDD
00000001000    EEEEEDDDDDD

```

Of course, your program should work for *any* valid test case, not just these ones.

# Answer
> 6 votes
# , ~~938~~ ~~896~~ ~~858~~ 952 bytes

```
function(N,M,m){U="We tried...
"
L=length
A=matrix
W=which
K=sum
S=sample
G=unique
H=function(s,p=s-1){Y=S(c(s-j,s+j,p*(p%%j>0),(s+1)*(s%%j>0)))
Y[Y>0&Y<=k]}
C=function(v,z=W(r==v))K(z%%j<2,z-j<0,(z+j)>k)
m=A(strsplit(m,"")[[1]],1)
i=W(m<0)[1]-1
m=((t(A(m,i+1))[,1:i]>0)-.5)*2
if((K(m)<M&(N-M)<1)|K(m>0)<(3*M))cat(U) else{j=max(1,nrow(m))
k=i*j;w=g=T
while(w<9&g){Z=R=N;Q=M;b=0
r=A(0,j,i)
while(b<9&g){s=W(r<1)
s=s[S(L(s))][1:min(L(s),R)]
r[s]=1:L(s);a=0
while(K(r<1)>0&a<(k^2)){a=a+1
s=S(W(r>0&r<=R),1);p=r[s]
Y=H(s)
Y=Y[r[Y]<1]
if(L(Y)){Y=Y[order(m[Y])]
if(K(m[r==p]>1))r[Y[1]]=p else r[Y[L(Y)]]=p}}
if(a<(k^2)){for(v in 1:R){if(K(m[r==v])>0){r[r==v]=max(k,max(r))+1
Q=Q-1;Z=Z-1}}
if(Q<1){g=F
for(v in 1:R)r[r==v]=max(k,max(r))+1
for(v in G(c(r)))g=g|(K(r==v)<4)|(L(G(r[H(W(r==v))]))+C(v))<3}}
b=b+1;r[r<=R]=0;R=Z}
w=w+1}
if(g)cat(U) else{u=G(c(r))
for(v in 1:L(u))r[r==u[v]]=v
cat(paste(apply(A(LETTERS[r],j,i),1,paste,collapse=""),collapse="
"))}}}

```

Try it online!

A massive ~~\>900~~ ~~\>800~~ (nope!) \>900 bytes solution. The code works as follows. Let N be the number of electoral districts and M the minimum number of district where 1 wishes to have a majority.

First, the code randomly assigns N districts to different groups. Next, it randomly expands them, i.e. adds a district to a randomly selected group, ensuring that the district is next to a district already belonging to that group. In the expansion process, it gives precedence to a district with a 1 majority, if the district group is not yet a full 1 majority; if the group is already a certain 1 majority, then it gives precedence to a 0 district. It continues until all districts have been assigned.

Every group where there is a majority for the 1 party is stored, and its districts are locked. If there are at least M groups with a majority of 1, then everything is good and ~~we can print the result~~ we can check whether there are at least 4 districts in each group. If the cutoff of 4 districts is met, then we can happily print the result. Otherwise, the code tries to reassign the districts that are not locked to as many groups as available, i.e. N - #stored-groups.

The codes tries a few times (9 times). If it fails, it resets everything and starts again. It does so for other 9 times before giving up and printing "we tried...".

If the code does not succeed at first, try again a few times. I tuned the number of repetitions such that it can run in TIO under a minute. However if there is a solution, this code can (eventually) find it. The randomness part of the algorithm gives a non-zero probability that, if there is a solution, it can find it. The limited number of trials is the only limiting factor to success.

EDIT: added the control that no district group can be fully surrounded by just another one, unless the district group has districts on the edge of the given square. I think I missed it at first.

# Answer
> 0 votes
# Python3, 1067 bytes:

```
E=enumerate
R=range
def P(b):
 c=[(x,y)for x,r in E(b)for y,_ in E(r)]
 while c:
  C=c.pop(0)
  q,s=[C],[C]
  while q:
   x,y=q.pop(0)
   for X,Y in[(0,1),(0,-1),(-1,0),(1,0)]:
    T=(x+X,y+Y)
    if T in c and T not in s and b[x+X][y+Y]==b[x][y]:q+=[T];s+=[T]
  yield s;c=[*{*c}-{*s}]
def S(b,g):
 k=[0,0]
 for x,y in g:k[b[x][y]]+=1
 return k[1]>k[0]
def F(n,m,b):
 B=eval(str(b))
 for G in P(B):
  if len(G)<4:
   for x,y in G:B[x][y]=int(not B[x][y])
 q=[(B,L:=[*P(B)],sum(S(b,i)for i in L))]
 H=[L]
 while 1:
  B,G,C=q.pop(0)
  O=max(j for k in B for j in k)+1
  if len(G)==n and sum(S(b,i)for i in G)>=m:
   for Y,i in E(G,65):
    for x,y in i:B[x][y]=chr(Y)
   return B
  for x in R(len(b)+1):
   for y in R(len(b[0])+1):
    for X in R(x+1,len(b)+1):
     for Y in R(y+1,len(b[0])+1):
      if(X-x)*(Y-y)>=4 and S(b,T:=[(j,k)for j in R(x,X)for k in R(y,Y)]):
       Q=eval(str(B))
       for U,I in T:Q[U][I]=O
       if len(W:=[*P(Q)])<=n and len(W)>=len(G)and W not in H and all(len(i)>=4 for i in W)and(N_C:=sum(S(b,i)for i in W))>=C:q+=[(Q,W,N_C)];H+=[W]

```

Try it online!

## Notes:

1. A little longer than the other solution, but deterministic and runs in ~3.65 seconds
2. Fatally-errors if there is no possible output

---
Tags: code-golf, ascii-art, grid, printable-ascii
---


# Question
Title: Count the size of the Levenshtein neighborhood
# Input

A binary string \\$s\\$ of length \\$n\\$ and a positive integer \\$k \leq n\\$.

# Output

The number of binary strings with Levenshtein distance exactly \\$k\\$ from the string \\$s\\$.

# Example outputs

Each example gives the largest possible output for the given \\$(n, k)\\$ pair.

```
k=1, s=1010, output=14

k=2, s=1010, outupt=55

k=3, s=1101, output=112

k=4, s=1001, output=229

k=1, s=1010101010, output=32

k=2, s=1010110101, output=362

k=3, s=1010110101, output=2016

k=4, s=1011001101, output=6538

k=5, s=1011001101, output=16223

k=6, s=1001100110, output=37620

k=7, s=1001100110, output=85028

k=8, s=1001100110, output=187667

k=9, s=1001100110, output=406183

k=10, s=1001100110, output=864793

k=1, s=101010101010, output=38

k=2, s=101010010101, output=533

k=3, s=101010010101, output=3804

k=4, s=101001100101, output=15708

k=5, s=101100110010, output=45717

```

# Score

The score will be the highest \\$n, k\\$ pair your code outputs the correct answer for on my Ubuntu desktop in one minute. The order should be (1,1), (2,1), (2,2), (3,1),(3,2), (3,3), (4,1), (4,2), (4,3), (4,4), (5,1) etc. The time is the total running time and not just for the last pair.

Your code should work for all strings but I will time it using random binary strings.

As always, this is a competition *per* language so Python coders don't need to worry about C competitors.

# Leaderboard

* **(28, 23)** in Rust by **Anders Kaseorg**
* **(12, 11)** in Rust by **corvus\_192**.
* **(12, 10)** in Pypy by **Jonathan Allen**.
* **(11, 10)** in Pypy by **Value Ink**.
* **(11, 9)** in Python by **Value Ink**.
* **(11, 9)** in Python by **Jonathan Allen**.
* **(7,6)** in Charcoal **by Neil**.

# Edit

I noticed this related question which has a link that suggests there is a fast algorithm

# Answer
> 8 votes
# Rust, score ≈ (28, 23)

The number of strings at distance \\$k\\$ from \\$s\\$ with some given prefix \\$p\\$ is a function of \\$s\\$, \\$k\\$, and the last column of the Wagner–Fischer table of \\$s\\$ and \\$p\\$. We use a recursive search on prefixes \\$p\\$, caching results based on this last column.

Build with `cargo build --release`, run with `target/release/levenshtein-neighborhood <s> <k>`.

**`Cargo.toml`**

```
[package]
name = "levenshtein-neighborhood"
version = "0.1.0"
edition = "2021"

[dependencies]
hashbrown = "0.14.0"
rustc-hash = "1.1.0"
typed-arena = "2.0.2"

```

**`src/main.rs`**

```
use hashbrown::hash_map::HashMap;
use rustc_hash::FxHasher;
use std::env;
use std::hash::{BuildHasher, BuildHasherDefault};
use typed_arena::Arena;

type Count = u64; // For n + k > 64, change this to u128
type Cache<'a> = HashMap<&'a [u8], Count, BuildHasherDefault<FxHasher>>;

fn count_state<'a>(
    target: &[bool],
    distance: u8,
    arena: &'a Arena<u8>,
    cache: &mut Cache<'a>,
    state: &mut [u8],
) -> Count {
    let hash = cache.hasher().hash_one(&state);
    if let Some((_, &count)) = cache.raw_entry().from_key_hashed_nocheck(hash, state) {
        count
    } else {
        let new_state = state;
        let state = arena.alloc_extend(new_state.iter().copied());
        let mut count = Count::from(state[target.len()] == distance);
        for symbol in [false, true] {
            let mut z = state[0].min(distance) + 1;
            new_state[0] = z;
            for (((o, &c), &x), &y) in new_state[1..]
                .iter_mut()
                .zip(target)
                .zip(&state[..state.len() - 1])
                .zip(&state[1..])
            {
                z = (x + u8::from(symbol != c)).min(y.min(z).min(distance) + 1);
                *o = z;
            }
            count += count_state(target, distance, arena, cache, new_state);
        }
        cache
            .raw_entry_mut()
            .from_hash(hash, |_| false)
            .insert(state, count);
        count
    }
}

fn count(target: &[bool], distance: u8) -> Count {
    let arena = Arena::new();
    let state = arena.alloc_extend((0..=target.len()).map(|i| (i as u8).min(distance + 1)));
    let mut cache = Cache::default();
    cache.insert(
        &arena.alloc_extend((0..=target.len()).map(|_| distance + 1))[..],
        0,
    );
    count_state(target, distance, &arena, &mut cache, state)
}

fn main() {
    if let [_program, target, distance] = &Vec::from_iter(env::args())[..] {
        let target = Vec::from_iter(target.chars().map(|c| c == '1'));
        let distance = distance.parse().unwrap();
        println!("{}", count(&target, distance));
    } else {
        panic!("usage: levenshtein-neighborhood <s> <k>");
    }
}

```

# Answer
> 4 votes
# Python, (11, 8); with Python PyPy (12, 10)

New version of Value Ink's answer using bit twiddling in place of string manipulation.

```
from collections import deque

def countFixedDistance(s: str, k: int) -> int:
    n = int('1' + s, 2)
    distances: dict[int, int] = {n: 0}
    queue = deque(((n, len(s)),))
    valid: set[int] = set()
    while len(queue) > 0:
        current, bit_count = queue.popleft()
        next_dist = distances[current] + 1
        next_bit_count = bit_count - 1
        for next_gen in (
            ((current >> e + 1 << e) + current % (1 << e) for e in range(bit_count)),
            (current ^ (1 << e) for e in range(bit_count)),
            (((current >> e << 1 | b) << e) + current % (1 << e) for b in (0, 1) for e in range(bit_count + 1)),
        ):
          for next in next_gen:
              if next in distances: continue
              distances[next] = next_dist
              if next_dist < k:
                  queue.append((next, next_bit_count))
              else:
                  valid.add(next)
          next_bit_count += 1
    return len(valid)

```

**Attempt This Online!**

---

With a lot of tweaks to do fewer operations, it does get further but still not to completion of (11, 9) on ATO, so it may also be worth benchmarking too:

```
from collections import deque

def countFixedDistance(s: str, k: int) -> int:
    n = int('1' + s, 2)
    distances: dict[int, int] = {n: 0}
    queue = deque(((n, len(s)),))
    valid: set[int] = set()
    while len(queue) > 0:
        current, bit_count = queue.popleft()
        next_dist = distances[current] + 1
        for e in range(bit_count):
            left = current >> e
            left_1 = left << 1
            pow = 1 << e
            right = current % pow
            bp1 = bit_count + 1
            for next, next_bit_count in (
                ((left >> 1 << e) | right, bit_count - 1),
                (current ^ pow, bit_count),
                ((left_1 << e) | right, bp1),
                (((left_1 | 1) << e) | right, bp1),
            ):
                if next in distances: continue
                distances[next] = next_dist
                if next_dist < k:
                    queue.append((next, next_bit_count))
                else:
                    valid.add(next)
        for next in (
            pow << 2 | current,
            3 << bit_count ^ current,
        ):
            if next in distances: continue
            distances[next] = next_dist
            if next_dist < k:
                queue.append((next, bit_count + 1))
            else:
                valid.add(next)
    return len(valid)

```

**Attempt This Online!**

# Answer
> 3 votes
# Python, ~(11,6)

Direct adaptation of my answer on Pick a random string at a fixed edit distance with a minor optimization of generating the sets inline instead of each one being a function call. ATO seems to flip-flop between (11,6) and (11,7) for me right now.

```
from collections import deque

def countFixedDistance(s: str, k: int) -> int:
  if k <= 0: return s

  chars: set[str]          = set('01')
  distances: dict[str,int] = {s: 0}
  queue                    = deque((s,))
  valid: set[str]          = set()

  while len(queue) > 0:
    current = queue.popleft()
    nextdist = distances[current] + 1
    for nxt in {current[:i] + c + current[i:] for c in chars for i in range(len(s)+1)} \
               | {current[:i] + c + current[i+1:] for c in chars for i in range(len(s)) if c != s[i]} \
               | {current[:i] + current[i+1:] for i in range(len(s))}:
      if nxt in distances: continue
      distances[nxt] = nextdist
      if nextdist < k:
        queue.append(nxt)
      else:
        valid.add(nxt)

  return len(valid)

```

Attempt This Online!

# Answer
> 3 votes
# Rust, (12, 11)

This is basically a line-by-line port of Jonathan Allan's answer, with is already very good. Thanks! I wrote this to practice some Rust.

It uses the nohash-hasher crate for extremely fast HashMap lookups, with take up the vast majority of the time.

Try it online on rustexplorer.com. Runs an unoptimized debug build, so don't rely on it for measurements.

I have a github repo with build instructions.

```
#![warn(clippy::all)]

use std::collections::VecDeque;
use std::collections::hash_map::Entry;
use std::time::Instant;

use nohash_hasher::{IntMap, IntSet};

fn count_fixed_distance(s: &str, k: u32) -> usize {
    let n = i32::from_str_radix(&format!("1{s}"), 2).unwrap();
    let mut distances = IntMap::with_capacity_and_hasher(1 << (s.len() + k as usize), Default::default());
    distances.insert(n, 0);
    let mut queue = VecDeque::from([(n, s.len())]);
    // capacity is just experimentation
    let mut valid = IntSet::with_capacity_and_hasher(1 << (k + 1), Default::default());
    while let Some((current, bit_count)) = queue.pop_front() {
        let next_dist = distances.get(&current).unwrap() + 1;
        let mut pow = 0;
        for e in 0..bit_count {
            let left = current >> e;
            let left_1 = left << 1;
            pow = 1 << e;
            let right = current % pow;
            let bp1 = bit_count + 1;
            for (next, next_bit_count) in [
                ((left >> 1 << e) | right, bit_count - 1),
                (current ^ pow, bit_count),
                ((left_1 << e) | right, bp1),
                (((left_1 | 1) << e) | right, bp1)
            ] {
                match distances.entry(next) {
                    Entry::Vacant(ve) => {
                        ve.insert(next_dist);
                    }
                    Entry::Occupied(_) => continue,
                }
                if next_dist < k {
                    queue.push_back((next, next_bit_count));
                } else {
                    valid.insert(next);
                }
            }
        }

        for next in [pow << 2 | current, 3 << bit_count ^ current] {
            match distances.entry(next) {
                Entry::Vacant(ve) => {
                    ve.insert(next_dist);
                }
                Entry::Occupied(_) => continue,
            }
            if next_dist < k {
                queue.push_back((next, bit_count + 1));
            } else {
                valid.insert(next);
            }
        }
    }
    valid.len()
}

fn main() {
    let start = Instant::now();
    let mut s = String::with_capacity(32);
    s.push('0');
    let mut v = 0;
    while s.len() <= 12 { // approx 2 minutes for profiling
        for k in 1..(s.len() + 1) {
            println!("{} {} {}", s.len(), k, count_fixed_distance(&s, k as u32));
        }
        s.push(['1', '1', '0', '0'][v % 4]);
        v += 1;
        println!("{}", s)
    }
    println!("{} seconds", start.elapsed().as_secs_f32());
}

```

# Answer
> 2 votes
# Charcoal, 81 bytes

```
⊞υη≔⦃η¹⦄ζＦＮ«≔υε≔⟦⟧υＦεＦΣ⁺Ｅκ⟦⭆κ¬⁼Ｉν⁼μξ⭆κ⎇⁼μξων⟧Ｅ²Ｅ⊕Ｌκ⁺⁺✂κ⁰ν¹λ✂κν¿¬§ζλ«⊞υλ§≔ζλ¹»»ＩＬυ

```

Attempt This Online! Link is to verbose version of code. Can handle results of up to about `20000` on ATO, so `5 1011001101` or `4 101001100101`. Explanation:

```
⊞υη

```

Start with one string of distance `0`.

```
≔⦃η¹⦄ζ

```

Start with one string found so far.

```
ＦＮ«

```

Loop `k` times.

```
≔υε≔⟦⟧υＦε

```

Start collecting strings of distance `i+1`.

```
ＦΣ⁺Ｅκ⟦⭆κ¬⁼Ｉν⁼μξ⭆κ⎇⁼μξων⟧Ｅ²Ｅ⊕Ｌκ⁺⁺✂κ⁰ν¹λ✂κν

```

Loop over all strings of edit distance `1` from the current string of distance `i`.

```
¿¬§ζλ«⊞υλ§≔ζλ¹»

```

If this string is new then mark it as seen and add it to the list of strings of edit distance `i+1`.

```
»ＩＬυ

```

Output the count of strings of edit distance `k`.

---
Tags: fastest-code, edit-distance
---