Lösungen - Informatique 1 – Informatik 1

Transcription

Lösungen - Informatique 1 – Informatik 1
Name/Nom : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Klasse/Classe: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
T EST SEMESTRIEL – S EMESTERPÜFUNG
SOLUTION
Informatique 1 | Informatik 1
Anweisung / Consigne :
Lesen Sie die Fragen gut durch und beantworten Sie diese leserlich auf den Aufgabenblättern. Alle
Hilfsmittel (Dokumentation, Kurs, etc.) sind erlaubt, jedoch keine elektronischen Hilfen.
Tipp: Verlieren Sie bei einzelnen Fragen nicht zu viel Zeit. Beantworten Sie zuerst die Fragen, die
Ihnen keine Probleme stellen, und kommen Sie später auf die für Sie schwierigeren Fragen zurück.
Die Skala ist unverbindlich
Lisez attentivement la donnée et répondez de manière lisible aux questions. Toute documentation est utilisable mais aucun moyen électronique ne l’est.
Un conseil : ne restez pas bloqués sur une question. Répondez tout d’abord aux questions
avec lesquelles vous êtes à l’aise et revenez ensuite aux questions posant problème. Le
barème indiqué est indicatif.
Question
Points
Bonus
Short questions
71/2
0
Functions analysis
6
0
Loops analysis
41/2
0
Static modifier understanding
4
0
Write some functions
9
0
Computing distance with a map
6
0
Display array
5
0
Gotta catch ‘Em all
8
0
Total:
50
0
Score
This exam has 8 questions, for a total of 50 points.
Rev 1.05
P.A. Mudry, P. Roduit
Januar | Janvier 2014
Page 1/14
29.1.2014
Question 1 – Short questions (71/2 points)
Diese Frage ist in verschiedene selbständige Aufgaben unterteilt. Die Anzahl Punkte von jeder Aufgabe wird am
Rand vermerkt. Cette question est séparée en plusieurs exercices indépendants. Le nombre de point pour
chaque exercice est indiqué dans la marge.
[3 Pt]
(a) Geben Sie an, ob die nachstehenden Ausdrücke korrekt sind oder nicht. Wenn sie korrekt sind, bestimmen Sie
den Typ und den Wert. Zur Erinnerung, der Wert von ’a’ ist 97.
Indiquez si les expressions suivantes sont correctes. Si elles sont correctes, donnez le type et la
valeur des expressions suivantes. Pour rappel, la valeur de ’a’ est 97.
(a) ’a’ >> 4
int, 6
(a)
(b) "Have a nice week".charAt("Hello World".indexOf("orl"))
char, ’n’
(b)
(c) 3 << 2 ^ 3 + 3
int, 10
(c)
(d) x >= 3 && < 6 mit/avec long x = 0x100
impossible
(d)
(e) "Hello " + (int)’c’+ " World"
(e) String, "Hello 99 World"
(f) (int) ("a" + (6 +’c’))
impossible
(f)
[3 Pt]
(g) Wahr oder falsch? | Vrai ou faux ?
[11/2 Pt]
Wenn x eine positive Ganzzahl ist, ist ∼x negativ.
Si x est un entier positif, ∼x est négatif.
True
⊗
False
Eine statische (static) Variable ist nie ausserhalb der Klasse erreichbar.
Une variable static n’est jamais accessible à l’extérieur de la classe.
True
False
⊗
Wenn x gleich 3 ist, hat die Variable y einen Wert von 4 nach dem Befehl int y =
x++;.
Si x vaut 3, la variable y vaut 4 après l’instruction int y = x++;.
True
False
⊗
Es ist unmöglich ein Klasse zu instanzieren, welche statische (static) Attribute
enthält.
Il n’est pas possible d’instancier une classe qui contient des attributs static.
True
False
⊗
Eine unstatische Methode kann statische Attribute modifizieren.
Une méthode non-statique peut modifier des attributs statiques.
True
⊗
False
Eine statische Methode kann nicht einen konstanten Wert zurückgeben.
Une méthode statique ne peut pas retourner une valeur constante.
True
False
⊗
(h) In welchem Fall ist es möglich, zwei Methoden mit dem gleichen Namen und der gleichen Anzahl Parameter
zu besitzen? Geben Sie ein Beispiel!
Dans quel cas est-il possible d’avoir deux méthodes ayant ont le même nom et le même nombre de
paramètres ? Donnez un exemple!
Solution: When the parameters have different types. For instance void foo(int toto) and
void foo(double toto)
Page 2/14
T EST SEMESTRIEL – S EMESTERPÜFUNG
Question 2 – Functions analysis (6 points)
Gegeben sei der folgende Code: | Soit le code suivant :
1
2
3
public static String mystery(String text) {
boolean newWord = true;
String result = "";
4
for (int i = 0; i < text.length(); i++) {
if (newWord) {
if (text.charAt(i) != ’ ’) {
newWord = false;
}
String s = text.substring(i, i + 1);
result += s.toUpperCase();
} else {
if (text.charAt(i) == ’.’) {
newWord = true;
}
result += text.charAt(i);
}
}
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
return result;
20
21
[1 Pt]
}
(a) Was gibt mystery("hello");?
Que vaut mystery("hello"); ?
Solution: Hello
[1 Pt]
(b) Was gibt mystery("hello there. this is hard. help, help");?
Que vaut mystery("hello there. this is hard. help, help"); ?
Solution: Hello there. This is hard. Help, help
[2 Pt]
(c) Erklären Sie was das Ziel der oben definierten Funktion mystery ist. Erklären Sie insbesonders in welchem
Kontext eine solche Funktion nützlich ist.
Expliquez quel est le sens (le but) de la fonction mystery ci-dessus. Expliquez notamment dans
quel contexte une telle fonction est utile.
Solution: This function capitalizes the first letter following a point and ignores the spaces. It
can be used for instance in a word processing programme to automatically capitalize sentences
to write faster. Note that it only works for ‘.’ and not for the other delimiters such as ‘!’ or ‘?’.
Page 3/14
29.1.2014
[2 Pt]
(d) Gegeben sei der folgende Code:
Soit le code suivant :
1
2
3
4
class Foo1 {
public static int a = 1;
private String b = "This is a string";
public final int c = 2;
5
void bar1(){
6
...
7
}
8
9
}
10
11
12
class Foo2 {
private Foo1 d = new Foo1();
13
void bar2(){
14
...
15
}
16
17
}
Sind die Variablen a, b, c und d veränderbar in den Methoden bar1 und bar2 ? Antorten Sie mit ja oder
nein in der folgenden Tabelle:
Les variables a, b, c et d sont-elles modifiables à l’intérieur des méthodes bar1 et bar2 ? Répondez
par oui ou non dans le tableau suivant :
Variables
bar1()
bar2()
a
b
c
d.a
d.b
d.c
yes
yes
no
no
no
yes
no
no
Question 3 – Loops analysis (41/2 points)
Welche Resultate werden auf der Konsole angezeigt?
Que vont afficher les boucles suivantes sur la console ?
1
2
int a = 3;
int n = 4;
3
4
5
(a)
6
7
8
9
10
11
1
2
3
(b)
do{
a = a + n--;
4
5
6
if(n != 0)
System.out.print(n + ",");
else
System.out.print(n);
} while(n != 0);
String g = "geosoad";
int k = 0, d = 7;
for(; k < d;){
System.out.print(g.charAt(k));
k+=4>>1;
}
Lösung | Solution:
Solution:
3,2,1,0
Lösung | Solution:
Solution:
good
Page 4/14
T EST SEMESTRIEL – S EMESTERPÜFUNG
1
2
3
4
(c)
5
6
7
8
int x = 0xa;
System.out.print("0b");
for(int i = 3; i >= 0; i--){
if(((1 << i) & x) > 0)
System.out.print("1");
else
System.out.print("0");
}
Lösung | Solution:
Solution:
0b1010
Question 4 – Static modifier understanding (4 points)
Was zeigt der folgende Code an? | Qu’affiche le code suivant ?
1
2
3
public class Foo {
public static int a = 0;
public int b;
4
public Foo(int c) {
a++;
int a = 3;
b = a + c;
}
5
6
7
8
9
10
public void bar(int a) {
a += b;
}
11
12
13
14
public void inc() {
a = b++;
}
15
16
17
18
public String toString() {
return "" + a + " " + b + " ";
}
19
20
21
22
public static void main(String[] args) {
Foo i1 = new Foo(3);
System.out.println(i1);
i1.inc();
System.out.println(i1);
Foo i2 = new Foo(1);
i2.bar(3);
System.out.println("" + i1 + i2);
Foo i3 = new Foo(2);
System.out.println("" + i1 + i2 + i3);
i3.inc();
i3.bar(4);
System.out.println("" + i1 + i2 + i3);
}
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
}
Solution:
Page 5/14
29.1.2014
1
2
3
4
5
1
6
7
8
5
6
7
7 7 4
7 8 4 8 5
7 5 4 5 6
Page 6/14
T EST SEMESTRIEL – S EMESTERPÜFUNG
Question 5 – Write some functions (9 points)
[11/2 Pt]
(a) Schreiben Sie eine Funktion namens shorter welche angibt, ob die erste Zeichenkette welche als Parameter
übergeben wurde kürzer oder gleich lang ist als die zweite als Parameter übergebene Zeichenkette.
Écrivez une fonction nommée shorter qui indique si la première chaîne de caractères passée en
argument est plus courte ou de même longueur que la seconde.
Solution:
1
2
3
[2 Pt]
public static boolean shorter(String a, String b) {
return a.length() <= b.length();
}
(b) Gegeben ist die Funktion isPrime(int x) welche zurückgibt, ob eine Zahl, welche als Parameter übergeben
wurde, eine Primzahl ist oder nicht. Schreiben Sie eine Funktion namens nbPrimes welche eine Ganzzahl
n als Parameter erhält und als Rückgabewert die Anzahl Primzahlen zwischen 1 und n (n inbegriffen)
zurückgibt.
Soit la fonction isPrime(int x) qui retourne si un nombre passé en argument est un nombre
premier ou non. Ecrivez une fonction nommée nbPrimes qui prend un entier n en paramètre et qui
retourne combien de nombres premiers se trouvent entre 1 et n compris.
Solution:
1
2
3
4
5
6
7
8
[2 Pt]
public static int nbPrimes(int n) {
int s = 0;
for (int i = 1; i <= n; i++) {
if (isPrime(i))
s++;
}
return s;
}
(c) Schreiben Sie eine Funktion namens count welche zurückgibt, wie oft ein Buchstabe, welcher als Parameter
übergeben wird in einer Zeichenkette, welche ebenfalls als Parameter übergeben wird, vorkommt.
Écrivez une fonction nommée count qui retourne combien de fois une lettre donnée en argument
apparaît dans une chaîne de caractères également passée en argument.
Solution:
1
2
public static int count(String s, char letter) {
int count = 0;
3
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == letter)
count++;
}
4
5
6
7
8
return count;
9
10
[31/2 Pt]
}
(d) Schreiben Sie eine Funktion namens randomArray welche vier Werte als Parameter erhält und ein zweidimensionales Array mit zufälligen Ganzzahlen erstellt. Die ersten zwei Parameter entsprechen der unteren
und oberen Grenze der Zufallszahlen, während die beiden letzten Parameter den beiden Dimensionen des
Page 7/14
29.1.2014
Arrays entsprechen. Zum Beispiel: randomArray(2,6,3,4) wird ein Array mit ganzen Zufallszahlen
zwischen 2 und 6 (6 inbegriffen) mit einer Grösse von 3 mal 4 zurückgeben.
Écrivez une fonction nommée randomArray qui reçoit quatre valeurs en paramètre et qui produit
un tableau bidimensionnel d’entiers aléatoires. Les deux premiers paramètres correspondent aux
bornes inférieure et supérieure des valeurs aléatoires, tandis que les deux derniers paramètres
correspondent aux deux dimensions du tableau. Par exemple, randomArray(2,6,3,4) va retourner
un tableau de nombres aléatoires entiers entre 2 et 6 (compris) de taille 3 par 4.
Solution:
1
2
3
4
5
6
7
8
public static int[][] randomArray(int min, int max, int width, int height) {
int[][] result = new int[width][height];
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++) {
result[i][j] = (int) (Math.random() * (max - min + 1)) + min;
}
return result;
}
BTurn page →
Page 8/14
T EST SEMESTRIEL – S EMESTERPÜFUNG
Question 6 – Computing distance with a map (6 points)
Figure 1: Parameters in the CH1903 format
In der Schweiz und in Liechtenstein benutzen die Kartendienste das Format CH1903. Es handelt sich um ein
einfaches kartesisches Koordinatensystem. Somit ist es einfach, eine Distanzrechnung durchzuführen, da es genügt,
wenn der Satz von Pythagoras wie in der Abbildung 1 angewendet wird.
En Suisse et au Liechtenstein, les services cartographiques utilisent le format CH1903. Il s’agit d’un
simple système de coordonnées cartésiennes. Ainsi, un calcul de distance est simple puisqu’il suffit
d’appliquer le théorème de Pythagore comme on le voit sur le dessin 1.
[2 Pt]
(a) Ihre Aufgabe besteht darin, eine Funktion zu schreiben, welche die totale Distanz einer GPS-Spur (im
Format CH1903), welche als Parameter übergeben wird, zu berechnen und zurückzugeben. Um dies zu tun,
definieren Sie zuerst die erforderliche Klasse damit der folgende Code gültig ist:
Votre tâche est d’écrire une fonction qui retourne la distance totale d’une trace GPS (au format
CH1903) donnée en paramètre. Pour cela, définissez d’abord la classe nécessaire pour que le code
suivant soit valable :
Coordinate[] track = {new Coordinate(1,1), new Coordinate(2,3)};
Solution:
1
2
3
4
5
6
7
[4 Pt]
class Coordinate {
int x, y;
Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}
(b) Schreiben Sie nun die Funktion computeDistance, welche als Parameter ein solches Array nimmt und die
totale Distanz zurückgibt.
Écrivez la fonction computeDistance qui reçoit un tel tableau et qui retourne la distance totale.
Solution:
Page 9/14
29.1.2014
1
2
[public] [static] double computeDistance(Coordinate[] track) {
double distance = 0;
3
for (int i
int dX =
int dY =
distance
}
4
5
6
7
8
= 1; i < track.length;
track[i].x - track[i track[i].y - track[i += Math.sqrt(dX * dX +
i++) {
1].x;
1].y;
dY * dY);
9
return distance;
10
11
}
Page 10/14
T EST SEMESTRIEL – S EMESTERPÜFUNG
Question 7 – Display array (5 points)
Gegeben sei die folgende Klasse: | Soit la classe suivante:
public class Array2D {
int[][] data;
}
1
2
3
Vervollständigen Sie den Code so, dass wenn eine Instanz mit Hilfe eines println angezeigt wird, der Inhalt der
Tabelle mit dem dazugehörigen Index an der Konsole ausgegeben wird. Zum Beispiel, der folgende Code:
Complétez le code de la classe afin que lorsque qu’une instance est affichée à l’aide d’un println, le
contenu du tableau soit affiché, avec la valeur des différents indices. Par exemple, le code suivant:
public static void main(String[] args) {
Array2D a = new Array2D();
a.data = new int[2][2];
a.data[0][0] = 4;
a.data[0][1] = 6;
a.data[1][0] = 7;
a.data[1][1] = 8;
System.out.println(a);
}
1
2
3
4
5
6
7
8
9
sollte folgendes Resultat liefern:
devrait produire le résultat:
0 1
0 4 6
1 7 8
1
2
3
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public String toString() {
String result = "";
for (int j = 0; j < data[0].length; j++) {
result += "\t" + j;
}
result += "\n";
for (int i = 0; i < data.length; i++) {
result += "" + i;
for (int j = 0; j < data[0].length; j++) {
result += "\t" + data[i][j];
}
result += "\n";
}
return result;
}
Page 11/14
29.1.2014
Question 8 – Gotta catch ‘Em all (8 points)
Schreiben Sie eine Klasse Pokémon, welche die folgenden Merkmale von einem Pokémon registriert: Name (name),
Anzahl Lebens-Punkte (health) und ID-Nummer (id). All diese Attribute sollen als private deklariert sein.
Die id-Nummer beginnt mit 1 für das erste Pokémon und wird inkrementiert, sobald ein neues Pokémon erstellt
wird. Ihre Klasse muss zwei Konstruktoren umfassen:
• Der erste Konstruktor hat zwei Parameter, mit denen der Namen und die Anzahl Lebens-Punkte des
Pokémons festgelegt werden können.
• Der zweite Konstruktor hat keine Parameter und legt der Namen des Pokémons auf Unknown fest und die
Anzahl Lebens-Punkte auf 0.
Schreiben Sie nun drei Methoden:
1. Mit der ersten Methode, namens modify, kann der Name eines Pokémons verändert werden.
2. Die zweite Methode, namens hit, ermöglicht es, die Anzahl Lebens-Punkte um eine gegebene Zahl zu
reduzieren.
3. Die dritte Methode, namens toString, gibt eine Zeichenkette mit dem Namen, Anzahl Lebens-Punkte und
der ID-Nummer zurück. Das Resultat hat folgende Form: Pokémon: X, PV: Y, ID: Z wobei X, Y und Z
durch die entsprechenden Werte des Pokémons ersetzt werden. X wird zudem immer in Grossbuchstaben
geschrieben. Zum Beispiel:
1
2
Pokemon p1 = new Pokemon("Pikachu", 40);
System.out.println(b1);
ergibt folgendes Resultat: Name: PIKACHU, PV: 40, ID: 1
Écrivez une classe Pokémon qui enregistre les caractéristiques suivantes : le nom (name), le nombre
de points de vie (health) ainsi qu’un numéro d’identification (id). Ces trois paramètres doivent être
déclarés comme étant private. L’id commence à 1 pour le premier Pokémon et est incrémenté lorsqu’un
nouveau Pokémon est crée.
Votre classe doit posséder deux constructeurs :
• Le premier, prenant deux paramètres permettant de fixer le nom et les points de vie du Pokémon.
• Le second, sans paramètres, fixe le nombre de points de vie à 0 et le nom du Pokémon à Unknown.
Ajoutez ensuite trois méthodes :
1. La première, nommée modify, permet de changer le nom du Pokémon.
2. La seconde, nommée hit, permet de réduire le nombre de points de vie d’un nombre donné.
3. Finalement, ajoutez une méthode toString afin d’afficher le Pokémon, en montrant son nom, ses
PVs ainsi que son ID. Le résultat sera sous la forme suivante: Pokémon: X, PV: Y, ID: Z où X, Y,
Z sont remplacés par les valeurs correspondantes du Pokémon. De plus, X est toujours écrit en
majuscules. Par exemple:
1
2
Pokemon p1 = new Pokemon("Pikachu", 40);
System.out.println(b1);
Donne le résultat suivant :
Name: PIKACHU, PV: 40, ID: 1
Page 12/14
T EST SEMESTRIEL – S EMESTERPÜFUNG
Lösung | Solution
Solution:
Page 13/14
29.1.2014
Fin|Ende
The end
Page 14/14

Documents pareils