Minimalna liczba wykluczona


14

To ma być łatwy do gry w golfa kodowego.

Mek (minimalna wykluczona liczba) skończonego zbioru liczb jest najmniejsza nieujemną liczbę całkowitą 0, 1, 2, 3, 4, ..., która jest nie pojawiają się w bazie. Innymi słowy, jest to minimum dopełnienia. Operacja mex ma kluczowe znaczenie dla analizy bezstronnych gier w kombinatorycznej teorii gier .

Twoim celem jest napisanie programu lub funkcji o nazwie, aby obliczyć mex przy użyciu jak najmniejszej liczby bajtów.

Wejście:

Lista liczb całkowitych nieujemnych w dowolnej kolejności. Może zawierać powtórzenia. Dla konkretności długość listy i dozwolony zakres elementów będą zawierać się między 0i 20włącznie.

Definicja „listy” tutaj jest elastyczna. Każda struktura reprezentująca zbiór liczb jest w porządku, o ile ma ustaloną kolejność elementów i umożliwia powtórzenia. Może nie zawierać żadnych informacji pomocniczych oprócz ich długości.

Dane wejściowe można traktować jako argument funkcji lub przez STDIN.

Wynik

Najmniejsza liczba wykluczona. Wydrukuj lub wydrukuj.

Przypadki testowe

[1]
0
[0]
1
[2, 0]
1
[3, 1, 0, 1, 3, 3]
2
[]
0
[1, 2, 3]
0
[5, 4, 1, 5, 4, 8, 2, 1, 5, 4, 0, 7, 7]
3
[3, 2, 1, 0]
4
[0, 0, 1, 1, 2, 2, 3]
4
[1, 0, 7, 6, 3, 11, 15, 1, 9, 2, 3, 1, 5, 2, 3, 4, 6, 8, 1, 18]
10

2
Ograniczenie liczb do ustalonego zakresu czyni ten problem jeszcze prostszym.
— Martin Ender

@ MartinBüttner Jeśli tablica zawiera wszystkie liczby 0do 20, poprawne dane wyjściowe to 21. Dodam przypadek testowy. Tak, ustalony zakres zdecydowanie ułatwia, choć nadal można z niego korzystać sys.maxintlub 2**64gdybym go nie określił.
— xnor

Nie ma potrzeby tego przypadku testowego. Powiedziałeś, że dane wejściowe mogą zawierać tylko 21 elementów.
— Martin Ender

@ MartinBüttner Prawo, słupek ogrodzeniowy. Dzięki.
— xnor

1
@KevinFegan Tak, maksymalna możliwa wydajność to 20. Mój komentarz się mylił i myślę, że MartinBüttner napisał na maszynie.
— xnor

Odpowiedzi:


11

Pyth , 6 bajtów

h-U21Q

Przykładowy przebieg

$ pyth -c h-U21Q <<< '[5, 4, 1, 5, 4, 8, 2, 1, 5, 4, 0, 7, 7]'
3

Jak to działa

  U21   range(21)
     Q  eval(input())
 -U21Q  setwisedifference(range(21), eval(input))          # Pyth function. Preserves order.
h-U21Q  setwisedifference(range(21), eval(input))[0]

Kiedy zestaw jest konwertowany na listę, czy zawsze jest posortowany?
— xnor

Różnica w ustawieniach Pytha zachowuje kolejność pierwszego argumentu ( range(21)), który jest uporządkowany. (Oznacza to również, że wyjaśnienie nie jest do końca dokładne. Pyth i Python 3 są dla mnie dość nowe).
— Dennis

1
Aby to wyjaśnić, -w Pyth jest w rzeczywistości filtrem - filtruje pierwszy argument na nieobecność z drugiego argumentu, a następnie konwertuje go do postaci pierwszego argumentu (ciąg, lista lub zestaw).
— isaacg

Ponadto, Dennis, powinno być h-U22Qtak, aby dawało poprawne wyjście 21 na wejściu zawierającym pełny dopuszczalny zakres.
— isaacg

@isaacg: Długość listy jest również ograniczona do 20, więc nie może zawierać wszystkich 21 liczb od 0 do 20.
— Dennis

6

CJam, 11 8 bajtów

K),l~^1<

Jak to działa:

K),         "Create an array with numbers 0 through 20"
   l~       "Read the input and eval it, resulting to an array"
     ^      "XOR the elements of two arrays, resulting in a complement array"
      1<    "Take the first element of the resultant array"

Przykładowe dane wejściowe:

[1 0 7 6 3 11 15 1 9 2 3 1 5 2 3 4 6 8 1 18]

Wynik:

10

Wypróbuj online tutaj


Jak wysokie są liczby jednoznakowe w CJam?
— xnor


Szczęśliwy wybór!
— xnor

5

J - 13 znaków

