Znajdź najwyższą unikalną cyfrę


33

Zaskakujące, że nie mieliśmy jeszcze prostego wyzwania „znajdź najwyższą cyfrę”, ale myślę, że to trochę zbyt trywialne.

Biorąc pod uwagę nieujemną liczbę całkowitą, zwróć najwyższą unikalną (tj. Nie powtórzoną) cyfrę znalezioną w liczbie całkowitej. Jeśli nie ma żadnych unikalnych cyfr, twój program może zrobić wszystko (niezdefiniowane zachowanie).

Dane wejściowe mogą być traktowane jako pojedyncza liczba całkowita, ciąg znaków lub lista cyfr.

Przypadki testowe

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

To jest więc wygrywa najmniej bajtów w każdym języku !


2
Czy zamiast tego możemy brać dane wejściowe jako ciąg?
Kritixi Lithos

3
Biorąc pod uwagę ostatni przypadek testowy, myślę, że jesteśmy zmuszeni przyjmować dane wejściowe jako ciąg ... (wiodących zer nie można przedstawić w liczbach całkowitych)
Leo

@Leo, który był moim złym, w zasadzie zmiksował liczby na mojej klawiaturze, nie zauważył wiodącego zera. Ale tak, dane wejściowe można traktować jako ciąg znaków
Skidsdev

25
@ Adám „niezdefiniowane zachowanie” ogólnie oznacza, że ​​możesz zrobić wszystko, łącznie z przywoływaniem bezimiennych okropności z pustki, jeśli to oszczędza bajty.
Martin Ender

22
@MartinEnder w rzeczywistości chętnie usunę 50% twoich bajtów, jeśli Twój kod pomyślnie przywoła cthulhu, ponieważ nie ma żadnych unikalnych cyfr;)
Skidsdev

Odpowiedzi:


16

05AB1E , 4 3 bajty

Zapisano 1 bajt dzięki panu Xcoderowi powiadamiającemu, że lista cyfr jest prawidłowym wprowadzeniem.

¢ÏM

Wypróbuj online!

Wyjaśnienie

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

Poczekaj więc w 05AB1E, 2nie jest prawdą; tylko 1? : o
HyperNeutrino

@HyperNeutrino: Poprawnie!
Emigna

2
To wydaje się zarówno bardzo przydatne, jak i bardzo uciążliwe ... To interesujące: o: D
HyperNeutrino

@HyperNeutrino: Często się przydaje, ale może być niekorzystne, gdy wyzwanie mówi, że zwraca prawdziwą wartość , gdy wiele języków może zwrócić dowolną dodatnią liczbę całkowitą lub nawet niepusty ciąg.
Emigna

Przekreślenie numeru nie jest łatwe do zauważenia!
MrZander

15

Python 3 , 40 bajtów

Oszczędność 2 bajtów dzięki movatica .

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

Wypróbuj online!

42 bajty

Działa zarówno z typem parametru Ciąg, jak i z listą cyfr. Zgłasza błąd w przypadku braku niepowtarzalnych cyfr, rodzaj nadużycia tej specyfikacji:

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

Wypróbuj online!


Wyjaśnienie

  • lambda i: - Deklaruje funkcję lambda za pomocą ciągu lub listy cyfr parametru i.
  • max(...) - Znajduje maksymalną wartość generatora.
  • x for x in i- Iteruje po znakach / cyfrach i.
  • if i.count(x)<2 - Sprawdza, czy cyfra jest unikalna.

40 bajtów:lambda i:max(x*(i.count(x)<2)for x in i)
movatica

1
@movatica Thanks!
Pan Xcoder

8

Alice , 15 bajtów

/&.sDo
\i-.tN@/

Wypróbuj online!

Wyjaśnienie

/...
\.../

Jest to prosta struktura dla kodu liniowego, która działa całkowicie w trybie porządkowym (co oznacza, że ​​ten program działa całkowicie poprzez przetwarzanie ciągów). Rozłożony kod liniowy jest wtedy po prostu:

i..DN&-sto@

Co to robi:

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.

-1, nie „ przywołuje bezimiennych horrorów z pustki ”, jeśli nie ma żadnych unikalnych cyfr. ;) (Przeczytaj: +1, jak zawsze świetna odpowiedź)
Kevin Cruijssen

1
@KevinCruijssen Próbowałem, ale nie oszczędzało bajtów. Może Dark może być bardziej odpowiednim językiem ...
Martin Ender


7

Węgiel drzewny , 18 12 bajtów

Fχ¿⁼№θIι¹PIι

Wypróbuj online! (Link do pełnej wersji)

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)


3
That's an interesting undefined behavior :)
Emigna

This sounds Finnish to me :D
fedorqui

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

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


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

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!


Nice! I didn't expect doing something with table would be shorter (plus I can never remember how to get names to work).
aPaulT

1
<2 for another byte. There should never be a zero in the counts.
MickyT

1
y=table(scan());max(names(y[y<2])) is a few bytes shorter.
JAD

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


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

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

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!


Welcome to PPCG! Looks like you've got everything down :)
Stephen

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

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.  

1
¬← could be more simply =1, same bytecount though :)
Leo

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

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&

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


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

Thanks! I think the 'duplicated' function doesn't count the first occurrence of a duplicate element so your version wouldn't quite work
aPaulT

ah, good point. I almost never use duplicated but I actually thought up another, shorter answer!
Giuseppe


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 .


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.


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

+1 just because it is bash
Anush


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


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

@CarlosAlejo Oops! Sorry! Just now read the specifications fully. Will edit the solution soon.
kakkarot

Edited. Are there any optimisations I can make?
kakkarot

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

@CarlosAlejo Thanks! Edited.
kakkarot

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


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.

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!


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

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

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!


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

@TwiNight Nice! Thank you.
Adám




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.



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.

Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.