Informatik II (D-BAUG) - Pr ufung - ETH Zürich

Die Seite wird erstellt Kimi Zander
 
WEITER LESEN
Prüfung
                                         Informatik II (D-BAUG)
                          Felix Friedrich, Hermann Lehner, Departement Informatik
                                                  ETH Zürich, 27.1.2020.

 Name, Vorname:              ..................................................................

 Legi-Nummer:                ..................................................................

Ich bestätige mit meiner Unterschrift, dass ich                       I confirm with my signature that I was able
diese Prüfung unter regulären Bedingungen                            to take this exam under regular conditions
ablegen konnte und dass ich die allgemeinen                            and that I have read and understood the
Richtlinien gelesen und verstanden habe.                               general guidelines.

 Unterschrift:

Allgemeine Richtlinien:                                                General guidelines:

    1. Dauer der Prüfung: 60 Minuten.                                    Exam duration: 60 minutes.

    2. Erlaubte Unterlagen: Wörterbuch (für von Ihnen gesproche-        Permitted examination aids: dictionary (for languages
       ne Sprachen). 4 A4 Seiten handgeschrieben oder ≥ 11pt              spoken by yourself). 4 A4 pages hand written or ≥ 11pt
       Schriftgrösse.                                                    font size.
    3. Benützen Sie einen Kugelschreiber (blau oder schwarz) und         Use a pen (black or blue), not a pencil. Please write
       keinen Bleistift. Bitte schreiben Sie leserlich. Nur lesbare       legibly. We will only consider solutions that we can
       Resultate werden bewertet.                                         read.
    4. Lösungen sind direkt auf das Aufgabenblatt in die dafür          Solutions must be written directly onto the exam
       vorgesehenen Boxen zu schreiben (und direkt darunter, falls        sheets in the provided boxes (and directly below, if
       mehr Platz benötigt wird). Ungültige Lösungen sind deut-        more space is needed). Invalid solutions need to be
       lich durchzustreichen! Korrekturen bei Multiple-Choice Auf-        crossed out clearly. Provide corrections to answers of
       gaben bitte unmissverständlich anbringen!                         multiple choice questions without any ambiguity!
    5. Es gibt keine Negativpunkte für falsche Antworten.                There are no negative points for wrong answers.

    6. Störungen durch irgendjemanden oder irgendetwas melden            If you feel disturbed by anyone or anything, let the
       Sie bitte sofort der Aufsichtsperson.                              supervisor of the exam know immediately.
    7. Wir sammeln die Prüfung zum Schluss ein. Wichtig: Stel-           We collect the exams at the end. Important: You must
       len Sie unbedingt selbst sicher, dass Ihre Prüfung von einem      ensure that your exam has been collected by an as-
       Assistenten eingezogen wird. Stecken Sie keine Prüfung ein        sistant. Do not take any exam with you and do not
       und lassen Sie Ihre Prüfung nicht einfach am Platz liegen.        leave your exam behind on your desk. The same app-
       Dasselbe gilt, wenn Sie früher abgeben wollen: Bitte mel-         lies when you want to finish early: Please contact us
       den Sie sich lautlos, und wir holen die Prüfung ab. Vor-          silently and we will collect the exam. Handing in your
       zeitige Abgaben sind nur bis 15 Minuten vor Prüfungsende          exam ahead of time is only possible until 15 minutes
       möglich.                                                          before the exam ends.
    8. Wenn Sie zur Toilette müssen, melden Sie dies einer Auf-          If you need to go to the toilet, raise your hand and
       sichtsperson durch Handzeichen.                                    wait for a supervisor.
    9. Wir beantworten keine inhaltlichen Fragen während der             We will not answer any content-related questions du-
       Prüfung. Kommentare zur Aufgabe schreiben Sie bitte auf           ring the exam. Please write comments referring to the
       das Aufgabenblatt.                                                 tasks on the exam sheets.

                           Question:          1         2          3        4         5       Total
                           Points:           19        10          8       12        11        60
                           Score:
Informatik II                                2/14                          Prüfung 27.1.2020

        Generelle Anmerkung / General Remark
        Verwenden Sie die Notation, Algorithmen und         Use notation, algorithms and data structu-
        Datenstrukturen aus der Vorlesung. Falls Sie        res from the course. If you use a different
        eine andere Herangehensweise wählen, er-           approach, explain your answers in a com-
        klären Sie Ihre Antworten in nachvollziehbarer     prehensible way!
        Weise!
        Aufgabe 1: Verschiedenes (19P)
       In dieser Aufgabe sollen nur Ergebnisse ange-        In this task only results have to be provi-
       geben werden. Begründungen sind nicht not-          ded. Explanations are not required.
       wendig.