f=:0{i.@21&-.

Bardzo proste działania w J, a zatem bardzo trudne do zmniejszenia.

i.@21tworzy listę od 0 do 20 włącznie. -.wykonuje set-odejmuje dane wejściowe z tej listy. 0{bierze pierwszy element tego, co zostało, tj. najmniejszą liczbę. f=:definiuje nazwaną funkcję. W REPL:

   f=:0{(i.21)&-.
   f 1
0
   f 0
1
   f 2 0
1
   f 3 1 0 1 3 3
2
   f ''    NB. empty list
0
   f 1 2 3
0
   f 5 4 1 5 4 8 2 1 5 4 0 7 7
3
   f 3 2 1 0
4
   f 0 0 1 1 2 2 3
4
   f 1 0 7 6 3 11 15 1 9 2 3 1 5 2 3 4 6 8 1 18
10

Od czasu wydania J806 w listopadzie 2017 r. Istnieje nowa składnia, która oszczędza nam jeden bajt, pozwalając nam używać i.@21starego (i.21)w tym kontekście.


Czy trzeba f=:?
— Esolanging Fruit

Od listopada 2017 r. i.@21-.]Zaoszczędzi 1 bajt.
— FrownyFrog,

4

Golfscript 7

~21,^0=

Dalsza gra w golfa w odpowiedzi Petera Taylora. Wiki społeczności, ponieważ nie mam przedstawiciela, który mógłby komentować jego post.

Różnica polega na użyciu znanego maksymalnego rozmiaru listy z pytania zamiast długości +1, aby zapisać znak i upuszczając nieistotne $.

Wypróbuj online


1
Dammit Golfscript za zapisanie 1 znaku, aby nie czytać wejścia -_-
— Optimizer

4

Burleska - 9 bajtów

20rzj\\<]

Pobiera dane wejściowe ze standardowego wejścia w formacie {7 6 5 5 1 2 2 4 2 0}

Wyjaśniono:

 20 rz   map a range from 0 to 20. (thanks to algorithmshark for the cocde fix)
  j \\    swaps the two arrays, and collects the difference between the two into a new array
  <]      gets the smallest element of the resulting array.

Wypróbuj kilka przykładów:

{1 0 7 6 3 11 15 1 9 2 3 1 5 2 3 4 6 8 1 18} 20rzj \\ <]

{5 4 1 5 4 8 2 1 5 4 0 7 7} 20rzj \\ <]


1
Nie daje to żadnego wyniku na wejściu {0 1 2}, ponieważ potrzebujesz rzjednego o więcej niż największej liczby. Po prostu idę prosto, aby 20rzj\\<]to naprawić i oszczędza znak.
— algorytmshark

@ algorytmshark Nie ma mowy, masz rację. Naprawiony. I dziękuję.
— AndoDaan

3

Bash + coreutils, 23 bajty

seq 0 20|egrep -vwm1 $1

Zakłada to wejście jako |listę oddzieloną (potokiem). Na przykład:

$ ./mex.sh "5|4|1|5|4|8|2|1|5|4|0|7|7"
3
$

1
Nie sądzę, że potrzebujesz "(...)"wokół $1.
— Dennis

1
Rozdzielanie rur jest w porządku, spełnia specyfikację podobną do listy.
— xnor

2

Rubinowy, 32 bajty

f=->n{(0..20).find{|i|n-[i]==n}}

Definiuje funkcję, fktóra ma być wywoływana za pomocą tablicy.


Wszelkie uwagi od downvoter? Czy przegapiłem jakąś część specyfikacji?
— Martin Ender

Wątpię. Kilka innych odpowiedzi (w tym moja) otrzymało tajemniczą opinię.
— Greg Hewgill

@ipi, ale robi ... w dokładnie takim samym formacie, jaki podano w przykładach w postach z wyzwaniami, np. f[[0, 1]](gdzie nawiasy zewnętrzne to składnia wywołania, a nawiasy wewnętrzne definiują tablicę).
— Martin Ender

Dlaczego potrzebne f=?
— Esolanging Fruit

2

GolfScript ( 10 9 bajtów)

~.,),^$0=

Pobiera dane wejściowe ze standardowego wejścia w formacie [5 4 1 5 4 8 2 1 5 4 0 7 7].

Demo online


Czy ;łańcuch wejściowy nie powinien być liczony w samym programie?
— Optymalizator

1
@Optimizer, to symulacja danych wejściowych ze standardowego wejścia, ponieważ internetowa strona GolfScript nie obsługuje osobnego pola wejściowego.
— Peter Taylor

2

Xojo, 55 bajtów

dim x as int8
while a.indexOf(x)>-1
x=x+1
wend
return x

2

Ruby, 22 lata

x=->n{([*0..20]-n)[0]}

