Find the highest unique digit

33

2

Surprisingly we haven't had a simple "find the highest digit" challenge yet, but I think that's a little too trivial.

Given input of a non-negative integer, return the highest unique (ie not repeated) digit found in the integer. If there are no unique digits, your program can do anything (undefined behaviour).

The input can be taken as a single integer, a string, or a list of digits.

Test cases

12         -> 2
0          -> 0
485902     -> 9
495902     -> 5
999999     -> Anything
999099     -> 0
1948710498 -> 7

This is so fewest bytes in each language wins!

Skidsdev

Posted 2017-06-28T08:09:22.013

Reputation: 9 656

2Can we take input as a string instead? – user41805 – 2017-06-28T08:13:05.043

3Given the last test case, I think we are forced to take input as a string... (leading zeroes can't be represented in integers) – Leo – 2017-06-28T08:14:27.247

@Leo that was my bad actually, basically mashed the numbers on my keyboard, didn't notice the leading zero. But yes, input can be taken as a string – Skidsdev – 2017-06-28T08:17:14.040

Then why can't we just take a list of digits (or numbers for that sake)? – Adám – 2017-06-28T08:19:09.787

Can we throw an error if there are no unique digits? – Adám – 2017-06-28T08:21:51.247

25@Adám "undefined behaviour" generally means you can do anything, including summoning nameless horrors from the void if that saves bytes. – Martin Ender – 2017-06-28T08:22:26.807

22@MartinEnder in fact I'll happily knock off 50% of your bytes if your code successfully summons cthulhu upon there being no unique digits ;) – Skidsdev – 2017-06-28T08:31:18.500

@Mayube Can we take a list of digits? – Adám – 2017-06-28T08:43:17.593

@Adám sure, most people are only splitting it into a list of some form anyway, I'll explicitly state accepted input formats on the post – Skidsdev – 2017-06-28T08:47:21.903

Regarding the list of digits: can it be either a list of integers or a list of characters? ([1,2,3] vs ['1','2','3']) – Arnauld – 2017-06-28T09:55:21.240

@Arnauld no. List of integer digits only. – Skidsdev – 2017-06-28T09:57:36.937

Answers

16

05AB1E, 4 3 bytes

Saved 1 byte thanks to Mr. Xcoder notifying that a digit list is valid input.

¢ÏM

Try it online!

Explanation

¢     # count occurrences of each digit in input
 Ï    # keep only the digits whose occurrences are true (1)
  M   # push the highest

Emigna

Posted 2017-06-28T08:09:22.013

Reputation: 50 798

Wait so in 05AB1E, 2 is not truthy; only 1? :o – HyperNeutrino – 2017-06-29T02:05:43.017

@HyperNeutrino: Correct! – Emigna – 2017-06-29T06:02:49.340

2That seems both very useful and very bothersome... That is interesting :o :D – HyperNeutrino – 2017-06-29T06:05:04.017

@HyperNeutrino: It often comes in handy, but it can be a disadvantage when the challenge says return a truthy value, when a lot of languages can return any positive integer or maybe even a non-empty string. – Emigna – 2017-06-29T06:27:15.633

A strikethrough on the number for is not easy to see! – MrZander – 2017-06-29T23:48:37.073

15

Python 3, 40 bytes

Saved 2 bytes thanks to movatica.

lambda i:max(x*(i.count(x)<2)for x in i)

Try it online!

42 bytes

Works for both String and list of digits parameter types. Throws an error for no unique digits, kind of abuses of that spec:

lambda i:max(x for x in i if i.count(x)<2)

Try it online!


Explanation

  • lambda i: - Declares a lambda function with a string or list of digits parameter i.
  • max(...) - Finds the maximum value of the generator.
  • x for x in i - Iterates through the characters / digits of i.
  • if i.count(x)<2 - Checks if the digit is unique.

Mr. Xcoder

Posted 2017-06-28T08:09:22.013

Reputation: 39 774

40 bytes: lambda i:max(x*(i.count(x)<2)for x in i) – movatica – 2019-05-21T22:00:15.080

1@movatica Thanks! – Mr. Xcoder – 2019-05-22T04:52:13.860

8

Alice, 15 bytes

/&.sDo
\i-.tN@/

Try it online!

Explanation

/...
\.../

This is a simple framework for linear code that operates entirely in Ordinal mode (meaning this program works completely through string processing). The unfolded linear code is then just:

i..DN&-sto@

What it does:

i    Read all input as a string.
..   Make two copies.
D    Deduplicate the characters in the top copy.
N    Get the multiset complement of this deduplicated string in the input.
     This gives us a string that only contains repeated digits (with one
     copy less than the original, but the number of them doesn't matter).
&-   Fold string subtraction over this string, which means that each of
     the repeated digits is removed from the input.
s    Sort the remaining digits.
t    Split off the last digit.
o    Print it.
@    Terminate the program.

Martin Ender

Posted 2017-06-28T08:09:22.013

Reputation: 184 808

-1, doesn't "summoning nameless horrors from the void" if there are no unique digits. ;) (Read: +1, great answer as always.) – Kevin Cruijssen – 2017-06-28T13:46:33.517

1

@KevinCruijssen I tried, but it didn't save bytes. Maybe Dark might be a more appropriate language...

– Martin Ender – 2017-06-28T13:52:53.640

7

Retina, 16 bytes

O`.
(.)\1+

!`.$

Try it online!

Explanation

O`.

Sort the digits.

(.)\1+

Remove repeated digits.

!`.$

Fetch the last (maximal) digit.

Martin Ender

Posted 2017-06-28T08:09:22.013

Reputation: 184 808

Too bad Deduplicate doesn't help here :( – CalculatorFeline – 2017-06-28T19:53:44.173

7

Charcoal, 18 12 bytes

Fχ¿⁼№θIι¹PIι

Try it online! (Link to verbose version)

Prints nothing if no solution is found. The trick is that the for loop prints every unique number in the input string, but without moving the cursor, thus the value keeps reprinting itself until the final solution is found.

The previous version printed the characters A to Z when no solution was found, hence the comments:

AααFχA⎇⁼№θIι¹Iιααα

Try it online! (Link to verbose version)

Charlie

Posted 2017-06-28T08:09:22.013

Reputation: 11 448

3That's an interesting undefined behavior :) – Emigna – 2017-06-28T08:42:29.893

This sounds Finnish to me :D – fedorqui – 2017-06-28T09:33:24.523

2@fedorqui nice to see you here! Yeah, but Charcoal is easier to learn than Jelly or O5AB1E, and it's funnier to use in ASCII-art games. :-) – Charlie – 2017-06-28T09:37:53.067

7

Husk, 7 bytes

→fo¬hgO

Try it online! (Test suite, crashes on the last test case since it has no unique digits)

This is a composition of functions in point-free style (the arguments are not mentioned explicitely anywhere). Takes input and returns output as a string, which in Husk is equivalent to a list of characters.

Explanation

Test case: "1948710498"

      O    Sort:                             "0114478899"
     g     Group consecutive equal elements: ["0","11","44","7","88","99"]
 fo¬h      Keep only those with length 1*:   ["0","7"]
→          Take the last element:            "7"

*The check for length 1 is done by taking the head of the list (all elements except the last one) and negating it (empty lists are falsy, non-empty lists are truthy).

Leo

Posted 2017-06-28T08:09:22.013

Reputation: 8 482

7

Haskell, 37 bytes

f s=maximum[x|x<-s,[x]==filter(==x)s]

Try it online!

How it works:

  [  |x<-s   ]          -- loop x through the input string s
    x                   -- and keep the x where
     [x]==filter(==x)s  -- all x extracted from s equal a singleton list [x]
maximum                 -- take the maximum of all the x

nimi

Posted 2017-06-28T08:09:22.013

Reputation: 34 639

7

R, 41 bytes

function(x,y=table(x))max(names(y[y==1]))

An anonymous function that takes a list of digits, either as integers or single character strings. It precomputes y as an optional argument to avoid using curly braces for the function body. Returns the digit as a string. This takes a slightly different approach than the other R answer and ends up being the tiniest bit shorter! looks like my comment there was wrong after all...

table computes the occurrences of each element in the list, with names(table(x)) being the unique values in x (as strings). Since digits are fortunately ordered the same lexicographically as numerically, we can still use max.

Try it online!

Giuseppe

Posted 2017-06-28T08:09:22.013

Reputation: 21 077

Nice! I didn't expect doing something with table would be shorter (plus I can never remember how to get names to work). – aPaulT – 2017-06-28T19:35:51.127

1<2 for another byte. There should never be a zero in the counts. – MickyT – 2017-06-28T20:28:22.573

1y=table(scan());max(names(y[y<2])) is a few bytes shorter. – JAD – 2017-06-29T08:53:20.387

6

JavaScript (ES6), 46 41 40 bytes

Takes input as a string. Returns RangeError if there are no unique digits.

s=>f=(i=9)=>s.split(i).length-2?f(--i):i

-7 bytes thanks to Rick Hitchcock

-1 byte thanks to Shaggy

Test cases

let f =

s=>g=(i=9)=>s.split(i).length-2?g(--i):i


console.log(f("12")())         // 2
console.log(f("0")())          // 0
console.log(f("485902")())     // 9
console.log(f("495902")())     // 5
//console.log(f("999999")())   // RangeError
console.log(f("999099")())     // 0
console.log(f("1948710498")()) // 7

Oki

Posted 2017-06-28T08:09:22.013

Reputation: 311

Remove the alert for 39 bytes: (s,i=9)=>s.split(i).length-2?f(s,--i):i. You can avoid the stack overflow for 42 bytes: (s,i=9)=>s.split(i).length-2?i&&f(s,--i):i. – Rick Hitchcock – 2017-06-28T13:09:14.430

Save a byte with currying: s=>g=(i=9)=>s.split(i).length-2?g(--i):i and then call it with f("12")() – Shaggy – 2017-06-28T14:08:26.047

5

Python 3, 40 bytes

lambda i:max(x+9-9*i.count(x)for x in i)

Only works for lists of digits. The edge case '990' works fine :)

Try it online!

Alex Varga

Posted 2017-06-28T08:09:22.013

Reputation: 171

Welcome to PPCG! Looks like you've got everything down :) – Stephen – 2017-06-28T23:29:33.557

4

Brachylog, 8 bytes

ọtᵒtᵍhth

Try it online!

Explanation

Example input: 495902

ọ          Occurences:    [[4,1],[9,2],[5,1],[0,1],[2,1]]
 tᵒ        Order by tail: [[0,1],[2,1],[4,1],[5,1],[9,2]]
   tᵍ      Group by tail: [[[0,1],[2,1],[4,1],[5,1]],[[9,2]]]
     h     Head:          [[0,1],[2,1],[4,1],[5,1]]
      t    Tail:          [5,1]
       h   Head:          5

Fatalize

Posted 2017-06-28T08:09:22.013

Reputation: 32 976

4

Husk, 9 8 bytes

Thanks to Leo for suggesting a slightly neater solution at the same byte count.

▲‡ȯf=1`#

Try it online!

Explanation

  ȯ       Compose the following thre functions into one binary function.
      `#  Count the occurrences of the right argument in the left.
    =1    Check equality with 1. This gives 1 (truthy) for values that 
          appear uniquely in the right-hand argument.
   f      Select the elements from the right argument, where the function
          in the left argument is truthy.
          Due to the composition and partial function application this
          means that the first argument of the resulting function actually
          curries `# and the second argument is passed as the second
          argument to f. So what we end up with is a function which selects
          the elements from the right argument that appear uniquely in
          the left argument.
 ‡        We call this function by giving it the input for both arguments.
          So we end up selecting unique digits from the input.
▲         Find the maximum.  

Martin Ender

Posted 2017-06-28T08:09:22.013

Reputation: 184 808

1¬← could be more simply =1, same bytecount though :) – Leo – 2017-06-28T09:08:03.843

1@Leo Ah yeah, I was too lazy to test whether the currying would work without parentheses. I need to trust more in the type inference. ;) – Martin Ender – 2017-06-28T09:10:00.517

4

Mathematica, 41 bytes

(t=9;While[DigitCount[#][[t]]!=1,t--];t)&

thanks @Martin Ender

here is Martin's approach on my answer

Mathematica, 35 bytes

9//.d_/;DigitCount[#][[d]]!=1:>d-1&

J42161217

Posted 2017-06-28T08:09:22.013

Reputation: 15 931

4

R, 45 43 bytes

function(x)max(setdiff(x,x[duplicated(x)]))

Try it online!

Takes input as a vector of integers. Finds the duplicated elements, removes them, and takes the maximum. (Returns -Inf with a warning if there is no unique maximum.)

Edited into an anonymous function per comment

aPaulT

Posted 2017-06-28T08:09:22.013

Reputation: 181

max(x[!duplicated(x)]) is quite a bit shorter, but this is a great answer. I knew the way I was going to do it was not this good. Also you can remove the f= from the beginning, as anonymous functions are perfectly valid answers.

Also, you can use TIO to test your functions if you use this format: Try it online!

– Giuseppe – 2017-06-28T19:06:50.873

Thanks! I think the 'duplicated' function doesn't count the first occurrence of a duplicate element so your version wouldn't quite work – aPaulT – 2017-06-28T19:10:09.160

ah, good point. I almost never use duplicated but I actually thought up another, shorter answer! – Giuseppe – 2017-06-28T19:25:57.630

3

Ruby, 42 bytes

->x{(?0..?9).select{|r|x.count(r)==1}[-1]}

Try it online!

G B

Posted 2017-06-28T08:09:22.013

Reputation: 11 099

Ruby ties Python :) – Mr. Xcoder – 2017-06-28T08:56:14.117

Because 42 is always the answer. :-) – G B – 2017-06-28T08:56:54.313

5@GB Or is it: ->x{x.chars.select{|r|x.count(r)<2}.max} – Martin Ender – 2017-06-28T09:00:00.597

1That would be 2 bytes shorter and ruin the whole thing. :-) – G B – 2017-06-29T09:02:30.383

3

C# (.NET Core), 27 97 86 58 57 75 bytes

using System.Linq;

n=>n.GroupBy(i=>i).Where(i=>i.Count()<2).Max(i=>i.Key)-48

Try it online!

Thanks @CarlosAlejo

kakkarot

Posted 2017-06-28T08:09:22.013

Reputation: 269

This does not work with "1948710498" as input (returns "9" instead of "7"), and you must add using System.Linq; to the byte count. – Charlie – 2017-06-28T09:03:06.223

@CarlosAlejo Oops! Sorry! Just now read the specifications fully. Will edit the solution soon. – kakkarot – 2017-06-28T09:05:06.157

Edited. Are there any optimisations I can make? – kakkarot – 2017-06-28T09:34:51.180

Sure: try using OrderBy(...).Last() instead of .OrderByDescending(...).First(), for instance. Or even better, change your last part with .Max(i=>i.Key) after the Where clause. – Charlie – 2017-06-28T09:39:34.550

@CarlosAlejo Thanks! Edited. – kakkarot – 2017-06-28T09:41:43.777

And even better: you can get rid of the Select clause and apply the transformation (changing '0'with its ASCII value 48) only to the final result, so you get: n=>n.GroupBy(i=>i).Where(i=>i.Count()<2).Max(i=>i.Key)-48.Try it online!

– Charlie – 2017-06-28T09:47:13.170

You need to include using System.Linq; into the byte count here. – TheLethalCoder – 2017-06-29T11:10:57.213

Wrote this off the top of my head so haven't checked it but I believe this will be shorter if it works: using System.Linq;n=>n.Where(c=>n.Distinct(h=>h).Contains(c)).Max()-48 or maybe this: using System.Linq;n=>n.Where(c=>n.Distinct(h=>h).Any(a=>a==c)).Max()-48 – TheLethalCoder – 2017-06-29T11:13:19.883

You can use the C# Interactive compiler now without counting using System.Linq;, and you can also move the both the Where and the GroupBy things into the Max call for 38 bytes. Try it online!

– my pronoun is monicareinstate – 2019-05-21T10:19:29.440

3

APL (Dyalog Unicode), 10 chars = 19 bytes

Method: multiply elements that occur multiple times by zero, and then fine the highest element.

⌈/×∘(1=≢)⌸

 for each unique element and its indices in the argument:

× multiply the unique element

∘() with:

  1= the Boolean for whether one is equal to

   the tally of indices (how many times the unique element occurs)

⌈/ the max of that

Try it online!

APL (Dyalog Classic), 15 bytes

⌈/×∘(1=≢)⎕U2338

Try it online!

Identical to the above, but uses ⎕U2338 instead of .

Adám

Posted 2017-06-28T08:09:22.013

Reputation: 37 779

3

Bash + coreutils, 30 28 bytes

-2 bytes thanks to Digital Trauma

fold -1|sort|uniq -u|tail -1

Try it online!


Bash + coreutils, 20 bytes

sort|uniq -u|tail -1

Try it online!

If input is given as a list of digits, one per line, we can skip the fold stage. That feels like cheating though.

Riley

Posted 2017-06-28T08:09:22.013

Reputation: 11 345

Replace grep -o . with fold -1 to save 2 bytes. I agree that an input integer given as a list of digits is stretching the rules too far. – Digital Trauma – 2017-06-28T18:54:26.273

+1 just because it is bash – Anush – 2019-05-19T18:39:52.877

3

Python 2, 39 bytes

lambda l:max(1/l.count(n)*n for n in l)

Try it online!

xnor

Posted 2017-06-28T08:09:22.013

Reputation: 115 687

I enjoyed this, it’s great! – Anush – 2019-05-19T04:46:05.483

2

APL (Dyalog), 14 bytes

-2 thanks toTwiNight.

⌈/⊢×1=(+/∘.=⍨)

⌈/ the largest of

 the arguments

× multiplied by

1=() the Boolean for each where one equals

+/ the row sums of

∘.=⍨ their equality table

Try it online!

Adám

Posted 2017-06-28T08:09:22.013

Reputation: 37 779

Since 0 is never the highest unique digit except for 0 itself, you can save 1 byte using × instead of /⍨, then save another byte converting that into a train – TwiNight – 2017-06-29T01:38:49.757

@TwiNight Nice! Thank you. – Adám – 2017-06-29T06:27:21.983

2

Japt, 12 11 10 bytes

Takes input as an array of digits.

k@¬èX ÉÃrw

Test it


Explanation

     :Implicit input of array U.
k    :Filter the array to the elements that return false when...
@    :Passed through a function that...
¬    :Joins U to a string and...
èX   :Counts the number of times the current element (X) appears in the string...
É    :Minus 1.
     :(The count of unique digits will be 1, 1-1=0, 0=false)
à   :End function.
r    :Reduce by...
w    :Getting the greater of the current element and the current value.
     :Implicit output of resulting single digit integer.

Shaggy

Posted 2017-06-28T08:09:22.013

Reputation: 24 623

2

JavaScript (ES6), 52 50 bytes

Takes input as a list of digits. Returns 0 if there are no unique digits.

s=>s.reduce((m,c)=>m>c|s.filter(x=>x==c)[1]?m:c,0)

Test cases

let f =

s=>s.reduce((m,c)=>m>c|s.filter(x=>x==c)[1]?m:c,0)

console.log(f([1,2]))                 // 2
console.log(f([0]))                   // 0
console.log(f([4,8,5,9,0,2]))         // 9
console.log(f([4,9,5,9,0,2]))         // 5
console.log(f([9,9,9,9,9,9]))         // (0)
console.log(f([9,9,9,0,9,9]))         // 0
console.log(f([1,9,4,8,7,1,0,4,9,8])) // 7

Arnauld

Posted 2017-06-28T08:09:22.013

Reputation: 111 334

2

PHP, 40 bytes

<?=array_flip(count_chars($argn))[1]-48;

Try it online!

PHP, 42 bytes

<?=chr(array_flip(count_chars($argn))[1]);

Try it online!

Jörg Hülsermann

Posted 2017-06-28T08:09:22.013

Reputation: 13 026

1-2 bytes: <?=array_flip(count_chars($argn))[1]-48; – Titus – 2017-07-15T08:40:18.923

2

Java (OpenJDK 8), 89 85 79 bytes

a->{int i=10,x[]=new int[i];for(int d:a)x[d]++;for(;i-->0&&x[i]!=1;);return i;}

Try it online!

-6 bytes thanks to @KevinCruijssen's insight!

Olivier Grégoire

Posted 2017-06-28T08:09:22.013

Reputation: 10 647

1You can replace return i>0?i:0; with return i;. The output will be -1 for test case [9,9,9,9,9,9], but that is fine with the challenge: "If there are no unique digits, your program can do anything (undefined behavior).". – Kevin Cruijssen – 2017-06-28T13:43:38.270

Indeed, I can since the current revision. Before I couldn't because of the test case 0. It's something I oversaw in the previous golf! :) – Olivier Grégoire – 2017-06-28T13:45:58.750

2

Java (JDK), 67 bytes

s->{int i=9;for(s=" "+s+" ";s.split(i+"").length!=2;i--);return i;}

Try it online!

Embodiment of Ignorance

Posted 2017-06-28T08:09:22.013

Reputation: 7 014

1

F#, 88 bytes

let f i=Seq.countBy(fun a->a)i|>Seq.maxBy(fun a->if snd a>1 then 0 else int(fst a))|>fst

Try it online!

An improved approach from my first effort, results in less bytes.

Points of interest: fst and snd return the first and second elements of a tuple respectively.

user20151

Posted 2017-06-28T08:09:22.013

Reputation:

1

Mathematica, 42 bytes

Max@Position[RotateRight@DigitCount@#,1]-1&

J42161217

Posted 2017-06-28T08:09:22.013

Reputation: 15 931

1

Jelly, 9 bytes

ṢŒrṪỊ$ÐfṀ

Try it online!

Erik the Outgolfer

Posted 2017-06-28T08:09:22.013

Reputation: 38 134

well – Leaky Nun – 2017-06-28T09:42:36.733

@LeakyNun outgolfed, son – Skidsdev – 2017-06-28T09:43:41.983

@Mayube but the core algorithm is the same – Leaky Nun – 2017-06-28T09:44:51.533

@LeakyNun no, it's quite different. – steenbergh – 2017-06-28T09:49:09.630

@LeakyNun I decided to post separately...basically a big difference is that in my case I just decide which to keep, while steenbergh takes some heads or something... – Erik the Outgolfer – 2017-06-28T09:50:15.150

1

Pyth, 8 7 6 bytes

1 byte thanks to isaacg.

1 byte thanks to FryAmTheEggman.

e{I#.g

Test suite.

Leaky Nun

Posted 2017-06-28T08:09:22.013

Reputation: 45 011

1

Pyth, 6 bytes

eS.m/Q

Test suite

Explanation:

eS.m/Q
eS.m/QbQ    Implicit variable introduction
  .m   Q    Find all minimal elements of the input by the following function:
    /Qb     Number of appearances in the input
eS          Take the maximum element remaining.

isaacg

Posted 2017-06-28T08:09:22.013

Reputation: 39 268

1

Perl 5, 59 bytes

for$x(split//,<>){$d[$x]++};for($x=11;--$d[--$x];){}print$x

Try it online!

Felix Palmen

Posted 2017-06-28T08:09:22.013

Reputation: 3 866

Shortened to 40 bytes: Try it online!. (you can look up -F flag on perlrun if needed)

– Dada – 2017-07-27T11:51:45.117

1

Octave, 31 bytes

@(a)find(hist(a,0:9)==1)(end)-1

Try it online!

rahnema1

Posted 2017-06-28T08:09:22.013

Reputation: 5 435

1

Python 2, 41 bytes

lambda s:max(s,key=lambda o:s.count(o)<2)

Accepts input as string or list of strings

Wondercricket

Posted 2017-06-28T08:09:22.013

Reputation: 251

1

Pyth -- 8 bytes

eSf!t/QT

And also

eS-Q.-Q{

Try it here and here

Explanation:

eSf!t/QT  # Takes string
  f       # Filter characters T of implicit input
     /QT  # by counting occurrences of that character in the input
   !t     # keeping only characters that occur once (i.e., !(# occurrences - 1)
 S        # Sort (puts them in ascending order
e         # Take the last (highest)

And

eS-Q.-Q{  # Takes list of digits
       {  # Deduplicate the list
    .-Q   # Take the original list, and remove each element in the deduplicated list once (so only duplicated digits are left)
  -Q      # Remove these duplicated digits from the list
eS        # As before, sort and take the last element

Maria

Posted 2017-06-28T08:09:22.013

Reputation: 644

1

Perl 6,  33  25 bytes

{max keys .comb∖.comb.repeated}

input is either an Int or Str.

Test it

{max keys $_∖.repeated}

input is a list of digits.

Test it

Expanded:

{ # bare block lambda with implicit parameter 「$_」

  max                  # the maximum from
    keys               # the keys (digits) out of the following Set

        $_             # the Input list of digits
      ∖                # Set minus (not 「\」)
        .repeated      # the repeated digits (implicit method call on 「$_」)
}

Brad Gilbert b2gills

Posted 2017-06-28T08:09:22.013

Reputation: 12 713

1

APL (Dyalog), 11 bytes

⌈/{⍺×2-≢⍵}⌸

Try it online!

TwiNight

Posted 2017-06-28T08:09:22.013

Reputation: 4 187

⌈/×∘(2-≢)⌸ – Adám – 2017-08-21T23:10:51.567

1

Java, 70 bytes

Input is taken as a List of digits, as per question parameters.

n->n.stream().reduce(0,(p,q)->p>q||n.indexOf(q)!=n.lastIndexOf(q)?p:q)

The power of Streams in the palm of your hand!

The secret here is the beautiful reduce function. Starting with a 0, we walk through our list of digits and perform a retaining algorithm, keeping the one we've got (?p:q) if it's bigger than the new one (p>q) or if the new one isn't unique (n.indexOf(q)!=n.lastIndexOf(q))

Xanderhall

Posted 2017-06-28T08:09:22.013

Reputation: 1 236

You can save a byte by changing || to |. – Kevin Cruijssen – 2017-11-13T15:23:17.017

1

CJam, 13 bytes

9A,sqfe=W%X#-

Try it Online

9    e# Push 9 to stack
A,s  e# Push "0123456789" to stack
q    e# Push input to stack ("1948710498")
fe=  e# Create array containing number of occurences of each digit in input number ([1,2,0,0,2,0,0,1,2,2])
W%   e# Reverse that array ([2,2,1,0,0,2,0,0,2,1])
X#   e# Get index of 1 in that array (2)
-    e# Calculate 9 - returned index to get highest unique digit (7)

geokavel

Posted 2017-06-28T08:09:22.013

Reputation: 6 352

1

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

n=>n.Max(x=>n.Count(a=>a==x)<2?x:0)-48

Try it online!

Embodiment of Ignorance

Posted 2017-06-28T08:09:22.013

Reputation: 7 014

1

J, 16 12 bytes

0{\:~-.}./.~

Try it online!

FrownyFrog

Posted 2017-06-28T08:09:22.013

Reputation: 3 112

This is really nice, and since "The input can be taken as a single integer, a string, or a list of digits." you can actually do 0{\:~-.}./.~ for 12: Try it online!

– Jonah – 2019-06-02T01:29:13.937

1@Jonah thank you! – FrownyFrog – 2019-06-02T20:40:46.743

1

Wolfram Language (Mathematica), 43 29 28 bytes

Max@*Cases[{d_,1}->d]@*Tally

Try it online!

Roman

Posted 2017-06-28T08:09:22.013

Reputation: 1 190

Removed 14 bytes by skipping IntegerDigits: according to the comments, the function can be given a list of digits instead of a number. – Roman – 2019-06-05T10:27:16.940

Removed 1 byte by using the operator form of Cases. – Roman – 2019-06-08T12:34:55.597

0

Clojure, 52 bytes

#(last(sort(for[c % :when(=((frequencies %)c)1)]c)))

Input is a string, returns a char, or nil if all digits are repeated.

NikoNyrh

Posted 2017-06-28T08:09:22.013

Reputation: 2 361

0

Actually, 16 bytes

╗1╤rR⌠$╜c⌡M1@í9-

Try it online!

Leaky Nun

Posted 2017-06-28T08:09:22.013

Reputation: 45 011

0

C (gcc), 76 bytes

d[58],i;main(){while((i=getchar())>0)++d[i];for(i=58;--d[--i];);putchar(i);}

Try it online!

Felix Palmen

Posted 2017-06-28T08:09:22.013

Reputation: 3 866

Suggest d[58];main(i) instead of d[58],i;main(). Also, suggest (~(i=getchar())) instead of ((i=getchar())>0) – ceilingcat – 2018-08-21T01:02:18.170

0

PHP, 79 76 bytes

Try it online!

foreach(array_count_values(str_split($n))as$x=>$i){$h=($i==1&&$x>$h)?$x:$h;}

Use with $n = 495902; it will print 5.

Daniel W.

Posted 2017-06-28T08:09:22.013

Reputation: 121

0

PowerShell v3+, 58 bytes

$i|% ToCharA*|sort|group|? count -lt 2|select -l 1 -exp N*

Assumes $i contains a string of digits.

Try it online!

GAT

Posted 2017-06-28T08:09:22.013

Reputation: 11

0

F#, 67 bytes

let f s=Seq.countBy id s|>Seq.filter(snd>>(=)1)|>Seq.maxBy fst|>fst

Try it online!

Lars

Posted 2017-06-28T08:09:22.013

Reputation: 101

0

Kotlin, 53 Bytes

val f={a:String->a.filter{a.count{b->it==b}<2}.max()}

Declares a lambda, f that takes in a string; same algorithm as the python answer. it is the implicit iterator of a.filter, and b is the explicitly declared iterator of a.count (because we can't use it again).

Try it online!

Jeffmagma

Posted 2017-06-28T08:09:22.013

Reputation: 145

0

Pip, 11 bytes

MX:_Na=1FIa

Takes input as a command-line argument. Try it online!

Explanation

          a  1st cmdline arg
        FI   Filter digits by this function:
   _Na        Count of digit in a
      =1      equals 1 (i.e. keep only digits that appear exactly once)
MX:          Max of resulting list (using : to lower precedence)
             Autoprint (implicit)

DLosc

Posted 2017-06-28T08:09:22.013

Reputation: 21 213

0

CJam, 15 bytes

r$e`{0=1=},e~W=

Explanation:

r    e# Read token:          "2515"
$    e# Sort:                "1255"
e`   e# Run-length encode:   [[1 '1] [1 '2] [2 '5]]
{    e# Filter where:
 0=  e#   The first element: [1 1 2]
 1=  e#   Equals one:        [1 1 0]
},   e# End filter:          [[1 '1] [1 '2]]
e~   e# Run-length decode:   "12"
W=   e# Last digit:          '2

Esolanging Fruit

Posted 2017-06-28T08:09:22.013

Reputation: 13 542

0

jq, 47 characters

(43 characters code + 4 characters command line options)

[./""|group_by(.)[]|select(length<2)[]]|max

Sample run:

bash-4.4$ jq -Rr '[./""|group_by(.)[]|select(length<2)[]]|max' <<< 1948710498
7

bash-4.4$ jq -Rr '[./""|group_by(.)[]|select(length<2)[]]|max' <<< 999999
null

Try on jq‣play

manatwork

Posted 2017-06-28T08:09:22.013

Reputation: 17 865

0

Braingolf, 15 bytes

k&gG{!L1-?$_|}X

Try it online!

Takes input as a list of digits

Explanation

k&gG{!L1-?$_|}X  Implicit input from commandline args
k                Sort in descending numerical order
 &g              Combine into single integer
   G             Split into digit runs
    {........}   Foreach loop..
     !L1-?       ..If length of item is greater than 1..
          $_     ....Remove item
            |    ..Endif
              X  Select highest value
                 Implicit output

To help visualize it a little, here's a run through showing the stack with input 122355567679

k&gG{!L1-?$_|}X  [1,2,2,3,5,5,5,6,7,6,7,9]
k                [9,7,7,6,6,5,5,5,3,2,2,1]
 &g              [977665553221]
   G             [9,77,66,555,3,22,1]
    {!L1-?$_|}   [9,3,1]
              X  [9]

Skidsdev

Posted 2017-06-28T08:09:22.013

Reputation: 9 656

0

Ruby, 42 bytes

Same byte count as the other Ruby answer, but different approach.

->x{x.chars.group_by{|d|x.count d}[1].max}

Crashes when there are no unique digits.

Try it online!

daniero

Posted 2017-06-28T08:09:22.013

Reputation: 17 193

0

x86 Machine Code (32-bit, requires built-in FPU), 35 bytes

C8 10 00 00 D9 EE DD 14 24 DD 5C 24 08 8B 01 FE 04 04
83 C1 04 4A 75 F5 6A 0A 58 48 FE 0C 04 75 FA C9 C3

The above code defines a function in 32-bit x86 machine code that finds the unique highest digit in an array of integer values. (The question says we can take the input as a "list of digits", and assembly language is like C in that it lacks a built-in list/array type, but rather represents them as a pointer and length. Therefore, the function is prototyped in C as follows:

int __fastcall FindHighestUniqueDigit(const int * ptrDigits, int count);

As the prototype suggests, this function is written to follow Microsoft's fastcall calling convention, which passes arguments in registers. The first parameter (ptrDigits) is passed in ECX, and the second argument (count) is passed in EDX. The return value is, as always, returned in EAX.

Try it online!

Here are the ungolfed assembly mnemonics:

FindHighestUniqueDigit:
   enter  16, 0                  ; reserve 16 bytes of space on the stack for a table
   fldz                          ; load 0 in the first x87 FPU register (st0)
   fst    QWORD PTR [esp+0]      ; store value in st0 on the stack, at offset 0
   fstp   QWORD PTR [esp+8]      ; store value in st0 on the stack, at offset 0, and pop st0
ReadDigits:
   mov    eax, DWORD PTR [ecx]   ; read next digit from array
   add    ecx, 4                 ; increment pointer to reference next digit (ints are 4-bytes long)
   inc    BYTE PTR [esp + eax]   ; increment value in table for this digit
   dec    edx                    ; decrement counter (length of array)
   jne    ReadDigits             ; keep looping as long as there are more digits to read
   push   10
   pop    eax                    ; space-efficient way to put '10' in EAX so we start with highest digit
ProcessDigits:
   dec    eax                    ; decrement EAX
   dec    BYTE PTR [esp + eax]   ; decrement value in table for this digit
   jnz    ProcessDigits          ; if that table value is now zero, we found a match; otherwise, keep looping
   leave                         ; undo effects of ENTER instruction
   ret                           ; return, with result in EAX (digit ID)

I suppose the code requires a bit of explanation…

Basically, what we do is create a table in memory, with enough space to store a unique count for each of the 9 possible digits (0 through 9).

| esp+0 | esp+1 | esp+2 | esp+3 | esp+4 | esp+5 | esp+6 | esp+7 | esp+8 | esp+9 | unused |
|-------|-------|-------|-------|-------|-------|-------|-------|-------|-------|--------|
|   9   |   8   |   7   |   6   |   5   |   4   |   3   |   2   |   1   |   0   |   ??   |

The first ENTER instruction is responsible for allocating this space on the stack. We allocate 16 bytes because it's good practice to keep this a power of 2 for alignment purposes, 8 bytes isn't enough, and it doesn't hurt or cost anymore code bytes to allocate more than we need. The next three instructions are responsible for zeroing out all entries in this array. It's basically equivalent to memset in C, but shorter. We could have used the x86's REP STOSD string instruction, but that requires some setup (getting the right values in the right registers), and it turned out that (ab)using the x87 FPU to do 8-byte stores was shorter (required fewer bytes of code). All we do is load 0 at the top of the x87 FPU stack, which is pseudo-register st0. Then, we store that value across the first 8 bytes of the table, and finally, we store that value across the next 8 bytes of the table, popping it off of the x87 FPU stack at the same time.

The next section of the code is ReadDigits. This just iterates through the array of digits that we were passed, one digit at a time, and increments the unique counter for that digit in our table. You should be able to figure out exactly how this works by reading the comments for each of the instructions.

Finally, we come to the final phase, ProcessDigits. Actually, the PUSH+POP instructions right above this label are conceptually part of this phase, too. They just initialize EAX with 10 so that we'll start processing the table values for the highest possible digit, 9. Inside of the ProcessDigits loop, we eagerly decrement EAX, and then decrement the value in the table for the corresponding digit. If the resulting table value/counter is 0, then we've found our match, and we exit the loop. Otherwise, we keep looping and trying smaller digits. (Note that we could have done a comparison here—e.g., cmp BYTE PTR [esp + eax], 1+jnz—and in fact that's what we're logically doing, but the decrement was shorter to encode.)

Notice that if we never find a matching digit, then the code exhibits undefined behavior: it just keeps looping through memory, decrementing values and waiting until one is non-zero. When it finally finds one, it will terminate and return the ID, but the ID will be meaningless, and more importantly, it will have stomped all over the stack, decrementing values aimlessly!

The very last two instructions just clean up the stack (LEAVE) and return, with the return value (the highest unique digit that we found) left in EAX.

Cody Gray

Posted 2017-06-28T08:09:22.013

Reputation: 2 639

0

k, 12 bytes

|/@&:1=#:'=:

Example:

k)F:|/@&:1=#:'=:
k)F "1948710498"
"7"
k)F "99999"
"\000"
k)F "mississippi"
"m"

The translation to q as explanation

max where 1 = count each group@

Interpreter available here

skeevey

Posted 2017-06-28T08:09:22.013

Reputation: 4 139

0

J, 19 bytes

[:>./(".*1=#)/.~@":

Explanation:

": converts the number to a string
@ propagates the result (composes the verbs)
/.~ classifies items of the list into partitions of identical items
". * 1=# - fork of 3 verbs:
   1=# - 1 if the key is unique, else 0
   ". converts the keys back to digits
   * multiplies the key values by 1 or 0 depending on their uniqueness
>./ finds the max digit
[: caps the fork, since we have 2 verbs only for the key operator

Example:

   a=.123456547
     ": a
    123456547  NB. string
    </.~@": a
    ┌─┬─┬─┬──┬──┬─┬─┐
    │1│2│3│44│55│6│7│          NB. keys
    └─┴─┴─┴──┴──┴─┴─┘

(1=#)/.~@": a
1 1 1 0 0 1 1                  NB. mask for unique digits

(".*1=#)/.~@": a
1 2 3 0 0 6 7                  NB. digits multiplied by the mask, rendering
                                   duplicates to 0

([:>./(".*1=#)/.~@":) a        NB. finds the max nonrepeating digit
7

Try it online!

Galen Ivanov

Posted 2017-06-28T08:09:22.013

Reputation: 13 815

0

Perl 5 -pF, 36 bytes

$_=join'',sort@F;s/(.)\1+//g;$_=chop

Try it online!

Xcali

Posted 2017-06-28T08:09:22.013

Reputation: 7 671

0

Stax, 4 bytes

|!|M

Run and debug it

This program takes an array of digits. It works by calculating the maximum "anti-mode". I'm not sure if anti-mode is a real thing outside of stax, but it refers to the rarest element in list.

recursive

Posted 2017-06-28T08:09:22.013

Reputation: 8 616

0

dc, 48 bytes

[1+dd;a+r:az0<A]dsAx[d]sD1[dd;a=D1+dB>M]dsMxr1-p

Try it online!

Takes input as digits entered on the stack. I'm assuming this is a fair stand-in for a list of digits, since the justification for that was that folks were just dropping in boilerplate to turn an integer into a list of digits, and the task would be the same here (just... as a stack). Returns '10' on an entry w/ no unique digits.

Macro A builds an array a by taking each digit, loading the value in its own index (this will be 0 if thus far unassigned), adding itself, and storing this new value. We actually have to add 1 to every digit first so that 0 works correctly, and at the end we subtract 1 from our final result to make up for this. Ignoring that briefly for illustrative purposes, any index (let's call it n) of a will now have one of the following: 0 if n didn't exist as a digit in our original number, n itself if n was unique, or some multiple of n other than n*1 if n existed and was not unique.

In dc, conditionals either run a macro if true or do nothing if false, so you need a macro for them to do anything. [d]sD is a macro, D that simply duplicates a value.

A 1 goes on the stack to act as a counter of sorts, and then macro M runs. M really just takes this counter number, loads that index from a, compares it to itself, and duplicates itself (by running D) if they're equal. So, if they aren't equal (digit didn't exist or wasn't unique), we're simply left with one instance of our counter; if they are equal, we now have another copy of it on the stack. Increment, and keep on going 1-10. When this is done, we swap the top two values on the stack and subtract one as mentioned earlier.

brhfl

Posted 2017-06-28T08:09:22.013

Reputation: 1 291

0

Julia 1.0, 41 bytes

s->maximum(c for c=s if count(==(c),s)<2)

Try it online!

gggg

Posted 2017-06-28T08:09:22.013

Reputation: 1 715

-1

Python3 24 bytes

Input type: List
Output : Number which is the maximum.
Code:

print(max(set(input())))

Rahul Bharadwaj

Posted 2017-06-28T08:09:22.013

Reputation: 145

1This doesn't seem to work, as you are supposed to find the maximum digit which is unique, so 495902 would return 5, not 9. – Zacharý – 2017-11-16T13:09:29.067