/6P (a) Kreuzen Sie an, ob die folgenden Aussagen            Mark if the following statements are true
          wahr oder falsch sind.                             or false.

           Eine Inorder-Traversierung eines binären Suchbaumes erzeugt eine             Wahr / True
           sortierte Liste der gespeicherten Schlüssel. / An in-order traversal
           of a binary search tree generates a sorted list of the stored keys.           Falsch / False

           Hat eine Folge von m Operationen im schlimmsten Fall Gesamtko-
           sten O(m), dann hat jede einzelne der Operationen im schlimmsten              Wahr / True
           Fall Kosten O(1). / If a sequence of m operations has overal worst
           case costs of O(m), then every single of the operations has worst             Falsch / False
           cases costs of O(1)

           Jeder vergleichbasierte Sortieralgorithmus kann zu einem stabilen
           Sortieralgorithmus gemacht werden mit asymptotisch, bis auf einen             Wahr / True
           konstanten Faktor, unveränderter Laufzeit. / Any comparison based
           sorting algorithm can be made to be stable, without affecting the             Falsch / False
           asymptotic running time by more than a constant factor.

           Sei G = (V, E) ein Graph. Jeder Teilgraph von G mit |V |−1 Kanten             Wahr / True
           ist ein Spannbaum von G. / Let G = (V, E) be a graph. Every
           subgraph of G with |V | − 1 edges is a spanning tree ot G.                    Falsch / False

           In einem Max-Heap mit n Schlüsseln ist die Laufzeit zur Extraktion
           des Minimums im schlechtesten Fall O(log n). / In a Max-Heap                  Wahr / True
           with n keys the worst-case running time to extract the minimum is             Falsch / False
           O(log n).

           In einem AVL-Baum dürfen sich die Anzahlen der Knoten im linken
           und im rechten Teilbaum maximal um 1 unterscheiden. / In an                   Wahr / True
           AVL-Tree the number of nodes in the left and right subtree must               Falsch / False
           not differ by more than 1.
Informatik II                                  3/14                           Prüfung 27.1.2020

(b)   Führen Sie auf dem folgenden Array                 On the following array, perform a par-     /2P
      einen Aufteilungsschritt des Sortieralgorith-       titioning step of the sorting algorithm
      mus Quicksort durch. Benutzen Sie als Pivot         Quicksort. As pivot, use the element 5.
      das Element 5.

                     3     8    10    11     9        5   7     8     2     6      4
                     0     1     2     3     4        5   6     7     8     9     10

                     0     1     2     3     4        5   6     7     8     9     10

(c)   Gegeben sei die folgende Schlüsselmenge:           Let the following set of keys be given:    /2P

                                       K = {5, 9, 11, 15, 7, 20}

      Zeichnen Sie die beiden binären Suchbäume,        Draw the two binary search trees that
      die genau die Schlüssel aus K verwalten und        contain the keys from K and that pro-
      die unter allen möglichen Suchbäumen mini-        vide minimal / maximal height.
      male bzw. maximale Höhe haben.

      Minimal:                                    Maximal:
Informatik II                                    4/14                           Prüfung 27.1.2020

/2P (d)   Fügen Sie die folgenden Schlüssel (in der an-       Enter the following keys (in the order
          gegebenen Reihenfolge) in die Hashtabelle             provided) into the hash-table. Use open
          ein. Verwenden Sie offene Addressierung und           addressing and linear probing. The used
          lineares Sondieren. Die verwendete Hash-              hash function h(k) is provided below (va-
          Funktion h(k) ist nachfolgend angegeben (es           lues are added, i.e. probing runs to the
          wird addiert, also nach rechts sondiert).             right).

          Hashfunktion / hash function : h(k) = k mod 11

          Schlüssel / keys : 2,13,24,40

                         0      1     2     3      4        5   6     7     8     9     10

          Wie viele Kollisionen treten bei der nach-            How many collisions occur when key
          folgenden (erfolglosen) Suche nach dem                100 is searched now (unsuccessfully)?
          Schlüssel 100 auf? (Gezählt werden nur Kol-         (We only count collisions with occupied
          lisionen mit belegten Plätzen)                       spaces)
Informatik II                                            5/14                                       Prüfung 27.1.2020