Wyjaśnienie

  • Dane wejściowe są traktowane jako argument dla lambda. To oczekuje Arrayod Integers.
  • Dane wejściowe są odejmowane od tablicy [0,1,2..20].
  • Ponieważ Array [0,1,2..20]jest posortowany, pierwszym elementem musi być mex.

Sweet, that was my first attempt, but I couldn't get the destructuring to work - I didn't think of surrounding it with brackets. Btw, you can use 20 instead of 21, because the input can only contain 20 elements.
— Martin Ender

2

Haskell, 30

f s=filter(`notElem`s)[0..]!!0

This works for lists of all size and lists beyond 20. This can be made 15 bytes long if Data.List is imported:

f s=[0..]\\s!!0

2

Scheme - 219

(define (A X) (define (B X) (if (equal? (length X) 1) (+ (car X) 1) (if (< (- (cadr X) (car X)) 2) (B (cdr X)) (+ (car X) 1)))) (if (empty? X) `() (if (equal? (car (sort X <)) 0) (B (sort X <)) (- (car (sort X <)) 1))))

Not very competitive. But I like writing scheme :),

Here's the ungolfed code:

(define (minExclude X)
  (define (firstNonOneDifference X)
     (if (equal? (length X) 1)
         (+ (car X) 1)
     (if (< (- (cadr X) (car X)) 2) 
         (firstNonOneDifference (cdr X))
         (+ (car X) 1)
     ))
  )
  (let ([s (sort X <)])
     (if (empty? X)
         `()
     (if (equal? (car s) 0)
        (firstNonOneDifference s)
        (- (car s) 1)
     ))
  )
)

1

Python, 37 characters

f=lambda a:min(set(range(21))-set(a))

Beat me by a couple of seconds. BTW, it's range(21).
— qwr

This seems to be the shortest solution. The recursive solution f=lambda l,i=0:i in l and f(l,i+1)or i is one char longer and the iterative solution i=0;l=input()\nwhile i in l:i+=1\nprint i is two chars longer (not storing the input makes it be taken repeatedly). Without the 20 bound, I think these approaches would prevail.
— xnor

Couldn't this be an anonymous function? If it could, you can save 2 bytes.
— Mega Man

1

C# - 64 chars

int f(int[] a){return Enumerable.Range(0,20).Except(a).First();}

Not always Rarely the best golfing language, but is easy to write and understand :)


1

Scala, 18 bytes

0 to 20 diff l min

l is a list of Int.

scala> val l = List(0,1,5)
l: List[Int] = List(0, 1, 5)

scala> 0 to 20 diff l min
res0: Int = 2


1

Java 7, 69 66 bytes

int c(java.util.List a){int r=0;for(;a.contains(r);r++);return r;}

-3 bytes thanks to @LeakyNun

Explanation:

Supports not only 0-20, but 0-2147483647 instead (which actually saves bytes).

int c(java.util.List a){    // Method with List parameter and integer return-type
  int r=0;                  //  Return integer
  for(;a.contains(r);r++);  //  Continue raising `r` as long as the list contains the current `r`
  return r;                 //  Return result-integer
}                           // End of method

Test code:

Try it here.

import java.util.ArrayList;
import java.util.Arrays;
class M{
  static int c(java.util.List a){int r=0;for(;a.contains(r);r++);return r;}

  public static void main(String[] a){
    System.out.println(c(Arrays.asList(1)));
    System.out.println(c(Arrays.asList(0)));
    System.out.println(c(Arrays.asList(2, 0)));
    System.out.println(c(Arrays.asList(3, 1, 0, 1, 3, 3)));
    System.out.println(c(new ArrayList()));
    System.out.println(c(Arrays.asList(1, 2, 3)));
    System.out.println(c(Arrays.asList(5, 4, 1, 5, 4, 8, 2, 1, 5, 4, 0, 7, 7)));
    System.out.println(c(Arrays.asList(3, 2, 1, 0)));
    System.out.println(c(Arrays.asList(0, 0, 1, 1, 2, 2, 3)));
    System.out.println(c(Arrays.asList(1, 0, 7, 6, 3, 11, 15, 1, 9, 2, 3, 1, 5, 2, 3, 4, 6, 8, 1, 18)));
  }
}

Output:

0
1
1
2
0
0
3
4
4
10




1

TI-BASIC, 24 bytes