(e)   Fügen Sie in folgendem AVL Baum den                           In the following AVL tree, insert key 55              /2P
      Schlüssel 55 ein und rebalancieren Sie. Wie                   and rebalance. What does the AVL tree
      sieht der AVL Baum nach dem in der Vor-                        look like according to the algorithms that
      lesung gezeigten Algorithmus aus? Kreuzen                      has been shown in class? Mark the cor-
      Sie die richtige Antwort an.                                   rect answer.

                                                               30

                                                     10                  50

                                                3         17                      60

                                            1         14 19

                             30                                                                  30

                   10                  50                                              10                   50

               3        17                      60                                3         17                   55

           1        14 19               55                                    1            14 19                  60

                             30                                                                  30

                   10                  50                                              10                   55

               3        17        55            60                                3         17         50        60

           1        14 19                                                     1            14 19

                                                               19

                                                     10                  50

                                                3         14        30            55

                                            1              17                         60
Informatik II                                                6/14                                Prüfung 27.1.2020

/5P (f)     Gegeben ist das folgende Flussnetzwerk mit                              Provided in the following is a flow net-
            Quelle s und Senke t. Die einzelnen Kapa-                               work with source s and sink t. Capacities
            zitäten ci und Flüsse φi sind an den Kanten                           ci and flows φi are provided at the ed-
            angegeben als ci |φi . Ergänzen Sie die feh-                           ges as ci |φi . Complete the missing flow
            lenden Flusswerte auf den Kanten, so dass φ                             values at the edges such that the overal
            ein gültiger Fluss ist. Dieser wird (in diesem                         flow φ is a valid flow. This will be maxi-
            Beispiel) in jedem Falle maximal sein. Geben                            mal (in this example) in all cases. Provide
            Sie den Wert des Flusses f an. Zeichnen Sie                             the value of the flow f . Draw into the fi-
            in der Abbildung einen Schnitt ein, der zeigt,                          gure a cut that shows that φ is indeed
            dass φ maximal ist.                                                     maximal.

                                                 4|
                                    a                                                d
                                                                                               5|
                      4|4                         8|6
                                                                              7|5

                 s          4|                               c                                        t

                                           3|3                                4|4
                      9|6                                                                      8|7

                                    b                                                e
                                                        3|
                                                                                                          f=

          Aufgabe 2: Asymptotik (10P)
/3P (a)     Geben Sie für die untenstehenden Funktio-                              Provide an order for the functions be-
            nen eine Reihenfolge an, so dass folgendes                              low such that the following holds: If a
            gilt: Wenn eine Funktion f links von einer                              function f is left of a function g then it
            Funktion g steht, dann gilt f ∈ O(g).                                   holds that f ∈ O(g). Example: the func-
            Beispiel: die drei Funktionen n3 , n5 und n7                            tions n3 , n5 and n7 are already in the
            sind bereits in der richtigen Reihenfolge, da                           correct order because n3 ∈ O(n5 ) and
            n3 ∈ O(n5 ) und n5 ∈ O(n7 ).                                            n5 ∈ O(n7 ).

                                   n2            n                Xn
                                                                 log
                                                                                              √
                                                                       2i ,    n log nn ,             n log n2 ,
                                                 X
                                       ,    n          i,    n                               n n,
                                 log n           i=0             i=0
Informatik II                                 7/14                              Prüfung 27.1.2020

      In den folgenden Aufgabenteilen wird jeweils     In the following parts of this task we assu-
      angenommen, dass die Funktion g mit g(n)         me that the function g is called as g(n).
      aufgerufen wird. Geben Sie jeweils die asym-     Fill in the asymptotic number of calls of
      ptotische Anzahl von Aufrufen der Funkti-        f () depending on n ∈ N using Θ notati-
      on f () in Abhängigkeit von n ∈ N mit Θ-        on as succinct as possible. The function
      Notation möglichst knapp an. Die Funktion       f does not call itself. You do not have to
      f ruft sich nicht selbst auf. Sie müssen Ihre   justify your answers.
      Antworten nicht begründen.

(b)                                                                                                         /2P

      void g(int n){
          for (double i = 1; i < n; i*=3){                    Anzahl Aufrufe von f / Number of calls of f
              f();
              i /= 2;
          }
      }

(c)                                                                                                         /2P

      void g(int n){
          if (n > 0){                                         Anzahl Aufrufe von f / Number of calls of f
              g(n-1);
          }
          f();
      }

(d)                                                                                                         /3P

      void g(int n){
          if (n>0){
              f();
              g(n/2);                                         Anzahl Aufrufe von f / Number of calls of f
              f();
              g(n/2);
          } else {
              f();
          }
      }
Informatik II                             8/14                         Prüfung 27.1.2020

          Aufgabe 3: Python (8P)
/8P (a)     Schreiben Sie eine Funktion, die zu einer      Write a function that for a given list of
            gegebenen Liste von Worten ein Dictionary      words returns a dictionary containing the
            zurückgibt, welches die Zuordnung der Wor-    mapping from words to frequency of the
            te zu ihren Häufigkeiten enthält.            words.
            Anwendungsbeispiel:                            Application example:

             Eingabe / Input                                   Ausgabe / Output
             words = ["a","cat","is","a","cat"]                a : 2
             count = word_count(words)                         is : 1
             for name in count:                                cat : 2
                 print name,":",count[name]

             def word_count(word_list):
Informatik II                                 9/14                            Prüfung 27.1.2020

  Aufgabe 4: Rekursion / Dynamische Programmierung (12P)
  Es sei ein Stab der Länge n ∈ N gegeben.            Consider a rod (stick) of length n ∈ N.
  Ausserdem sei ein Array p von k ∈ N ver-             Let an array of k ∈ N different lengths
  schiedenen Längen pi ∈ N (0 ≤ i < k) gege-          pi ∈ N, 0 ≤ i < k be given. Goal is to
  ben. Ziel ist, den Stab in möglichst viele (N )     cut the rod into as many pieces (N ) as
  Stücke zu zersägen. Dabei muss allerdings je-      possible. Each piece length must be of one
  des Stück eine der gegebenen Längen aus p          of the given lengths of p. No piece may be
  aufweisen. Es darf kein Stück übrig bleiben.       left over
  Beispiel:                                            Example:

                         n = 5, k = (2, 3, 5) ⇒ N = 2 (5 = 2 + 3),
                         n = 7, k = (2, 3, 5) ⇒ N = 3 (7 = 2 + 2 + 3)