:0→A                 //Store 0 to A
:Prompt X            //Prompt list X
:While not(prod(ʟX-A //While A is not missing from list X
:A+1→A               //Increment A
:End                 //End While loop
:A                   //Print A

If Prompt X is given a list instead of a single number, it will automatically create a list named X that can be accessed with ʟX.


20 bytes using Ans: Prompt X:0:While not(prod(ʟX-Ans:Ans+1:End:Ans
— JosiahRyanW

1

Stax, 6 bytes

¢╔⌂♀╠▬

Run and debug it

Explanation

21r:IUI             # Full program, unpacked
21                  # Push 21
  r                 # Range from 0...20
   :I               # Find all elements in input that exist in range
    U               # push -1
     I              # Get index of first occurrence of


1

Jelly, 7 bytes

Another approach. Can be used in a chain with any arity, and doesn't need chain separator or anything.

‘Ṭ;0i0’

Because the answer is guaranteed to be less than 256, this also works:

Jelly, 5 bytes

⁹ḶḟµḢ

Try it online!


1

Powershell, 28 bytes

for(;+$i-in$args){$i++}+$i

Test script:

$f = {
 for(;+$i-in$args){$i++}+$i
#for(;$i++-in$args){}(--$i)   # alternative version
}

@(
    ,(0 , 1)
    ,(1 , 0)
    ,(2 , 3, 1, 0, 1, 3, 3)
    ,(0 )
    ,(0 , 1, 2, 3)
    ,(3 , 5, 4, 1, 5, 4, 8, 2, 1, 5, 4, 0, 7, 7)
    ,(4 , 3, 2, 1, 0)
    ,(4 , 0, 0, 1, 1, 2, 2, 3)
    ,(10, 1, 0, 7, 6, 3, 11, 15, 1, 9, 2, 3, 1, 5, 2, 3, 4, 6, 8, 1, 18)
) | % {
    $e, $a = $_
    $r = &$f @a
    "$($r-eq$e): $r"
}

Output:

True: 0
True: 1
True: 2
True: 0
True: 0
True: 3
True: 4
True: 4
True: 10

Explanation:

  • Increment $i while the $args array contains the integer value +$i.
  • Output a last integer value +$i.

1

MathGolf, 5 4 bytes

Jr,╓

Try it online!

This solution is restricted to just the range 0 to 20, though this can be extended easily by increasing the initial range.

Explanation:

Jr     Range from 0 to 20
  ,    Remove elements from the input list from this range
   ╓   Return the minimum element

Alternatively, a 5 byte solution for all numbers:

Åï╧▲ï

Try it online!

Explanation:

Å  ▲   Do while true
  ╧    Does the input contain
 ï     The index of the loop?
    ï  Push the number of iterations of the last loop

With the new changes that are (hopefully) being added to TIO today, there's a 4 byte solution to this problem. It is restricted to an upper limit defined in the code, but since MathGolf has a 1-byte literal for 10^8, it shouldn't be noticeable.
— maxb

This was the exact solution I had (I used Z instead of J because I was lazy).
— maxb

0

Perl - 34

Here's a subroutine.

sub f{$_~~@_?1:return$_ for0..20}

Test with:

perl -e'print f(0,1,3,4,5,6,7); sub f{$_~~@_?1:return$_ for 0..20}'

0

Java, 93

int f(int[]a){int i=0,j=0,k=a.length;for(;i++<20&j<k;){for(j=0;j<k&&a[j++]!=i;);}return i-1;}

Ungolfed:

int f(int[] a) {
    int i = 0, j = 0, length = a.length;
    for (; i < 20 & j < length; i++) {
        for (j = 0; j < length && a[j] != i; j++) { }
    }
    return i - 1;
}

Produces -1 for test case [].
— OldCurmudgeon


0

Javascript, 74

i=-1;a=prompt().split(',');while(i<21&&a.indexOf(String(++i))>=0);alert(i)

Nice and simple! Note the empty while loop.


0

JavaScript (E6) 35

Recursive function, array parameter in input and returning the mex. Not limited to 20

F=(l,i=0)=>~l.indexOf(i)?F(l,++i):i

Test in FireFox/FireBug console

;[[1],[0],[2, 0],[3, 1, 0, 1, 3, 3],[],[1, 2, 3],
[5, 4, 1, 5, 4, 8, 2, 1, 5, 4, 0, 7, 7],[3, 2, 1, 0],[0, 0, 1, 1, 2, 2, 3],
[1, 0, 7, 6, 3, 11, 15, 1, 9, 2, 3, 1, 5, 2, 3, 4, 6, 8, 1, 18]]
.forEach(list => console.log(list, F(list)))

Output

[1] 0
[0] 1
[2, 0] 1
[3, 1, 0, 1, 3, 3] 2
[] 0
[1, 2, 3] 0
[5, 4, 1, 5, 4, 8, 2, 1, 5, 4, 0, 7, 7] 3
[3, 2, 1, 0] 4
[0, 0, 1, 1, 2, 2, 3] 4
[1, 0, 7, 6, 3, 11, 15, 1, 9, 2, 3, 1, 5, 2, 3, 4, 6, 8, 1, 18] 10

0

PHP, 38 Bytes

<?=min(array_diff(range(0,20),$_GET));

PHP, 39 Bytes

<?for(;in_array($i++,$_GET););echo$i-1;
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.