(a)   Aufgabe: Vervollständigen Sie die folgende    Task: complement the following recursi-    /2P
      rekursive Funktion so, dass sie die maxima-    ve function such that it returns the maxi-
      le Anzahl Stücke zurückgibt. Wenn der Stab   mum number of pieces. If the stick can-
      nicht ohne Rest zerteilbar ist, muss die Funk- not be divided without rest, the function
      tion −1 zurückgeben.                          must return 0.
      // return the maximum number of pieces to cut n with pieces of lengths from p
      // if no possibility to cut without rest, -1 is returned
      public static int solve(int n, int[] p){
         if (n
Informatik II                                  10/14                                 Prüfung 27.1.2020

/3P (b)   Sie stellen fest, dass Ihre Funktion für gros-           You realize that your function takes a lot
          se n sehr lange benötigt. Skizzieren Sie den             of time for large n. Sketch the recursion
          Rekursionsbaum (einen Teil davon, etwa drei               tree (a part of it, about 3 levels) for k =
          Ebenen) für k = 3. Geben Sie die asympto-                3. Provide the asymptotic running time
          tische Laufzeit des rekursiven Algorithmus in             of the recursive algorithm as a function
          Abhängigkeit von n und k an.                             of n and k.

                                                            n

          Asymptotische Laufzeit / Asymptotic running time:

/2P (c)   Überlegen Sie sich die Abhängigkeiten Ihres             Now think about the dependencies of
          Problems. Zeichnen Sie in folgender kleinen               your problem. Draw into the following
          Skizze (für n = 7, p = (2, 3)), die Abhängig-           small sketch (for n = 7, p = (2, 3)) the
          keiten ein. Sie zeigen damit dass es keine zir-           dependencies. Doing so, you show that
          kulären Abhängigkeiten gibt.                            there are no circular dependencies.

           7            6           5           4               3             2            1           0
Informatik II                             11/14                       Prüfung 27.1.2020

(d)   Vervollständigen Sie nun die folgende (nicht- Now complement the following (non-       /3P
      rekursive) Funktion so, dass sie das gegebene  recursive) function such that the given
      Problem effizient löst.                       problem is solved in an efficient way.
      Tipp: verwenden Sie die Abhängigkeiten, die   Hint: use the dependencies that you have
      Sie sich soeben überlegt haben für die Be-   just developed in order to compute the
      rechnung der DP-Tabelle.                       DP-table.
      // return the maximum number of pieces to cut n with pieces of lengths from p
      // if no possibility to cut without rest, -1 is returned
      public static int solve(int n, int[] p){
        int[] solution = new int[n+1];
        solution[0] = 0;
        for (int i = 1; i
Informatik II                               12/14                           Prüfung 27.1.2020

          Aufgabe 5: Algorithmen (11P)
/1P (a)     Um einen kürzesten Pfade Algorithmus auf          In order to implement a shortest path al-
            einem ungewichteten Graphen mit einer              gorithm on an unweighted graph with an
            asymptotischen Laufzeit zu implementieren,         asymptotic runtime that is linear in num-
            welche linear in Anzahl Knoten und Anzahl          ber of nodes and number of egdes, which
            Kanten ist, verwendet man im Algorithmus           data structure is used for the algorithm?
            welche Datenstruktur?
                      Warteschlange/Queue
                      Stapel/Stack
                      Heap/Heap
                      AVL Baum/AVL Tree

/1P (b)     Was ist die asymptotische Laufzeit des             What is the asymptotic runtime of the
            Bellman-Ford-Algorithmus      auf    einem         Bellman-Ford algorithm on a complete
            vollständigen Graphen mit n Knoten?               graph with n nodes?

                      Θ(n2 )
                      Θ(n log n)
                      Θ(n3 )
                      Θ(n4 )

/1P (c)     Angenommen wir haben einen korrekt imple-          Assume you have a correctly implemen-
            mentierten Kürzeste-Pfade Algorithmus auf         ted shortest-path algorithm on a graph
            einem Graphen mit ganzzahligen Kantenge-           with integer edge weights. If we add 1
            wichten. Wenn wir zu jeder Kante den Wert          to each edge, obviously all path lengths
            1 hinzuaddieren ändern sich offensichtlich        change. But does the algorithm always
            die Pfadlängen. Aber findet der Algorithmus       find the same shortest paths?
            stets dieselben kürzesten Pfade?
                      Ja, bei allen Graphen / Yes, with all graphs
                      Ja, bei allen positiv gewichteten Graphen / Yes, with all positively weighted graphs
                      Nein / No
Informatik II                                       13/14                                Prüfung 27.1.2020

(d)   Betrachten Sie folgenden gerichteten Graph.                 Consider the following directed graph.        /2P
      Geben Sie die Knoten in der Reihenfolge an,                 Provide the nodes in the order in which
      in der sie der Dijkstra-Algorithmus besuchen                the Dijkstra algorithm visits them when
      würde, wenn er vom Knoten A aus star-                      it starts from node A. To each node pro-
      tet. Geben Sie zu jedem Knoten die kürzeste                vide the shortest path length from A.
      Pfadlänge von A aus an.

                                          1                            7
                                 B                            E                G
                                      3                                    2
                             1                        2

                             A                                D                I       2
                                              2                    2
                                 8                        6                        1
                                                  3                    4
                                      C                       F                H

                                 Knoten / Node                Distanz / Distance

                                 A                            0
Informatik II                                     14/14                          Prüfung 27.1.2020

/3P (e)   Betrachten Sie folgende Adjazenzmatrix,                Consider the following adjacency matrix
          welche zu einem ungerichteten Graphen mit              that corresponds to an undirected graph
          vier Knoten gehört. Skizzieren Sie zuerst den         with four nodes. First sketch the graph.
          Graph. Was ist die grösste ganze Zahl für x,         What is the largest integer number for x
          so dass es ein Paar von Knoten a und b gibt,           such that there is a pair of nodes a and
          so dass die zu x zugehörige Kante zwingend            b such that a shortest path from a to b
          auf einem kürzesten Pfad von a nach b liegt.          must include the edge that corresponds
                                                                 to x?
                                                    0    1   7   4
                                                                    
                                                
                                                   1    0   4   7   
                                                                     
                                                    7    4   0   x
                                                                    
                                                                    
                                                    4    7   x   0

          Graph

          x=

/3P (f)   Sie haben einen sehr grossen Datensatz aus             You have a huge data set with n diffe-
          n unterschiedlichen Zahlen und wollen das              rent numbers and you want to find the
          k-kleinste Element finden (k  n). Wie ma-             k-smallest element (k  n). How do you
          chen Sie das effizient? Benennen Sie verwen-           do this efficiently? Provide the used data
          dete Datenstrukturen und Laufzeit des Algo-            structures and the runtime of the algo-
          rithmus.                                               rithm.
Sie können auch lesen