diff --git a/package-lock.json b/package-lock.json index 3397ec1..3159b21 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "@sourcecodeoer/cli", - "version": "1.0.0", + "version": "1.1.3", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/results/results1.json b/results/results1.json index fa9a223..ad2696e 100644 --- a/results/results1.json +++ b/results/results1.json @@ -2,7 +2,7 @@ "exercises": [ { "title": "Absolute value", - "description": "The absolute value of a number is defined as *|n| = n* if *n >= 0*,\r\n*|n| = -n* else.\r\n", + "description": "

The absolute value of a number is defined as |n| = n if n >= 0, |n| = -n else.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -51,7 +51,7 @@ }, { "title": "Advanced queue", - "description": "You must implement the `enqueue` and `dequeue` functions of a Queue that is implemented as a simple circular\r\nlist. This [Wikipedia\r\npage](https://en.wikipedia.org/wiki/Linked_list#Circularly_linked_vs._linearly_linked)\r\ndescribes such a list as follows:\r\n\r\n\"With a circular list, a pointer to the last node gives easy access also\r\nto the first node, by following one link. Thus, in applications that\r\nrequire access to both ends of the list (e.g., in the implementation of\r\na queue), a circular structure allows one to handle the structure by a\r\nsingle pointer, instead of two.\"\r\n\r\n![image](https://upload.wikimedia.org/wikipedia/commons/d/df/Circularly-linked-list.svg)\r\n\r\nAssume that the head of the queue is the leftmost node and that the tail\r\nof the queue is the rightmost node. In the previous example, the head\r\nand the tail are respectively `12` and `37`. So in this case, the only\r\npointer you can use will point to the `37` node.\r\n\r\nYou can use the following datastructures for this exercise:\r\n\r\n``` c\r\ntypedef struct node{\r\n struct node* next;\r\n int value;\r\n} node_t;\r\n\r\ntypedef struct queue{\r\n struct node* tail;\r\n int size;\r\n} queue_t ;\r\n```\r\n", + "description": "

You must implement the enqueue and dequeue functions of a Queue that is implemented as a simple circular list. This Wikipedia page describes such a list as follows:

\r\n

\"With a circular list, a pointer to the last node gives easy access also to the first node, by following one link. Thus, in applications that require access to both ends of the list (e.g., in the implementation of a queue), a circular structure allows one to handle the structure by a single pointer, instead of two.\"

\r\n

\"image\"

\r\n

Assume that the head of the queue is the leftmost node and that the tail of the queue is the rightmost node. In the previous example, the head and the tail are respectively 12 and 37. So in this case, the only pointer you can use will point to the 37 node.

\r\n

You can use the following datastructures for this exercise:

\r\n
typedef struct node{\r\n  struct node* next;\r\n  int value;\r\n} node_t;\r\n\r\ntypedef struct queue{\r\n  struct node* tail;\r\n  int size;\r\n} queue_t  ;
\r\n", "tags": [ { "text": "INGINIOUS", @@ -110,7 +110,7 @@ }, { "title": "ArrayList", - "description": "Vous devez modifier une librairie qui implémente une ArrayList en y\r\najoutant une fonction. Cette ArrayList s'utilise comme suit\r\n\r\n``` c\r\nint main(void) {\r\n struct array_list *head = arraylist_init((size_t) 2, (size_t) sizeof(int));\r\n int first = 5;\r\n int second = 6;\r\n int third = 7;\r\n int tmp;\r\n\r\n int ret;\r\n\r\n if (!head)\r\n return 0;\r\n\r\n set_element(head, 0, (void *)&first);\r\n set_element(head, 1, (void *)&second);\r\n\r\n get_element(head, 1, (void *)&tmp);\r\n // tmp contient 6\r\n add_tail(head, (void *)&third);\r\n get_element(head, 2, (void *)&tmp);\r\n // tmp contient 7\r\n printf(\"array-list size: %d element-size %d\\n\", get_size(head), get_elem_size(head));\r\n // affiche array-list size: 3 element-size 4\r\n array_list_destroy(head);\r\n return 0;\r\n}\r\n```\r\n\r\nLe syllabus est accessible depuis l'URL\r\n\r\n\r\nLes pages de manuel sont accessibles depuis les URLs suivants : -\r\n (commandes) -\r\n (appels systèmes) -\r\n (fonctions\r\nlibrairies)\r\n", + "description": "

Vous devez modifier une librairie qui implémente une ArrayList en y ajoutant une fonction. Cette ArrayList s'utilise comme suit

\r\n
int main(void) {\r\n     struct array_list *head = arraylist_init((size_t) 2, (size_t) sizeof(int));\r\n     int first = 5;\r\n     int second = 6;\r\n     int third = 7;\r\n     int tmp;\r\n\r\n     int ret;\r\n\r\n     if (!head)\r\n             return 0;\r\n\r\n     set_element(head, 0, (void *)&first);\r\n     set_element(head, 1, (void *)&second);\r\n\r\n     get_element(head, 1, (void *)&tmp);\r\n     // tmp contient 6\r\n     add_tail(head, (void *)&third);\r\n     get_element(head, 2, (void *)&tmp);\r\n     // tmp contient 7\r\n     printf("array-list size: %d element-size %d\\n", get_size(head), get_elem_size(head));\r\n     // affiche array-list size: 3 element-size 4\r\n     array_list_destroy(head);\r\n     return 0;\r\n}
\r\n

Le syllabus est accessible depuis l'URL http://sites.uclouvain.be/SystInfo

\r\n

Les pages de manuel sont accessibles depuis les URLs suivants : - http://sites.uclouvain.be/SystInfo/manpages/man1 (commandes) - http://sites.uclouvain.be/SystInfo/manpages/man2 (appels systèmes) - http://sites.uclouvain.be/SystInfo/manpages/man3 (fonctions librairies)

\r\n", "tags": [ { "text": "INGINIOUS", @@ -169,7 +169,7 @@ }, { "title": "Get an array from a binary file using mmap", - "description": "Given a file containing a linked list of the structure *student\\_t*\r\nfollowing, you have to write a function to load the entire linked list\r\nfrom the file and to return a pointer to the head of this linked list.\r\nAssume that, in the file, if **a** is followed by **b**, you will have\r\n`a->next = b`.\r\n\r\n``` c\r\ntypedef struct student{\r\n struct student* next;\r\n int noma;\r\n} student_t;\r\n```\r\n\r\nIn this exercice, you **cannot** use *fopen*, *read*, *fread*, *fgetc*,\r\n*fgets*, which means that you must use\r\n[mmap(2).](https://sites.uclouvain.be/SystInfo/manpages/man2/mmap.2.html)\r\n\r\nIn case of error (using malloc), you have to free **all** the memory you\r\nhave allocated.\r\n", + "description": "

Given a file containing a linked list of the structure student_t following, you have to write a function to load the entire linked list from the file and to return a pointer to the head of this linked list. Assume that, in the file, if a is followed by b, you will have a->next = b.

\r\n
typedef struct student{\r\n    struct student* next;\r\n    int noma;\r\n} student_t;
\r\n

In this exercice, you cannot use fopen, read, fread, fgetc, fgets, which means that you must use mmap(2).

\r\n

In case of error (using malloc), you have to free all the memory you have allocated.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -235,7 +235,7 @@ }, { "title": "Traduction de code assembleur", - "description": "Le syllabus est accessible depuis l'URL\r\n\r\n\r\nLes pages de manuel sont accessibles depuis les URLs suivants :\r\n\r\n- (commandes)\r\n- (appels systèmes)\r\n- (fonctions\r\n librairies)\r\n", + "description": "

Le syllabus est accessible depuis l'URL http://sites.uclouvain.be/SystInfo

\r\n

Les pages de manuel sont accessibles depuis les URLs suivants :

\r\n\r\n", "tags": [ { "text": "INGINIOUS", @@ -294,7 +294,7 @@ }, { "title": "Traduction de code assembleur", - "description": "Le syllabus est accessible depuis l'URL\r\n\r\n\r\nLes pages de manuel sont accessibles depuis les URLs suivants :\r\n\r\n- (commandes)\r\n- (appels systèmes)\r\n- (fonctions des\r\n librairies)\r\n", + "description": "

Le syllabus est accessible depuis l'URL http://sites.uclouvain.be/SystInfo

\r\n

Les pages de manuel sont accessibles depuis les URLs suivants :

\r\n\r\n", "tags": [ { "text": "INGINIOUS", @@ -353,7 +353,7 @@ }, { "title": "Traduction de code assembleur", - "description": "Le syllabus est accessible depuis l'URL\r\n\r\n\r\nLes pages de manuel sont accessibles depuis les URLs suivants : \r\n- (commandes)\r\n- (appels systèmes)\r\n- (fonctions des\r\n librairies)\r\n\r\n**Attention:** veuillez utiliser la version **HTML** du syllabus\r\n", + "description": "

Le syllabus est accessible depuis l'URL http://sites.uclouvain.be/SystInfo

\r\n
\r\n
Les pages de manuel sont accessibles depuis les URLs suivants :
\r\n
\r\n
\r\n
\r\n

Attention: veuillez utiliser la version HTML du syllabus

\r\n", "tags": [ { "text": "INGINIOUS", @@ -412,7 +412,7 @@ }, { "title": "Traduction de code assembleur", - "description": "Le syllabus est accessible depuis l'URL\r\n\r\n\r\nLes pages de manuel sont accessibles depuis les URLs suivants : \r\n- (commandes)\r\n- (appels systèmes)\r\n- (fonctions des\r\n librairies)\r\n\r\n**Attention:** veuillez utiliser la version **HTML** du syllabus\r\n", + "description": "

Le syllabus est accessible depuis l'URL http://sites.uclouvain.be/SystInfo

\r\n
\r\n
Les pages de manuel sont accessibles depuis les URLs suivants :
\r\n
\r\n
\r\n
\r\n

Attention: veuillez utiliser la version HTML du syllabus

\r\n", "tags": [ { "text": "INGINIOUS", @@ -471,7 +471,7 @@ }, { "title": "Simple linked list", - "description": "We ask you to write two simple functions that are needed to implement a\r\nsimple linked list.\r\n\r\n``` c\r\n/**\r\n* Structure node\r\n*\r\n* @next: pointer to the next node in the list, NULL if last node_t\r\n* @value: value stored in the node\r\n*/\r\ntypedef struct node {\r\n struct node *next;\r\n int value;\r\n} node_t;\r\n\r\n/**\r\n* Structure list\r\n*\r\n* @first: first node of the list, NULL if list is empty\r\n* @size: number of nodes in the list\r\n*/\r\ntypedef struct list {\r\n struct node *first;\r\n int size;\r\n} list_t;\r\n```\r\n\r\n**In your functions, you cannot use the function**\r\n[calloc(3)](https://sites.uclouvain.be/SystInfo/manpages/man3/malloc.3.html)\r\n", + "description": "

We ask you to write two simple functions that are needed to implement a simple linked list.

\r\n
/**\r\n* Structure node\r\n*\r\n* @next: pointer to the next node in the list, NULL if last node_t\r\n* @value: value stored in the node\r\n*/\r\ntypedef struct node {\r\n  struct node *next;\r\n  int value;\r\n} node_t;\r\n\r\n/**\r\n* Structure list\r\n*\r\n* @first: first node of the list, NULL if list is empty\r\n* @size: number of nodes in the list\r\n*/\r\ntypedef struct list {\r\n  struct node *first;\r\n  int size;\r\n} list_t;
\r\n

In your functions, you cannot use the function calloc(3)

\r\n", "tags": [ { "text": "INGINIOUS", @@ -534,7 +534,7 @@ }, { "title": "Bitwise operation: high order bits", - "description": "In this exercise, we will work with operation on bits. When we speak\r\nabout the position of a bit, index 0 corresponds to lowest order bit, 1\r\nto the second-lowest order bit, ...\r\n\r\nIn C source code, you can write a number in binary (base 2) by prefixing\r\nit via 0b., e.g. 0b11010 = 26.\r\n\r\nThis exercise will introduce some non-standard data types which\r\nguarantee that the variable has a fixed number of bits. Indeed, on some\r\nmachines, a *int* could use 2, 4 or 8 bytes. Hence, if we want to\r\nperform bitwise operations, we have to know first on how many bits we\r\nare working.\r\n\r\nFor this, C introduces a new class of variable types :\r\n\r\n- *int8\\_t* (signed integer of 8 bits)\r\n- *uint8\\_t* (unsigned integer of 8 bits)\r\n- *uint16\\_t* (unsigned integer of 16 bits)\r\n\r\nYou can mix *uint* or *int* with bit-lengths 8, 16, 32 and 64). These\r\ntypes are defined in <stdint.h>\r\n", + "description": "

In this exercise, we will work with operation on bits. When we speak about the position of a bit, index 0 corresponds to lowest order bit, 1 to the second-lowest order bit, ...

\r\n

In C source code, you can write a number in binary (base 2) by prefixing it via 0b., e.g. 0b11010 = 26.

\r\n

This exercise will introduce some non-standard data types which guarantee that the variable has a fixed number of bits. Indeed, on some machines, a int could use 2, 4 or 8 bytes. Hence, if we want to perform bitwise operations, we have to know first on how many bits we are working.

\r\n

For this, C introduces a new class of variable types :

\r\n
    \r\n
  • int8_t (signed integer of 8 bits)
  • \r\n
  • uint8_t (unsigned integer of 8 bits)
  • \r\n
  • uint16_t (unsigned integer of 16 bits)
  • \r\n
\r\n

You can mix uint or int with bit-lengths 8, 16, 32 and 64). These types are defined in <stdint.h>

\r\n", "tags": [ { "text": "INGINIOUS", @@ -588,7 +588,7 @@ }, { "title": "Bitwise operation: extract low order bits", - "description": "In this exercise, we will work with operations on bits. When we speak\r\nabout the position of a bit, index 0 corresponds to lowest order bit, 1\r\nto the second-lowest order bit, ...\r\n\r\nIn C source code, you can write a number in binary (base 2) by prefixing\r\nit via 0b., e.g. `0b11010` = 26.\r\n\r\nThis exercise will introduce some non-standard data types which\r\nguarantee that the variable has a fixed number of bits. Indeed, on some\r\nmachines, a *int* could use 2, 4 or 8 bytes. Hence, if we want to\r\nperform bitwise operations, we have to know first on how many bits we\r\nare working.\r\n\r\nFor this, C introduces a new class of variable types :\r\n\r\n- *int8\\_t* (signed integer of 8 bits)\r\n- *uint8\\_t* (unsigned integer of 8 bits)\r\n- *uint16\\_t* (unsigned integer of 16 bits)\r\n\r\nYou can mix *uint* or *int* with bit-lengths 8, 16, 32 and 64). These\r\ntypes are defined in <stdint.h>\r\n", + "description": "

In this exercise, we will work with operations on bits. When we speak about the position of a bit, index 0 corresponds to lowest order bit, 1 to the second-lowest order bit, ...

\r\n

In C source code, you can write a number in binary (base 2) by prefixing it via 0b., e.g. 0b11010 = 26.

\r\n

This exercise will introduce some non-standard data types which guarantee that the variable has a fixed number of bits. Indeed, on some machines, a int could use 2, 4 or 8 bytes. Hence, if we want to perform bitwise operations, we have to know first on how many bits we are working.

\r\n

For this, C introduces a new class of variable types :

\r\n
    \r\n
  • int8_t (signed integer of 8 bits)
  • \r\n
  • uint8_t (unsigned integer of 8 bits)
  • \r\n
  • uint16_t (unsigned integer of 16 bits)
  • \r\n
\r\n

You can mix uint or int with bit-lengths 8, 16, 32 and 64). These types are defined in <stdint.h>

\r\n", "tags": [ { "text": "INGINIOUS", @@ -642,7 +642,7 @@ }, { "title": "Bitwise operation: cycling bits", - "description": "In this exercise, we will work with operations on bits. When we speak\r\nabout the position of a bit, index 0 corresponds to lowest order bit, 1\r\nto the second-lowest order bit, ...\r\n\r\nIn C source code, you can write a number in binary (base 2) by prefixing\r\nit via 0b., e.g. 0b11010 = 26.\r\n\r\nThis exercise will introduce some non-standard data types which\r\nguarantee that the variable has a fixed number of bits. Indeed, on some\r\nmachines, a *int* could use 2, 4 or 8 bytes. Hence, if we want to\r\nperform bitwise operations, we have to know first on how many bits we\r\nare working.\r\n\r\nFor this, C introduces a new class of variable types :\r\n\r\n- *int8\\_t* (signed integer of 8 bits)\r\n- *uint8\\_t* (unsigned integer of 8 bits)\r\n- *uint16\\_t* (unsigned integer of 16 bits)\r\n\r\nYou can mix *uint* or *int* with bit-lengths 8, 16, 32 and 64). These\r\ntypes are defined in <stdint.h>\r\n", + "description": "

In this exercise, we will work with operations on bits. When we speak about the position of a bit, index 0 corresponds to lowest order bit, 1 to the second-lowest order bit, ...

\r\n

In C source code, you can write a number in binary (base 2) by prefixing it via 0b., e.g. 0b11010 = 26.

\r\n

This exercise will introduce some non-standard data types which guarantee that the variable has a fixed number of bits. Indeed, on some machines, a int could use 2, 4 or 8 bytes. Hence, if we want to perform bitwise operations, we have to know first on how many bits we are working.

\r\n

For this, C introduces a new class of variable types :

\r\n
    \r\n
  • int8_t (signed integer of 8 bits)
  • \r\n
  • uint8_t (unsigned integer of 8 bits)
  • \r\n
  • uint16_t (unsigned integer of 16 bits)
  • \r\n
\r\n

You can mix uint or int with bit-lengths 8, 16, 32 and 64). These types are defined in <stdint.h>

\r\n", "tags": [ { "text": "INGINIOUS", @@ -696,7 +696,7 @@ }, { "title": "Bitwise operation: resetting the highest order bit", - "description": "In this exercise, we will work with operations on bits. When we speak\r\nabout the position of a bit, index 0 corresponds to lowest order bit, 1\r\nto the second-lowest order bit, ...\r\n\r\nIn C source code, you can write a number in binary (base 2) by prefixing\r\nit via 0b., e.g. 0b11010 = 26.\r\n\r\nThis exercise will introduce some non-standard data types which\r\nguarantee that the variable has a fixed number of bits. Indeed, on some\r\nmachines, a *int* could use 2, 4 or 8 bytes. Hence, if we want to\r\nperform bitwise operations, we have to know first on how many bits we\r\nare working.\r\n\r\nFor this, C introduces a new class of variable types :\r\n\r\n- *int8\\_t* (signed integer of 8 bits)\r\n- *uint8\\_t* (unsigned integer of 8 bits)\r\n- *uint16\\_t* (unsigned integer of 16 bits)\r\n\r\nYou can mix *uint* or *int* with bit-lengths 8, 16, 32 and 64). These\r\ntypes are defined in <stdint.h>\r\n", + "description": "

In this exercise, we will work with operations on bits. When we speak about the position of a bit, index 0 corresponds to lowest order bit, 1 to the second-lowest order bit, ...

\r\n

In C source code, you can write a number in binary (base 2) by prefixing it via 0b., e.g. 0b11010 = 26.

\r\n

This exercise will introduce some non-standard data types which guarantee that the variable has a fixed number of bits. Indeed, on some machines, a int could use 2, 4 or 8 bytes. Hence, if we want to perform bitwise operations, we have to know first on how many bits we are working.

\r\n

For this, C introduces a new class of variable types :

\r\n
    \r\n
  • int8_t (signed integer of 8 bits)
  • \r\n
  • uint8_t (unsigned integer of 8 bits)
  • \r\n
  • uint16_t (unsigned integer of 16 bits)
  • \r\n
\r\n

You can mix uint or int with bit-lengths 8, 16, 32 and 64). These types are defined in <stdint.h>

\r\n", "tags": [ { "text": "INGINIOUS", @@ -750,7 +750,7 @@ }, { "title": "Bitwise operation: counting set bits", - "description": "In this exercise, we will work with operations on bits. When we speak\r\nabout the position of a bit, index 0 corresponds to lowest order bit, 1\r\nto the second-lowest order bit, ...\r\n\r\nIn C source code, you can write a number in binary (base 2) by prefixing\r\nit via 0b., e.g. 0b11010 = 26.\r\n\r\nThis exercise will introduce some non-standard data types which\r\nguarantee that the variable has a fixed number of bits. Indeed, on some\r\nmachines, a *int* could use 2, 4 or 8 bytes. Hence, if we want to\r\nperform bitwise operations, we have to know first on how many bits we\r\nare working.\r\n\r\nFor this, C introduces a new class of variable types :\r\n\r\n- *int8\\_t* (signed integer of 8 bits)\r\n- *uint8\\_t* (unsigned integer of 8 bits)\r\n- *uint16\\_t* (unsigned integer of 16 bits)\r\n\r\nYou can mix *uint* or *int* with bit-lengths 8, 16, 32 and 64). These\r\ntypes are defined in <stdint.h>\r\n", + "description": "

In this exercise, we will work with operations on bits. When we speak about the position of a bit, index 0 corresponds to lowest order bit, 1 to the second-lowest order bit, ...

\r\n

In C source code, you can write a number in binary (base 2) by prefixing it via 0b., e.g. 0b11010 = 26.

\r\n

This exercise will introduce some non-standard data types which guarantee that the variable has a fixed number of bits. Indeed, on some machines, a int could use 2, 4 or 8 bytes. Hence, if we want to perform bitwise operations, we have to know first on how many bits we are working.

\r\n

For this, C introduces a new class of variable types :

\r\n
    \r\n
  • int8_t (signed integer of 8 bits)
  • \r\n
  • uint8_t (unsigned integer of 8 bits)
  • \r\n
  • uint16_t (unsigned integer of 16 bits)
  • \r\n
\r\n

You can mix uint or int with bit-lengths 8, 16, 32 and 64). These types are defined in <stdint.h>

\r\n", "tags": [ { "text": "INGINIOUS", @@ -804,7 +804,7 @@ }, { "title": "Opérations sur les bits", - "description": "On souhaite effectuer des opérations spécifiques sur certains bits d'un\r\nentier non-signé de 32 bits. Lorsque l'on parle de position, l'indice 0\r\ncorrespond au bit le plus faible, et 31 au bit le plus fort. Dans cet\r\nexercice, un unsigned char représente\r\ntoujours un seul bit et ne pourra donc que prendre les valeurs\r\nnumériques 0 ou 1 (et non '0' et '1')\r\n\r\nÉcrivez une fonction unsigned char\r\nget\\_bit(unsigned int x, unsigned int pos) qui renvoie le bit à\r\nla position pos de x.\r\n\r\nÉcrivez une fonction unsigned int\r\nset\\_bit(unsigned int x, unsigned int pos, unsigned char value)\r\nqui met le bit à la position pos de x à\r\nla valeur value.\r\n\r\nÉcrivez une fonction unsigned char\r\nget\\_3\\_leftmost\\_bits(unsigned int x) qui renvoie les 3 bits les\r\nplus à gauches de x. Par exemple, si on a la séquence 11011001, la\r\nfonction doit renvoyer la valeur correspondant à 00000110.\r\n\r\nÉcrivez une fonction unsigned char\r\nget\\_4\\_rightmost\\_bits(unsigned int x) qui renvoie les 4 bits\r\nles plus à droite de x.\r\n\r\nÉcrivez une fonction unsigned int\r\nunset\\_last\\_bit(unsigned int x) qui met à 0 le premier bit de\r\npoids fort à 1 qu'il trouve, et ne fait rien s'il n'y a pas de bit mis à\r\n1.\r\n\r\nÉcrivez une fonction unsigned int\r\ncycle\\_bits(unsigned int x, unsigned int n) qui déplace tous les\r\nbits de n places vers la gauche selon la formule x\\[(i+n)%32\\] = x\\[i\\]\r\noù x\\[i\\] représente le ième bit de x.\r\n\r\nVous pouvez faire appel aux fonctions get\\_bit et set\\_bit dans les autres.\r\n", + "description": "

On souhaite effectuer des opérations spécifiques sur certains bits d'un entier non-signé de 32 bits. Lorsque l'on parle de position, l'indice 0 correspond au bit le plus faible, et 31 au bit le plus fort. Dans cet exercice, un unsigned char représente toujours un seul bit et ne pourra donc que prendre les valeurs numériques 0 ou 1 (et non '0' et '1')

\r\n

Écrivez une fonction unsigned char get_bit(unsigned int x, unsigned int pos) qui renvoie le bit à la position pos de x.

\r\n

Écrivez une fonction unsigned int set_bit(unsigned int x, unsigned int pos, unsigned char value) qui met le bit à la position pos de x à la valeur value.

\r\n

Écrivez une fonction unsigned char get_3_leftmost_bits(unsigned int x) qui renvoie les 3 bits les plus à gauches de x. Par exemple, si on a la séquence 11011001, la fonction doit renvoyer la valeur correspondant à 00000110.

\r\n

Écrivez une fonction unsigned char get_4_rightmost_bits(unsigned int x) qui renvoie les 4 bits les plus à droite de x.

\r\n

Écrivez une fonction unsigned int unset_last_bit(unsigned int x) qui met à 0 le premier bit de poids fort à 1 qu'il trouve, et ne fait rien s'il n'y a pas de bit mis à 1.

\r\n

Écrivez une fonction unsigned int cycle_bits(unsigned int x, unsigned int n) qui déplace tous les bits de n places vers la gauche selon la formule x[(i+n)%32] = x[i] où x[i] représente le ième bit de x.

\r\n

Vous pouvez faire appel aux fonctions get_bit et set_bit dans les autres.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -858,7 +858,7 @@ }, { "title": "Gestion d'une librairie", - "description": "On souhaite gérer le catalogue d'une librairie dans lequel chaque livre\r\nest identifié par son auteur et son titre. La structure de données\r\nchoisie est la suivante : il y a une liste chaînée d'auteurs dont chaque\r\nélément pointe vers une liste chaînée d'ouvrages.\r\n\r\n``` c\r\ntypedef struct cellAuteur {\r\n char *auteur;\r\n struct cellLivre *Livres;\r\n struct cellAuteur *next;\r\n} cellAuteur;\r\n\r\ntypedef struct cellLivre {\r\n char *titre;\r\n struct cellLivre *suiv;\r\n} cellLivre;\r\n```\r\n\r\nÉcrivez une fonction cellAuteur\r\n\\*existe(cellAuteur \\*librairie, char \\*strAuteur) qui teste si\r\nun auteur existe dans la liste librairie et dans ce cas renvoie un\r\npointeur sur sa cellule de la liste (et NULL sinon).\r\n\r\nÉcrivez une fonction int\r\ncompteOuvrage(cellAuteur \\*librairie, char \\*strAuteur) qui\r\ncompte le nombre de livres d'un auteur dans la liste librairie.\r\n\r\nÉcrivez une fonction void add(cellAuteur\r\n\\*librairie, char \\*strAuteur, char \\*strTitre) qui ajoute dans\r\nle catalogue un livre de l'auteur indiqué. L'auteur existe dans le\r\ncatalogue. Un même livre ne peut pas être présent 2 fois dans la\r\ncatalogue.\r\n\r\nÉcrivez une fonction void supprimer(cellAuteur\r\n\\*\\*librairie, char \\*strAuteur) qui supprime du catalogue un\r\nauteur et tous ses livres. L'auteur existe dans le catalogue.\r\n\r\nVous avez accès aux fonctions de string.h.\r\n", + "description": "

On souhaite gérer le catalogue d'une librairie dans lequel chaque livre est identifié par son auteur et son titre. La structure de données choisie est la suivante : il y a une liste chaînée d'auteurs dont chaque élément pointe vers une liste chaînée d'ouvrages.

\r\n
typedef struct cellAuteur {\r\n    char *auteur;\r\n    struct cellLivre *Livres;\r\n    struct cellAuteur *next;\r\n} cellAuteur;\r\n\r\ntypedef struct cellLivre {\r\n    char *titre;\r\n    struct cellLivre *suiv;\r\n} cellLivre;
\r\n

Écrivez une fonction cellAuteur *existe(cellAuteur *librairie, char *strAuteur) qui teste si un auteur existe dans la liste librairie et dans ce cas renvoie un pointeur sur sa cellule de la liste (et NULL sinon).

\r\n

Écrivez une fonction int compteOuvrage(cellAuteur *librairie, char *strAuteur) qui compte le nombre de livres d'un auteur dans la liste librairie.

\r\n

Écrivez une fonction void add(cellAuteur *librairie, char *strAuteur, char *strTitre) qui ajoute dans le catalogue un livre de l'auteur indiqué. L'auteur existe dans le catalogue. Un même livre ne peut pas être présent 2 fois dans la catalogue.

\r\n

Écrivez une fonction void supprimer(cellAuteur **librairie, char *strAuteur) qui supprime du catalogue un auteur et tous ses livres. L'auteur existe dans le catalogue.

\r\n

Vous avez accès aux fonctions de string.h.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -912,7 +912,7 @@ }, { "title": "Simple Binary Search Tree", - "description": "For this task, you will implement a simple binary search on an existing\r\nbinary tree. A binary tree has the following structure:\r\n\r\n\"image\"\r\n\r\nThis binary tree is composed of nodes implemented using the following\r\nstructure.\r\n\r\n``` c\r\n/*\r\n* Node has a value, @value, and two children, @left and @right.\r\n* All the children of @left and itself have a smaller value than the node and all the children of @right and itself have a larger value than node\r\n*/\r\ntypedef struct node{\r\n int value;\r\n struct node* left; // to smaller values\r\n struct node* right; // to larger values\r\n} node_t;\r\n```\r\n\r\nThe binary tree itself is defined as follows.\r\n\r\n``` c\r\ntypedef struct bt{\r\n struct node* root;\r\n} bt_t;\r\n```\r\n", + "description": "

For this task, you will implement a simple binary search on an existing binary tree. A binary tree has the following structure:

\r\n

\"image\"

\r\n

This binary tree is composed of nodes implemented using the following structure.

\r\n
/*\r\n* Node has a value, @value, and two children, @left and @right.\r\n* All the children of @left and itself have a smaller value than the node and all the children of @right and itself have a larger value than node\r\n*/\r\ntypedef struct node{\r\n    int value;\r\n    struct node* left; // to smaller values\r\n    struct node* right; // to larger values\r\n} node_t;
\r\n

The binary tree itself is defined as follows.

\r\n
typedef struct bt{\r\n    struct node* root;\r\n} bt_t;
\r\n", "tags": [ { "text": "INGINIOUS", @@ -975,7 +975,7 @@ }, { "title": "BST : Insert and Delete", - "description": "To help you study your english course, you've got the wonderful idea of\r\ncreating a Binary Search Tree (BST). This will also help you to study\r\nfor the LSINF1252 course! The key of each node will be the english word\r\nand the value will be the french word corresponding. Those are\r\nrepresented using an array of char. So let's define our 2 structures :\r\n\r\n``` c\r\ntypedef struct bt {\r\n struct node *root;\r\n} bt_t;\r\n\r\ntypedef struct node {\r\n char *enWord;\r\n char *frWord;\r\n struct node *left;\r\n struct node *right;\r\n} node_t;\r\n```\r\n\r\n**What is a Binary Search Tree (BST) ?**\r\n\r\nA Binary Search Tree is a tree for which every node has a special\r\nproperty : the subtree defined by node.left only contains keys(enWord)\r\nlower than the node's key. Similarly, the subtree defined by node.right\r\nonly contains keys higher than the node's key. This is helpful when\r\nsearching for a specific key in the data structure.\r\n\r\nTODO : SCHEME NEEDED + EXPLAIN WHICH NODE IS THE ROOT. + CHANGE THE CODE\r\n: word -> enWord, definition -> frWord.\r\n\r\n**Your mission**\r\n\r\nYour mission will be to implement the **insert** and the **delete**\r\nfunctions.\r\n\r\n- **Insert** function :\r\n\r\nFor each node we know this : every key (*enWord*) in the node.left\r\nsubpart is lower than the key of the node. Similarly, every key\r\n(*enWord*) in the node.right subpart is lower than the key of the node.\r\nWe use the alphabetical order to check if one word is lower or higher\r\nthan another one.\r\n\r\n- **Delete** function :\r\n\r\nDeleting a node in a tree like that might not be easy ! That's why I'll\r\nexplain you how to proceed (you'll have to use this procedure in order\r\nto get the points). If the node we want to delete has 0 or only 1 child,\r\nit's quite easy, we only have to replace this node by his child (if\r\nthere is one). When it comes to a node which has two children, it's\r\nharder. We first have to find the right subtree's leftmost child. In the\r\nexample, if we want to suppress *XXX*, the leftmost node of the right\r\nsubpart is *YYY*. Then, we can move *YYY* to *XXX* and replace *YYY* by\r\nhis child (if it has one).\r\n\r\nSCHEME NEEDED for XXX and YYY.\r\n\r\n*Hints :*\r\n\r\n- `char *enWord` and `char *frWord` are pointers, memory must be\r\n allocated by using\r\n [malloc(3)](https://sites.uclouvain.be/SystInfo/manpages/man3/malloc.3.html)\r\n to copy the strings in the tree.\r\n- Other useful commands:\r\n [strcpy(3)](https://sites.uclouvain.be/SystInfo/manpages/man3/strcpy.3.html),\r\n [strlen(3)](https://sites.uclouvain.be/SystInfo/manpages/man3/strlen.3.html)\r\n and\r\n [strcmp(3)](https://sites.uclouvain.be/SystInfo/manpages/man3/strcmp.3.html).\r\n- Do not forget to free **all** the allocated space deleting an\r\n element.\r\n", + "description": "

To help you study your english course, you've got the wonderful idea of creating a Binary Search Tree (BST). This will also help you to study for the LSINF1252 course! The key of each node will be the english word and the value will be the french word corresponding. Those are represented using an array of char. So let's define our 2 structures :

\r\n
typedef struct bt {\r\n    struct node *root;\r\n} bt_t;\r\n\r\ntypedef struct node {\r\n    char *enWord;\r\n    char *frWord;\r\n    struct node *left;\r\n    struct node *right;\r\n} node_t;
\r\n

What is a Binary Search Tree (BST) ?

\r\n

A Binary Search Tree is a tree for which every node has a special property : the subtree defined by node.left only contains keys(enWord) lower than the node's key. Similarly, the subtree defined by node.right only contains keys higher than the node's key. This is helpful when searching for a specific key in the data structure.

\r\n

TODO : SCHEME NEEDED + EXPLAIN WHICH NODE IS THE ROOT. + CHANGE THE CODE : word -> enWord, definition -> frWord.

\r\n

Your mission

\r\n

Your mission will be to implement the insert and the delete functions.

\r\n
    \r\n
  • Insert function :
  • \r\n
\r\n

For each node we know this : every key (enWord) in the node.left subpart is lower than the key of the node. Similarly, every key (enWord) in the node.right subpart is lower than the key of the node. We use the alphabetical order to check if one word is lower or higher than another one.

\r\n
    \r\n
  • Delete function :
  • \r\n
\r\n

Deleting a node in a tree like that might not be easy ! That's why I'll explain you how to proceed (you'll have to use this procedure in order to get the points). If the node we want to delete has 0 or only 1 child, it's quite easy, we only have to replace this node by his child (if there is one). When it comes to a node which has two children, it's harder. We first have to find the right subtree's leftmost child. In the example, if we want to suppress XXX, the leftmost node of the right subpart is YYY. Then, we can move YYY to XXX and replace YYY by his child (if it has one).

\r\n

SCHEME NEEDED for XXX and YYY.

\r\n

Hints :

\r\n
    \r\n
  • char *enWord and char *frWord are pointers, memory must be allocated by using malloc(3) to copy the strings in the tree.
  • \r\n
  • Other useful commands: strcpy(3), strlen(3) and strcmp(3).
  • \r\n
  • Do not forget to free all the allocated space deleting an element.
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1025,7 +1025,7 @@ }, { "title": "Parcours d'un arbre binaire de recherche", - "description": "On souhaite parcourir un arbre binaire de recherche. Un arbre de\r\nrecherche binaire est une structure de données où chaque nœud possède\r\nune clé et une valeur. En outre, chaque nœud peut avoir 2 nœuds fils :\r\nun à gauche dont la clé est toujours inférieure à la sienne, et un à\r\ndroite dont la clé est toujours supérieure à la sienne. Autrement dit si\r\nvous êtes à un nœud dont la clé vaut 10 et que vous cherchez un nœud\r\ndont la clé vaut 5, vous savez que vous devez descendre à gauche pour\r\nespérer trouver un éventuel nœud dont la clé vaut 5.\r\n\r\n``` c\r\ntypedef struct BSTreeNode {\r\n int key;\r\n int value;\r\n\r\n struct BSTreeNode *left;\r\n struct BSTreeNode *right;\r\n} Node;\r\n```\r\n\r\nÉcrivez une fonction int has\\_key(Node root, int\r\nkey) qui vérifie si l'arbre binaire dont le sommet est le nœud\r\nroot possède un nœud dont la clé vaut key et renvoie 1 si oui, renvoie 0\r\nsinon.\r\n\r\nÉcrivez une fonction int compare(Node root\\_a,\r\nNode root\\_b) qui vérifie si les 2 arbres binaires passés en\r\nargument sont identiques (ils ont la même structure et tous les nœuds\r\npossèdent la même paire clé/valeur). Renvoie 1 si les arbres sont\r\nidentiques, 0 sinon. Indice : pensez récursivement.\r\n", + "description": "

On souhaite parcourir un arbre binaire de recherche. Un arbre de recherche binaire est une structure de données où chaque nœud possède une clé et une valeur. En outre, chaque nœud peut avoir 2 nœuds fils : un à gauche dont la clé est toujours inférieure à la sienne, et un à droite dont la clé est toujours supérieure à la sienne. Autrement dit si vous êtes à un nœud dont la clé vaut 10 et que vous cherchez un nœud dont la clé vaut 5, vous savez que vous devez descendre à gauche pour espérer trouver un éventuel nœud dont la clé vaut 5.

\r\n
typedef struct BSTreeNode {\r\n    int key;\r\n    int value;\r\n\r\n    struct BSTreeNode *left;\r\n    struct BSTreeNode *right;\r\n} Node;
\r\n

Écrivez une fonction int has_key(Node root, int key) qui vérifie si l'arbre binaire dont le sommet est le nœud root possède un nœud dont la clé vaut key et renvoie 1 si oui, renvoie 0 sinon.

\r\n

Écrivez une fonction int compare(Node root_a, Node root_b) qui vérifie si les 2 arbres binaires passés en argument sont identiques (ils ont la même structure et tous les nœuds possèdent la même paire clé/valeur). Renvoie 1 si les arbres sont identiques, 0 sinon. Indice : pensez récursivement.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1079,7 +1079,7 @@ }, { "title": "Coder calloc en utilisant malloc", - "description": "Ecrire la fonction `calloc2`, ayant le même prototype et le même\r\nfonctionnement que\r\n[calloc(3)](https://sites.uclouvain.be/SystInfo/manpages/man3/calloc.3.html)\r\nmais qui utilise\r\n[malloc(3)](https://sites.uclouvain.be/SystInfo/manpages/man3/malloc.3.html)\r\npour allouer la mémoire.\r\n", + "description": "

Ecrire la fonction calloc2, ayant le même prototype et le même fonctionnement que calloc(3) mais qui utilise malloc(3) pour allouer la mémoire.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1133,7 +1133,7 @@ }, { "title": "Comparing functions", - "description": "Pointers to functions can be used to handle functions in a dynamic\r\nfashion, and will be of great importance later in this course. It is\r\nhence important to grasp how they work.\r\n\r\nIn this exercise, you will code a function which receives pointers to\r\ntwo functions, to determine if these functions are equivalent. Two\r\nfunctions are considered to be equivalent if they always produce the\r\nsame output for the same input.\r\n\r\nThe functions passed by pointers will be of the form\r\n`uint8_t func(uint8_t n)`.\r\n", + "description": "

Pointers to functions can be used to handle functions in a dynamic fashion, and will be of great importance later in this course. It is hence important to grasp how they work.

\r\n

In this exercise, you will code a function which receives pointers to two functions, to determine if these functions are equivalent. Two functions are considered to be equivalent if they always produce the same output for the same input.

\r\n

The functions passed by pointers will be of the form uint8_t func(uint8_t n).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1192,7 +1192,7 @@ }, { "title": "Le programme test", - "description": "La commande\r\n[test(1)](https://sites.uclouvain.be/SystInfo/manpages/man1/test.1.html)\r\npermet d'évaluer une expression passée en paramètre. Elle retourne:\r\n\r\n- `0` si l'expression passée en argument est vraie\r\n- `1` si l'expression passée en argument est fausse\r\n\r\nOn vous demande d'écrire un sous-ensemble de la commande\r\n[test(1)](https://sites.uclouvain.be/SystInfo/manpages/man1/test.1.html)\r\nen C. Les expressions à implémenter sont `-eq`, `-ge`, `-gt`, `-le`,\r\n`-lt` et `-ne`.\r\n\r\nPour rappel, la commande\r\n[test(1)](https://sites.uclouvain.be/SystInfo/manpages/man1/test.1.html)\r\nest décrite dans la [page de\r\nmanuel](https://sites.uclouvain.be/SystInfo/manpages/man1/test.1.html)\r\nqui lui est consacrée.\r\n\r\nPour répondre à cette question, vous devez structurer votre programme\r\navec des appels de sous-fonction et donc de ne pas faire toute\r\nl'exécution dans la fonction `main()`.\r\n\r\nIl existe plusieurs façons pour tester votre code, une de ces façons est\r\nde regarder dans le shell le contenu de la variable `$?` après chaque\r\nexécution de votre programme. Une autre façon est de profiter de\r\nl'instruction conditionnelle `if-then-else` du shell.\r\n", + "description": "

La commande test(1) permet d'évaluer une expression passée en paramètre. Elle retourne:

\r\n
    \r\n
  • 0 si l'expression passée en argument est vraie
  • \r\n
  • 1 si l'expression passée en argument est fausse
  • \r\n
\r\n

On vous demande d'écrire un sous-ensemble de la commande test(1) en C. Les expressions à implémenter sont -eq, -ge, -gt, -le, -lt et -ne.

\r\n

Pour rappel, la commande test(1) est décrite dans la page de manuel qui lui est consacrée.

\r\n

Pour répondre à cette question, vous devez structurer votre programme avec des appels de sous-fonction et donc de ne pas faire toute l'exécution dans la fonction main().

\r\n

Il existe plusieurs façons pour tester votre code, une de ces façons est de regarder dans le shell le contenu de la variable $? après chaque exécution de votre programme. Une autre façon est de profiter de l'instruction conditionnelle if-then-else du shell.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1251,7 +1251,7 @@ }, { "title": "Count the '\\0'", - "description": "The character '\\\\0' identifies the end of a string in C. But it can also\r\nplay the role of a real character.\r\n\r\nIn this exercice, write the body of the function `counting_zero`, which\r\ncounts the number of occurence of the character '\\\\0'.\r\n\r\nYou cannot use any function from the string library.\r\n", + "description": "

The character '\\0' identifies the end of a string in C. But it can also play the role of a real character.

\r\n

In this exercice, write the body of the function counting_zero, which counts the number of occurence of the character '\\0'.

\r\n

You cannot use any function from the string library.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1354,7 +1354,7 @@ }, { "title": "Liste doublement chaînée", - "description": "Le syllabus est accessible depuis l'URL\r\n\r\n\r\nLes pages de manuel sont accessibles depuis les URLs suivants : \r\n- (commandes)\r\n- (appels systèmes)\r\n- (fonctions des\r\n librairies)\r\n\r\n**Attention:** veuillez utiliser la version **HTML** du syllabus\r\n", + "description": "

Le syllabus est accessible depuis l'URL http://sites.uclouvain.be/SystInfo

\r\n
\r\n
Les pages de manuel sont accessibles depuis les URLs suivants :
\r\n
\r\n
\r\n
\r\n

Attention: veuillez utiliser la version HTML du syllabus

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1413,7 +1413,7 @@ }, { "title": "Manipulation de liste", - "description": "Le syllabus est accessible depuis l'URL\r\n\r\n\r\nLes pages de manuel sont accessibles depuis les URLs suivants : \r\n- (commandes)\r\n- (appels systèmes)\r\n- (fonctions des\r\n librairies)\r\n\r\n**Attention:** veuillez utiliser la version **HTML** du syllabus\r\n", + "description": "

Le syllabus est accessible depuis l'URL http://sites.uclouvain.be/SystInfo

\r\n
\r\n
Les pages de manuel sont accessibles depuis les URLs suivants :
\r\n
\r\n
\r\n
\r\n

Attention: veuillez utiliser la version HTML du syllabus

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1467,7 +1467,7 @@ }, { "title": "Factorial", - "description": "The factorial of an integer *n!* is defined as `n! = 1*2*3*...*(n-1)*n`,\r\nwith *0! = 1*.\r\n", + "description": "

The factorial of an integer n! is defined as n! = 1*2*3*...*(n-1)*n, with 0! = 1.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1521,7 +1521,7 @@ }, { "title": "Parcours de fichiers", - "description": "Parcourez un fichier sans jamais utiliser l'appel système read. Le\r\nsyllabus est accessible depuis \r\n", + "description": "

Parcourez un fichier sans jamais utiliser l'appel système read. Le syllabus est accessible depuis http://sites.uclouvain.be/SystInfo

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1571,7 +1571,7 @@ }, { "title": "Déterminer la valeur de retour d'un programme exécutable", - "description": "Dans un programme similaire à un shell, on vous demander d'écrire une\r\nfonction qui permet de lancer un exécutable et d'indiquer si :\r\n\r\n- le programme ne s'est pas exécuté ou a retourné une valeur de retour\r\n positive\r\n- le programme s'est exécuté correctement et a retourné une valeur de\r\n retour =0\r\n- le programme a été interrompu par un signal\r\n\r\nLe syllabus est accessible depuis l'URL\r\n\r\n\r\nLes pages de manuel sont accessibles depuis les URLs suivants : \r\n- (commandes)\r\n- (appels systèmes)\r\n- (fonctions des\r\n librairies)\r\n", + "description": "

Dans un programme similaire à un shell, on vous demander d'écrire une fonction qui permet de lancer un exécutable et d'indiquer si :

\r\n
    \r\n
  • le programme ne s'est pas exécuté ou a retourné une valeur de retour positive
  • \r\n
  • le programme s'est exécuté correctement et a retourné une valeur de retour =0
  • \r\n
  • le programme a été interrompu par un signal
  • \r\n
\r\n

Le syllabus est accessible depuis l'URL http://sites.uclouvain.be/SystInfo

\r\n
\r\n
Les pages de manuel sont accessibles depuis les URLs suivants :
\r\n
\r\n
\r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1630,7 +1630,7 @@ }, { "title": "Threads : plus grand commun diviseur", - "description": "On cherche à calculer le plus grand commun diviseur de deux très grands\r\nnombres. Pour ce faire, on calcule tous les diviseurs de chacun des 2\r\nnombres, et on regarde quel est leur PGCD. Pour ce faire, on déclare la\r\nliste chaînée suivante, permettant d'enregistrer en mémoire les\r\ndiviseurs d'un nombre :\r\n\r\n``` c\r\nstruct Node {\r\n unsigned int divisor;\r\n struct Node *next;\r\n};\r\n```\r\n\r\nÉcrivez une fonction void \\*factorize(void\r\n\\*n) qui retourne un pointeur vers une liste chaînée contenant\r\ntous les diviseurs dans l'ordre décroissant du nombre de type unsigned int vers lequel n pointe.\r\n\r\nÉcrivez une fonction unsigned int gcd(unsigned\r\nint a, unsigned int b) qui va lancer l'exécution de factorize pour a et b dans 2 threads différents\r\net va extraire des deux listes renvoyées le PGCD. Le nombre 1 est\r\nconsidéré comme un diviseur. Cette fonction renvoie 0 si une erreur\r\ns'est produite.\r\n", + "description": "

On cherche à calculer le plus grand commun diviseur de deux très grands nombres. Pour ce faire, on calcule tous les diviseurs de chacun des 2 nombres, et on regarde quel est leur PGCD. Pour ce faire, on déclare la liste chaînée suivante, permettant d'enregistrer en mémoire les diviseurs d'un nombre :

\r\n
struct Node {\r\n    unsigned int divisor;\r\n    struct Node *next;\r\n};
\r\n

Écrivez une fonction void *factorize(void *n) qui retourne un pointeur vers une liste chaînée contenant tous les diviseurs dans l'ordre décroissant du nombre de type unsigned int vers lequel n pointe.

\r\n

Écrivez une fonction unsigned int gcd(unsigned int a, unsigned int b) qui va lancer l'exécution de factorize pour a et b dans 2 threads différents et va extraire des deux listes renvoyées le PGCD. Le nombre 1 est considéré comme un diviseur. Cette fonction renvoie 0 si une erreur s'est produite.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1684,7 +1684,7 @@ }, { "title": "Conversions hexadécimales", - "description": "On souhaite convertir un entier non signé vers sa représentation\r\nhexadécimale. Par exemple l'entier 42 vaut \"2A\" en hexadécimal. De même,\r\non souhaite faire la conversion dans l'autre sens.\r\n\r\nÉcrivez une fonction unsigned int\r\nhex\\_to\\_int(char \\*hex) qui prend en argument une chaîne de\r\ncaractères représentant un nombre hexadécimal (cette chaîne ne peut\r\ncomporter que les chiffres de 0 à 9 et les lettres A à F).\r\n\r\nÉcrivez une fonction char\r\n\\*int\\_to\\_hex(unsigned int value, char \\*dest) qui prend en\r\nargument un entier non-signé et enregistre sa représentation\r\nhexadécimale dans la chaîne de caractères indiquée par dest. On suppose\r\nque dest est un tableau de 9 char au minimum. La fonction devra toujours\r\nrenvoyer le pointeur dest.\r\n", + "description": "

On souhaite convertir un entier non signé vers sa représentation hexadécimale. Par exemple l'entier 42 vaut \"2A\" en hexadécimal. De même, on souhaite faire la conversion dans l'autre sens.

\r\n

Écrivez une fonction unsigned int hex_to_int(char *hex) qui prend en argument une chaîne de caractères représentant un nombre hexadécimal (cette chaîne ne peut comporter que les chiffres de 0 à 9 et les lettres A à F).

\r\n

Écrivez une fonction char *int_to_hex(unsigned int value, char *dest) qui prend en argument un entier non-signé et enregistre sa représentation hexadécimale dans la chaîne de caractères indiquée par dest. On suppose que dest est un tableau de 9 char au minimum. La fonction devra toujours renvoyer le pointeur dest.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1738,7 +1738,7 @@ }, { "title": "Indexation d'un texte", - "description": "On souhaite indexer un texte afin de savoir quels mots reviennent le\r\nplus fréquemment dans un corpus. Le processus d'indexation se fait en 2\r\nphases : on compte d'abord le nombre d'occurrences de chaque mot, et on\r\nsupprime ensuite de la table d'indexation tous les mots qui n'ont pas\r\nété indexés au moins N fois. Le corpus est une chaîne de caractères\r\ncomposées uniquement de minuscules et où le seul délimiteur est un\r\nespace (pas de ponctuation). Votre programme n'est jamais censé produire\r\nd'erreurs de segmentation.\r\n\r\nOn définit la structure suivante représentant une entrée de l'index :\r\n\r\n``` c\r\ntypedef struct indexEntry {\r\n char word[26];\r\n int count; //nombre de fois qu'un mot est apparu dans le corpus\r\n struct indexEntry *next;\r\n} Entry;\r\n```\r\n\r\nÉcrivez une fonction Entry \\*build\\_index(char\r\n\\*corpus) qui renvoie l'index associé au corpus passé en\r\nparamètre. Vous pouvez modifier la chaine passée en argument.\r\n\r\nÉcrivez une fonction void filter\\_index(Entry\r\n\\*\\*index\\_head, int treshold) qui supprime de l'index tous les\r\nmots qui n'ont pas été recensés au moins treshold fois.\r\n\r\nVous avez accès aux fonctions de string.h\r\net de stdlib.h.\r\n", + "description": "

On souhaite indexer un texte afin de savoir quels mots reviennent le plus fréquemment dans un corpus. Le processus d'indexation se fait en 2 phases : on compte d'abord le nombre d'occurrences de chaque mot, et on supprime ensuite de la table d'indexation tous les mots qui n'ont pas été indexés au moins N fois. Le corpus est une chaîne de caractères composées uniquement de minuscules et où le seul délimiteur est un espace (pas de ponctuation). Votre programme n'est jamais censé produire d'erreurs de segmentation.

\r\n

On définit la structure suivante représentant une entrée de l'index :

\r\n
typedef struct indexEntry {\r\n    char word[26];\r\n    int count; //nombre de fois qu'un mot est apparu dans le corpus\r\n    struct indexEntry *next;\r\n} Entry;
\r\n

Écrivez une fonction Entry *build_index(char *corpus) qui renvoie l'index associé au corpus passé en paramètre. Vous pouvez modifier la chaine passée en argument.

\r\n

Écrivez une fonction void filter_index(Entry **index_head, int treshold) qui supprime de l'index tous les mots qui n'ont pas été recensés au moins treshold fois.

\r\n

Vous avez accès aux fonctions de string.h et de stdlib.h.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1792,7 +1792,7 @@ }, { "title": "Tri par insertion", - "description": "On désire implémenter un algorithme de tri par insertion sur un tableau\r\nde N entiers, le tableau et sa taille étant passés en argument.\r\n\r\nL'algorithme de tri est le suivant : Pour chaque élément d'indice i (i\r\nvariant de 1 à N-1)\r\n\r\n- cet élément devient la clé\r\n- on la compare avec l'élément d'indice i-1\r\n- si la clé est plus petite, on les échange et on recommence la\r\n comparaison avec l'élément précédent (d'indice i-2) et ainsi de\r\n suite, tant que la clé est plus petite que l'élément qui lui précède\r\n (ou qu'on est revenu au début du tableau)\r\n- quand la clé est à sa place (c'est-à-dire qu'elle est plus grande\r\n que ou égale à l'élément qui lui précède), la boucle intérieure est\r\n finie et on passe à l'élément d'indice i+1.\r\n", + "description": "

On désire implémenter un algorithme de tri par insertion sur un tableau de N entiers, le tableau et sa taille étant passés en argument.

\r\n

L'algorithme de tri est le suivant : Pour chaque élément d'indice i (i variant de 1 à N-1)

\r\n
    \r\n
  • cet élément devient la clé
  • \r\n
  • on la compare avec l'élément d'indice i-1
  • \r\n
  • si la clé est plus petite, on les échange et on recommence la comparaison avec l'élément précédent (d'indice i-2) et ainsi de suite, tant que la clé est plus petite que l'élément qui lui précède (ou qu'on est revenu au début du tableau)
  • \r\n
  • quand la clé est à sa place (c'est-à-dire qu'elle est plus grande que ou égale à l'élément qui lui précède), la boucle intérieure est finie et on passe à l'élément d'indice i+1.
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1846,7 +1846,7 @@ }, { "title": "Intersection de fichiers", - "description": "Le syllabus est accessible depuis l'URL\r\n\r\n\r\nLes pages de manuel sont accessibles depuis les URLs suivants : \r\n- (commandes)\r\n- (appels systèmes)\r\n- (fonctions des\r\n librairies)\r\n\r\n**Attention:** veuillez utiliser la version **HTML** du syllabus\r\n", + "description": "

Le syllabus est accessible depuis l'URL http://sites.uclouvain.be/SystInfo

\r\n
\r\n
Les pages de manuel sont accessibles depuis les URLs suivants :
\r\n
\r\n
\r\n
\r\n

Attention: veuillez utiliser la version HTML du syllabus

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2005,7 +2005,7 @@ }, { "title": "Filtering a linked list", - "description": "You have a linked list. Each element of the list is a `struct node`.\r\n\r\n``` c\r\nstruct node {\r\n struct node *next;\r\n int hash;\r\n int id;\r\n char name[20];\r\n char buffer[100];\r\n unsigned int timestamp;\r\n char acl;\r\n short flow;\r\n char *parent;\r\n void *fifo;\r\n};\r\n```\r\n", + "description": "

You have a linked list. Each element of the list is a struct node.

\r\n
struct node {\r\n    struct node *next;\r\n    int hash;\r\n    int id;\r\n    char name[20];\r\n    char buffer[100];\r\n    unsigned int timestamp;\r\n    char acl;\r\n    short flow;\r\n    char *parent;\r\n    void *fifo;\r\n};
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2064,7 +2064,7 @@ }, { "title": "Reading arguments", - "description": "When you execute a C program, its function `main()` is called with, as\r\nparameters, the name of the program and the arguments after the\r\nexecutable's name.\r\n", + "description": "

When you execute a C program, its function main() is called with, as parameters, the name of the program and the arguments after the executable's name.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2118,7 +2118,7 @@ }, { "title": "malloc, realloc et free INCOMPLETE", - "description": "La type de la plupart des variables en C est facile à déterminer.\r\nNéanmoins, le C contient aussi des types qui ne diffèrent que de façons\r\nsubtiles, comme les\r\n", + "description": "

La type de la plupart des variables en C est facile à déterminer. Néanmoins, le C contient aussi des types qui ne diffèrent que de façons subtiles, comme les

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2168,7 +2168,7 @@ }, { "title": "Multiplication de matrices", - "description": "Écrivez une fonction\r\n`int access(int *A, int taille, int ordonnee, int abscisse)` qui renvoie\r\nl'élément d'abscisse et d'ordonnée indiquées dans une matrice carrée\r\ntaille x taille d'entiers (il s'agit donc de l'élément A\\[ordonnee\\]\\[abscisse\\]). Les indices ordonnee et abscisse vont de 1 à taille.\r\n\r\nÉcrivez une fonction qui effectue la multiplication de deux matrices\r\ncarrées taille x taille d'entiers. Le prototype de la fonction est la\r\nsuivante : void mult(int \\*A, int \\*B, int \\*C,\r\nint taille) et elle calcule C = A x B. Les trois matrices sont\r\nstockées sous forme de tableau ligne par ligne et la place de la matrice\r\nC est déjà allouée.\r\n", + "description": "

Écrivez une fonction int access(int *A, int taille, int ordonnee, int abscisse) qui renvoie l'élément d'abscisse et d'ordonnée indiquées dans une matrice carrée taille x taille d'entiers (il s'agit donc de l'élément A[ordonnee][abscisse]). Les indices ordonnee et abscisse vont de 1 à taille.

\r\n

Écrivez une fonction qui effectue la multiplication de deux matrices carrées taille x taille d'entiers. Le prototype de la fonction est la suivante : void mult(int *A, int *B, int *C, int taille) et elle calcule C = A x B. Les trois matrices sont stockées sous forme de tableau ligne par ligne et la place de la matrice C est déjà allouée.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2222,7 +2222,7 @@ }, { "title": "strlen, strcat et strcasecmp", - "description": "La libraire\r\n[string(3)](https://sites.uclouvain.be/SystInfo/manpages/man3/string.3.html)\r\nimplémente un grand nombre de fonctions de manipulation des strings qui\r\nvous seront utiles lors de différents projets de programmation.\r\n", + "description": "

La libraire string(3) implémente un grand nombre de fonctions de manipulation des strings qui vous seront utiles lors de différents projets de programmation.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2280,7 +2280,7 @@ }, { "title": "Reading from the wire", - "description": "Back in 1977, you want to read your e-mail with your freshly bought\r\nApple II. You are connected to the ARPANET through a modem, but\r\nunfortunately the modem's manufacturer has only given a single function\r\n`modem_read`, to read the data received by the modem, with the following\r\nprototype :\r\n\r\n`void modem_read(void *buffer, int *buf_len);`\r\n\r\nThis function fills the supplied buffer with the data received from the\r\nmodem (an array of `char`), and writes the number of bytes written to\r\nthe value pointed by `buf_len`. It can write up to maximum 256 bytes in\r\na single call. This function is guaranteed to return.\r\n", + "description": "

Back in 1977, you want to read your e-mail with your freshly bought Apple II. You are connected to the ARPANET through a modem, but unfortunately the modem's manufacturer has only given a single function modem_read, to read the data received by the modem, with the following prototype :

\r\n

void modem_read(void *buffer, int *buf_len);

\r\n

This function fills the supplied buffer with the data received from the modem (an array of char), and writes the number of bytes written to the value pointed by buf_len. It can write up to maximum 256 bytes in a single call. This function is guaranteed to return.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2343,7 +2343,7 @@ }, { "title": "Manipulate the memory", - "description": "Given the following structure *university\\_t*:\r\n\r\n``` c\r\ntypedef struct university {\r\n char* city;\r\n int creation;\r\n person_t* rector;\r\n} university_t;\r\n```\r\n\r\nAnd the structure *person\\_t*:\r\n\r\n``` c\r\ntypedef struct person {\r\n char* name;\r\n int salary;\r\n int age;\r\n} person_t;\r\n```\r\n\r\nYou are asked to implement the functions `init_all` and `free_all`,\r\nwhich respectively initialises the structure *universiy\\_t* and frees\r\nall the memory associated with it.\r\n\r\nThe *name* and the *city* have been allocated with *malloc*.\r\n\r\n*Hint:* all the data may not have been initialised correctly. Therefore,\r\nyou have to handle all the cases (e.g. some pointers can be already\r\nNULL, and don't need to be freed).\r\n", + "description": "

Given the following structure university_t:

\r\n
typedef struct university {\r\n    char* city;\r\n    int creation;\r\n    person_t* rector;\r\n} university_t;
\r\n

And the structure person_t:

\r\n
typedef struct person {\r\n    char* name;\r\n    int salary;\r\n    int age;\r\n} person_t;
\r\n

You are asked to implement the functions init_all and free_all, which respectively initialises the structure universiy_t and frees all the memory associated with it.

\r\n

The name and the city have been allocated with malloc.

\r\n

Hint: all the data may not have been initialised correctly. Therefore, you have to handle all the cases (e.g. some pointers can be already NULL, and don't need to be freed).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2402,7 +2402,7 @@ }, { "title": "Mes propres sémaphores", - "description": "On souhaite écrire notre propre type de sémaphore à l'aide de mutex. On\r\ndéclare pour ce faire les 2 structures suivantes :\r\n\r\n``` c\r\ntypedef struct semProcess {\r\n pthread_mutex_t mutex;\r\n struct semProcess *next;\r\n} sem_process_t;\r\n\r\ntypedef struct mySem {\r\n int value;\r\n int capacity;\r\n sem_process_t *blocked_procs;\r\n pthread_mutex_t mutex;\r\n} mysem_t;\r\n```\r\n\r\nChaque sémaphore contient une valeur et une liste de processus bloqués.\r\nLe mutex de mySem devra être utilisé pour éviter que des appels\r\nconcurrents des fonctions sousmentionnées sur la même sémaphore ne\r\nsoient pas exécutés simultanément.\r\n\r\nÉcrivez une fonction int mysem\\_wait(mysem\\_t\r\n\\*sem) qui bloque le fil d'exécution si value de sem\r\nvaut 0 et ajoute le processus à la fin de la liste des processus\r\nbloqués. Pour bloquer un processus, vous devrez ajouter un sem\\_process\\_t à blocked\\_procs du sémaphore et verrouiller le\r\nmutex de sem\\_process\\_t. Si value est plus grand que 0, il est décrémenté.\r\n\r\nÉcrivez une fonction int mysem\\_post(mysem\\_t\r\n\\*sem) qui incrémente value de\r\nsem si aucun autre processus n'est\r\nbloqué, et sinon débloque le premier processus de la liste des processus\r\nbloqués. value ne peut jamais excéder\r\ncapacity. **ATTENTION** : Ne libérez pas\r\nla structure sem\\_process\\_t d'un processus libéré, contentez-vous de\r\nsupprimer son mutex. Considérez que la fonction mysem\\_close que vous n'avez pas à implémenter\r\ns'occupe de la libération des ressources.\r\n", + "description": "

On souhaite écrire notre propre type de sémaphore à l'aide de mutex. On déclare pour ce faire les 2 structures suivantes :

\r\n
typedef struct semProcess {\r\n    pthread_mutex_t mutex;\r\n    struct semProcess *next;\r\n} sem_process_t;\r\n\r\ntypedef struct mySem {\r\n    int value;\r\n    int capacity;\r\n    sem_process_t *blocked_procs;\r\n    pthread_mutex_t mutex;\r\n} mysem_t;
\r\n

Chaque sémaphore contient une valeur et une liste de processus bloqués. Le mutex de mySem devra être utilisé pour éviter que des appels concurrents des fonctions sousmentionnées sur la même sémaphore ne soient pas exécutés simultanément.

\r\n

Écrivez une fonction int mysem_wait(mysem_t *sem) qui bloque le fil d'exécution si value de sem vaut 0 et ajoute le processus à la fin de la liste des processus bloqués. Pour bloquer un processus, vous devrez ajouter un sem_process_t à blocked_procs du sémaphore et verrouiller le mutex de sem_process_t. Si value est plus grand que 0, il est décrémenté.

\r\n

Écrivez une fonction int mysem_post(mysem_t *sem) qui incrémente value de sem si aucun autre processus n'est bloqué, et sinon débloque le premier processus de la liste des processus bloqués. value ne peut jamais excéder capacity. ATTENTION : Ne libérez pas la structure sem_process_t d'un processus libéré, contentez-vous de supprimer son mutex. Considérez que la fonction mysem_close que vous n'avez pas à implémenter s'occupe de la libération des ressources.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2456,7 +2456,7 @@ }, { "title": "My strlen - REVIEWED", - "description": "Your objective is to implement\r\n[strlen](https://sites.uclouvain.be/SystInfo/manpages/man3/strlen.3.html)\r\none of the basic functions of the C library that deals with strings.\r\n", + "description": "

Your objective is to implement strlen one of the basic functions of the C library that deals with strings.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2510,7 +2510,7 @@ }, { "title": "Ordered linked list", - "description": "Given the provided implementation of a linked list, you need to\r\nimplement the `insert` function based on a specific order relation. The\r\ngoal is to implement an ordered list similar to a LinkedList with a Comparator in Java.\r\n", + "description": "

Given the provided implementation of a linked list, you need to implement the insert function based on a specific order relation. The goal is to implement an ordered list similar to a LinkedList with a Comparator in Java.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2569,7 +2569,7 @@ }, { "title": "Soumission du projet de seconde session", - "description": "Cette tâche permet de vérifier la validité de l'archive à soumettre pour\r\nle projet de seconde session sur les matrices creuses. Une archive ne\r\npassant pas le test ne sera pas corrigée.\r\n", + "description": "

Cette tâche permet de vérifier la validité de l'archive à soumettre pour le projet de seconde session sur les matrices creuses. Une archive ne passant pas le test ne sera pas corrigée.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2609,7 +2609,7 @@ }, { "title": "Palindrome", - "description": "Palindrome are strings of text which read the same backward as forward,\r\ni.e. : \"racecar\", \"a man a plan a canal panama\" or \"kayak\".\r\n", + "description": "

Palindrome are strings of text which read the same backward as forward, i.e. : \"racecar\", \"a man a plan a canal panama\" or \"kayak\".

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2663,7 +2663,7 @@ }, { "title": "Producteurs/Consommateurs", - "description": "Le syllabus est accessible depuis l'URL\r\n\r\n\r\nLes pages de manuel sont accessibles depuis les URLs suivants : \r\n- (commandes)\r\n- (appels systèmes)\r\n- (fonctions des\r\n librairies)\r\n\r\n**Attention:** veuillez utiliser la version **HTML** du syllabus\r\n\r\n![image](https://inginious.info.ucl.ac.be/course/LSINF1252/PC/buffer.png)\r\n", + "description": "

Le syllabus est accessible depuis l'URL http://sites.uclouvain.be/SystInfo

\r\n
\r\n
Les pages de manuel sont accessibles depuis les URLs suivants :
\r\n
\r\n
\r\n
\r\n

Attention: veuillez utiliser la version HTML du syllabus

\r\n

\"image\"

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2722,7 +2722,7 @@ }, { "title": "Pointer arithmetic", - "description": "A hacker wanted to challenge you and encrypted your hard drive. To\r\nunlock your drive, he gave you a function\r\n`get_key(int a, char b, int c)` which returns the decryption key if the\r\ncorrect parameters are given.\r\n\r\nHe then hid the parameters *a*, *b* and *c* in memory, and gave you a\r\npointer from which you can retrieve these parameters.\r\n", + "description": "

A hacker wanted to challenge you and encrypted your hard drive. To unlock your drive, he gave you a function get_key(int a, char b, int c) which returns the decryption key if the correct parameters are given.

\r\n

He then hid the parameters a, b and c in memory, and gave you a pointer from which you can retrieve these parameters.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2776,7 +2776,7 @@ }, { "title": "Polynômes", - "description": "On souhaite gérer des polynômes réels de degré inférieur ou égal à 10 en\r\nutilisant la structure suivante :\r\n\r\ntypedef struct { double coeff\\[10\\]; }\r\npoly;\r\n\r\nqui servira à représenter le polynôme où coeff\\[0\\] est le coefficient\r\ndu terme indépendant, coeff\\[1\\] le coefficient du terme en x, etc.\r\n\r\nÉcrivez une fonction double eval(poly \\*P,\r\ndouble x) qui calcule la valeur du polynôme P au point x. On\r\npourra se servir de la formule de Horner : P(x) = ((...(a\\_9\\*x +\r\na\\_8)*x + a\\_7)*x + ...)x + a\\_1)\\*x + a\\_0 où a\\_i est coeff\\[i\\].\r\n\r\nÉcrivez une fonction void derivee(poly \\*P, poly\r\n\\*Pderiv) qui inscrit dans Pderiv\r\nla dérivée du polynôme P.\r\n\r\nÉcrivez une fonction double racine(poly \\*P,\r\ndouble x0) qui calcule via la méthode de Newton la racine du\r\npolynôme P. La méthode est la suivante : on part d'un point initial, et\r\non construit une suite de points qui se rapprochent de la racine en\r\ncalculant à chaque étape un nouveau point à partir de la valeur du\r\npolynôme et de sa dérivée : x\\_n+1 = x\\_n - P(x\\_n)/P'(x\\_n). La\r\nfonction s'arrête lorsque abs(P(x\\_n)) < 0.0001. On suppose que le\r\ncalcul converge toujours vers une racine.\r\n", + "description": "

On souhaite gérer des polynômes réels de degré inférieur ou égal à 10 en utilisant la structure suivante :

\r\n

typedef struct { double coeff[10]; } poly;

\r\n

qui servira à représenter le polynôme où coeff[0] est le coefficient du terme indépendant, coeff[1] le coefficient du terme en x, etc.

\r\n

Écrivez une fonction double eval(poly *P, double x) qui calcule la valeur du polynôme P au point x. On pourra se servir de la formule de Horner : P(x) = ((...(a_9*x + a_8)x + a_7)x + ...)x + a_1)*x + a_0 où a_i est coeff[i].

\r\n

Écrivez une fonction void derivee(poly *P, poly *Pderiv) qui inscrit dans Pderiv la dérivée du polynôme P.

\r\n

Écrivez une fonction double racine(poly *P, double x0) qui calcule via la méthode de Newton la racine du polynôme P. La méthode est la suivante : on part d'un point initial, et on construit une suite de points qui se rapprochent de la racine en calculant à chaque étape un nouveau point à partir de la valeur du polynôme et de sa dérivée : x_n+1 = x_n - P(x_n)/P'(x_n). La fonction s'arrête lorsque abs(P(x_n)) < 0.0001. On suppose que le calcul converge toujours vers une racine.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2830,7 +2830,7 @@ }, { "title": "Printing data", - "description": "In this exercise, you will familiarize yourself with the functions\r\n[printf(3)](https://sites.uclouvain.be/SystInfo/manpages/man3/printf.3.html)\r\n(printing on the standard output) and\r\n[sprintf(3)](https://sites.uclouvain.be/SystInfo/manpages/man3/sprintf.3.html)\r\n(text formatting).\r\n", + "description": "

In this exercise, you will familiarize yourself with the functions printf(3) (printing on the standard output) and sprintf(3) (text formatting).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2889,7 +2889,7 @@ }, { "title": "Modification de fichier", - "description": "La fonction `reverse`, dont les spécifications sont reprises ci-dessous,\r\npermet de manipuler les données dans un fichier.\r\n\r\nLe syllabus est accessible depuis l'URL\r\n Les pages de manuel sont\r\naccessibles depuis les URLs suivants :\r\n\r\n- (commandes)\r\n- (appels systèmes)\r\n- (fonctions\r\n librairies)\r\n", + "description": "

La fonction reverse, dont les spécifications sont reprises ci-dessous, permet de manipuler les données dans un fichier.

\r\n

Le syllabus est accessible depuis l'URL http://sites.uclouvain.be/SystInfo Les pages de manuel sont accessibles depuis les URLs suivants :

\r\n\r\n", "tags": [ { "text": "INGINIOUS", @@ -2948,7 +2948,7 @@ }, { "title": "Calculatrice en notation polonaise inversée", - "description": "La notation polonaise inversée permet d'écrire de façon non-ambigüe sans\r\nparenthèses des formules arithmétiques. Par exemple, le calcul ((1 + 2)\r\n× 4) + 3 peut être noté 1 2 + 4 \\* 3 + en notation polonaise inverse, ou\r\nencore 3 4 1 2 + \\* +. L'avantage de cette notation est qu'elle est très\r\nfacilement compréhensible par un ordinateur : on imagine une pile où on\r\npeut soit ajouter un élément sur la pile, soit retirer le dernier\r\nélément ajouté. En parcourant la formule arithmétique, si on rencontre\r\nun nombre, on l'ajoute à la pile, si on rencontre une opérande (par ex.\r\nle symbole '+'), on retire les 2 derniers éléments de la pile, on en\r\nfait la somme et on ajoute le résultat à la pile.\r\n\r\nPour ce problème, vous ne pourrez utiliser que la variable globale double stack\\[STACK\\_SIZE\\], représentant la\r\npile, et int stack\\_height, représentant\r\nla hauteur actuelle de la pile, qui seront déjà initialisées à 0 et\r\naccessibles par vos fonctions. Vous pouvez supposer que les exemples\r\nutilisés par les tests feront en sorte que le nombre d'éléments actuels\r\ndans la pile ne dépassera jamais STACK\\_SIZE.\r\n\r\nÉcrivez une fonction void push(double value)\\` qui permet d'ajouter\r\nl'élément value à la pile.\r\n\r\nÉcrivez une fonction double pop(void) qui\r\nenlève et retourne l'élément au sommet de la pile.\r\n\r\nÉcrivez une fonction double rpn(char\r\n\\*expr) qui calcule l'expression en notation polonaise inverse\r\ncontenue dans expr et retourne le résultat. Vous pouvez supposer que\r\nexpr contiendra toujours une expression\r\ncorrecte où il ne restera jamais qu'un seul élément sur la pile à la fin\r\nde l'exécution. Indice : utilisez la fonction strtok(3) pour séparer les\r\ndifférents éléments de la chaîne et la fonction atof(3) pour convertir\r\nl'éventuel nombre rencontré en double. Exemple : \"4 2 5 \\* + 1 3 2 \\* +\r\n/\" est censé renvoyer 2. Les opérandes possibles sont + (addition), -\r\n(soustraction), \\* (multiplication) et / (division).\r\n", + "description": "

La notation polonaise inversée permet d'écrire de façon non-ambigüe sans parenthèses des formules arithmétiques. Par exemple, le calcul ((1 + 2) × 4) + 3 peut être noté 1 2 + 4 * 3 + en notation polonaise inverse, ou encore 3 4 1 2 + * +. L'avantage de cette notation est qu'elle est très facilement compréhensible par un ordinateur : on imagine une pile où on peut soit ajouter un élément sur la pile, soit retirer le dernier élément ajouté. En parcourant la formule arithmétique, si on rencontre un nombre, on l'ajoute à la pile, si on rencontre une opérande (par ex. le symbole '+'), on retire les 2 derniers éléments de la pile, on en fait la somme et on ajoute le résultat à la pile.

\r\n

Pour ce problème, vous ne pourrez utiliser que la variable globale double stack[STACK_SIZE], représentant la pile, et int stack_height, représentant la hauteur actuelle de la pile, qui seront déjà initialisées à 0 et accessibles par vos fonctions. Vous pouvez supposer que les exemples utilisés par les tests feront en sorte que le nombre d'éléments actuels dans la pile ne dépassera jamais STACK_SIZE.

\r\n

Écrivez une fonction void push(double value)` qui permet d'ajouter l'élément value à la pile.

\r\n

Écrivez une fonction double pop(void) qui enlève et retourne l'élément au sommet de la pile.

\r\n

Écrivez une fonction double rpn(char *expr) qui calcule l'expression en notation polonaise inverse contenue dans expr et retourne le résultat. Vous pouvez supposer que expr contiendra toujours une expression correcte où il ne restera jamais qu'un seul élément sur la pile à la fin de l'exécution. Indice : utilisez la fonction strtok(3) pour séparer les différents éléments de la chaîne et la fonction atof(3) pour convertir l'éventuel nombre rencontré en double. Exemple : \"4 2 5 * + 1 3 2 * + /\" est censé renvoyer 2. Les opérandes possibles sont + (addition), - (soustraction), * (multiplication) et / (division).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3002,7 +3002,7 @@ }, { "title": "Redirection des flux de sortie et d'erreur standards", - "description": "Dans un shell, il est parfois nécessaire d'exécuter des programmes en\r\nredirigeant leurs flux standards de sortie et d'erreur vers un fichier.\r\n\r\nLe syllabus est accessible depuis l'URL\r\n\r\n\r\nLes pages de manuel sont accessibles depuis les URLs suivants : -\r\n (commandes) -\r\n (appels systèmes) -\r\n (fonctions des\r\nlibrairies)\r\n", + "description": "

Dans un shell, il est parfois nécessaire d'exécuter des programmes en redirigeant leurs flux standards de sortie et d'erreur vers un fichier.

\r\n

Le syllabus est accessible depuis l'URL http://sites.uclouvain.be/SystInfo

\r\n

Les pages de manuel sont accessibles depuis les URLs suivants : - http://sites.uclouvain.be/SystInfo/manpages/man1 (commandes) - http://sites.uclouvain.be/SystInfo/manpages/man2 (appels systèmes) - http://sites.uclouvain.be/SystInfo/manpages/man3 (fonctions des librairies)

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3056,7 +3056,7 @@ }, { "title": "Capture The Flag 1", - "description": "Téléchargez [cette\r\narchive](https://inginious.info.ucl.ac.be/course/LSINF1252/s1_ctf1/archive.tar.gz),\r\nouvrez `FirstMission` et suivez les instructions. Un code individuel\r\nvous sera fourni à la fin de l'exercice. Entrez-le ci-dessous pour\r\nconfirmer que vous avez complètement réalisé cet exercice.\r\n", + "description": "

Téléchargez cette archive, ouvrez FirstMission et suivez les instructions. Un code individuel vous sera fourni à la fin de l'exercice. Entrez-le ci-dessous pour confirmer que vous avez complètement réalisé cet exercice.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3109,7 +3109,7 @@ }, { "title": "Capture The Flag 2", - "description": "Téléchargez [cette\r\narchive](https://inginious.info.ucl.ac.be/course/LSINF1252/s1_ctf2/CTF2.tar.gz).\r\nPlacez son contenu dans un dossier de votre choix, lisez le fichier\r\n`FirstMission` et suivez les consignes.\r\n", + "description": "

Téléchargez cette archive. Placez son contenu dans un dossier de votre choix, lisez le fichier FirstMission et suivez les consignes.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3158,7 +3158,7 @@ }, { "title": "Diff", - "description": "3 students are suspected of doing illegal things with computers of the\r\nuniversity. They know that the computers send logs to the server and so\r\nhid their activity from the server. But they don't know that logs are\r\nalso saved on the different computers. There are the logs from the\r\nserver and from the students, use\r\n[diff(1)](https://sites.uclouvain.be/SystInfo/manpages/man1/diff.1.html)\r\nto compare them and find which students are innocent.\r\n\r\n- [syslog](https://inginious.info.ucl.ac.be/course/LSINF1252/s1_diff/syslog.log)\r\n- [student\r\n 1](https://inginious.info.ucl.ac.be/course/LSINF1252/s1_diff/student1.log)\r\n- [student\r\n 2](https://inginious.info.ucl.ac.be/course/LSINF1252/s1_diff/student2.log)\r\n- [student\r\n 3](https://inginious.info.ucl.ac.be/course/LSINF1252/s1_diff/student3.log)\r\n", + "description": "

3 students are suspected of doing illegal things with computers of the university. They know that the computers send logs to the server and so hid their activity from the server. But they don't know that logs are also saved on the different computers. There are the logs from the server and from the students, use diff(1) to compare them and find which students are innocent.

\r\n\r\n", "tags": [ { "text": "INGINIOUS", @@ -3211,7 +3211,7 @@ }, { "title": "grep", - "description": "The [grep(1)\r\ncommand](https://sites.uclouvain.be/SystInfo/manpages/man1/grep.1.html)\r\ncan be used to detect or extract lots of information from text files.\r\nWhen working with source code,\r\n[grep(1)](https://sites.uclouvain.be/SystInfo/manpages/man1/grep.1.html)\r\ncan help you to find in which files some functions or constants have\r\nbeen defined. For this exercise, we will use the source code of the\r\n[CUnit](http://cunit.sourceforge.net) testing framework that you can\r\ndownload as a [tar\r\narchive](https://inginious.info.ucl.ac.be/course/LSINF1252/s1_grep/CUnit.tar).\r\n", + "description": "

The grep(1) command can be used to detect or extract lots of information from text files. When working with source code, grep(1) can help you to find in which files some functions or constants have been defined. For this exercise, we will use the source code of the CUnit testing framework that you can download as a tar archive.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3260,7 +3260,7 @@ }, { "title": "Pipes", - "description": "In this exercise you will learn to use pipes, refer to [this\r\nsection](https://sites.uclouvain.be/SystInfo/notes/Theorie/html/intro.html#shell)\r\nfor their use.\r\n\r\nDownload the following\r\n[input](https://inginious.info.ucl.ac.be/course/LSINF1252/s1_pipes/input.txt)\r\nfrom where you want to extract an alphabetically **sorted** list of\r\n**unique** hashtags. This can easily be done with pipes. To only select\r\nhashtags from the input, you can either use `sed '/ [^{#}]/d'` or\r\n[grep(1)](https://sites.uclouvain.be/SystInfo/manpages/man1/grep.1.html).\r\n", + "description": "

In this exercise you will learn to use pipes, refer to this section for their use.

\r\n

Download the following input from where you want to extract an alphabetically sorted list of unique hashtags. This can easily be done with pipes. To only select hashtags from the input, you can either use sed '/ [^{#}]/d' or grep(1).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3313,7 +3313,7 @@ }, { "title": "tar", - "description": "Unix users often need to backup files and directories or send them over\r\nthe Internet.\r\n[tar(1)](https://sites.uclouvain.be/SystInfo/manpages/man1/tar.1.html)\r\nis a very useful tool which can be used to create compressed archives of\r\ndirectories and all the files that they contain. At the end of a\r\nproject, you will have created the following files (you can download\r\nthem from\r\n[here](https://inginious.info.ucl.ac.be/course/LSINF1252/s1_tar/Enonce.zip))\r\n\r\n``` console\r\n/\r\n file\r\n folder1/\r\n file1.c\r\n file2.c\r\n file3.c\r\n folder2/\r\n file1.h\r\n fime2.h\r\n file3.h\r\n```\r\n\r\nUsing\r\n[tar(1)](https://sites.uclouvain.be/SystInfo/manpages/man1/tar.1.html),\r\ncreate a `.tar.gz` compressed archive which contains all these files and\r\ndirectories and submit it below.\r\n", + "description": "

Unix users often need to backup files and directories or send them over the Internet. tar(1) is a very useful tool which can be used to create compressed archives of directories and all the files that they contain. At the end of a project, you will have created the following files (you can download them from here)

\r\n
/\r\n    file\r\n    folder1/\r\n        file1.c\r\n        file2.c\r\n        file3.c\r\n    folder2/\r\n        file1.h\r\n        fime2.h\r\n        file3.h
\r\n

Using tar(1), create a .tar.gz compressed archive which contains all these files and directories and submit it below.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3366,7 +3366,7 @@ }, { "title": "make basics", - "description": "*Estimated time: 20 minutes*\r\n\r\n`make` is a task runner for targets described in a Makefile. It is mostly used to control the\r\ncompilation of an executable from source code. Thus, you can use it to\r\nautomate the tidious task of compiling your c code, or even automate the\r\ncompilation of a report made with LaTeX.\r\n\r\n`make` a new beginning\r\n======================\r\n\r\nTo give you a first taste, open up a *terminal* and type the following\r\ncommand: `make`.\r\n\r\n`make` will greet you with the following message:\r\n\r\n``` \r\nmake: *** No targets specified and no makefile found. Stop.\r\n```\r\n\r\nSo what happened? `make` first start to search in your *current\r\ndirectory* for a file called `Makefile`. This file contains\r\n*instructions*, aka *rules*, that tell `make` what to do. Since there is\r\nno such file, `make` stops almost instantly.\r\n\r\n`make` it simple\r\n================\r\n\r\nNow write a simple hello world program, which you will save into a file\r\ncalled `hello.c`. This program will print the following on the standard\r\noutput:\r\n\r\n``` \r\nHello make\r\n```\r\n\r\nNow, fire up your terminal, use `cd path/to/hello/folder/` to go to the\r\ndirectory which contains `hello.c` ([download\r\nhello.c](https://inginious.info.ucl.ac.be/course/LSINF1252/s2_make/hello.c)\r\nto compare with what you did) and type: `make hello`\r\n\r\nNow the `make` comes alive and tells you something like:\r\n\r\n``` \r\ngcc hello.c -o hello\r\n```\r\n\r\nWow! What happened? When you typed `make hello`, `hello` is what is\r\ncalled a **target**. A **target** is usually the name of a file that is\r\ngenerated by a program; examples of targets are executable or object\r\nfiles.\r\n\r\nBasically, `make` will search for a file named `hello` and detect from\r\nthat file what programming language it uses. For most languages, `make`\r\nhas some basic builtin recipes, called **implicit rules**, to compile\r\nit. Here the **recipe** is given in the above output.\r\n\r\nIn that output:\r\n\r\n- `gcc` stands for *GNU C Compiler*;\r\n- `hello.c` the C program to be compiled;\r\n- `-o hello` an option to place the output of the compilation in the\r\n file `hello`.\r\n\r\nNow if you type `ls` in your command line, you will see that a file\r\n`hello` appeared. This is the **executable** built by `make` from\r\n`hello.c`. Now you can execute it and verify what is printed on the\r\nstandard output.\r\n\r\nIf you type again `make hello` in your command line, it will tell you:\r\n\r\n``` \r\nmake: 'hello' is up to date.\r\n```\r\n\r\nThat is because `make` only builds the files that are changed. If\r\n`hello` is more recent than its source file `hello.c`, `make` will skip\r\nthe compilation process.\r\n\r\nTo see this, modify `hello.c` to write the following on the standard\r\noutput:\r\n\r\n``` \r\nHello, make!\r\n```\r\n\r\nFinally, run `make hello` again. Since `hello.c` is more recent than\r\n`hello`, `make` will compile the source file again.\r\n\r\nThats it, you made your first experiences with `make`.\r\n\r\nNow I strongly recommend you read [sections 2.1 to 2.3. in the GNU make\r\nmanual](https://www.gnu.org/software/make/manual/make.html#Introduction).\r\nIt will only take you 10 minutes (included in the above given estimated\r\ntime) and will help you understand how to `make` magic happen.\r\n\r\nOnce you read these 3 sections, let us practice a bit.\r\n\r\nTo try the following questions locally, you can download a zip file of\r\nthe questions folder\r\n[here](https://inginious.info.ucl.ac.be/course/LSINF1252/s2_make/make_me.zip).\r\n\r\n------------------------------------------------------------------------\r\n\r\nReferences\r\n==========\r\n\r\n- \r\n- \r\n", + "description": "

Estimated time: 20 minutes

\r\n

make is a task runner for targets described in a Makefile. It is mostly used to control the compilation of an executable from source code. Thus, you can use it to automate the tidious task of compiling your c code, or even automate the compilation of a report made with LaTeX.

\r\n

make a new beginning

\r\n

To give you a first taste, open up a terminal and type the following command: make.

\r\n

make will greet you with the following message:

\r\n
make: *** No targets specified and no makefile found.  Stop.
\r\n

So what happened? make first start to search in your current directory for a file called Makefile. This file contains instructions, aka rules, that tell make what to do. Since there is no such file, make stops almost instantly.

\r\n

make it simple

\r\n

Now write a simple hello world program, which you will save into a file called hello.c. This program will print the following on the standard output:

\r\n
Hello make
\r\n

Now, fire up your terminal, use cd path/to/hello/folder/ to go to the directory which contains hello.c (download hello.c to compare with what you did) and type: make hello

\r\n

Now the make comes alive and tells you something like:

\r\n
gcc     hello.c   -o hello
\r\n

Wow! What happened? When you typed make hello, hello is what is called a target. A target is usually the name of a file that is generated by a program; examples of targets are executable or object files.

\r\n

Basically, make will search for a file named hello and detect from that file what programming language it uses. For most languages, make has some basic builtin recipes, called implicit rules, to compile it. Here the recipe is given in the above output.

\r\n

In that output:

\r\n
    \r\n
  • gcc stands for GNU C Compiler;
  • \r\n
  • hello.c the C program to be compiled;
  • \r\n
  • -o hello an option to place the output of the compilation in the file hello.
  • \r\n
\r\n

Now if you type ls in your command line, you will see that a file hello appeared. This is the executable built by make from hello.c. Now you can execute it and verify what is printed on the standard output.

\r\n

If you type again make hello in your command line, it will tell you:

\r\n
make: 'hello' is up to date.
\r\n

That is because make only builds the files that are changed. If hello is more recent than its source file hello.c, make will skip the compilation process.

\r\n

To see this, modify hello.c to write the following on the standard output:

\r\n
Hello, make!
\r\n

Finally, run make hello again. Since hello.c is more recent than hello, make will compile the source file again.

\r\n

Thats it, you made your first experiences with make.

\r\n

Now I strongly recommend you read sections 2.1 to 2.3. in the GNU make manual. It will only take you 10 minutes (included in the above given estimated time) and will help you understand how to make magic happen.

\r\n

Once you read these 3 sections, let us practice a bit.

\r\n

To try the following questions locally, you can download a zip file of the questions folder here.

\r\n
\r\n

References

\r\n\r\n", "tags": [ { "text": "INGINIOUS", @@ -3433,7 +3433,7 @@ }, { "title": "make basics - calculator", - "description": "*Estimated time: 5 minutes*\r\n\r\nYou have just built a simple calculator. When typing `ls` in your\r\ncommand line, the source folder has the following structure:\r\n\r\n``` console\r\ncalc.c calc.h Makefile operations.c operations.h\r\n```\r\n\r\n`calc.c` contains the calculator which handles the 4 basic operations:\r\naddition, substraction, multiplication, and division. These 4 operations\r\nare implemented in `operations.c`.\r\n\r\nAs you might have noticed, there are also two other files: `calc.h` and\r\n`operations.h`. These are the corresponding **header** files of `calc.c`\r\nand `operations.c`. These headers contain the function prototypes and\r\nspecifications, but not their definitions. They can also contain\r\n`extern` declarations of variables. For more on that, see [this\r\npage](https://www.tutorialspoint.com/cprogramming/c_header_files.htm) or\r\nchapter 4 in\r\n[kernighan2006c].\r\n\r\nWhen compiling this calculator, you need to specify in the `Makefile`\r\nrules the header files needed by `calc.c`, that is both `calc.h` and\r\n`operations.h`.\r\n\r\n------------------------------------------------------------------------\r\n\r\nkernighan2006c \r\nKernighan, B. W., & Ritchie, D. M. (2006). The C programming language.\r\n", + "description": "

Estimated time: 5 minutes

\r\n

You have just built a simple calculator. When typing ls in your command line, the source folder has the following structure:

\r\n
calc.c    calc.h    Makefile    operations.c    operations.h
\r\n

calc.c contains the calculator which handles the 4 basic operations: addition, substraction, multiplication, and division. These 4 operations are implemented in operations.c.

\r\n

As you might have noticed, there are also two other files: calc.h and operations.h. These are the corresponding header files of calc.c and operations.c. These headers contain the function prototypes and specifications, but not their definitions. They can also contain extern declarations of variables. For more on that, see this page or chapter 4 in [kernighan2006c].

\r\n

When compiling this calculator, you need to specify in the Makefile rules the header files needed by calc.c, that is both calc.h and operations.h.

\r\n
\r\n
\r\n
\r\n
kernighan2006c
\r\n

Kernighan, B. W., & Ritchie, D. M. (2006). The C programming language.

\r\n
\r\n
\r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -3495,7 +3495,7 @@ }, { "title": "make basics - multiple choice questions", - "description": "*Estimated time: 5 minutes*\r\n", + "description": "

Estimated time: 5 minutes

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3552,7 +3552,7 @@ }, { "title": "Cunit basics", - "description": "*Estimated time: 5 minutes*\r\n", + "description": "

Estimated time: 5 minutes

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3604,7 +3604,7 @@ }, { "title": "make more basics", - "description": "*Estimated time: 20 minutes*\r\n\r\nFirst, read [sections 2.4 to 2.7. in the GNU make\r\nmanual](https://www.gnu.org/software/make/manual/make.html#Variables-Simplify).\r\nIt will only take you 10 minutes (included in the above given estimated\r\ntime) and will help you understand how to `make` more magic happen.\r\n\r\nAs you have just read, one very useful use of Makefiles is to use\r\nvariables. You can use a variable to define the C compiler you will use\r\nand the flags you want it to use.\r\n\r\nFor instance, let us consider the following excerpt of a Makefile:\r\n\r\n``` console\r\n# See gcc/clang manual to understand all flags\r\nCFLAGS += -std=c99 # Define which version of the C standard to use\r\nCFLAGS += -Wall # Enable the 'all' set of warnings\r\nCFLAGS += -Werror # Treat all warnings as error\r\nCFLAGS += -Wshadow # Warn when shadowing variables\r\nCFLAGS += -Wextra # Enable additional warnings\r\nCFLAGS += -O2 -D_FORTIFY_SOURCE=2 # Add canary code, i.e. detect buffer overflows\r\nCFLAGS += -fstack-protector-all # Add canary code to detect stack smashing\r\n\r\n# Object files\r\nOBJ = # TODO\r\n\r\n## all : Build calculator (by default)\r\n# Default target\r\nall: calc\r\n\r\n## calc : Build calculator\r\ncalc: # TODO\r\n\r\ncalc.o: # TODO\r\n\r\noperations.o: # TODO\r\n\r\n.PHONY: clean mrproper help\r\n\r\n## clean : Remove auto-generated files\r\nclean:\r\n @rm -f src/*.o\r\n\r\n## mrproper : Remove both auto-generated & built files\r\nmrproper: clean\r\n @rm -f calc\r\n\r\n## help : Show different make options\r\nhelp: Makefile\r\n @sed -n 's/^##//p' $<\r\n```\r\n\r\nIn this file we used 3 variables: `CC` to define the C Compiler;\r\n`CFLAGS` to define the C Compiler flags; `OBJ` to define the object\r\nfiles. This is a common use of variables to both simplify the Makefile\r\nand easily change the settings of the compiler.\r\n\r\nNotice the use of two `.PHONY` targets: `clean` which will remove\r\nauto-generated files, e.g. object files; `mrproper` which will remove\r\nboth auto-generated & built files, e.g. executable files; `help` which\r\nwill search for lines starting with `##` and print them on `stdout`\r\nwithout the `##`. Try it out by tipping `make help`.\r\n", + "description": "

Estimated time: 20 minutes

\r\n

First, read sections 2.4 to 2.7. in the GNU make manual. It will only take you 10 minutes (included in the above given estimated time) and will help you understand how to make more magic happen.

\r\n

As you have just read, one very useful use of Makefiles is to use variables. You can use a variable to define the C compiler you will use and the flags you want it to use.

\r\n

For instance, let us consider the following excerpt of a Makefile:

\r\n
# See gcc/clang manual to understand all flags\r\nCFLAGS += -std=c99 # Define which version of the C standard to use\r\nCFLAGS += -Wall # Enable the 'all' set of warnings\r\nCFLAGS += -Werror # Treat all warnings as error\r\nCFLAGS += -Wshadow # Warn when shadowing variables\r\nCFLAGS += -Wextra # Enable additional warnings\r\nCFLAGS += -O2 -D_FORTIFY_SOURCE=2 # Add canary code, i.e. detect buffer overflows\r\nCFLAGS += -fstack-protector-all # Add canary code to detect stack smashing\r\n\r\n# Object files\r\nOBJ = # TODO\r\n\r\n## all        : Build calculator (by default)\r\n# Default target\r\nall: calc\r\n\r\n## calc        : Build calculator\r\ncalc: # TODO\r\n\r\ncalc.o: # TODO\r\n\r\noperations.o: # TODO\r\n\r\n.PHONY: clean mrproper help\r\n\r\n## clean        : Remove auto-generated files\r\nclean:\r\n    @rm -f src/*.o\r\n\r\n## mrproper    : Remove both auto-generated & built files\r\nmrproper: clean\r\n    @rm -f calc\r\n\r\n## help        : Show different make options\r\nhelp: Makefile\r\n    @sed -n 's/^##//p' $<
\r\n

In this file we used 3 variables: CC to define the C Compiler; CFLAGS to define the C Compiler flags; OBJ to define the object files. This is a common use of variables to both simplify the Makefile and easily change the settings of the compiler.

\r\n

Notice the use of two .PHONY targets: clean which will remove auto-generated files, e.g. object files; mrproper which will remove both auto-generated & built files, e.g. executable files; help which will search for lines starting with ## and print them on stdout without the ##. Try it out by tipping make help.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3661,7 +3661,7 @@ }, { "title": "make more basics - multiple choice questions", - "description": "*Estimated time: 15 minutes*\r\n", + "description": "

Estimated time: 15 minutes

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3713,7 +3713,7 @@ }, { "title": "make tests", - "description": "*Estimated time: 15 minutes*\r\n\r\nThis week, we will see how to automate the testing process. You have the\r\nfollowing project folder structure:\r\n\r\n``` \r\nsrc/\r\n calc.c\r\n calc.h\r\n operations.c\r\n operations.h\r\ntest/\r\n calc_test.c\r\n operations_test.c\r\nMakefile\r\n```\r\n\r\nThe `Makefile` is partially done, but somehow the target `test` for\r\nbuilding the tests was lost.\r\n\r\n``` \r\nCC = gcc\r\n# See gcc/clang manual to understand all flags\r\nCFLAGS += -std=c99 # Define which version of the C standard to use\r\nCFLAGS += -Wall # Enable the 'all' set of warnings\r\nCFLAGS += -Werror # Treat all warnings as error\r\nCFLAGS += -Wshadow # Warn when shadowing variables\r\nCFLAGS += -Wextra # Enable additional warnings\r\nCFLAGS += -O2 -D_FORTIFY_SOURCE=2 # Add canary code, i.e. detect buffer overflows\r\nCFLAGS += -fstack-protector-all # Add canary code to detect stack smashing\r\n\r\n# We have no libraries to link against except libc, but we want to keep\r\n# the symbols for debugging\r\nLDFLAGS= -rdynamic -lcunit\r\n\r\n## all : Build calc (by default)\r\n# Default target\r\nall: calc\r\n\r\n## debug : Build calc in debug mode\r\n# If we run `make debug` instead, keep the debug symbols for gdb\r\n# and define the DEBUG macro.\r\ndebug: CFLAGS += -g -DDEBUG -Wno-unused-parameter -fno-omit-frame-pointer\r\ndebug: clean calc\r\n\r\n## calc : Build calc\r\n# We use an implicit rule: look for the files {calc,operations}.{c,h},\r\n# compile them and link the resulting *.o into an executable named calc\r\ncalc: calc.o operations.o\r\n $(CC) $(CFLAGS) -o calc {calc,operations}.o\r\n\r\n# We use an implicit rule: look for the files calc.{c,h},\r\n# compile them w/out linking\r\ncalc.o: src/calc.c src/calc.h\r\n $(CC) $(CFLAGS) -c src/calc.{c,h}\r\n# We use an implicit rule: look for the files operations.{c,h},\r\n# compile them w/out linking\r\noperations.o: src/operations.c src/operations.h\r\n $(CC) $(CFLAGS) -c src/operations.{c,h}\r\n\r\n# YOUR CODE HERE #\r\n\r\n# Declare clean, mrproper and help as a phony targets\r\n.PHONY: clean mrproper help\r\n\r\n## clean : Remove auto-generated files from build\r\nclean:\r\n @rm -f *.o\r\n\r\n## clean-debug : Removve auto-generated files from debug mode build\r\nclean-debug:\r\n @rm -f src/*.gch\r\n## mrproper : Remove both auto-generated & built files\r\nmrproper: clean clean-debug\r\n @rm -f calc\r\n\r\n## help : Show different make options\r\nhelp: Makefile\r\n @sed -n 's/^##//p' $<\r\n```\r\n\r\nTo try locally, you can download the project folder \\_here <>\r\n", + "description": "

Estimated time: 15 minutes

\r\n

This week, we will see how to automate the testing process. You have the following project folder structure:

\r\n
src/\r\n    calc.c\r\n    calc.h\r\n    operations.c\r\n    operations.h\r\ntest/\r\n    calc_test.c\r\n    operations_test.c\r\nMakefile
\r\n

The Makefile is partially done, but somehow the target test for building the tests was lost.

\r\n
CC = gcc\r\n# See gcc/clang manual to understand all flags\r\nCFLAGS += -std=c99 # Define which version of the C standard to use\r\nCFLAGS += -Wall # Enable the 'all' set of warnings\r\nCFLAGS += -Werror # Treat all warnings as error\r\nCFLAGS += -Wshadow # Warn when shadowing variables\r\nCFLAGS += -Wextra # Enable additional warnings\r\nCFLAGS += -O2 -D_FORTIFY_SOURCE=2 # Add canary code, i.e. detect buffer overflows\r\nCFLAGS += -fstack-protector-all # Add canary code to detect stack smashing\r\n\r\n# We have no libraries to link against except libc, but we want to keep\r\n# the symbols for debugging\r\nLDFLAGS= -rdynamic -lcunit\r\n\r\n## all        : Build calc (by default)\r\n# Default target\r\nall: calc\r\n\r\n## debug        : Build calc in debug mode\r\n# If we run `make debug` instead, keep the debug symbols for gdb\r\n# and define the DEBUG macro.\r\ndebug: CFLAGS += -g -DDEBUG -Wno-unused-parameter -fno-omit-frame-pointer\r\ndebug: clean calc\r\n\r\n## calc        : Build calc\r\n# We use an implicit rule: look for the files {calc,operations}.{c,h},\r\n# compile them and link the resulting *.o into an executable named calc\r\ncalc: calc.o operations.o\r\n    $(CC) $(CFLAGS)  -o calc {calc,operations}.o\r\n\r\n# We use an implicit rule: look for the files calc.{c,h},\r\n# compile them w/out linking\r\ncalc.o: src/calc.c src/calc.h\r\n    $(CC) $(CFLAGS) -c src/calc.{c,h}\r\n# We use an implicit rule: look for the files operations.{c,h},\r\n# compile them w/out linking\r\noperations.o: src/operations.c src/operations.h\r\n    $(CC) $(CFLAGS) -c src/operations.{c,h}\r\n\r\n# YOUR CODE HERE #\r\n\r\n# Declare clean, mrproper and help as a phony targets\r\n.PHONY: clean mrproper help\r\n\r\n## clean        : Remove auto-generated files from build\r\nclean:\r\n    @rm -f *.o\r\n\r\n## clean-debug        : Removve auto-generated files from debug mode build\r\nclean-debug:\r\n    @rm -f src/*.gch\r\n## mrproper    : Remove both auto-generated & built files\r\nmrproper: clean clean-debug\r\n    @rm -f calc\r\n\r\n## help        : Show different make options\r\nhelp: Makefile\r\n    @sed -n 's/^##//p' $<
\r\n

To try locally, you can download the project folder _here <>

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3775,7 +3775,7 @@ }, { "title": "Save struct into file", - "description": "*Estimated time: 25 minutes*\r\n\r\nYou are currently processing an array composed of `struct point` defined\r\nbelow. In this programme, you need to store the content of the entire\r\narray in a file to be able to reuse it later. Write a C function to\r\nwrite the array composed of `struct point` into a file. The file may\r\nalready exist or not. After the execution of the function, the file\r\nshould only contain the array. If the file has to be created, the user\r\nwho created it must have the permission to read it.\r\n\r\n``` c\r\ntypedef struct point {\r\n int x;\r\n int y;\r\n int z;\r\n} point_t;\r\n```\r\n\r\nUse only `open(2)`, `write(2)` and `close(2)`. You can only call\r\n`write(2)` once.\r\n\r\nHint : read carefully the man page of `open(2)` to manage all the cases\r\nmentioned above. Be sure to open the file with the appropriate rights.\r\n", + "description": "

Estimated time: 25 minutes

\r\n

You are currently processing an array composed of struct point defined below. In this programme, you need to store the content of the entire array in a file to be able to reuse it later. Write a C function to write the array composed of struct point into a file. The file may already exist or not. After the execution of the function, the file should only contain the array. If the file has to be created, the user who created it must have the permission to read it.

\r\n
typedef struct point {\r\n    int x;\r\n    int y;\r\n    int z;\r\n} point_t;
\r\n

Use only open(2), write(2) and close(2). You can only call write(2) once.

\r\n

Hint : read carefully the man page of open(2) to manage all the cases mentioned above. Be sure to open the file with the appropriate rights.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3841,7 +3841,7 @@ }, { "title": "Reading integers in a binary file", - "description": "*Estimated time: 25 minutes*\r\n\r\nGiven a binary file containing some (possibly none) positive integers\r\n(`int`) that were stored in the file by successive calls of\r\n`write(fd,&num,sizeof(int))` write code that computes the sum of all\r\nintegers that were stored in the file. The function returns the sum when\r\nthere are no errors. In case of errors, it returns.\r\n\r\n- If `open()` fails, return `-1`.\r\n- If `read()` fails, return `-2`.\r\n- If `close()` fails, return `-3`.\r\n\r\nYou can only use `open(2)`, `read(2)`, `write(2)` and `close(2)`.\r\n", + "description": "

Estimated time: 25 minutes

\r\n

Given a binary file containing some (possibly none) positive integers (int) that were stored in the file by successive calls of write(fd,&num,sizeof(int)) write code that computes the sum of all integers that were stored in the file. The function returns the sum when there are no errors. In case of errors, it returns.

\r\n
    \r\n
  • If open() fails, return -1.
  • \r\n
  • If read() fails, return -2.
  • \r\n
  • If close() fails, return -3.
  • \r\n
\r\n

You can only use open(2), read(2), write(2) and close(2).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3911,7 +3911,7 @@ }, { "title": "Get and set on array stored in binary file", - "description": "*Estimated time: 30 minutes*\r\n\r\nGiven a file containing a large array of integers, you have to write a\r\nfunction to edit the element at a given index in the array and another\r\nfunction to retrieve a specific element from this array.\r\n\r\nSince the array is huge, you cannot load it completely in memory.\r\nConsequently, you have to naviguate directly through the array in the\r\nfile by using `lseek(2)`.\r\n\r\nYou may want to use `fstat(2)` to obtain informations about a given\r\nfile.\r\n\r\nUse only `open(2)`, `read(2)`, `write(2)`, `close(2)` and `lseek(2)`.\r\n", + "description": "

Estimated time: 30 minutes

\r\n

Given a file containing a large array of integers, you have to write a function to edit the element at a given index in the array and another function to retrieve a specific element from this array.

\r\n

Since the array is huge, you cannot load it completely in memory. Consequently, you have to naviguate directly through the array in the file by using lseek(2).

\r\n

You may want to use fstat(2) to obtain informations about a given file.

\r\n

Use only open(2), read(2), write(2), close(2) and lseek(2).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3973,7 +3973,7 @@ }, { "title": "File copy", - "description": "*Estimated time: 30 minutes*\r\n\r\nGiven a file containing arbitrary bytes, you must write a function that\r\ncopies the file. Obviously, your function cannot modify the content of\r\nthe original file. Beware that the copied file should have the same\r\npermissions as the original file.\r\n\r\nUse only `open(2)`, `read(2)`, `write(2)`, `stat(2)` and `close(2)`.\r\n\r\n*Hint: you may need either to go through the file or to get the total\r\nsize to copy all of it.*\r\n", + "description": "

Estimated time: 30 minutes

\r\n

Given a file containing arbitrary bytes, you must write a function that copies the file. Obviously, your function cannot modify the content of the original file. Beware that the copied file should have the same permissions as the original file.

\r\n

Use only open(2), read(2), write(2), stat(2) and close(2).

\r\n

Hint: you may need either to go through the file or to get the total size to copy all of it.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4043,7 +4043,7 @@ }, { "title": "File exists", - "description": "*Estimated time: 10 minutes*\r\n\r\nUsing\r\n[open(2)](https://sites.uclouvain.be/SystInfo/manpages/man2/open.2.html),\r\ndetermine if a file exists.\r\n", + "description": "

Estimated time: 10 minutes

\r\n

Using open(2), determine if a file exists.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4101,7 +4101,7 @@ }, { "title": "Search and replace", - "description": "Le syllabus est accessible depuis l'URL\r\n\r\n\r\nLes pages de manuel sont accessibles depuis les URLs suivants : -\r\n (commandes) -\r\n (appels systèmes) -\r\n (fonctions des\r\nlibrairies)\r\n", + "description": "

Le syllabus est accessible depuis l'URL http://sites.uclouvain.be/SystInfo

\r\n

Les pages de manuel sont accessibles depuis les URLs suivants : - http://sites.uclouvain.be/SystInfo/manpages/man1 (commandes) - http://sites.uclouvain.be/SystInfo/manpages/man2 (appels systèmes) - http://sites.uclouvain.be/SystInfo/manpages/man3 (fonctions des librairies)

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4155,7 +4155,7 @@ }, { "title": "Bitwise operation: setting a bit", - "description": "In this exercise, we will work with operations on bits. When we speak\r\nabout the position of a bit, index 0 corresponds to lowest order bit, 1\r\nto the second-lowest order bit, ...\r\n\r\nIn C source code, you can write a number in binary (base 2) by prefixing\r\nit via 0b., e.g. 0b11010 = 26.\r\n\r\nThis exercise will introduce some non-standard data types which\r\nguarantee that the variable has a fixed number of bits. Indeed, on some\r\nmachines, a *int* could use 2, 4 or 8 bytes. Hence, if we want to\r\nperform bitwise operations, we have to know first on how many bits we\r\nare working.\r\n\r\nFor this, C introduces a new class of variable types :\r\n\r\n- *int8\\_t* (signed integer of 8 bits)\r\n- *uint8\\_t* (unsigned integer of 8 bits)\r\n- *uint16\\_t* (unsigned integer of 16 bits)\r\n\r\nYou can mix *uint* or *int* with bit-lengths 8, 16, 32 and 64). These\r\ntypes are defined in <stdint.h>\r\n", + "description": "

In this exercise, we will work with operations on bits. When we speak about the position of a bit, index 0 corresponds to lowest order bit, 1 to the second-lowest order bit, ...

\r\n

In C source code, you can write a number in binary (base 2) by prefixing it via 0b., e.g. 0b11010 = 26.

\r\n

This exercise will introduce some non-standard data types which guarantee that the variable has a fixed number of bits. Indeed, on some machines, a int could use 2, 4 or 8 bytes. Hence, if we want to perform bitwise operations, we have to know first on how many bits we are working.

\r\n

For this, C introduces a new class of variable types :

\r\n
    \r\n
  • int8_t (signed integer of 8 bits)
  • \r\n
  • uint8_t (unsigned integer of 8 bits)
  • \r\n
  • uint16_t (unsigned integer of 16 bits)
  • \r\n
\r\n

You can mix uint or int with bit-lengths 8, 16, 32 and 64). These types are defined in <stdint.h>

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4259,7 +4259,7 @@ }, { "title": "Simple stack", - "description": "You are asked to implement the `pop` and `push` functions of the\r\nfollowing\r\n[stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type))\r\ninterface :\r\n\r\n``` c\r\nstruct node {\r\n node *next;\r\n char *name;\r\n};\r\n```\r\n\r\n\"image\"\r\n\r\n*Hints* :\r\n\r\n- `char *name` is also a pointer, memory must be allocated by using\r\n [malloc(3)](https://sites.uclouvain.be/SystInfo/manpages/man3/malloc.3.html)\r\n to copy the string on the stack.\r\n- Other useful commands:\r\n [strncpy(3)](https://sites.uclouvain.be/SystInfo/manpages/man3/strncpy.3.html)\r\n and\r\n [strlen(3)](https://sites.uclouvain.be/SystInfo/manpages/man3/strlen.3.html).\r\n- Do not forget to free **all** the allocated space when popping one\r\n element.\r\n", + "description": "

You are asked to implement the pop and push functions of the following stack interface :

\r\n
struct node {\r\n    node *next;\r\n    char *name;\r\n};
\r\n

\"image\"

\r\n

Hints :

\r\n
    \r\n
  • char *name is also a pointer, memory must be allocated by using malloc(3) to copy the string on the stack.
  • \r\n
  • Other useful commands: strncpy(3) and strlen(3).
  • \r\n
  • Do not forget to free all the allocated space when popping one element.
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -4318,7 +4318,7 @@ }, { "title": "Sleepy malloc", - "description": "The\r\n[malloc(3)](https://sites.uclouvain.be/SystInfo/manpages/man3/malloc.3.html)\r\nfunction may fail, for instance if the OS has no free memory remaining.\r\nIn this case, it may be possible that some other processes may free some\r\nmemory after some time.\r\n\r\nIn our program, instead of reporting an error immediately if no free\r\nmemory is available, we will wait some time to see if the OS has freed\r\nmemory for us.\r\n", + "description": "

The malloc(3) function may fail, for instance if the OS has no free memory remaining. In this case, it may be possible that some other processes may free some memory after some time.

\r\n

In our program, instead of reporting an error immediately if no free memory is available, we will wait some time to see if the OS has freed memory for us.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4377,7 +4377,7 @@ }, { "title": "Soumission du projet fractale", - "description": "Cette tâche vous permet de soumettre votre projet. Elle va également\r\nvalider le format de votre archive, la présence des fichiers requis, la\r\nprésence des cibles requises dans votre Makefile et la bonne compilation\r\nde votre projet. Le format requis est décrit dans l'énoncé disponible\r\nsur Moodle.\r\n\r\nVotre archive doit respecter le format de nommage fractal\\_NUMGroupe\\_NOM1\\_NOM2.zip. **Un seul\r\ndes deux membres du groupe doit soumettre.**\r\n\r\nLa dernière soumission **valide** sera considérée pour l'évaluation. En\r\nl'absence de telle soumission (donc si votre soumission comporte une\r\nerreur), votre projet **ne sera pas considéré pour l'évaluation**.\r\n", + "description": "

Cette tâche vous permet de soumettre votre projet. Elle va également valider le format de votre archive, la présence des fichiers requis, la présence des cibles requises dans votre Makefile et la bonne compilation de votre projet. Le format requis est décrit dans l'énoncé disponible sur Moodle.

\r\n

Votre archive doit respecter le format de nommage fractal_NUMGroupe_NOM1_NOM2.zip. Un seul des deux membres du groupe doit soumettre.

\r\n

La dernière soumission valide sera considérée pour l'évaluation. En l'absence de telle soumission (donc si votre soumission comporte une erreur), votre projet ne sera pas considéré pour l'évaluation.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4422,7 +4422,7 @@ }, { "title": "Global and local variables", - "description": "In a C program, variables are stored in different regions in memory,\r\ndepending on where the variables have been initialized. Each memory\r\nregion has different properties about how the variables can be accessed,\r\nmodified, ... This exercise will show you how global variables and\r\nvariables on the stack are managed.\r\n\r\n``` c\r\nint result;\r\n\r\nvoid sum1(int a1, int b1) {\r\n a1 = a1 + b1;\r\n}\r\n\r\nvoid main(int argc, char **argv) {\r\n int a1 = 5, b1 = 6;\r\n\r\n sum1(a1, b1);\r\n printf(\"sum1: %d\\n\", a1);\r\n\r\n int a2 = 3, b2 = 7;\r\n sum2(a2, b2)\r\n printf(\"sum2: %d\\n\", result);\r\n\r\n int a3 = 1, b3 = 8;\r\n sum3(&a3, &b3);\r\n printf(\"sum3: %d\\n\", a3);\r\n}\r\n```\r\n", + "description": "

In a C program, variables are stored in different regions in memory, depending on where the variables have been initialized. Each memory region has different properties about how the variables can be accessed, modified, ... This exercise will show you how global variables and variables on the stack are managed.

\r\n
int result;\r\n\r\nvoid sum1(int a1, int b1) {\r\n    a1 = a1 + b1;\r\n}\r\n\r\nvoid main(int argc, char **argv) {\r\n    int a1 = 5, b1 = 6;\r\n\r\n    sum1(a1, b1);\r\n    printf("sum1: %d\\n", a1);\r\n\r\n    int a2 = 3, b2 = 7;\r\n    sum2(a2, b2)\r\n    printf("sum2: %d\\n", result);\r\n\r\n    int a3 = 1, b3 = 8;\r\n    sum3(&a3, &b3);\r\n    printf("sum3: %d\\n", a3);\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -4490,7 +4490,7 @@ }, { "title": "Exponentially static counter - REVIEWED", - "description": "A variable declared inside a function with the keyword *static* implies\r\nthat the value of this variable will be kept across the different calls\r\nto this function.\r\n\r\nFor example, the first call to your function should return `1`. The next\r\ncall `2`, then `4`, ..., `4096`, `1`, ...\r\n", + "description": "

A variable declared inside a function with the keyword static implies that the value of this variable will be kept across the different calls to this function.

\r\n

For example, the first call to your function should return 1. The next call 2, then 4, ..., 4096, 1, ...

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4544,7 +4544,7 @@ }, { "title": "Improved strcpy", - "description": "The classic function\r\n`char *strcpy(char *destination, const char *source);`\r\n[strcpy(3)](https://linux.die.net/man/3/strcpy) needs a destination\r\nbuffer where the source string is copied. We ask you to code a function\r\nwhich allocates a buffer itself, and then performs the copy.\r\n\r\nThe use of copy functions as `memcpy` is not allowed.\r\n\r\n*Hint* : use\r\n[malloc(3)](https://sites.uclouvain.be/SystInfo/manpages/man3/malloc.3.html)\r\n", + "description": "

The classic function char *strcpy(char *destination, const char *source); strcpy(3) needs a destination buffer where the source string is copied. We ask you to code a function which allocates a buffer itself, and then performs the copy.

\r\n

The use of copy functions as memcpy is not allowed.

\r\n

Hint : use malloc(3)

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4602,7 +4602,7 @@ }, { "title": "Manipulation de chaines de caractères", - "description": "Le syllabus est accessible depuis l'URL\r\n\r\n\r\nLes pages de manuel sont accessibles depuis les URLs suivants : \r\n- (commandes)\r\n- (appels systèmes)\r\n- (fonctions des\r\n librairies)\r\n\r\n**Attention:** veuillez utiliser la version **HTML** du syllabus\r\n", + "description": "

Le syllabus est accessible depuis l'URL http://sites.uclouvain.be/SystInfo

\r\n
\r\n
Les pages de manuel sont accessibles depuis les URLs suivants :
\r\n
\r\n
\r\n
\r\n

Attention: veuillez utiliser la version HTML du syllabus

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4661,7 +4661,7 @@ }, { "title": "Echange de valeurs de fractions", - "description": "Soit la définition de la structure représentant des fractions entières\r\nsuivante:\r\n\r\n``` c\r\nstruct fract_t {\r\n int num;\r\n int denum;\r\n};\r\n```\r\n\r\nOn veut pouvoir swapper (échanger) les valeurs de deux fractions en\r\nutilisant la fonction `void swap(struct fract_t *a, struct fract_t *b)`.\r\nEcrivez le code de cette fonction.\r\n", + "description": "

Soit la définition de la structure représentant des fractions entières suivante:

\r\n
struct fract_t {\r\n        int num;\r\n        int denum;\r\n};
\r\n

On veut pouvoir swapper (échanger) les valeurs de deux fractions en utilisant la fonction void swap(struct fract_t *a, struct fract_t *b). Ecrivez le code de cette fonction.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4778,7 +4778,7 @@ }, { "title": "Through the array", - "description": "In C, an array is a set of variables sharing the same data type :\r\n`int array[3] = {42, 1337, 0};`.\r\n\r\nAn item of an array can be retrieved through its index. For example\r\n`array[1]` gives the second element of the array (here `1337`).\r\n", + "description": "

In C, an array is a set of variables sharing the same data type : int array[3] = {42, 1337, 0};.

\r\n

An item of an array can be retrieved through its index. For example array[1] gives the second element of the array (here 1337).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4832,7 +4832,7 @@ }, { "title": "Trier une liste chainée", - "description": "Le but de cet exercice est de trier une liste chaînée. Pour ce faire, on\r\nvous laisse le choix de l'algorithme que vous souhaitez implémenter. La\r\nseule contrainte est que la liste se décrit comme suit :\r\n\r\n``` c\r\nstruct list {\r\n struct node* head;\r\n}\r\nstruct node {\r\n int elem;\r\n struct node* next;\r\n}\r\n```\r\n", + "description": "

Le but de cet exercice est de trier une liste chaînée. Pour ce faire, on vous laisse le choix de l'algorithme que vous souhaitez implémenter. La seule contrainte est que la liste se décrit comme suit :

\r\n
struct list {\r\n    struct node* head;\r\n}\r\nstruct node {\r\n    int elem;\r\n    struct node* next;\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -4891,7 +4891,7 @@ }, { "title": "true false", - "description": "true false\r\n", + "description": "

true false

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4940,7 +4940,7 @@ }, { "title": "Les types (1/2)", - "description": "Le type de la plupart des variables en C est facile à déterminer.\r\nNéanmoins, le C contient aussi des types qui diffèrent de façons parfois\r\nsubtiles.\r\n", + "description": "

Le type de la plupart des variables en C est facile à déterminer. Néanmoins, le C contient aussi des types qui diffèrent de façons parfois subtiles.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4994,7 +4994,7 @@ }, { "title": "Les types (2/2)", - "description": "Le type de la plupart des variables en C est facile à déterminer.\r\nNéanmoins, le C contient aussi des types qui diffèrent de façons parfois\r\nsubtiles.\r\n", + "description": "

Le type de la plupart des variables en C est facile à déterminer. Néanmoins, le C contient aussi des types qui diffèrent de façons parfois subtiles.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -5048,7 +5048,7 @@ }, { "title": "Stockage d'un vecteur de réels dans un fichier", - "description": "Le syllabus est accessible depuis l'URL\r\n\r\n\r\nLes pages de manuel sont accessibles depuis les URLs suivants : \r\n- (commandes)\r\n- (appels systèmes)\r\n- (fonctions des\r\n librairies)\r\n\r\n**Attention:** veuillez utiliser la version **HTML** du syllabus\r\n", + "description": "

Le syllabus est accessible depuis l'URL http://sites.uclouvain.be/SystInfo

\r\n
\r\n
Les pages de manuel sont accessibles depuis les URLs suivants :
\r\n
\r\n
\r\n
\r\n

Attention: veuillez utiliser la version HTML du syllabus

\r\n", "tags": [ { "text": "INGINIOUS", @@ -5111,6 +5111,6 @@ "1": "Misconception", "2": "autres" }, - "extraction_date": "2019-12-18T16:15:40.106Z", + "extraction_date": "2020-03-04T17:48:45.884Z", "url": "https://github.com/UCL-INGI/LSINF1252" } \ No newline at end of file diff --git a/results/results2.json b/results/results2.json index 853a827..571c9a6 100644 --- a/results/results2.json +++ b/results/results2.json @@ -2,7 +2,7 @@ "exercises": [ { "title": "Coverage Testing", - "description": "Example of Task using Coverage testing\r\n", + "description": "

Example of Task using Coverage testing

\r\n", "tags": [ { "text": "INGINIOUS", @@ -65,7 +65,7 @@ }, { "title": "JavaGrading Testing", - "description": "Example of Task using JavaGrading\r\n", + "description": "

Example of Task using JavaGrading

\r\n", "tags": [ { "text": "INGINIOUS", @@ -128,7 +128,7 @@ }, { "title": "Abstract Class", - "description": "In this task, you have to implement the following code represented by\r\nthis UML diagram :\r\n\r\n
\r\n\"\"\r\n
\r\n\r\nBefore jumping to the code, a few things to keep in mind : \r\n- Shape and all its methods are abstract (since instantiating a Shape\r\n class doesn't make sense )\r\n- Don't forget every needed modifier, keywords, etc (abstract, public,\r\n ...)\r\n- No need of instance variables in your code as we pass you the needed\r\n parameter to apply your computation\r\n- Use Math.PI in your Circle implementation\r\n- Advanced feedback are available only if your code has complied\r\n", + "description": "

In this task, you have to implement the following code represented by this UML diagram :

\r\n
\r\n\"\"\r\n
\r\n
\r\n
Before jumping to the code, a few things to keep in mind :
\r\n
    \r\n
  • Shape and all its methods are abstract (since instantiating a Shape class doesn't make sense )
  • \r\n
  • Don't forget every needed modifier, keywords, etc (abstract, public, ...) as your classes are stored inside another package that the one for the testing
  • \r\n
  • No need of instance variables in your code as we pass you the needed parameter to apply your computation
  • \r\n
  • Use Math.PI in your Circle implementation
  • \r\n
  • Advanced feedback are available only if your code has complied
  • \r\n
\r\n
\r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -171,7 +171,7 @@ "text": "java" }, { - "text": "Module 4", + "text": "Module 3", "category": 2 } ], @@ -241,7 +241,7 @@ }, { "title": "Arrays 2D and Matrix", - "description": "In order to understand the differences between a matrix and a\r\nmultidimensional array, you have to implement the functions of the\r\n[MyBuilder](https://inginious.info.ucl.ac.be/course/LEPL1402/Array2D/MyBuilder.java) class that\r\nimplements the\r\n[Array2DBuilderInterface](https://inginious.info.ucl.ac.be/course/LEPL1402/Array2D/Array2DBuilderInterface.java):\r\n\r\n``` java\r\npackage src;\r\n\r\npublic interface Array2DBuilderInterface {\r\n// from a String of int, build and return a array of 2D\r\n// integers are separated by spaces ; lines by the \\n character\r\n// As array 2d aren't always regular matrix, you may build a Irregular matrix with the given input\r\n// Example :\r\n// String s = \"1 2 3 \\n 4 5 \\n 42 \\n\";\r\n// Gives :\r\n// int[][] array2d = { {1, 2, 3}, {4, 5}, {42} };\r\n// hint: there is a method in java that removes space at the start and end of a string\r\npublic int[][] buildFrom(String s);\r\n\r\n// Compute the sum of all integers in the 2d array (not necessarily a regular matrix )\r\npublic int sum(int[][] array);\r\n\r\n// return the transpose of the matrix (the given parameter is a regular matrix)\r\npublic int[][] transpose(int[][] matrix);\r\n\r\n// return the product of : matrix1 X matrix2\r\n// (row1 X column1) X (row2 X column2) (row1 and column2 not necessarily the same but regular matrices)\r\npublic int[][] product(int[][] matrix1, int[][] matrix2);\r\n}\r\n```\r\n\r\nYour job:\r\n\r\n``` java\r\npublic class MyBuilder implements Array2DBuilderInterface {\r\n public int[][] buildFrom(String s){\r\n //TODO\r\n }\r\n public int sum(int[][] array){\r\n //TODO\r\n }\r\n public int[][] transpose(int[][] matrix){\r\n //TODO\r\n }\r\n public int[][] product(int[][] matrix1, int[][] matrix2){\r\n //TODO\r\n }\r\n}\r\n```\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/Array2D/LEPL1402_Array2D.zip) that contains\r\nfew tests to help you.\r\n", + "description": "

In order to understand the differences between a matrix and a multidimensional array, you have to implement the functions of the MyBuilder class that implements the Array2DBuilderInterface:

\r\n
package src;\r\n\r\npublic interface Array2DBuilderInterface {\r\n// from a String of int, build and return a array of 2D\r\n// integers are separated by spaces ; lines by the \\n character\r\n// As array 2d aren't always regular matrix, you may build a Irregular matrix with the given input\r\n// Example :\r\n//      String s = "1 2 3 \\n 4 5 \\n 42 \\n";\r\n// Gives :\r\n//      int[][] array2d = { {1, 2, 3}, {4, 5}, {42} };\r\n// hint: there is a method in java that removes space at the start and end of a string\r\npublic int[][] buildFrom(String s);\r\n\r\n// Compute the sum of all integers in the 2d array (not necessarily a regular matrix )\r\npublic int sum(int[][] array);\r\n\r\n// return the transpose of the matrix (the given parameter is a regular matrix)\r\npublic int[][] transpose(int[][] matrix);\r\n\r\n// return the product of : matrix1 X matrix2\r\n// (row1 X column1) X (row2 X column2) (row1 and column2 not necessarily the same but regular matrices)\r\npublic int[][] product(int[][] matrix1, int[][] matrix2);\r\n}
\r\n

Your job:

\r\n
public class MyBuilder implements Array2DBuilderInterface {\r\n    public int[][] buildFrom(String s){\r\n        //TODO\r\n    }\r\n    public int sum(int[][] array){\r\n        //TODO\r\n    }\r\n    public int[][] transpose(int[][] matrix){\r\n        //TODO\r\n    }\r\n    public int[][] product(int[][] matrix1, int[][] matrix2){\r\n        //TODO\r\n    }\r\n}
\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -300,7 +300,7 @@ }, { "title": "ASCII Decoder", - "description": "For this exercise we want you to make a method able to decode a set of\r\nASCII (decimal) codes into a String. Please, read carefully the\r\nsignature and the comments above the method's signature below :\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/ASCIIDecoder/LEPL1402_ASCIIDecoder.zip) that\r\ncontains few tests to help you.\r\n\r\n``` java\r\n/*\r\n* Forbidden characters are passed as an array of int.\r\n* Each element of this array correspond to the decimal ASCII code\r\n* of a forbidden character OR null if there's no forbidden character\r\n* If you encounter one of these forbidden character\r\n* you must ignore it when you translate your sentence.\r\n*\r\n* the 2D array \"sentences\" contain a set of decimal ASCII code we want you\r\n* to translate. Each sub-element of this array is a different sentence.\r\n* Ex : if we pass this array : { {\"42\", \"72\", \"88\"}, {\"98\", \"99\", \"111\", \"47\", \"55\"} }\r\n* to your decode method, you should return : { \"*HX\", \"bco/7\" }\r\n*\r\n* You should NEVER return null or an array containing null\r\n*/\r\npublic static String [] decode(int[] forbidden, String[][] sentences){\r\n // YOUR CODE HERE\r\n}\r\n```\r\n\r\nWe also highly suggest you to have a look at the\r\n[StringBuilder](https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html)\r\nand\r\n[ArrayList](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html)\r\nAPIs. We strongly encourage you to use them for this exercise.\r\n", + "description": "

For this exercise we want you to make a method able to decode a set of ASCII (decimal) codes into a String. Please, read carefully the signature and the comments above the method's signature below :

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n
/*\r\n* Forbidden characters are passed as an array of int.\r\n* Each element of this array correspond to the decimal ASCII code\r\n* of a forbidden character OR null if there's no forbidden character\r\n* If you encounter one of these forbidden character\r\n* you must ignore it when you translate your sentence.\r\n*\r\n* the 2D array "sentences" contain a set of decimal ASCII code we want you\r\n* to translate. Each sub-element of this array is a different sentence.\r\n* Ex : if we pass this array : { {"42", "72", "88"}, {"98", "99", "111", "47", "55"} }\r\n* to your decode method, you should return : { "*HX", "bco/7" }\r\n*\r\n* You should NEVER return null or an array containing null\r\n*/\r\npublic static String [] decode(int[] forbidden, String[][] sentences){\r\n    // YOUR CODE HERE\r\n}
\r\n

We also highly suggest you to have a look at the StringBuilder and ArrayList APIs. We strongly encourage you to use them for this exercise.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -354,7 +354,7 @@ }, { "title": "BlackBox Testing - Binary Search", - "description": "In this task, you will need to provide a JUnit4 TestSuite for the\r\n**static method** `binarySearch` located in the **class** `Exercise` :\r\n\r\n``` java\r\n/*\r\n * This method returns:\r\n * index of elem if it is between the \"low\" and \"high\" indexes.\r\n * -1 if elem is not the there\r\n * -2 if the parameters do not respect the preconditions.\r\n *\r\n * @pre low >= 0, high <= |arr|, low <= high, sorted(arr[low...high]) == true\r\n * @post returns :\r\n * index in which the searched element is located,\r\n * -1 if it is not present.\r\n * -2 if it does not respect @pre\r\n */\r\npublic static int binarySearch(int [] arr, int low, int high, int elem) {\r\n ...\r\n}\r\n```\r\n\r\nBased on the specifications provided, create test cases for different\r\ninput and possible outputs. We strongly suggest you to read the\r\n[Junit4](https://junit.org/junit4/javadoc/4.12/org/junit/Assert.html)\r\nasserts documentation. Here is a signature to start your test suite:\r\n\r\n``` java\r\nimport org.junit.Test;\r\nimport static org.junit.Assert.*;\r\n\r\npublic class TestSuite{\r\n\r\n @Test\r\n public void test(){\r\n Exercise.binarySearch(...)\r\n }\r\n\r\n // Add more tests here.\r\n\r\n}\r\n```\r\n", + "description": "

In this task, you will need to provide a JUnit4 TestSuite for the static method binarySearch located in the class Exercise :

\r\n
/*\r\n * This method returns:\r\n *             index of elem if it is between the "low" and "high" indexes.\r\n *             -1 if elem is not the there\r\n *             -2 if the parameters do not respect the preconditions.\r\n *\r\n * @pre low >= 0, high < |arr|, low <= high\r\n * @post returns :\r\n *            index in which the searched element is located,\r\n *            -1 if it is not present.\r\n *            -2 if it does not respect @pre\r\n */\r\npublic static int binarySearch(int [] arr, int low, int high, int elem) {\r\n    ...\r\n}
\r\n

Based on the specifications provided, create test cases for different input and possible outputs. We strongly suggest you to read the Junit4 asserts documentation. Here is a signature to start your test suite:

\r\n
import org.junit.Test;\r\nimport static org.junit.Assert.*;\r\n\r\npublic class TestSuite{\r\n\r\n    @Test\r\n    public void test(){\r\n        Exercise.binarySearch(...)\r\n    }\r\n\r\n    // Add more tests here.\r\n\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -413,7 +413,7 @@ }, { "title": "Bounded Buffer", - "description": "A bounded buffer is a way for multiple producers and consumers to\r\nsynchronised. Indeed multiple producers are going to fill the buffer\r\nwhile consumers are going to clear out this buffer.\r\n\r\nYou have to implement the class\r\n[BoundedBuffer](https://inginious.info.ucl.ac.be/course/LEPL1402/BoundedBuffer/BoundedBuffer.java). In a\r\nbounded buffer, the element window grows to the right, shrinks to the\r\nleft and slides t the right on the buffer. Here is a little example\r\nabout the fonctioning of a bounded buffer :\r\n\r\n\"image\"\r\n\r\nBefore submitting don't hesitate to create a producer and a consumer and\r\nto test your code.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/BoundedBuffer/LEPL1402_BoundedBuffer.zip):\r\n", + "description": "

A bounded buffer is a way for multiple producers and consumers to synchronised. Indeed multiple producers are going to fill the buffer while consumers are going to clear out this buffer.

\r\n

You have to implement the class BoundedBuffer. In a bounded buffer, the element window grows to the right, shrinks to the left and slides t the right on the buffer. Here is a little example about the fonctioning of a bounded buffer :

\r\n

\"image\"

\r\n

Before submitting don't hesitate to create a producer and a consumer and to test your code.

\r\n

You can download the IntelliJ Project:

\r\n", "tags": [ { "text": "INGINIOUS", @@ -472,7 +472,7 @@ }, { "title": "Bubble Sort Invariant (MCQ)", - "description": "In this exercise, the questions will be about the bubble sort algorithm,\r\nits complexities and invariant.\r\n\r\nHere its implementation in java:\r\n\r\n``` java\r\npublic static void bubbleSort(Comparable[] array){\r\n int n = array.length;\r\n Comparable temp = 0;\r\n for(int i=0; i < n; i++){\r\n for(int j=1; j < (n-i); j++){\r\n if(array[j-1].compareTo(array[j])>0){\r\n //swap elements\r\n temp = array[j-1];\r\n array[j-1] = array[j];\r\n array[j] = temp;\r\n }\r\n }\r\n }\r\n}\r\n```\r\n", + "description": "

In this exercise, the questions will be about the bubble sort algorithm, its complexities and invariant.

\r\n

Here its implementation in java:

\r\n
public static void bubbleSort(Comparable[] array){\r\n    int n = array.length;\r\n    Comparable temp = 0;\r\n    for(int i=0; i < n; i++){\r\n        for(int j=1; j < (n-i); j++){\r\n            if(array[j-1].compareTo(array[j])>0){\r\n                //swap elements\r\n                temp = array[j-1];\r\n                array[j-1] = array[j];\r\n                array[j] = temp;\r\n            }\r\n        }\r\n    }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -580,7 +580,7 @@ }, { "title": "Circular Linked list", - "description": "In this task, you have to implement a Circular linked list : a list\r\nwhere the last element points to the first element. In this exercise,\r\nthe list must maintain a reference to the last of its elements. Each\r\ntime you want to add an element, you must append it at the end of the\r\nlist. Removing an element is a bit different: you need to specify an\r\nindex to choose which element of the list you want to remove\r\n(`remove(0)` for the first ... `remove(size()-1)` for the last). **Pay\r\nattention**: your `remove` method must throw an\r\n`IndexOutOfBoundsException` if the index parameter is smaller than `0`\r\nor greater than `size()-1`\r\n\r\n
\r\n\"\"\r\n
\r\n\r\nYou also need to implement the `ListIterator` class.\r\n[Iterator](https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html)\r\nis an interface you have to implement in order to make the class\r\nimplementing it able to enumerate/browse/iterate over an object : here,\r\nwe want you to implement a FIFO order iterator over your\r\n`CircularLinkedList`. **Pay attention**:\r\n\r\n> - Your iterator don't have to implement the `remove` method from\r\n> [Iterator](https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html).\r\n> - Your iterator must throw a `ConcurrentModificationException` when\r\n> you want to get the next element but some other element has been\r\n> added to the list meanwhile.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/CircularLL/LEPL1402_CircularLL.zip):\r\n\r\nHere is the class (downloadable\r\n[here](https://inginious.info.ucl.ac.be/course/LEPL1402/CircularLL/CircularLinkedList.java)) where we\r\nwill insert your code :\r\n\r\n``` java\r\nimport java.util.ConcurrentModificationException;\r\nimport java.util.Iterator;\r\n\r\n\r\npublic class CircularLinkedList implements Iterable {\r\n\r\n private int n; // size of the list\r\n private Node last; // trailer of the list\r\n\r\n // helper linked list class\r\n private class Node {\r\n\r\n private Item item;\r\n private Node next;\r\n\r\n private Node(Item item){\r\n this.item = item;\r\n this.next = null;\r\n }\r\n\r\n }\r\n\r\n public CircularLinkedList() {\r\n last = null;\r\n n = 0;\r\n }\r\n\r\n public boolean isEmpty() {\r\n return n == 0;\r\n }\r\n\r\n public int size() {\r\n return n;\r\n }\r\n\r\n public Node getLast(){\r\n return last;\r\n }\r\n\r\n public Item getItem(Node n){\r\n return n.item;\r\n }\r\n\r\n\r\n\r\n /**\r\n * Append an item at the end of the list\r\n * @param item the item to append\r\n */\r\n public void enqueue(Item item) {\r\n // YOUR CODE HERE\r\n }\r\n\r\n /**\r\n * Removes the element at the specified position in this list.\r\n * Shifts any subsequent elements to the left (subtracts one from their indices).\r\n * Returns the element that was removed from the list.\r\n */\r\n public Item remove(int index) {\r\n // YOUR CODE HERE\r\n }\r\n\r\n\r\n /**\r\n * Returns an iterator that iterates through the items in FIFO order.\r\n * @return an iterator that iterates through the items in FIFO order.\r\n */\r\n public Iterator iterator() {\r\n return new ListIterator();\r\n }\r\n\r\n /**\r\n * Implementation of an iterator that iterates through the items in FIFO order.\r\n *\r\n */\r\n private class ListIterator implements Iterator {\r\n // YOUR CODE HERE\r\n }\r\n\r\n\r\n}\r\n```\r\n", + "description": "

In this task, you have to implement a Circular linked list : a list where the last element points to the first element. In this exercise, the list must maintain a reference to the last of its elements. Each time you want to add an element, you must append it at the end of the list. Removing an element is a bit different: you need to specify an index to choose which element of the list you want to remove (remove(0) for the first ... remove(size()-1) for the last). Pay attention: your remove method must throw an IndexOutOfBoundsException if the index parameter is smaller than 0 or greater than size()-1

\r\n
\r\n\"\"\r\n
\r\n

You also need to implement the ListIterator class. Iterator is an interface you have to implement in order to make the class implementing it able to enumerate/browse/iterate over an object : here, we want you to implement a FIFO order iterator over your CircularLinkedList. Pay attention:

\r\n
\r\n
    \r\n
  • Your iterator don't have to implement the remove method from Iterator.
  • \r\n
  • Your iterator must throw a ConcurrentModificationException when you want to get the next element but some other element has been added to the list meanwhile.
  • \r\n
\r\n
\r\n

You can download the IntelliJ Project:

\r\n

Here is the class (downloadable here) where we will insert your code :

\r\n
import java.util.ConcurrentModificationException;\r\nimport java.util.Iterator;\r\n\r\n\r\npublic class CircularLinkedList<Item> implements Iterable<Item> {\r\n\r\n    private int n;          // size of the list\r\n    private Node last;   // trailer of the list\r\n\r\n    // helper linked list class\r\n    private class Node {\r\n\r\n        private Item item;\r\n        private Node next;\r\n\r\n        private Node(Item item){\r\n            this.item = item;\r\n            this.next = null;\r\n        }\r\n\r\n    }\r\n\r\n    public CircularLinkedList() {\r\n        last = null;\r\n        n = 0;\r\n    }\r\n\r\n    public boolean isEmpty() {\r\n        return n == 0;\r\n    }\r\n\r\n    public int size() {\r\n        return n;\r\n    }\r\n\r\n    public Node getLast(){\r\n        return last;\r\n    }\r\n\r\n    public Item getItem(Node n){\r\n        return n.item;\r\n    }\r\n\r\n\r\n\r\n    /**\r\n    * Append an item at the end of the list\r\n    * @param item the item to append\r\n    */\r\n    public void enqueue(Item item) {\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n    /**\r\n    * Removes the element at the specified position in this list.\r\n    * Shifts any subsequent elements to the left (subtracts one from their indices).\r\n    * Returns the element that was removed from the list.\r\n    */\r\n    public Item remove(int index) {\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n\r\n    /**\r\n    * Returns an iterator that iterates through the items in FIFO order.\r\n    * @return an iterator that iterates through the items in FIFO order.\r\n    */\r\n    public Iterator<Item> iterator() {\r\n        return new ListIterator();\r\n    }\r\n\r\n    /**\r\n    * Implementation of an iterator that iterates through the items in FIFO order.\r\n    *\r\n    */\r\n    private class ListIterator implements Iterator<Item> {\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -693,7 +693,7 @@ }, { "title": "Quick Sort - Implem exercise", - "description": "In order to discover the importance of pre/post conditions and\r\ninvariants in your programs, we will take the example of QuickSort.\r\n\r\nQuicksort is a divide-and-conquer method for sorting. It works by\r\npartitioning an array into two parts, then sorting the parts\r\nindependently. It takes the first element of the Array, then it\r\ndetermines its position in the array by iterating through it. If an\r\nelement is lower, it moves the element to its left and increment its own\r\nposition. Then it recursivly do the same operation for each sub array\r\n(left and right of the pivot).\r\n\r\n
\r\n\"\"\r\n
\r\n\r\nThe crux of the method is the partitioning process , which can be\r\nsummarized as follows :\r\n\r\n
\r\n\"\"\r\n
\r\n\r\nEven with this simple algorithm, mistakes can occur and that is why we\r\nask you to complete the implementation contained in this\r\n[file](https://inginious.info.ucl.ac.be/course/LEPL1402/CodeAccuracy2/QuickSort.java) , without\r\nforgetting to add assert statements in each method (as they will be\r\ntested separately in INGINIOUS).\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/CodeAccuracy2/LEPL1402_CodeAccuracy2.zip).\r\n", + "description": "

In order to discover the importance of pre/post conditions and invariants in your programs, we will take the example of QuickSort.

\r\n

Quicksort is a divide-and-conquer method for sorting. It works by partitioning an array into two parts, then sorting the parts independently. It takes the first element of the Array, then it determines its position in the array by iterating through it. If an element is lower, it moves the element to its left and increment its own position. Then it recursivly do the same operation for each sub array (left and right of the pivot).

\r\n
\r\n\"\"\r\n
\r\n

The crux of the method is the partitioning process , which can be summarized as follows :

\r\n
\r\n\"\"\r\n
\r\n

Even with this simple algorithm, mistakes can occur and that is why we ask you to complete the implementation contained in this file , without forgetting to add assert statements in each method (as they will be tested separately in INGINIOUS).

\r\n

You can download the IntelliJ Project.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -806,7 +806,7 @@ }, { "title": "Comparator and Collections", - "description": "In this task, the challenge is to sort a custom class **Person**\r\ndescribed as :\r\n\r\n``` java\r\npublic class Person {\r\n\r\n public String name;\r\n public int age;\r\n\r\n public Person(String name, int age) {\r\n this.name = name;\r\n this.age = age;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return name + \" \" + age;\r\n }\r\n}\r\n```\r\n\r\nYour task is to implement the function\r\n`public static void sortPerson(ArrayList persons)` that should\r\nsort an ArrayList of Persons as follows :\r\n\r\n- sort in the lexicographical order of their name\r\n- If two persons have the same name, they should be classified\r\n according to their age (ascending order).\r\n\r\nIn order to succeed this task (whose solution is contained on 8 lines),\r\nwe invite you to discover the following JavaDoc resource :\r\n[Collections](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html)\r\n(method sort)\r\n\r\nGiven this example :\r\n\r\n``` java\r\npublic class Main\r\n\r\n public static void main(String[] args) {\r\n ArrayList persons = new ArrayList<>();\r\n persons.add(new Person(\"Guillaume\",20));\r\n persons.add(new Person(\"John\",50));\r\n persons.add(new Person(\"Guillaume\",10));\r\n persons.add(new Person(\"John\",10));\r\n persons.add(new Person(\"Luc\",5));\r\n\r\n sortPerson(persons);\r\n System.out.println(persons);\r\n\r\n }\r\n}\r\n```\r\n\r\nYou should get this on the output :\r\n\r\n``` java\r\n[Guillaume 10, Guillaume 20, John 10, John 20, Luc 5]\r\n```\r\n", + "description": "

In this task, the challenge is to sort a custom class Person described as :

\r\n
public class Person {\r\n\r\n    public String name;\r\n    public int age;\r\n\r\n    public Person(String name, int age) {\r\n        this.name = name;\r\n        this.age = age;\r\n    }\r\n\r\n    @Override\r\n    public String toString() {\r\n        return name + " " + age;\r\n    }\r\n}
\r\n

Your task is to implement the function public static void sortPerson(ArrayList<Person> persons) that should sort an ArrayList of Persons as follows :

\r\n
    \r\n
  • sort in the lexicographical order of their name
  • \r\n
  • If two persons have the same name, they should be classified according to their age (ascending order).
  • \r\n
\r\n

In order to succeed this task (whose solution is contained on 8 lines), we invite you to discover the following JavaDoc resource : Collections (method sort)

\r\n

Given this example :

\r\n
public class Main\r\n\r\n  public static void main(String[] args) {\r\n    ArrayList<Person> persons = new ArrayList<>();\r\n    persons.add(new Person("Guillaume",20));\r\n    persons.add(new Person("John",50));\r\n    persons.add(new Person("Guillaume",10));\r\n    persons.add(new Person("John",10));\r\n    persons.add(new Person("Luc",5));\r\n\r\n    sortPerson(persons);\r\n    System.out.println(persons);\r\n\r\n  }\r\n}
\r\n

You should get this on the output :

\r\n
[Guillaume 10, Guillaume 20, John 10, John 20, Luc 5]
\r\n", "tags": [ { "text": "INGINIOUS", @@ -860,7 +860,7 @@ }, { "title": "Comparator vs Comparable", - "description": "In this exercise, you have to answer questions about\r\n[Comparator](https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html)\r\nand\r\n[Comparable](https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html).\r\n\r\nWe are going to work on the\r\n[Plant](https://inginious.info.ucl.ac.be/course/LEPL1402/ComparatorvsComparable/Plant.java),\r\n[Tree](https://inginious.info.ucl.ac.be/course/LEPL1402/ComparatorvsComparable/Tree.java),\r\n[Flower](https://inginious.info.ucl.ac.be/course/LEPL1402/ComparatorvsComparable/Flower.java) and\r\n[Sorter](https://inginious.info.ucl.ac.be/course/LEPL1402/ComparatorvsComparable/Sorter.java) classes.\r\nRead and understand the code in this classes before doing this is\r\nexercise!\r\n\r\nAll the information on how the different method should work are given in\r\ncomments in each class.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/ComparatorvsComparable/LEPL1402_ComparatorvsComparable.zip).\r\n", + "description": "

In this exercise, you have to answer questions about Comparator and Comparable.

\r\n

We are going to work on the Plant, Tree, Flower and Sorter classes. Read and understand the code in this classes before doing this is exercise!

\r\n

All the information on how the different method should work are given in comments in each class.

\r\n
\r\n
\r\n

Warning

\r\n
\r\n

In the code, when we write \"in that order\", we mean that you must first sort in function of the first criterion, and in case of equality, sort in function of the second, and so on.

\r\n
\r\n

You can download the IntelliJ Project.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -903,8 +903,12 @@ "text": "java" }, { - "text": "Module 5", + "text": "Module 3", "category": 2 + }, + { + "category": 2, + "text": "Module3" } ], "url": "https://inginious.info.ucl.ac.be/course/LEPL1402/ComparatorvsComparable", @@ -919,7 +923,7 @@ }, { "title": "Array Search", - "description": "In this task, you have to implement a method `search` that looks for an\r\nelement in an ascending sorted array. Your method must return the\r\n**index** of the element in the array or **-1** if you can't find the\r\nelement in the array.\r\n\r\nWe'll test the complexity of your code so try to find the best possible\r\nalgorithm.\r\n\r\n``` java\r\npublic class Search {\r\n\r\n /**\r\n * @param tab is an ordered array of int.\r\n * @return index of elem or -1\r\n */\r\n public static int search(int[] tab, int elem){\r\n //TODO YOUR CODE HERE\r\n }\r\n}\r\n```\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/ComplexityArraySearch/LEPL1402_ComplexityArraySearch.zip)\r\nthat contains few tests to help you.\r\n", + "description": "

In this task, you have to implement a method search that looks for an element in an ascending sorted array. Your method must return the index of the element in the array or -1 if you can't find the element in the array.

\r\n

We'll test the complexity of your code so try to find the best possible algorithm.

\r\n
public class Search {\r\n\r\n    /**\r\n     * @param tab is an ordered array of int.\r\n     * @return index of elem or -1\r\n     */\r\n    public static int search(int[] tab, int elem){\r\n        //TODO YOUR CODE HERE\r\n    }\r\n}
\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1032,7 +1036,7 @@ }, { "title": "Time Complexity MCQ (trees, tsp, sort, lists)", - "description": "The three first questions will be time complexity questions about trees,\r\nthe trees we are talking about is a complete ordered binary tree. Like\r\nthe example you see here under:\r\n\r\n\"image\"\r\n\r\nThe rest of the questions are harder question about the time complexity\r\nof operations on list and arrays. Some questions will be about simple\r\nlinked list, other about double linked list and some about circular\r\nlinked list.\r\n", + "description": "

The three first questions will be time complexity questions about trees, the trees we are talking about is a complete ordered binary tree. Like the example you see here under:

\r\n

\"image\"

\r\n

The rest of the questions are harder question about the time complexity of operations on list and arrays. Some questions will be about simple linked list, other about double linked list and some about circular linked list.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1086,7 +1090,7 @@ }, { "title": "Space Complexity MCQ", - "description": "Multiple choice questions about space complexity\r\n", + "description": "

Multiple choice questions about space complexity

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1140,7 +1144,7 @@ }, { "title": "Coverage Testing", - "description": "In this task, you should provide a TestSuite for coverage check of the\r\nfollowing class :\r\n\r\n``` java\r\npublic class BigDecimal {\r\n /*\r\n * parse exponent\r\n */\r\n public static long parseExp(char[] in, int offset, int len){\r\n long exp = 0;\r\n offset++;\r\n char c = in[offset];\r\n len--;\r\n boolean negexp = (c == '-');\r\n // optional sign\r\n if (negexp || c == '+') {\r\n offset++;\r\n c = in[offset];\r\n len--;\r\n }\r\n if (len <= 0) // no exponent digits\r\n throw new NumberFormatException();\r\n // skip leading zeros in the exponent\r\n while (len > 10 && (c=='0' || (Character.digit(c, 10) == 0))) {\r\n offset++;\r\n c = in[offset];\r\n len--;\r\n }\r\n if (len > 10) // too many nonzero exponent digits\r\n throw new NumberFormatException();\r\n // c now holds first digit of exponent\r\n for (;; len--) {\r\n int v;\r\n if (c >= '0' && c <= '9') {\r\n v = c - '0';\r\n } else {\r\n v = Character.digit(c, 10);\r\n if (v < 0) // not a digit\r\n throw new NumberFormatException();\r\n }\r\n exp = exp * 10 + v;\r\n if (len == 1)\r\n break; // that was final character\r\n offset++;\r\n c = in[offset];\r\n }\r\n if (negexp) // apply sign\r\n exp = -exp;\r\n return exp;\r\n }\r\n}\r\n```\r\n\r\nIn order to succeed this task, you must cover all the different\r\nexecution cases. To grade your tests, we use the tool `Jacoco`, it\r\nchecks wether you navigate among the entire code that was given. First\r\nunderstand what this code does, then you should write tests that will\r\nnavigate through each condition, loop etc.\r\n\r\nTake a look at this\r\n[link](https://www.eclemma.org/jacoco/trunk/doc/counters.html) to\r\nunderstand the feedback you'll be given.\r\n", + "description": "

In this task, you should provide a TestSuite for coverage check of the following class :

\r\n
public class BigDecimal {\r\n    /*\r\n     * parse exponent\r\n     */\r\n    public static long parseExp(char[] in, int offset, int len){\r\n        long exp = 0;\r\n        offset++;\r\n        char c = in[offset];\r\n        len--;\r\n        boolean negexp = (c == '-');\r\n        // optional sign\r\n        if (negexp || c == '+') {\r\n            offset++;\r\n            c = in[offset];\r\n            len--;\r\n        }\r\n        if (len <= 0) // no exponent digits\r\n            throw new NumberFormatException();\r\n        // skip leading zeros in the exponent\r\n        while (len > 10 && (c=='0' || (Character.digit(c, 10) == 0))) {\r\n            offset++;\r\n            c = in[offset];\r\n            len--;\r\n        }\r\n        if (len > 10) // too many nonzero exponent digits\r\n            throw new NumberFormatException();\r\n        // c now holds first digit of exponent\r\n        for (;; len--) {\r\n            int v;\r\n            if (c >= '0' && c <= '9') {\r\n                v = c - '0';\r\n            } else {\r\n                v = Character.digit(c, 10);\r\n                if (v < 0) // not a digit\r\n                    throw new NumberFormatException();\r\n            }\r\n            exp = exp * 10 + v;\r\n            if (len == 1)\r\n                break; // that was final character\r\n            offset++;\r\n            c = in[offset];\r\n        }\r\n        if (negexp) // apply sign\r\n            exp = -exp;\r\n        return exp;\r\n    }\r\n}
\r\n

In order to succeed this task, you must cover all the different execution cases. To grade your tests, we use the tool Jacoco, it checks wether you navigate among the entire code that was given. First understand what this code does, then you should write tests that will navigate through each condition, loop etc.

\r\n

Take a look at this link to understand the feedback you'll be given.

\r\n

To start your test suite :

\r\n
import org.junit.Test;\r\nimport static org.junit.Assert.*;\r\n\r\npublic class TestSuite{\r\n\r\n    @Test\r\n    public void test(){\r\n         // parameters for parseExp\r\n         char[] in = new char[]{/*Some chars here*/};\r\n         // also possible to use .toCharArray from String class for that :\r\n         // char[] in = myString.toCharArray();\r\n         int offset = /*Some value HERE*/;\r\n         int len = /*Some value HERE*/;\r\n         // run the program with the given situation\r\n         BigDecimal.parseExp(in, offset, len);\r\n    }\r\n\r\n    // Add more tests here.\r\n\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1199,7 +1203,7 @@ }, { "title": "Cyclic Barrier", - "description": "A Cyclic barrier in concurrent programming is a synchronization\r\nconstruct that helps you synchronize threads every once in a while. The\r\nidea is simple, after a thread finished executing a certain amount of\r\noperation, it waits until the barrier thread recover the result to\r\nrestart. Note that the barrier recover this result when every thread is\r\nwaiting, it thus recover all the results and then the threads can\r\nrestart their computing before stopping at the next checkpoint.\r\n\r\nIn this exercise we ask you to compute the highest sum in a set of\r\narray. Imagine that you have a large set of 2D-arrays stored as one\r\n3D-array. We ask you to use a fixed amount of threads, and a small\r\nbuffer. Each thread is going to compute the sum of the values in a\r\n2D-array and store this sum in the shared buffer. Once every thread has\r\nfinished computing the sum of his array, the barrier recovers the\r\nmaximum. When you don't need to compute sums the threads stop and the\r\nbarrier returns the final result (the index of the maximal sum).\r\n\r\nWe give you the class\r\n[MaxFinder](https://inginious.info.ucl.ac.be/course/LEPL1402/CyclicBarrier/MaxFinder.java) that you must\r\ncomplete, read the code carefully before you start writing any line of\r\ncode.\r\n\r\nYou should also read the class\r\n[CyclicBarrier](https://docs.oracle.com/javase/8/docs/api/index.html?java/util/concurrent/CyclicBarrier.html)\r\nin the java api.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/CyclicBarrier/LEPL1402_CyclicBarrier.zip).\r\n", + "description": "

A Cyclic barrier in concurrent programming is a synchronization construct that helps you synchronize threads every once in a while. The idea is simple, after a thread finished executing a certain amount of operation, it waits until the barrier thread recover the result to restart. Note that the barrier recover this result when every thread is waiting, it thus recover all the results and then the threads can restart their computing before stopping at the next checkpoint.

\r\n

In this exercise we ask you to compute the highest sum in a set of array. Imagine that you have a large set of 2D-arrays stored as one 3D-array. We ask you to use a fixed amount of threads, and a small buffer. Each thread is going to compute the sum of the values in a 2D-array and store this sum in the shared buffer. Once every thread has finished computing the sum of his array, the barrier recovers the maximum. When you don't need to compute sums the threads stop and the barrier returns the final result (the index of the maximal sum).

\r\n

We give you the class MaxFinder that you must complete, read the code carefully before you start writing any line of code.

\r\n

You should also read the class CyclicBarrier in the java api.

\r\n

You can download the IntelliJ Project.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1258,7 +1262,7 @@ }, { "title": "Factory design pattern - Level generator", - "description": "In this task, we will ask you to implement a labyrinth mini-game level\r\nbuilder using The factory design pattern. Each level consists in a set\r\nof [Wall](https://inginious.info.ucl.ac.be/course/LEPL1402/Factory/Wall.java),\r\n[Key](https://inginious.info.ucl.ac.be/course/LEPL1402/Factory/Key.java),\r\n[Floor](https://inginious.info.ucl.ac.be/course/LEPL1402/Factory/Floor.java),\r\n[Door](https://inginious.info.ucl.ac.be/course/LEPL1402/Factory/Door.java), all of them implementing the\r\n[LevelComponent](https://inginious.info.ucl.ac.be/course/LEPL1402/Factory/LevelComponent.java)\r\ninterface. Your objective is thus to implement the two following\r\nclasses:\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/Factory/LEPL1402_Factory.zip).\r\n\r\n``` java\r\npublic class ElementFactory extends Factory {\r\n\r\n // YOUR CODE HERE\r\n\r\n public static ElementFactory getInstance() {\r\n // YOUR SINGLETON HERE\r\n }\r\n\r\n}\r\n\r\n\r\npublic class Level extends AbstractLevel {\r\n\r\n public Level(String input){\r\n // YOUR CODE HERE\r\n }\r\n\r\n //Example of level building with this String : String s = \"#-K\\n-D-\\n#-K\"\r\n //Gives : LevelComponent[][] componentsObjects = {\r\n // {new Wall(), new Floor(), new Key()},\r\n // {new Floor(), new Door(), new Floor()},\r\n // {new Wall(), new Floor(), new Key()}}\r\n public LevelComponent getElement(char c){\r\n // YOUR CODE HERE\r\n }\r\n\r\n // YOUR CODE HERE\r\n}\r\n```\r\n\r\nNote that these two classes extends the abstract classes\r\n[Factory](https://inginious.info.ucl.ac.be/course/LEPL1402/Factory/Factory.java) and\r\n[AbstractLevel](https://inginious.info.ucl.ac.be/course/LEPL1402/Factory/AbstractLevel.java). Pay\r\nattention, we add a small constraint to this exercise: your\r\nElementFactory **must** be a singleton (i.e, it should not be possible\r\nto instantiate your factory with java's `new` keyword). For your `Level`\r\nclass, what we want you to do is, given a String, create a `Level`\r\nobject whose `components` is a 2D array where each cell represent a\r\n`LevelComponent`. Note that all sub-arrays in `components` will have the\r\nsame size as we will only ask you to create \"square\" labyrinths. If a\r\ncharacter does not correspond to one of the component, your code should\r\nthrow an IllegalArgumentException.\r\n", + "description": "

In this task, we will ask you to implement a labyrinth mini-game level builder using The factory design pattern. Each level consists in a set of Wall, Key, Floor, Door, all of them implementing the LevelComponent interface. Your objective is thus to implement the two following classes:

\r\n

You can download the IntelliJ Project.

\r\n
public class ElementFactory extends Factory {\r\n\r\n    // YOUR CODE HERE\r\n\r\n    public static ElementFactory getInstance() {\r\n        // YOUR SINGLETON HERE\r\n    }\r\n\r\n}\r\n\r\n\r\npublic class Level extends AbstractLevel {\r\n\r\n    public Level(String input){\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n    /* Example of level building with this String : String s = "#-K\\n-D-\\n#-K\\n"\r\n     * Gives : LevelComponent[][] componentsObjects = {\r\n     *                                        {new Wall(), new Floor(), new Key()},\r\n     *                                        {new Floor(), new Door(), new Floor()},\r\n     *                                        {new Wall(), new Floor(), new Key()}}\r\n     */\r\n\r\n\r\n    // YOUR CODE HERE\r\n}
\r\n

Note that these two classes extends the abstract classes Factory and AbstractLevel. Pay attention, we add a small constraint to this exercise: your ElementFactory must be a singleton (i.e, it should not be possible to instantiate your factory with java's new keyword). For your Level class, what we want you to do is, given a String, create a Level object whose components is a 2D array where each cell represent a LevelComponent and whose size is the total number of components in the level. Note that all sub-arrays in components will have the same size as we will only ask you to create \"square\" labyrinths. If a character does not correspond to one of the component, your code should throw an IllegalArgumentException.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1317,7 +1321,7 @@ }, { "title": "Introduction to recursion in Java - Fibonacci", - "description": "In this task, we will ask you to implement two different versions of the\r\n[Fibonacci](https://inginious.info.ucl.ac.be/course/LEPL1402/Fibonacci/Fibonacci.java) sequence number:\r\na recursive one and an iterative one. The objective of this exercise is\r\nto make you aware of what a call stack is and what problem could occur.\r\nWe strongly suggest you to test your code with various input : what will\r\nhappen if you test your recursive implementation with a very large\r\nindex. Why ? Will the same thing happen with your iterative\r\nimplementation ? Why ?\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/Fibonacci/LEPL1402_Fibonacci.zip) that\r\ncontains few tests to help you.\r\n\r\n``` java\r\npublic class Fibonacci {\r\n\r\n /*\r\n * Returns the index-th element of the fibonnaci sequence, computed recursively\r\n */\r\n public static int fiboRecursive(int index){\r\n // YOUR CODE HERE\r\n }\r\n\r\n /*\r\n * Returns the index-th element of the fibonnaci sequence, computed iteratively\r\n */\r\n public static int fiboIterative(int index){\r\n // YOUR CODE HERE\r\n }\r\n\r\n}\r\n```\r\n\r\nReminder : Fibonacci's sequence is computed as follows\r\n\r\n$$\\\\begin{aligned}\r\nf(n) =\\\\begin{cases}0 & n=0 \\\\\\\\1 & n = 1\\\\\\\\ f(n-1) + f(n-2) & n > 1\\\\end{cases}\r\n\\\\end{aligned}$$\r\n", + "description": "

In this task, we will ask you to implement two different versions of the Fibonacci sequence number: a recursive one and an iterative one. The objective of this exercise is to make you aware of what a call stack is and what problem could occur. We strongly suggest you to test your code with various input : what will happen if you test your recursive implementation with a very large index. Why ? Will the same thing happen with your iterative implementation ? Why ?

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n
public class Fibonacci {\r\n\r\n    /*\r\n     * Returns the index-th element of the fibonnaci sequence, computed recursively\r\n     */\r\n    public static int fiboRecursive(int index){\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n    /*\r\n     * Returns the index-th element of the fibonnaci sequence, computed iteratively\r\n     */\r\n    public static int fiboIterative(int index){\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n}
\r\n

Reminder : Fibonacci's sequence is computed as follows

\r\n


$$\\begin{aligned}\r\nf(n) =\\begin{cases}0 & n=0 \\\\1 & n = 1\\\\ f(n-1) + f(n-2) & n > 1\\end{cases}\r\n\\end{aligned}$$

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1376,7 +1380,7 @@ }, { "title": "Functional list implementation", - "description": "Functional\r\n[programming](https://en.wikipedia.org/wiki/Functional_programming) is\r\nan increasingly important programming paradigm. In this paradigm, data\r\nstructures are\r\n[immutable](https://en.wikipedia.org/wiki/Purely_functional_data_structure).\r\nYou are asked to implement an immutable list called FList that can be\r\nused in functionnal programming.\r\n\r\nYou should first make sure that you understood the code that is given to\r\nyou and what is asked to you before trying any implementation.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/FList/LEPL1402_FList.zip) that contains few\r\ntests to help you.\r\n\r\nHere is the API of an [FList](https://inginious.info.ucl.ac.be/course/LEPL1402/FList/FList.java) and the\r\nFList [class](https://inginious.info.ucl.ac.be/course/LEPL1402/FList/FListClass.java) you have to\r\nimplement:\r\n\r\n``` java\r\npublic abstract class FList implements Iterable {\r\n\r\n // creates an empty list\r\n public static FList nil();\r\n\r\n // prepend a to the list and return the new list\r\n public final FList cons(final A a);\r\n\r\n public final boolean isNotEmpty();\r\n\r\n public final boolean isEmpty();\r\n\r\n public final int length();\r\n\r\n // return the head element of the list\r\n public abstract A head();\r\n\r\n // return the tail of the list\r\n public abstract FList tail();\r\n\r\n // return a list on which each element has been applied function f\r\n public final FList map(Function f);\r\n\r\n // return a list on which only the elements that satisfies predicate are kept\r\n public final FList filter(Predicate f);\r\n\r\n // return an iterator on the element of the list\r\n public Iterator iterator();\r\n\r\n}\r\n```\r\n\r\nHere is an example of how we could test your code:\r\n\r\n``` java\r\nFList list = FList.nil();\r\n\r\nfor (int i = 0; i < 10; i++) {\r\n list = list.cons(i);\r\n}\r\n\r\nlist = list.map(i -> i+1);\r\n// will print 1,2,...,11\r\nfor (Integer i: list) {\r\n System.out.println(i);\r\n}\r\n\r\nlist = list.filter(i -> i%2 == 0);\r\n// will print 2,4,6,...,10\r\nfor (Integer i: list) {\r\n System.out.println(i);\r\n}\r\n```\r\n\r\nSince you know how your code should work, we **strongly** recommend you\r\nto test it on your computer before trying any submission. The iterator\r\nis the most critical part, if it doesn't work, most of the test will not\r\nwork.\r\n", + "description": "

Functional programming is an increasingly important programming paradigm. In this paradigm, data structures are immutable. You are asked to implement an immutable list called FList that can be used in functionnal programming.

\r\n

You should first make sure that you understood the code that is given to you and what is asked to you before trying any implementation.

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n

Here is the API of an FList and the FList class you have to implement:

\r\n
public abstract class FList<A> implements Iterable<A> {\r\n\r\n    // creates an empty list\r\n    public static <A> FList<A> nil();\r\n\r\n    // prepend a to the list and return the new list\r\n    public final FList<A> cons(final A a);\r\n\r\n    public final boolean isNotEmpty();\r\n\r\n    public final boolean isEmpty();\r\n\r\n    public final int length();\r\n\r\n    // return the head element of the list\r\n    public abstract A head();\r\n\r\n    // return the tail of the list\r\n    public abstract FList<A> tail();\r\n\r\n    // return a list on which each element has been applied function f\r\n    public final <B> FList<B> map(Function<A,B> f);\r\n\r\n    // return a list on which only the elements that satisfies predicate are kept\r\n    public final FList<A> filter(Predicate<A> f);\r\n\r\n    // return an iterator on the element of the list\r\n    public Iterator<A> iterator();\r\n\r\n}
\r\n

Here is an example of how we could test your code:

\r\n
FList<Integer> list = FList.nil();\r\n\r\nfor (int i = 0; i < 10; i++) {\r\n    list = list.cons(i);\r\n}\r\n\r\nlist = list.map(i -> i+1);\r\n// will print 1,2,...,11\r\nfor (Integer i: list) {\r\n    System.out.println(i);\r\n}\r\n\r\nlist = list.filter(i -> i%2 == 0);\r\n// will print 2,4,6,...,10\r\nfor (Integer i: list) {\r\n    System.out.println(i);\r\n}
\r\n

Since you know how your code should work, we strongly recommend you to test it on your computer before trying any submission. The iterator is the most critical part, if it doesn't work, most of the test will not work.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1435,7 +1439,7 @@ }, { "title": "FList MergeSort", - "description": "To complete this task you must implement a mergesort for FList using\r\nonly FList. Arrays, ArrayList, etc. are prohibited for this exercise.\r\n\r\nHere is the class [FList](https://inginious.info.ucl.ac.be/course/LEPL1402/FListMergeSort/FList.java)\r\nyou will be using. Try first to implement the FList by yourself in this\r\n[exercise](https://inginious.info.ucl.ac.be/course/LEPL1402/FList)\r\nbefore starting this one.\r\n\r\nAnd here is the method you must implement: note that you have to\r\nimplement merge recursivly and you are allowed to create other methods.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/FListMergeSort/LEPL1402_FListMergeSort.zip)\r\nthat contains few tests to help you.\r\n\r\n``` java\r\npublic class FListMerge {\r\n\r\n\r\n /*\r\n * This method receives an FList and returns the FList containing the same values but sorted with the smallest value to the highest one.\r\n *\r\n */\r\n public static FList mergeSort(FList fList){\r\n //TODO By Student\r\n }\r\n\r\n //TO Complete if needed\r\n}\r\n```\r\n", + "description": "

To complete this task you must implement a mergesort for FList using only FList. Arrays, ArrayList, etc. are prohibited for this exercise.

\r\n

Here is the class FList you will be using. Try first to implement the FList by yourself in this exercise before starting this one.

\r\n

And here is the method you must implement: note that you have to implement merge recursivly and you are allowed to create other methods.

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n
public class FListMerge {\r\n\r\n\r\n    /*\r\n    * This method receives an FList and returns the FList containing the same values but sorted with the smallest value to the highest one.\r\n    *\r\n    */\r\n    public static FList<Integer> mergeSort(FList<Integer> fList){\r\n        //TODO By Student\r\n    }\r\n\r\n    //TO Complete if needed\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1494,7 +1498,7 @@ }, { "title": "Functional immutable tree", - "description": "In this exercise you have to complete the class\r\n[FTree](https://inginious.info.ucl.ac.be/course/LEPL1402/FTree/FTree.java),\r\n[Node](https://inginious.info.ucl.ac.be/course/LEPL1402/FTree/Node.java) and\r\n[Leaf](https://inginious.info.ucl.ac.be/course/LEPL1402/FTree/Leaf.java).\r\n[Ftree](https://inginious.info.ucl.ac.be/course/LEPL1402/FTree/FTree.java) is an abstract class that\r\nrepresents a binary true, it is extended by Node and Leaf. A\r\n[Node](https://inginious.info.ucl.ac.be/course/LEPL1402/FTree/Node.java) is a\r\n[FTree](https://inginious.info.ucl.ac.be/course/LEPL1402/FTree/FTree.java) with two children (left and\r\nright) and a value. A [Leaf](https://inginious.info.ucl.ac.be/course/LEPL1402/FTree/Leaf.java) is\r\nterminal, so it has a value but no children.\r\n\r\nIn the [FTree](https://inginious.info.ucl.ac.be/course/LEPL1402/FTree/FTree.java) class you must *recursivly* implement: \r\n- depth : returns the depth of the tree (we assume that the tree is\r\n balanced)\r\n- map : receives a function as argument and apply it to all the values\r\n contained in the tree\r\n\r\nTo complete the [Node](https://inginious.info.ucl.ac.be/course/LEPL1402/FTree/Node.java) class you must: \r\n- implement the constructor\r\n- extend [FTree](https://inginious.info.ucl.ac.be/course/LEPL1402/FTree/FTree.java)\r\n\r\nTo complete the [Leaf](https://inginious.info.ucl.ac.be/course/LEPL1402/FTree/Leaf.java) class you must : \r\n- implement the constructor\r\n- extend [FTree](https://inginious.info.ucl.ac.be/course/LEPL1402/FTree/FTree.java)\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/FTree/LEPL1402_FTree.zip) that contains few\r\ntests to help you.\r\n", + "description": "

In this exercise you have to complete the class FTree, Node and Leaf. Ftree is an abstract class that represents a binary true, it is extended by Node and Leaf. A Node is a FTree with two children (left and right) and a value. A Leaf is terminal, so it has a value but no children.

\r\n
\r\n
In the FTree class you must recursivly implement:
\r\n
    \r\n
  • depth : returns the depth of the tree (we assume that the tree is balanced)
  • \r\n
  • map : receives a function as argument and apply it to all the values contained in the tree
  • \r\n
\r\n
\r\n
To complete the Node class you must:
\r\n
    \r\n
  • implement the constructor
  • \r\n
  • extend FTree
  • \r\n
\r\n
\r\n
To complete the Leaf class you must :
\r\n
    \r\n
  • implement the constructor
  • \r\n
  • extend FTree
  • \r\n
\r\n
\r\n
\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1553,7 +1557,7 @@ }, { "title": "Future", - "description": "For this task you will learn use\r\n[Future](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html)\r\nand\r\n[ExecutorService](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html)\r\nin order to load a web page with images asynchronously. Indeed html is\r\nlightweight compared to the images so we want the images to be\r\ndownloaded asynchronously while the html is displayed without the\r\nimages.\r\n\r\nIn this task we give you the\r\n[WebPage](https://inginious.info.ucl.ac.be/course/LEPL1402/Future/WebPage.java) class to complete and\r\nthree other class to use : [URL](https://inginious.info.ucl.ac.be/course/LEPL1402/Future/URL.java),\r\n[Image](https://inginious.info.ucl.ac.be/course/LEPL1402/Future/Image.java) and\r\n[HTML](https://inginious.info.ucl.ac.be/course/LEPL1402/Future/HTML.java).\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/Future/LEPL1402_Future.zip) that contains few\r\ntests to help you.\r\n\r\n``` java\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\nimport java.util.concurrent.ExecutionException;\r\nimport java.util.concurrent.ExecutorService;\r\nimport java.util.concurrent.Executors;\r\nimport java.util.concurrent.Future;\r\n\r\npublic class WebPage {\r\n\r\n private ExecutorService executor;\r\n private HTML html;\r\n\r\n /*\r\n * Bound executor to a fixed thread pool size\r\n */\r\n public WebPage(int threadNumber, HTML html){\r\n //TODO\r\n }\r\n\r\n /*\r\n * submit the download of the image specified by the url\r\n * to be executed by thread pool\r\n */\r\n public Future loadImage(URL url){\r\n //TODO\r\n }\r\n\r\n /*\r\n * Download the image specified by the url\r\n */\r\n public Image downloadImageFromURL(URL url){\r\n //HIDDEN\r\n }\r\n\r\n /*\r\n * Load all images of the page\r\n */\r\n public List> loadImages(List urls){\r\n //TODO\r\n }\r\n\r\n /*\r\n * Load the page while images are being downloaded\r\n */\r\n private void displayPageWithoutImage(){\r\n //HIDDEN\r\n }\r\n\r\n /*\r\n * Display all images on the page\r\n */\r\n private void displayImages(List images){\r\n //HIDDEN\r\n }\r\n\r\n /*\r\n * load the page\r\n */\r\n public void loadPage(){\r\n // First the image are downloaded asynchronously\r\n List> futures = loadImages(this.html.getUrls());\r\n // While the image are being downloaded, we display the page without them\r\n displayPageWithoutImage();\r\n // Then we need all images to display them\r\n List images = new ArrayList(futures.size());\r\n try{\r\n for(Future future : futures){\r\n // the \"get()\" function is waiting for the result of the future task (here download the images)\r\n images.add(future.get());\r\n }\r\n } catch(InterruptedException e){\r\n\r\n } catch (ExecutionException e){\r\n\r\n }\r\n // we can display now images on the page\r\n displayImages(images);\r\n // shut down the executor service now\r\n executor.shutdown();\r\n\r\n }\r\n\r\n}\r\n```\r\n", + "description": "

For this task you will learn use Future and ExecutorService in order to load a web page with images asynchronously. Indeed html is lightweight compared to the images so we want the images to be downloaded asynchronously while the html is displayed without the images.

\r\n

In this task we give you the WebPage class to complete and three other class to use : URL, Image and HTML.

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n
import java.util.ArrayList;\r\nimport java.util.List;\r\nimport java.util.concurrent.ExecutionException;\r\nimport java.util.concurrent.ExecutorService;\r\nimport java.util.concurrent.Executors;\r\nimport java.util.concurrent.Future;\r\n\r\npublic class WebPage {\r\n\r\n    private ExecutorService executor;\r\n    private HTML html;\r\n\r\n    /*\r\n     * Bound executor to a fixed thread pool size\r\n     */\r\n    public WebPage(int threadNumber, HTML html){\r\n        //TODO\r\n    }\r\n\r\n    /*\r\n     * submit the download of the image specified by the url\r\n     * to be executed by thread pool\r\n     */\r\n    public Future<Image> loadImage(URL url){\r\n        //TODO\r\n    }\r\n\r\n    /*\r\n     * Download the image specified by the url\r\n     */\r\n    public Image downloadImageFromURL(URL url){\r\n        //HIDDEN\r\n    }\r\n\r\n    /*\r\n     * Load all images of the page\r\n     */\r\n    public List<Future<Image>> loadImages(List<URL> urls){\r\n        //TODO\r\n    }\r\n\r\n    /*\r\n     * Load the page while images are being downloaded\r\n     */\r\n    private void displayPageWithoutImage(){\r\n        //HIDDEN\r\n    }\r\n\r\n    /*\r\n     * Display all images on the page\r\n     */\r\n    private void displayImages(List<Image> images){\r\n        //HIDDEN\r\n    }\r\n\r\n    /*\r\n     * load the page\r\n     */\r\n    public void loadPage(){\r\n        // First the image are downloaded asynchronously\r\n        List<Future<Image>> futures = loadImages(this.html.getUrls());\r\n        // While the image are being downloaded, we display the page without them\r\n        displayPageWithoutImage();\r\n        // Then we need all images to display them\r\n        List<Image> images = new ArrayList<Image>(futures.size());\r\n        try{\r\n            for(Future<Image> future : futures){\r\n                // the "get()" function is waiting for the result of the future task (here download the images)\r\n                images.add(future.get());\r\n            }\r\n        } catch(InterruptedException e){\r\n\r\n        } catch (ExecutionException e){\r\n\r\n        }\r\n        // we can display now images on the page\r\n        displayImages(images);\r\n        // shut down the executor service now\r\n        executor.shutdown();\r\n\r\n    }\r\n\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1611,8 +1615,8 @@ } }, { - "title": "Generics 1", - "description": "In this task, you have to implement the map / filter functions of the\r\nfollowing class :\r\n\r\n``` java\r\npublic class Cons {\r\n // the item inside this list node\r\n public int v;\r\n // The next element, null if nothing\r\n public Cons next;\r\n // creates a new Cons that applies function f on all elements\r\n public Cons map(F f) {\r\n // TODO by student\r\n }\r\n // creates a new Cons with all elements that matches predicate p\r\n public Cons filter(P p) {\r\n // TODO by student\r\n }\r\n // Constructor\r\n public Cons(int v, Cons next) {\r\n this.v = v;\r\n this.next = next;\r\n }\r\n}\r\n```\r\n\r\nHere are the interfaces for the object parameter for filter/map\r\n\r\n``` java\r\ninterface F {\r\n int apply(int v);\r\n}\r\n\r\ninterface P {\r\n boolean filter(int v);\r\n}\r\n```\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/Generics/LEPL1402_Generics.zip) that contains\r\nfew tests to help you.\r\n\r\n( You can find all the required files here :\r\n[Cons](https://inginious.info.ucl.ac.be/course/LEPL1402/Generics/Cons.java) ,\r\n[Function](https://inginious.info.ucl.ac.be/course/LEPL1402/Generics/F.java) ,\r\n[Predicate](https://inginious.info.ucl.ac.be/course/LEPL1402/Generics/P.java) )\r\n", + "title": "Map, Filter, Cons", + "description": "

In this task, you have to implement the map / filter functions of the following class :

\r\n
public class Cons {\r\n    // the item inside this list node\r\n    public int v;\r\n    // The next element, null if nothing\r\n    public Cons next;\r\n    // creates a new Cons that applies function f on all elements\r\n    public Cons map(F f) {\r\n        // TODO by student\r\n    }\r\n    // creates a new Cons with all elements that matches predicate p\r\n    public Cons filter(P p) {\r\n        // TODO by student\r\n    }\r\n    // Constructor\r\n    public Cons(int v, Cons next) {\r\n        this.v = v;\r\n        this.next = next;\r\n    }\r\n}
\r\n

Here are the interfaces for the object parameter for filter/map

\r\n
interface F {\r\n    int apply(int v);\r\n}\r\n\r\ninterface P {\r\n    boolean filter(int v);\r\n}
\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n

( You can find all the required files here : Cons , Function , Predicate )

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1655,7 +1659,7 @@ "text": "java" }, { - "text": "Module 3", + "text": "Module 5", "category": 2 } ], @@ -1670,8 +1674,8 @@ } }, { - "title": "Generics 2", - "description": "In this task, you have to implement the generic map / filter functions\r\nof the following class :\r\n\r\n``` java\r\nimport java.util.function.Predicate;\r\nimport java.util.function.Function;\r\n\r\npublic class Cons < E > {\r\n // the item inside this list node\r\n public E v;\r\n // The next element, null if nothing\r\n public Cons next;\r\n // creates a new Cons that applies function f on all elements\r\n public Cons map(Function function) {\r\n // TODO by student\r\n }\r\n // creates a new Cons with all elements that matches predicate p\r\n public Cons filter(Predicate predicate) {\r\n // TODO by student\r\n }\r\n // Constructor\r\n public Cons(E v, Cons < E > next) {\r\n this.v = v;\r\n this.next = next;\r\n }\r\n}\r\n```\r\n\r\nTo help you understand how Predicate and Function works, check the\r\n[documentation](https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html).\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/Generics2/LEPL1402_Generics2.zip) that\r\ncontains few tests to help you.\r\n\r\n(You can find here all documents :\r\n[Cons](https://inginious.info.ucl.ac.be/course/LEPL1402/Generics2/Cons.java),\r\n[Function](https://inginious.info.ucl.ac.be/course/LEPL1402/Generics2/F.java),\r\n[Predicate](https://inginious.info.ucl.ac.be/course/LEPL1402/Generics2/P.java))\r\n", + "title": "Map, Filter, Cons with Generics", + "description": "

In this task, you have to implement the generic map / filter functions of the following class :

\r\n
import java.util.function.Predicate;\r\nimport java.util.function.Function;\r\n\r\npublic class Cons < E > {\r\n    // the item inside this list node\r\n    public E v;\r\n    // The next element, null if nothing\r\n    public Cons<E> next;\r\n    // creates a new Cons that applies function f on all elements\r\n    public <R> Cons <R> map(Function <E,R> function) {\r\n        // TODO by student\r\n    }\r\n    // creates a new Cons with all elements that matches predicate p\r\n    public Cons <E> filter(Predicate <E> predicate) {\r\n        // TODO by student\r\n    }\r\n    // Constructor\r\n    public Cons(E v, Cons < E > next) {\r\n        this.v = v;\r\n        this.next = next;\r\n    }\r\n}
\r\n

To help you understand how Predicate and Function works, check the documentation. You can download the IntelliJ Project that contains few tests to help you.

\r\n

(You can find here all documents : Cons)

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1714,7 +1718,7 @@ "text": "java" }, { - "text": "Module 3", + "text": "Module 5", "category": 2 } ], @@ -1729,8 +1733,8 @@ } }, { - "title": "Generics 3", - "description": "In this task, you have to implement the solver of this well-known logic\r\ncircuit :\r\n\r\n
\r\n\"\"\r\n
\r\n\r\nInstead of directly using a chain of logical operators ( that can lead\r\nyou to a error prone code sometimes), we will be using\r\n[BiFunction](https://docs.oracle.com/javase/8/docs/api/java/util/function/BiFunction.html)\r\nand\r\n[Function](https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html)\r\nto implement the logic gates. Your task is thus to implement the\r\nfollowing class : [Evaluator](https://inginious.info.ucl.ac.be/course/LEPL1402/Generics3/Evaluator.java)\r\n. You can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/Generics3/LEPL1402_Generics3.zip) that\r\ncontains few tests to help you.\r\n", + "title": "Logical Circuit Functional", + "description": "

In this task, you have to implement the solver of this well-known logic circuit :

\r\n
\r\n\"\"\r\n
\r\n

Instead of directly using a chain of logical operators ( that can lead you to a error prone code sometimes), we will be using BiFunction and Function to implement the logic gates. Your task is thus to implement the following class : Evaluator . You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1773,7 +1777,7 @@ "text": "java" }, { - "text": "Module 3", + "text": "Module 5", "category": 2 } ], @@ -1789,7 +1793,7 @@ }, { "title": "Hanoi Tower", - "description": "The tower of Hanoi is a mathematical puzzle, it consists of three rods\r\nand a number of disk of different size which can slide onto any rod. The\r\ngame starts with all the disks in an ascending order forming a stack on\r\nthe first rod. The objective of this puzzle is to move the entire stack\r\nto another rod. We know, it sounds easy, but there are 3 simple rules\r\nthat make the game harder than you think.\r\n\r\nHere they are : \r\n- You can only move one disk at a time.\r\n- Each move consists of taking the upper disk from one stack and\r\n moving it to another stack or on an empty rod.\r\n- No larger disk may be placed on top of a smaller disk.\r\n\r\nTo help you a little bit, here is an example of how you can solve the\r\nproblem with a stack of size 3.\r\n\r\n\"image\"\r\n\r\nIn this exercise, you are asked to solve this puzzle for any size of\r\nstack by implementing this method and this method only! We are using\r\n[Stack](https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html),\r\nto get the first element of a stack, use the method `pop`, and to add an\r\nelement use the method `push`. The object\r\n[Disk](https://inginious.info.ucl.ac.be/course/LEPL1402/HanoiTower/Disk.java) is here to make sure you\r\nwill not solve the exercise by just creating another stack.\r\n\r\nHere is the class\r\n[TowerOfHanoi](https://inginious.info.ucl.ac.be/course/LEPL1402/HanoiTower/TowerOfHanoi.java) you must\r\nimplement, you can create disk by yourself to test your method but it\r\nwill not compile on Inginious if you try to do it.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/HanoiTower/LEPL1402_HanoiTower.zip) that\r\ncontains few tests to help you.\r\n\r\n**hint:** you can call `towerOfHanoi` inside itself\r\n", + "description": "

The tower of Hanoi is a mathematical puzzle, it consists of three rods and a number of disk of different size which can slide onto any rod. The game starts with all the disks in an ascending order forming a stack on the first rod. The objective of this puzzle is to move the entire stack to another rod. We know, it sounds easy, but there are 3 simple rules that make the game harder than you think.

\r\n
\r\n
Here they are :
\r\n
    \r\n
  • You can only move one disk at a time.
  • \r\n
  • Each move consists of taking the upper disk from one stack and moving it to another stack or on an empty rod.
  • \r\n
  • No larger disk may be placed on top of a smaller disk.
  • \r\n
\r\n
\r\n
\r\n

To help you a little bit, here is an example of how you can solve the problem with a stack of size 3.

\r\n

\"image\"

\r\n

In this exercise, you are asked to solve this puzzle for any size of stack by implementing this method and this method only! We are using Stack, to get the first element of a stack, use the method pop, and to add an element use the method push. The object Disk is here to make sure you will not solve the exercise by just creating another stack.

\r\n

Here is the class TowerOfHanoi you must implement, you can create disk by yourself to test your method but it will not compile on Inginious if you try to do it.

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n

hint: you can call towerOfHanoi inside itself

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1848,7 +1852,7 @@ }, { "title": "Infinite Streams", - "description": "The\r\n[Stream](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html)\r\ninterface of java allows to create infinite streams. In order to\r\nunderstand how it works, we will create our own infinite streams.\r\n\r\nFor this task we give you an incomplete interface named\r\n[IStream](https://inginious.info.ucl.ac.be/course/LEPL1402/InfiniteStreams/IStream.java) that represents\r\nan infinite stream. You first have to complete the three default methods\r\nof this interface. Since IStream is an interface, you have to complete\r\nthe class [Cons](https://inginious.info.ucl.ac.be/course/LEPL1402/InfiniteStreams/Cons.java) that\r\nimplements [IStream](https://inginious.info.ucl.ac.be/course/LEPL1402/InfiniteStreams/IStream.java).\r\n\r\nSince an infinite stream is not always usefull, we give you the class\r\n[Empty](https://inginious.info.ucl.ac.be/course/LEPL1402/InfiniteStreams/Empty.java) that implements\r\n[IStream](https://inginious.info.ucl.ac.be/course/LEPL1402/InfiniteStreams/IStream.java) and marks the\r\nend of a stream.\r\n\r\nFinally you will use all of it to create different finite and infinite\r\nstreams in the class\r\n[PlayWithStreams](https://inginious.info.ucl.ac.be/course/LEPL1402/InfiniteStreams/PlayWithStreams.java).\r\n\r\nThere may seem like a lot to do, but most functions can be implemented\r\nin one line.\r\n\r\nNote that you will need to use the\r\n[Supplier](https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html)\r\nobject in order to make the creation of your stream (so the tail of a\r\nCons) lazy.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/InfiniteStreams/LEPL1402_InfiniteStreams.zip)\r\nthat contains few tests to help you.\r\n", + "description": "

The Stream interface of java allows to create infinite streams. In order to understand how it works, we will create our own infinite streams.

\r\n

For this task we give you an incomplete interface named IStream that represents an infinite stream. You first have to complete the three default methods of this interface. Since IStream is an interface, you have to complete the class Cons that implements IStream.

\r\n

Since an infinite stream is not always usefull, we give you the class Empty that implements IStream and marks the end of a stream.

\r\n

Finally you will use all of it to create different finite and infinite streams in the class PlayWithStreams.

\r\n

There may seem like a lot to do, but most functions can be implemented in one line.

\r\n

Note that you will need to use the Supplier object in order to make the creation of your stream (so the tail of a Cons) lazy.

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1907,7 +1911,7 @@ }, { "title": "Inheritance : Fill the gaps (Small Exercise)", - "description": "Will you be able to fill the gaps inside these three source files (\r\n[Animal](https://inginious.info.ucl.ac.be/course/LEPL1402/Inheritance/Animal.java) ,\r\n[Cat](https://inginious.info.ucl.ac.be/course/LEPL1402/Inheritance/Cat.java) ,\r\n[SuperCat](https://inginious.info.ucl.ac.be/course/LEPL1402/Inheritance/SuperCat.java) ) so that it\r\ncompiles and passes our tests ?\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/Inheritance/LEPL1402_Inheritance.zip) that\r\ncontains few tests to help you.\r\n", + "description": "

Will you be able to fill the gaps inside these three source files ( Animal , Cat , SuperCat ) so that it compiles and passes our tests ?

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1966,7 +1970,7 @@ }, { "title": "Introduction to java, exercises", - "description": "Welcome to the first task of a long series!\r\n\r\nThis serie of inginious tasks will accompany you throughout the\r\nquadrimester to learn java and apprehend the material seen in class.\r\nSuccessful completion of all tasks is a major step towards the success\r\nof this course. We encourage you to try to do them yourself without\r\ngoing on the Internet.\r\n\r\nWe also encourage you to try your solutions by yourself on you computer.\r\nTo do so take a look at [this\r\ntutorial](https://lepl1402.readthedocs.io/en/latest/tools/index.html) on\r\nthe tools you will need.\r\n\r\nThis first task will cover the basics of java step by step. In most\r\nexercises we want you to paste the **signature** and the **body** of the\r\nmethods you create. In other cases we just wan to you paste the **body**\r\nand we give you the **signature**.\r\n\r\nHere is the class that you must implements in this task. The context of\r\nall variable must be static and the modifier public. You must find the\r\nreturn type by yourself.\r\n\r\n``` java\r\npublic class IntroductionExercises {\r\n\r\n public static int variable = 0;\r\n\r\n public static int[] squares;\r\n\r\n //TODO\r\n\r\n}\r\n```\r\n", + "description": "

Welcome to the first task of a long series!

\r\n

This serie of inginious tasks will accompany you throughout the quadrimester to learn java and apprehend the material seen in class. Successful completion of all tasks is a major step towards the success of this course. We encourage you to try to do them yourself without going on the Internet.

\r\n

We also encourage you to try your solutions by yourself on you computer. To do so take a look at this tutorial on the tools you will need.

\r\n

This first task will cover the basics of java step by step. In most exercises we want you to paste the signature and the body of the methods you create. In other cases we just wan to you paste the body and we give you the signature.

\r\n

Here is the class that you must implements in this task. The context of all variable must be static and the modifier public. You must find the return type by yourself.

\r\n
public class IntroductionExercises {\r\n\r\n    public static int variable = 0;\r\n\r\n    public static int[] squares;\r\n\r\n    //TODO\r\n\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2025,7 +2029,7 @@ }, { "title": "Lambda Expression in Java", - "description": "In this exercise you will learn to use basic lambda expression. Since\r\nyou are going to use them later, they are worth a small introduction\r\nexercise.\r\n\r\nSince we work with lambda, we have decided to block the `return`\r\nstatement.\r\n\r\nHere you can find the java documentation about\r\n[Function](https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html),\r\n[Predicate](https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html)\r\nand\r\n[Comparator](https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html).\r\n", + "description": "

In this exercise you will learn to use basic lambda expression. Since you are going to use them later, they are worth a small introduction exercise.

\r\n

Since we work with lambda, we have decided to block the return statement.

\r\n

Here you can find the java documentation about Function, Predicate and Comparator.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2084,7 +2088,7 @@ }, { "title": "Learn Exception in Java", - "description": "In this task we ask you to implement method throwing and catching\r\nexceptions. In Java, Exceptions are handled using `try` and `catch`\r\nstatement like the example below\r\n\r\n``` java\r\ntry{\r\n String s = methodThatCanThrowException();\r\n}catch(ExceptionCaught e){\r\n //Do something\r\n}\r\n\r\n//Continue\r\n```\r\n\r\nWhen a method can throw an exception, it has to be specified in the\r\nsignature like the example below:\r\n\r\n``` java\r\npublic static double divide(int i1, int i2) throws ArithmeticException\r\n```\r\n\r\nIt means that it is possible that the method uses a statement like this:\r\n\r\n``` java\r\nthrow new ArithmeticException();\r\n```\r\n\r\nDownload [Divider](https://inginious.info.ucl.ac.be/course/LEPL1402/LearnException/Divider.java) and\r\nread the comment to know what you have to do. Download [intellij\r\nproject](https://inginious.info.ucl.ac.be/course/LEPL1402/LearnException/LEPL1402_LearnException.zip)\r\nwith tests.\r\n", + "description": "

In this task we ask you to implement method throwing and catching exceptions. In Java, Exceptions are handled using try and catch statement like the example below

\r\n
try{\r\n    String s = methodThatCanThrowException();\r\n}catch(ExceptionCaught e){\r\n    //Do something\r\n}\r\n\r\n//Continue
\r\n

When a method can throw an exception, it has to be specified in the signature like the example below:

\r\n
public static double divide(int i1, int i2) throws ArithmeticException
\r\n

It means that it is possible that the method uses a statement like this:

\r\n
throw new ArithmeticException();
\r\n

Download Divider and read the comment to know what you have to do. Download intellij project with tests.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2143,7 +2147,7 @@ }, { "title": "Make Mistake To Understand Them", - "description": "Although it will seem a bit weird, we will ask you to write code\r\ngenerating Exception. But why? The reason is simple, when you start\r\nprogramming in a new language it sometimes is really hard to understand\r\nwhy your code won't run properly. We made this exercise to help you\r\nunderstand what your mistake can be.\r\n\r\nBefore starting this exercise we recommend you to read about\r\n[NullPointerException](https://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html),\r\n[ArrayIndexOutOfBoundsException](https://docs.oracle.com/javase/8/docs/api/java/lang/ArrayIndexOutOfBoundsException.html)\r\nand\r\n[ConcurrentModificationException](https://docs.oracle.com/javase/8/docs/api/java/util/ConcurrentModificationException.html).\r\n", + "description": "

Although it will seem a bit weird, we will ask you to write code generating Exception. But why? The reason is simple, when you start programming in a new language it sometimes is really hard to understand why your code won't run properly. We made this exercise to help you understand what your mistake can be.

\r\n

Before starting this exercise we recommend you to read about NullPointerException, ArrayIndexOutOfBoundsException and ConcurrentModificationException.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2202,7 +2206,7 @@ }, { "title": "Largest Sum Contiguous Subarray", - "description": "In this exercise you must write a method `maxSubArray` that finds the\r\nlargest sum in a contiguous subarray :\r\n\r\nGiven: \r\n- an array *s*,\r\n- (*i*, *j*), two indexes defining the start and the end of a subarray\r\n *s**u**b* such that 0 ≤ *i* ≤ *j* < *s*.*l**e**n**g**t**h*\r\n- *s**u**m*(*s**u**b*) the sum of all elements of the subarray\r\n *s**u**b*.\r\n\r\n∀*s**u**b* ∈ *s* such that\r\n*s**u**b* ≠ *s**u**b**o**p**t**i**m**a**l*;\r\n*s**u**b**o**p**t**i**m**a**l* is the maximum subarray of *s*\r\nif and only if\r\n*s**u**m*(*s**u**b**o**p**t**i**m**a**l*) > *s**u**m*(*s**u**b*).\r\n\r\nWhat it means is that given an array, your program should find the\r\n**first** subarray that produces the maximum result.\r\n\r\nYour method must return an array of three integers : \r\n- The sum of the subarray\r\n- The index of the start of the subarray\r\n- The index of the end of the subarray\r\n\r\n\r\n\r\n``` java\r\n/*\r\n* Given the array [-2,1,-3,4,-1,2,1,-5,4]\r\n* The contiguous subarray that produces the best result is [4,-1,2,1]\r\n* For this array your method should return [6, 3, 6]\r\n*/\r\npublic static int[] maxSubArray(int[] a){\r\n\r\n //TODO By Student\r\n\r\n}\r\n```\r\n\r\nNote that the length of the array **a** is strictly greater than 0.\r\n", + "description": "

In this exercise you must write a method maxSubArray that finds the largest sum in a contiguous subarray :

\r\n
\r\n
Given:
\r\n
    \r\n
  • an array s,
  • \r\n
  • (i, j), two indexes defining the start and the end of a subarray sub such that 0 ≤ i ≤ j < s.length
  • \r\n
  • sum(sub) the sum of all elements of the subarray sub.
  • \r\n
\r\n
\r\n
\r\n

sub ∈ s such that sub ≠ suboptimal; suboptimal is the maximum subarray of s if and only if sum(suboptimal) > sum(sub).

\r\n

What it means is that given an array, your program should find the first subarray that produces the maximum result.

\r\n
\r\n
Your method must return an array of three integers :
\r\n
    \r\n
  • The sum of the subarray
  • \r\n
  • The index of the start of the subarray
  • \r\n
  • The index of the end of the subarray
  • \r\n
\r\n
\r\n
\r\n
/*\r\n*    Given the array [-2,1,-3,4,-1,2,1,-5,4]\r\n*    The contiguous subarray that produces the best result is [4,-1,2,1]\r\n*    For this array your method should return [6, 3, 6]\r\n*/\r\npublic static int[] maxSubArray(int[] a){\r\n\r\n    //TODO By Student\r\n\r\n}
\r\n

Note that the length of the array a is strictly greater than 0.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2261,7 +2265,7 @@ }, { "title": "Merge Sort Implementation", - "description": "In this exercise we ask you to implement the\r\n[top-down](https://inginious.info.ucl.ac.be/course/LEPL1402/MergeSortImplementation/topdown.png) merge\r\nsort algorithm on an array of integer. You have to use **2 methods**:\r\n\r\n> - Sort, this method has to divide the array and apply merge.\r\n> - Merge, this method has to merge the array given the 2 index, it\r\n> receives from sort 3 index, lower bound, middle and high. It also\r\n> receives a copy of the first array.\r\n\r\nThe tests are build to make you able to test the two methods separly but\r\nwe **recommand** you to test them by yourself.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/MergeSortImplementation/LEPL1402_MergeSortImplementation.zip)\r\nthat contains few tests to help you.\r\n\r\nHere is the class\r\n[MergeSort](https://inginious.info.ucl.ac.be/course/LEPL1402/MergeSortImplementation/MergeSort.java):\r\n\r\n``` java\r\npublic class MergeSort {\r\n\r\n /**\r\n * Pre-conditions: a[lo..mid] and a[mid+1..hi] are sorted\r\n * Post-conditions: a[lo..hi] is sorted\r\n */\r\n private static void merge(int[] a, int[] aux, int lo, int mid, int hi) {\r\n // TODO By Student\r\n }\r\n /**\r\n * Rearranges the array in ascending order, using the natural order\r\n */\r\n public static void sort(int[] a) {\r\n // TODO By Student\r\n }\r\n\r\n //TODO Optionnal additionnal method\r\n}\r\n```\r\n", + "description": "

In this exercise we ask you to implement the top-down merge sort algorithm on an array of integer. You have to use 2 methods:

\r\n
\r\n
    \r\n
  • Sort, this method has to divide the array and apply merge.
  • \r\n
  • Merge, this method has to merge the array given the 2 index, it receives from sort 3 index, lower bound, middle and high. It also receives a copy of the first array.
  • \r\n
\r\n
\r\n

The tests are build to make you able to test the two methods separly but we recommand you to test them by yourself.

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n

Here is the class MergeSort:

\r\n
public class MergeSort {\r\n\r\n    /**\r\n     * Pre-conditions: a[lo..mid] and a[mid+1..hi] are sorted\r\n     * Post-conditions: a[lo..hi] is sorted\r\n     */\r\n    private static void merge(int[] a, int[] aux, int lo, int mid, int hi) {\r\n        // TODO By Student\r\n    }\r\n    /**\r\n     * Rearranges the array in ascending order, using the natural order\r\n     */\r\n    public static void sort(int[] a) {\r\n        // TODO By Student\r\n    }\r\n\r\n    //TODO Optionnal additionnal method\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2310,7 +2314,7 @@ }, { "title": "MyArrayList", - "description": "In this task, you have to implement your own version of the famous\r\njava's `ArrayList` : a dynamic sized array. Each time you want to add\r\nan element, you must check that the item can fit and then append it at\r\nthe end of the list. If the array is too small, you need to resize it so\r\nthat new items can be added in the future. To remove an element you need\r\nto specify an index to choose which element of the list you want to\r\nremove (`remove(0)` for the first ... `remove(size()-1)` for the last).\r\n**Never** leave \"blanks\" in your array. When you remove an element at\r\nsome `index`, **all subsequents** elements must be \"shifted\".\r\n\r\nSo if your list look like this:\r\n\r\n
\r\n\"\"\r\n
\r\n\r\nThen after the call `remove(1)` it should look like this:\r\n\r\n
\r\n\"\"\r\n
\r\n\r\nYou also need to implement the `MyArrayListIterator` class.\r\n[Iterator](https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html)\r\nis an interface you have to implement in order to make the class\r\nimplementing it able to enumerate/browse/iterate over an object : here,\r\nwe want you to implement a FIFO order iterator over your `MyArrayList`.\r\n\r\n> **Pay attention**, we add some constraints for this task:\r\n>\r\n> > - Your iterator don't have to implement the `remove` method from\r\n> > [Iterator](https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html).\r\n> > - Your iterator must throw a `ConcurrentModificationException`\r\n> > when you want to get the next element but some other element has\r\n> > been added to the list meanwhile.\r\n> > - You cannot use `System.arraycopy` for this task.\r\n> > - Your constructor must throw an `IndexOutOfBoundsException` if\r\n> > the parameter is smaller than 0.\r\n> > - your `remove` method must throw an `IndexOutOfBoundsException`\r\n> > if the index parameter is smaller than `0` or greater than\r\n> > `size()-1`.\r\n\r\nA lot of classes implement this interface, including the official\r\n[ArrayList](https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html)\r\nfrom java. We **strongly** encourage you to experiment how the\r\n`ArrayList` iterator works before implementing yours.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/MyArrayList/LEPL1402_MyArrayList.zip) that\r\ncontains few tests to help you.\r\n\r\nHere is the class (downloadable\r\n[here](https://inginious.info.ucl.ac.be/course/LEPL1402/MyArrayList/MyArrayList.java)) where we will\r\ninsert your code :\r\n\r\n``` java\r\nimport java.util.ConcurrentModificationException;\r\nimport java.util.Iterator;\r\n\r\npublic class MyArrayList implements Iterable {\r\n\r\n private Object [] list;\r\n private int size;\r\n\r\n\r\n public MyArrayList(int initSize){\r\n // YOUR CODE HERE\r\n }\r\n\r\n\r\n /*\r\n * Checks if 'list' needs to be resized then add the element at the end\r\n * of the list.\r\n */\r\n public void enqueue(Item item){\r\n // YOUR CODE HERE\r\n }\r\n\r\n\r\n /*\r\n * Removes the element at the specified position in this list.\r\n * Returns the element that was removed from the list. You dont need to\r\n * resize when removing an element.\r\n */\r\n public Item remove(int index){\r\n // YOUR CODE HERE\r\n }\r\n\r\n\r\n public int size(){\r\n return this.size;\r\n }\r\n\r\n\r\n @Override\r\n public Iterator iterator() {\r\n return new MyArrayListIterator();\r\n }\r\n\r\n\r\n private class MyArrayListIterator implements Iterator {\r\n // YOUR CODE HERE\r\n }\r\n\r\n}\r\n```\r\n", + "description": "

In this task, you have to implement your own version of the famous java's ArrayList<E> : a dynamic sized array. Each time you want to add an element, you must check that the item can fit and then append it at the end of the list. If the array is too small, you need to resize it so that new items can be added in the future. To remove an element you need to specify an index to choose which element of the list you want to remove (remove(0) for the first ... remove(size()-1) for the last). Never leave \"blanks\" in your array. When you remove an element at some index, all subsequents elements must be \"shifted\".

\r\n

So if your list look like this:

\r\n
\r\n\"\"\r\n
\r\n

Then after the call remove(1) it should look like this:

\r\n
\r\n\"\"\r\n
\r\n

You also need to implement the MyArrayListIterator class. Iterator is an interface you have to implement in order to make the class implementing it able to enumerate/browse/iterate over an object : here, we want you to implement a FIFO order iterator over your MyArrayList.

\r\n
\r\n

Pay attention, we add some constraints for this task:

\r\n
\r\n
    \r\n
  • Your iterator don't have to implement the remove method from Iterator.
  • \r\n
  • Your iterator must throw a ConcurrentModificationException when you want to get the next element but some other element has been added to the list meanwhile.
  • \r\n
  • You cannot use System.arraycopy for this task.
  • \r\n
  • Your constructor must throw an IndexOutOfBoundsException if the parameter is smaller than 0.
  • \r\n
  • your remove method must throw an IndexOutOfBoundsException if the index parameter is smaller than 0 or greater than size()-1.
  • \r\n
\r\n
\r\n
\r\n

A lot of classes implement this interface, including the official ArrayList from java. We strongly encourage you to experiment how the ArrayList<E> iterator works before implementing yours.

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n

Here is the class (downloadable here) where we will insert your code :

\r\n
import java.util.ConcurrentModificationException;\r\nimport java.util.Iterator;\r\n\r\npublic class MyArrayList<Item> implements Iterable<Item> {\r\n\r\n    private Object [] list;\r\n    private int size;\r\n\r\n\r\n    public MyArrayList(int initSize){\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n\r\n    /*\r\n    * Checks if 'list' needs to be resized then add the element at the end\r\n    * of the list.\r\n    */\r\n    public void enqueue(Item item){\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n\r\n    /*\r\n    * Removes the element at the specified position in this list.\r\n    * Returns the element that was removed from the list. You dont need to\r\n    * resize when removing an element.\r\n    */\r\n    public Item remove(int index){\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n\r\n    public int size(){\r\n        return this.size;\r\n    }\r\n\r\n\r\n    @Override\r\n    public Iterator<Item> iterator() {\r\n        return new MyArrayListIterator();\r\n    }\r\n\r\n\r\n    private class MyArrayListIterator implements Iterator<Item> {\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2369,7 +2373,7 @@ }, { "title": "Observer design pattern", - "description": "In this task, you have to implement the Observer design pattern for the\r\ncase of a meteo station:\r\n\r\n``` java\r\npublic class MeteoStation extends Observable {\r\n // YOUR CODE HERE\r\n}\r\n\r\n\r\npublic class Client extends Observer {\r\n // YOUR CODE HERE\r\n}\r\n```\r\n\r\nNote that [Observable](https://inginious.info.ucl.ac.be/course/LEPL1402/Observer/Observable.java) and\r\n[Observer](https://inginious.info.ucl.ac.be/course/LEPL1402/Observer/Observer.java) are two abstract\r\nclasses containing abstract methods. Therefore, check and read them\r\ncarefully in order to implement things correctly. For your `Client`\r\nclass you have to extend the observer class and implement a constructor\r\n(do not forget instance variables). For the `MeteoStation` class, extend\r\nthe Observable abstract class, you will need to use\r\n[Pair](https://inginious.info.ucl.ac.be/course/LEPL1402/Observer/Pair.java) for this one.\r\n\r\nNote that your observers start to receive messages at the moment they\r\nsubscribe but they should not see messages that were broadcast before\r\nthey subscribed.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/Observer/LEPL1402_Observer.zip) that contains\r\nfew tests to help you.\r\n", + "description": "

In this task, you have to implement the Observer design pattern for the case of a meteo station:

\r\n
public class MeteoStation extends Observable {\r\n    // YOUR CODE HERE\r\n}\r\n\r\n\r\npublic class Client extends Observer {\r\n    // YOUR CODE HERE\r\n}
\r\n

Note that Observable and Observer are two abstract classes containing abstract methods. Therefore, check and read them carefully in order to implement things correctly. For your Client class you have to extend the observer class and implement a constructor (do not forget instance variables). For the MeteoStation class, extend the Observable abstract class, you will need to use Pair for this one.

\r\n

Note that your observers start to receive messages at the moment they subscribe but they should not see messages that were broadcast before they subscribed.

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2428,7 +2432,7 @@ }, { "title": "Optional - no more concerns about NullPointerException", - "description": "The 8th version of java introduced the\r\n[Optional](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html)\r\nobject to avoid NullPointerException in our codes without using too many\r\ncheck on nullable objects.\r\n\r\nFor this task, we give you three small classes\r\n([Person](https://inginious.info.ucl.ac.be/course/LEPL1402/Optional/Person.java),\r\n[Team](https://inginious.info.ucl.ac.be/course/LEPL1402/Optional/Team.java) and\r\n[TeamLeader](https://inginious.info.ucl.ac.be/course/LEPL1402/Optional/TeamLeader.java)) and you have to\r\nimplement the different methods of\r\n[OptionalTest](https://inginious.info.ucl.ac.be/course/LEPL1402/Optional/OptionalTest.java). All methods\r\ncan be implemented in one line of code thanks to the different methods\r\nof\r\n[Optional](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html)\r\nand the lambda expressions.\r\n\r\nYou are not allow to use `new TeamLeader()` in these exercises.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/Optional/LEPL1402_Optional.zip) that contains\r\nfew tests to help you.\r\n", + "description": "

The 8th version of java introduced the Optional object to avoid NullPointerException in our codes without using too many check on nullable objects.

\r\n

For this task, we give you three small classes (Person, Team and TeamLeader) and you have to implement the different methods of OptionalTest. All methods can be implemented in one line of code thanks to the different methods of Optional and the lambda expressions.

\r\n

You are not allow to use new TeamLeader() in these exercises.

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2487,7 +2491,7 @@ }, { "title": "Parallel Merge Sort", - "description": "In this task, you will be asked to implement a special kind of merge\r\nsort using the\r\n[RecursiveAction](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/RecursiveAction.html)\r\n,\r\n[ForkJoinPool](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html)\r\nand\r\n[ForkJoinTask](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinTask.html)\r\ninterfaces. You will understand by reading these interfaces that the\r\nmerge sort you must implement is not only recursive but in parallel.\r\n\r\nYou have to complete the following class :\r\n[ParallelMergeSort](https://inginious.info.ucl.ac.be/course/LEPL1402/ParallelelMergeSort/ParallelMergeSort.java)\r\n\r\nHere is an example of how we can use your implementation :\r\n\r\n``` java\r\nint size = 1000;\r\nInteger[] array = new Integer[size];\r\nfor(int i = 0 ; i < size ; i++){\r\n array[i] = rng.nextInt(10000);\r\n}\r\nParallelMergeSort task = new ParallelMergeSort(array, 0, size-1, new Integer[size],\r\n Comparator.comparing(Integer::intValue));\r\nnew ForkJoinPool().invoke(task);\r\n```\r\n\r\nYou will see that we've fixed a threshold, the reason we are using a\r\nthreshold is easy to understand. Since you want your code to be\r\neffective on very large array, starting a thread for every element can\r\nbe very ressource consuming and thus you would be losing the advantage\r\nyou had of using concurrent programming. So when the subarray you're\r\nworking on is smaller than the threshold, it simply run a normal sort.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/ParallelelMergeSort/LEPL1402_ParallelelMergeSort.zip)\r\nthat contains few tests to help you.\r\n", + "description": "

In this task, you will be asked to implement a special kind of merge sort using the RecursiveAction , ForkJoinPool and ForkJoinTask interfaces. You will understand by reading these interfaces that the merge sort you must implement is not only recursive but in parallel.

\r\n

You have to complete the following class : ParallelMergeSort

\r\n

Here is an example of how we can use your implementation :

\r\n
int size = 1000;\r\nInteger[] array = new Integer[size];\r\nfor(int i = 0 ; i < size ; i++){\r\n    array[i] = rng.nextInt(10000);\r\n}\r\nParallelMergeSort task = new ParallelMergeSort(array, 0, size-1, new Integer[size],\r\n                Comparator.comparing(Integer::intValue));\r\nnew ForkJoinPool().invoke(task);
\r\n

You will see that we've fixed a threshold, the reason we are using a threshold is easy to understand. Since you want your code to be effective on very large array, starting a thread for every element can be very ressource consuming and thus you would be losing the advantage you had of using concurrent programming. So when the subarray you're working on is smaller than the threshold, it simply run a normal sort.

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2546,7 +2550,7 @@ }, { "title": "Postscript interpreter", - "description": "You are asked to write a mini-PostScript interpreter as described in the\r\n*pdf* ([Mission](https://inginious.info.ucl.ac.be/course/LEPL1402/PostScript/mission.pdf)) of the\r\nmission. Precisely, you must implement the following interface :\r\n\r\n``` java\r\npublic interface InterpreterInterface {\r\n /**\r\n * @pre: 'instructions' is a valid chain of PostScript instructions\r\n * @post: returns a String representing the state of the stack when a 'pstack' instruction is encountered.\r\n * If several 'pstack' instructions are present in the chain, a concatenation of the corresponding states (when 'pstack' is encountered) must be returned, separated by whitespaces.\r\n * If several elements are still on the stack, separate them with whitespaces.\r\n * If there is no element on the stack or no 'pstack' instruction, return the empty string (\"\").\r\n */\r\n public String interpret(String instructions);\r\n}\r\n```\r\n\r\nWe expect your interpreter to be able to handle all of the following\r\nspecified operations:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n

Before

\r\n
AfterDescription
any pstackpstackprint the top element of the pile to the standard output
any1 any2 exchany2 any1Swap the two top most element of the stack
any popPop the top most element of the stack
any dupany anyDuplicate the top most element of the stack
any1 any2 addany1+any2Pop two elements from the stack, compute their sum and push the result
any1 any2 subany1-any2Same, but with a subtraction
any1 any2 mulany1*any2Same, but with a multiplication
any1 any2 divany1/any2Same, but with a division
any1 any2 idivany3
\r\n

Compute the quotient of an integer division of any1 by any2, then push the result to the stack

\r\n
\r\n\r\nThe element of the stack could be: \r\n- Operators - any operators from the array above.\r\n- Operands - any integer, double or boolean (true, false)\r\n\r\nDon't forget to throw exceptions : `EmptyStackException` if there's not\r\nenough operand left on the stack, `ArithmeticException` when an illegal\r\ncomputation is submitted to your interpreter, `IllegalArgumentException`\r\nwhen a bad operand is found (for example, a boolean instead of an\r\ninteger when performing a mathematical operation)\r\n", + "description": "

You are asked to write a mini-PostScript interpreter as described in the pdf (Mission) of the mission. Precisely, you must implement the following interface :

\r\n
public interface InterpreterInterface {\r\n    /**\r\n     * @pre: 'instructions' is a valid chain of PostScript instructions\r\n     * @post: returns a String representing the state of the stack when a 'pstack' instruction is encountered.\r\n     *    If several 'pstack' instructions are present in the chain, a concatenation of the corresponding states (when 'pstack' is encountered) must be returned, separated by whitespaces.\r\n     *    If several elements are still on the stack, separate them with whitespaces.\r\n     *    If there is no element on the stack or no 'pstack' instruction, return the empty string ("").\r\n     */\r\n    public String interpret(String instructions);\r\n}
\r\n

We expect your interpreter to be able to handle all of the following specified operations:

\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n

Before

\r\n
AfterDescription
any pstackpstackprint the top element of the pile to the standard output
any1 any2 exchany2 any1Swap the two top most element of the stack
any popPop the top most element of the stack
any dupany anyDuplicate the top most element of the stack
any1 any2 addany1+any2Pop two elements from the stack, compute their sum and push the result
any1 any2 subany1-any2Same, but with a subtraction
any1 any2 mulany1*any2Same, but with a multiplication
any1 any2 divany1/any2Same, but with a division
any1 any2 idivany3
\r\n

Compute the quotient of an integer division of any1 by any2, then push the result to the stack

\r\n
\r\n
\r\n
The element of the stack could be:
\r\n
    \r\n
  • Operators - any operators from the array above.
  • \r\n
  • Operands - any integer, double or boolean (true, false)
  • \r\n
\r\n
\r\n
\r\n

Don't forget to throw exceptions : EmptyStackException if there's not enough operand left on the stack, ArithmeticException when an illegal computation is submitted to your interpreter, IllegalArgumentException when a bad operand is found (for example, a boolean instead of an integer when performing a mathematical operation)

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2605,7 +2609,7 @@ }, { "title": "Threads - Producer/Consumer with locks", - "description": "In this task we will ask you to solve the producer/consumer problem,\r\nrepresented here as a concurrent bounded FIFO queue. We will run\r\nsimultaneously two different types of threads on your queue :\r\n\r\n> - Consumers, consuming (= dequeuing) elements from the queue.\r\n> - Producers, producing (= enqueuing) elements to the queue.\r\n\r\nYour queue needs to be thread-safe : it must be able to operate in a\r\nconcurrent environment. It also means that threads must wait if\r\nnecessary. A producer can't progress if there's no space left in the\r\nqueue. A consumer can't take element from the queue if it is empty. For\r\nthis exercise, you will need to implement `enqueue` and `dequeue`, using\r\nall the instance variables that are in the\r\n[LockQueue](https://inginious.info.ucl.ac.be/course/LEPL1402/ProducerConsumer/LockQueue.java) class\r\nbelow. We strongly suggest you to look at\r\n[await](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Condition.html#await--)\r\nand\r\n[signal](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Condition.html#signal--)\r\n(or `signalAll`) methods. You are not allowed to instantiate new locks\r\nor condition objects.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/ProducerConsumer/LEPL1402_ProducerConsumer.zip)\r\nthat contains few tests to help you.\r\n\r\n``` java\r\nimport java.util.concurrent.locks.Condition;\r\nimport java.util.concurrent.locks.ReentrantLock;\r\n\r\npublic class LockQueue {\r\n\r\n public final static int SIZE = 100;\r\n\r\n private final ReentrantLock lock = new ReentrantLock();\r\n private final Condition notFull = lock.newCondition();\r\n private final Condition notEmpty = lock.newCondition();\r\n\r\n public int head = 0;\r\n public int tail = 0;\r\n public final Integer [] cells = new Integer[SIZE];\r\n public int count = 0;\r\n\r\n\r\n\r\n public Integer dequeue() {\r\n // YOUR CODE HERE\r\n }\r\n\r\n\r\n public void enqueue(Integer i) {\r\n // YOUR CODE HERE\r\n }\r\n\r\n public boolean full(){\r\n return this.count == SIZE;\r\n }\r\n\r\n public boolean empty(){\r\n return this.head == this.tail;\r\n }\r\n\r\n public int size() { return this.tail - this.head; }\r\n\r\n}\r\n```\r\n", + "description": "

In this task we will ask you to solve the producer/consumer problem, represented here as a concurrent bounded FIFO queue. We will run simultaneously two different types of threads on your queue :

\r\n
\r\n
    \r\n
  • Consumers, consuming (= dequeuing) elements from the queue.
  • \r\n
  • Producers, producing (= enqueuing) elements to the queue.
  • \r\n
\r\n
\r\n

Your queue needs to be thread-safe : it must be able to operate in a concurrent environment. It also means that threads must wait if necessary. A producer can't progress if there's no space left in the queue. A consumer can't take element from the queue if it is empty. For this exercise, you will need to implement enqueue and dequeue, using all the instance variables that are in the LockQueue class below. We strongly suggest you to look at await and signal (or signalAll) methods. You are not allowed to instantiate new locks or condition objects.

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n
import java.util.concurrent.locks.Condition;\r\nimport java.util.concurrent.locks.ReentrantLock;\r\n\r\npublic class LockQueue {\r\n\r\n    public final static int SIZE = 100;\r\n\r\n    private final ReentrantLock lock = new ReentrantLock();\r\n    private final Condition notFull = lock.newCondition();\r\n    private final Condition notEmpty = lock.newCondition();\r\n\r\n    public int head = 0;\r\n    public int tail = 0;\r\n    public final Integer [] cells = new Integer[SIZE];\r\n    public int count = 0;\r\n\r\n\r\n\r\n    public Integer dequeue() {\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n\r\n    public void enqueue(Integer i) {\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n    public boolean full(){\r\n        return this.count == SIZE;\r\n    }\r\n\r\n    public boolean empty(){\r\n        return this.head == this.tail;\r\n    }\r\n\r\n    public int size() { return this.tail - this.head; }\r\n\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2664,7 +2668,7 @@ }, { "title": "Queue with two stacks", - "description": "In this short exercise we will ask you to implement a FIFO queue using\r\ntwo stacks (provided as two Java `Stack`). We need you to provide 4\r\nmethods : `enqueue`, `dequeue`, `peek`, `empty`. You can use the `Stack`\r\n[API](https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html) ,\r\nbut you can't instantiate a new `Stack`. Use `s1` and `s2` from the\r\n[MyQueue](https://inginious.info.ucl.ac.be/course/LEPL1402/QueueWithStacks/MyQueue.java) class below.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/QueueWithStacks/LEPL1402_QueueWithStacks.zip)\r\nthat contains few tests to help you.\r\n\r\n``` java\r\nimport java.util.Stack;\r\n\r\npublic class MyQueue {\r\n\r\n Stack s1;\r\n Stack s2;\r\n\r\n private E front;\r\n\r\n /*\r\n * Constructor\r\n */\r\n public MyQueue() {\r\n s1 = new Stack<>();\r\n s2 = new Stack<>();\r\n this.front = null;\r\n }\r\n\r\n /*\r\n * Push element x to the end of the queue (remember, a queue is FIFO)\r\n */\r\n public void enqueue(E elem) {\r\n //TODO\r\n }\r\n\r\n /*\r\n * Removes the front element of this queue\r\n */\r\n public E dequeue() {\r\n //TODO\r\n }\r\n\r\n /*\r\n * Get the first element of this list but does not remove it\r\n */\r\n public E peek() {\r\n //TODO\r\n }\r\n\r\n /*\r\n * Tells if the queue is empty or not.\r\n */\r\n public boolean empty() {\r\n //TODO\r\n }\r\n}\r\n```\r\n", + "description": "

In this short exercise we will ask you to implement a FIFO queue using two stacks (provided as two Java Stack<E>). We need you to provide 4 methods : enqueue, dequeue, peek, empty. You can use the Stack API , but you can't instantiate a new Stack. Use s1 and s2 from the MyQueue class below.

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n
import java.util.Stack;\r\n\r\npublic class MyQueue<E> {\r\n\r\n    Stack<E> s1;\r\n    Stack<E> s2;\r\n\r\n    private E front;\r\n\r\n    /*\r\n    * Constructor\r\n    */\r\n    public MyQueue() {\r\n        s1 = new Stack<>();\r\n        s2 = new Stack<>();\r\n        this.front = null;\r\n    }\r\n\r\n    /*\r\n    * Push element x to the end of the queue (remember, a queue is FIFO)\r\n    */\r\n    public void enqueue(E elem) {\r\n        //TODO\r\n    }\r\n\r\n    /*\r\n    * Removes the front element of this queue\r\n    */\r\n    public E dequeue() {\r\n        //TODO\r\n    }\r\n\r\n    /*\r\n    * Get the first element of this list but does not remove it\r\n    */\r\n    public E peek() {\r\n        //TODO\r\n    }\r\n\r\n    /*\r\n    * Tells if the queue is empty or not.\r\n    */\r\n    public boolean empty() {\r\n        //TODO\r\n    }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2723,7 +2727,7 @@ }, { "title": "Threads - Shared counter with monitors", - "description": "In this task we will ask you to use monitors for a thread-shared\r\ncounter. When threads are executed concurrently and they share some\r\npiece of memory, unexpected/wrong results are very likely to happen. For\r\nexample, if you run four threads on the same counter, each thread\r\nincrementing ten thousands times the counter, you would of course expect\r\nthat the final value of the counter will be fourty thousands when all\r\nfour threads are done... But in practice, if there is no synchronization\r\nmechanism of any kind between threads, you will see that the final value\r\nwill certainly be different from what we expect. Your job for this task\r\nis thus to implement a synchronization mechanism for a counter using\r\nonly java's built-in monitors. We ask you to implement the three\r\nfollowing methods:\r\n\r\n> - void inc() : increment once the counter.\r\n> - void dec() : decrement the counter **if and only if** its current\r\n> value is positive. In fact, the counter we ask you to implement\r\n> must **always** be positive. If a thread wants to decrement the\r\n> counter but its value is 0, it has to wait.\r\n> - int get() : returns the current value of the counter.\r\n\r\nPay attention, you are not allowed to use `Lock` for this mission, only\r\nbuilt-in\r\n[monitors](https://www.artima.com/insidejvm/ed2/threadsynch.html). You\r\nmight also face a [deadlock](https://en.wikipedia.org/wiki/Deadlock)\r\nproblem.\r\n\r\n``` java\r\npublic class SharedCounter {\r\n\r\n private int counter = 0;\r\n\r\n // YOUR CODE HERE\r\n\r\n}\r\n```\r\n", + "description": "

In this task we will ask you to use monitors for a thread-shared counter. When threads are executed concurrently and they share some piece of memory, unexpected/wrong results are very likely to happen. For example, if you run four threads on the same counter, each thread incrementing ten thousands times the counter, you would of course expect that the final value of the counter will be fourty thousands when all four threads are done... But in practice, if there is no synchronization mechanism of any kind between threads, you will see that the final value will certainly be different from what we expect. Your job for this task is thus to implement a synchronization mechanism for a counter using only java's built-in monitors. We ask you to implement the three following methods:

\r\n
\r\n
    \r\n
  • void inc() : increment once the counter.
  • \r\n
  • void dec() : decrement the counter if and only if its current value is positive. In fact, the counter we ask you to implement must always be positive. If a thread wants to decrement the counter but its value is 0, it has to wait.
  • \r\n
  • int get() : returns the current value of the counter.
  • \r\n
\r\n
\r\n

Pay attention, you are not allowed to use Lock for this mission, only built-in monitors. You might also face a deadlock problem.

\r\n
public class SharedCounter {\r\n\r\n    private int counter = 0;\r\n\r\n    // YOUR CODE HERE\r\n\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2782,7 +2786,7 @@ }, { "title": "Sieve of Eratosthenes Implementation", - "description": "In this task you are asked to implement the method\r\n`numberOfPrime(int n)` that returns the number of prime numbers between\r\n0 and *n* using the [Eratosthene\r\nalgorithm](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes). To\r\nimplement this we force you to use a\r\n[BitSet](https://docs.oracle.com/javase/8/docs/api/java/util/BitSet.html),\r\nyou are not allowed to use an array: you must work with the `bits`\r\nvariable.\r\n\r\nThe goal of this exercise is to introduce you to the [java\r\ndocumentation](https://docs.oracle.com/javase/8/docs/api/) and to make\r\nsure that you are able to read, understand and use class that are\r\ndefined and documented in java.\r\n\r\n``` java\r\npublic static BitSet bits; //You should work on this BitSet\r\n\r\npublic static int numberOfPrime(int n){\r\n //TODO By Student\r\n}\r\n```\r\n", + "description": "

In this task you are asked to implement the method numberOfPrime(int n) that returns the number of prime numbers between 0 and n using the Eratosthene algorithm. To implement this we force you to use a BitSet, you are not allowed to use an array: you must work with the bits variable.

\r\n

The goal of this exercise is to introduce you to the java documentation and to make sure that you are able to read, understand and use class that are defined and documented in java.

\r\n
public static BitSet bits; //You should work on this BitSet\r\n\r\npublic static int numberOfPrime(int n){\r\n    //TODO By Student\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2836,7 +2840,7 @@ }, { "title": "MCQ Sieve of Eratosthenes", - "description": "The following mcq will introduce you to the next exercise, we strongly\r\nrecommend you to answer and understand them before starting the exercise\r\nSieve Of Eratosthene implementation.\r\n\r\nThe sieve of Eratosthene is an algorithm that helps you determine how\r\nmany/which of the number are prime numbers in a set of integer from 0 to\r\n*n*.\r\n\r\nTo implement this algorithm we want you to use a\r\n[BitSet](https://docs.oracle.com/javase/8/docs/api/java/util/BitSet.html),\r\nthe idea here is to force you to read and understand the java\r\ndocumentation. Thus, we will ask you questions about the different\r\nmethod you might need in the implementation of the sieve.\r\n\r\nThe difficulty will increase each question and ask you to read the doc a\r\n*bit* more.\r\n", + "description": "

The following mcq will introduce you to the next exercise, we strongly recommend you to answer and understand them before starting the exercise Sieve Of Eratosthene implementation.

\r\n

The sieve of Eratosthene is an algorithm that helps you determine how many/which of the number are prime numbers in a set of integer from 0 to n.

\r\n

To implement this algorithm we want you to use a BitSet, the idea here is to force you to read and understand the java documentation. Thus, we will ask you questions about the different method you might need in the implementation of the sieve.

\r\n

The difficulty will increase each question and ask you to read the doc a bit more.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2885,7 +2889,7 @@ }, { "title": "Stack with a Queue", - "description": "In this short exercise we will ask you to implement a LIFO stack using a\r\nqueue (provided as a Java `LinkedList`). We need you to provide 4\r\nmethods : `push`, `pop`, `peek`, `empty`. You can't use the `LinkedList`\r\nAPI except for the methods listed below:\r\n\r\n- `add`\r\n- `remove`\r\n- `peek`\r\n- `isEmpty`\r\n- `size`\r\n\r\n(You can find the file\r\n[here](https://inginious.info.ucl.ac.be/course/LEPL1402/StackWithQueue/MyStack.java)). The challenge of\r\nthis exercise is to use **only** the queue that is provided as instance\r\nvariable: `queue`. In other words, you **can't** instantiate a new\r\n`LinkedList` anywhere.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/StackWithQueue/LEPL1402_StackWithQueue.zip)\r\nthat contains few tests to help you.\r\n\r\n``` java\r\nimport java.util.LinkedList;\r\n\r\npublic class MyStack {\r\n\r\n private LinkedList queue;\r\n\r\n /*\r\n * Constructor\r\n */\r\n public MyStack() {\r\n this.queue = new LinkedList<>();\r\n }\r\n\r\n /*\r\n * push an element at top (remember, a stack is \"Last In First Out\")\r\n */\r\n public void push(E elem) {\r\n //TODO\r\n }\r\n\r\n /*\r\n * Return the top of the stack AND remove the retrieved element\r\n */\r\n public E pop() {\r\n //TODO\r\n }\r\n\r\n /*\r\n * Return the top element of the stack, without removing it\r\n */\r\n public E peek() {\r\n //TODO\r\n }\r\n\r\n /*\r\n * Tells if the stack is empty or not\r\n */\r\n public boolean empty() {\r\n //TODO\r\n }\r\n```\r\n", + "description": "

In this short exercise we will ask you to implement a LIFO stack using a queue (provided as a Java LinkedList<E>). We need you to provide 4 methods : push, pop, peek, empty. You can't use the LinkedList API except for the methods listed below:

\r\n
    \r\n
  • add
  • \r\n
  • remove
  • \r\n
  • peek
  • \r\n
  • isEmpty
  • \r\n
  • size
  • \r\n
\r\n

(You can find the file here). The challenge of this exercise is to use only the queue that is provided as instance variable: queue. In other words, you can't instantiate a new LinkedList anywhere.

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n
import java.util.LinkedList;\r\n\r\npublic class MyStack<E> {\r\n\r\n    private LinkedList<E> queue;\r\n\r\n    /*\r\n    * Constructor\r\n    */\r\n    public MyStack() {\r\n        this.queue = new LinkedList<>();\r\n    }\r\n\r\n    /*\r\n    * push an element at top (remember, a stack is "Last In First Out")\r\n    */\r\n    public void push(E elem) {\r\n        //TODO\r\n    }\r\n\r\n    /*\r\n    * Return the top of the stack AND remove the retrieved element\r\n    */\r\n    public E pop() {\r\n        //TODO\r\n    }\r\n\r\n    /*\r\n    * Return the top element of the stack, without removing it\r\n    */\r\n    public E peek() {\r\n        //TODO\r\n    }\r\n\r\n    /*\r\n    * Tells if the stack is empty or not\r\n    */\r\n    public boolean empty() {\r\n        //TODO\r\n    }
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2944,7 +2948,7 @@ }, { "title": "Dealing with Streams", - "description": "Given the [Student](https://inginious.info.ucl.ac.be/course/LEPL1402/Streams/Student.java) class, You\r\nare asked to write the implementation of the\r\n[StudentFunctions](https://inginious.info.ucl.ac.be/course/LEPL1402/Streams/StudentFunctions.java) class\r\n( that implements the\r\n[StudentStreamFunction](https://inginious.info.ucl.ac.be/course/LEPL1402/Streams/StudentStreamFunction.java)\r\ninterface ) :\r\n\r\n``` java\r\nimport java.util.stream.Stream;\r\n\r\npublic interface StudentStreamFunction {\r\n\r\n // Find the N°2 and N°3 top students for the given course name in parameter\r\n public Stream findSecondAndThirdTopStudentForGivenCourse(\r\n Stream studentStream, String name);\r\n\r\n // Compute for each student in the given section their average grade result,\r\n // sorted by their result (ascending) as an array of array structured like that :\r\n // [ [\"Student FirstName1 LastName1\", 7.5], [\"Student FirstName2 LastName2\", 9.5] ]\r\n public Object[] computeAverageForStudentInSection(Stream studentStream,\r\n int section);\r\n\r\n // Give the number of students that success in all courses (> 10.0)\r\n public int getNumberOfSuccessfulStudents(Stream studentStream);\r\n\r\n // Find the student that is the last one in the lexicographic order\r\n // ( You must first compare students on their lastNames then on their firstNames )\r\n public Student findLastInLexicographicOrder(Stream studentStream);\r\n\r\n\r\n // Give the full sum of the grade obtained by all students\r\n public double getFullSum(Stream studentStream);\r\n\r\n}\r\n```\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/Streams/LEPL1402_Streams.zip) that contains\r\nfew tests to help you.\r\n", + "description": "

Given the Student class, You are asked to write the implementation of the StudentFunctions class ( that implements the StudentStreamFunction interface ) :

\r\n
import java.util.stream.Stream;\r\n\r\npublic interface StudentStreamFunction {\r\n\r\n   // Find the N°2 and N°3 top students for the given course name in parameter\r\n   public Stream<Student> findSecondAndThirdTopStudentForGivenCourse(\r\n       Stream<Student> studentStream, String name);\r\n\r\n   // Compute for each student in the given section their average grade result,\r\n   // sorted by their result (ascending) as an array of array structured like that :\r\n   // [ ["Student FirstName1 LastName1", 7.5], ["Student FirstName2 LastName2", 9.5] ]\r\n   public Object[] computeAverageForStudentInSection(Stream<Student> studentStream,\r\n                                                       int section);\r\n\r\n   // Give the number of students that success in all courses (> 10.0)\r\n   public int getNumberOfSuccessfulStudents(Stream<Student> studentStream);\r\n\r\n   // Find the student that is the last one in the lexicographic order\r\n   // ( You must first compare students on their lastNames then on their firstNames )\r\n   public Student findLastInLexicographicOrder(Stream<Student> studentStream);\r\n\r\n\r\n   // Give the full sum of the grade obtained by all students\r\n   public double getFullSum(Stream<Student> studentStream);\r\n\r\n}
\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3003,7 +3007,7 @@ }, { "title": "Dealing with Streams - 2", - "description": "In order to understand why the Stream class could be useful for\r\ngenericity, we purpose you this small exercise that merged casting and\r\nstreams.\r\n\r\nGiven the [Student](https://inginious.info.ucl.ac.be/course/LEPL1402/Streams2/Student.java) class, You\r\nare asked to write the implementation of the\r\n[StudentFunctions](https://inginious.info.ucl.ac.be/course/LEPL1402/Streams/StudentFunctions.java) class\r\n( that implements the\r\n[StudentStreamFunction](https://inginious.info.ucl.ac.be/course/LEPL1402/Streams2/StudentStreamFunction.java)\r\ninterface ) :\r\n\r\n``` java\r\nimport java.util.Map;\r\nimport java.util.function.Predicate;\r\nimport java.util.stream.Stream;\r\nimport java.util.Comparator;\r\n\r\npublic interface StudentStreamFunction {\r\n\r\n// In order to test efficiently your code, we use a Map>\r\n// structured like that :\r\n// Key : String that is one of the fields of Student\r\n// ( \"firstName\", \"lastName\", \"section\", \"courses_results\")\r\n// Value : Predicate bounded to the type of the field to perform a check condition\r\n//\r\n// For example :\r\n// Key: \"firstName\"\r\n// Value: Predicate\r\n\r\n\r\n// Returns a student if any match the given conditions\r\n// if it is not possible, you must return null\r\npublic Student findFirst(Stream studentsStream,\r\n Map> conditions);\r\n\r\n// Returns a array of student(s) that match the given conditions\r\npublic Student[] findAll(Stream studentsStream,\r\n Map> conditions);\r\n\r\n// Return true if we could find n student(s) that match the given condition\r\npublic boolean exists(Stream studentsStream,\r\n Map> conditions,\r\n int n);\r\n\r\n// Returns a ordered array of student(s) that match the given conditions,\r\n// depending of the given comparator\r\npublic Student[] filterThenSort(Stream studentsStream,\r\n Map> conditions,\r\n Comparator comparator);\r\n\r\n}\r\n```\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/Streams2/LEPL1402_Streams2.zip) that contains\r\nfew tests to help you.\r\n", + "description": "

In order to understand why the Stream class could be useful for genericity, we purpose you this small exercise that merged casting and streams.

\r\n

Given the Student class, You are asked to write the implementation of the StudentFunctions class ( that implements the StudentStreamFunction interface ) :

\r\n
import java.util.Map;\r\nimport java.util.function.Predicate;\r\nimport java.util.stream.Stream;\r\nimport java.util.Comparator;\r\n\r\npublic interface StudentStreamFunction {\r\n\r\n// In order to test efficiently your code, we use a Map<String, Predicate<?>>\r\n// structured like that :\r\n//    Key : String that is one of the fields of Student\r\n//          ( "firstName", "lastName", "section", "courses_results")\r\n//    Value : Predicate bounded to the type of the field to perform a check condition\r\n//\r\n// For example :\r\n//    Key:   "firstName"\r\n//  Value:   Predicate<String>\r\n\r\n\r\n// Returns a student if any match the given conditions\r\n// if it is not possible, you must return null\r\npublic Student findFirst(Stream<Student> studentsStream,\r\n                         Map<String, Predicate<?>> conditions);\r\n\r\n// Returns a array of student(s) that match the given conditions\r\npublic Student[] findAll(Stream<Student> studentsStream,\r\n                         Map<String, Predicate<?>> conditions);\r\n\r\n// Return true if we could find n student(s) that match the given condition\r\npublic boolean exists(Stream<Student> studentsStream,\r\n                      Map<String, Predicate<?>> conditions,\r\n                      int n);\r\n\r\n// Returns a ordered array of student(s) that match the given conditions,\r\n// depending of the given comparator\r\npublic Student[] filterThenSort(Stream<Student> studentsStream,\r\n                                Map<String, Predicate<?>> conditions,\r\n                                Comparator<Student> comparator);\r\n\r\n}
\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3062,7 +3066,7 @@ }, { "title": "Strings", - "description": "In this task, we ask you to implement several common methods inspired\r\nfrom java's\r\n[String](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#subSequence-int-int-)\r\nAPI. The objective of this task is to get you used to String\r\nmanipulation in java. In order to succeed this task, you will have to\r\nimplement four different methods from a class we called `StringUtils` :\r\n\r\n- `split(String str, char marker)` : separate a String into fragments\r\n each time a specific character `marker` is encountered. Note that,\r\n for simplicity, marker is a `char` whereas in java's\r\n [String](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#subSequence-int-int-)\r\n it is a `String`. For example, calling your method with \"Here. I.\r\n Go.\" with marker '.' should return an array of size three with\r\n \"Here\", \"I\" and \"Go\" in its cells.\r\n- `indexOf(String str, String sub)` : returns the index of the first\r\n occurrence of the `String` sub in the `String` str. For example\r\n `indexOf(\"Hello\", \"ell\")` should return 1, `indexOf(\"Hello\", \"o\")`\r\n should return 4. If there is no occurrence of sub in str, return -1.\r\n- `toLowerCase(String str)` : returns a String with the same\r\n characters as 'str' except that all upper case characters have been\r\n replaced by their lower case equivalent.\r\n- `palindrome(String str)` : Returns true if the string 'str' is a\r\n palindrome : a string that reads the same from left to right AND\r\n from right to left (for example, \"kayak\"). Note that this method\r\n does not exist in java's\r\n [String](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#subSequence-int-int-)\r\n API because it's not very useful. But it is still a good exercise to\r\n train yourself to manipulate String objects in java.\r\n\r\nHere is the skeleton of the `StringUtils` (downloadable\r\n[here](https://inginious.info.ucl.ac.be/course/LEPL1402/StringUtils/StringUtils.java)):\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/StringUtils/LEPL1402_StringUtils.zip) that\r\ncontains few tests to help you.\r\n\r\n``` java\r\npublic class StringUtils {\r\n\r\n\r\n /*\r\n * Split the input string 'str' w.r.t the character 'marker' in an array of String\r\n * for example split(\"test-test\", '-') => {\"test\", \"test\"}\r\n * Must return null if there is no occurrence of 'marker' in 'str'\r\n */\r\n public static String [] split(String str, char marker){\r\n // YOUR CODE HERE\r\n }\r\n\r\n\r\n /*\r\n * Returns the index of the first occurrence of sub in str\r\n * or -1 if there is no occurrence of sub in str at all.\r\n * Be careful, we ask you to make CASE SENSITIVE comparison between str and sub.\r\n */\r\n public static int indexOf(String str, String sub){\r\n // YOUR CODE HERE\r\n }\r\n\r\n /*\r\n * Returns a String with the same characters as 'str' except that\r\n * all upper case characters have been replaced by their lower case equivalent.\r\n */\r\n public static String toLowerCase(String str){\r\n // YOUR CODE HERE\r\n }\r\n\r\n\r\n /*\r\n * Returns true if the string 'str' is a palindrome (a string that reads the same from\r\n * left to right AND from right to left).\r\n */\r\n public static boolean palindrome(String str){\r\n // YOUR CODE HERE\r\n }\r\n\r\n\r\n}\r\n```\r\n", + "description": "

In this task, we ask you to implement several common methods inspired from java's String API. The objective of this task is to get you used to String manipulation in java. In order to succeed this task, you will have to implement four different methods from a class we called StringUtils :

\r\n
    \r\n
  • split(String str, char marker) : separate a String into fragments each time a specific character marker is encountered. Note that, for simplicity, marker is a char whereas in java's String it is a String. For example, calling your method with \"Here. I. Go.\" with marker '.' should return an array of size three with \"Here\", \"I\" and \"Go\" in its cells.
  • \r\n
  • indexOf(String str, String sub) : returns the index of the first occurrence of the String sub in the String str. For example indexOf(\"Hello\", \"ell\") should return 1, indexOf(\"Hello\", \"o\") should return 4. If there is no occurrence of sub in str, return -1.
  • \r\n
  • toLowerCase(String str) : returns a String with the same characters as 'str' except that all upper case characters have been replaced by their lower case equivalent.
  • \r\n
  • palindrome(String str) : Returns true if the string 'str' is a palindrome : a string that reads the same from left to right AND from right to left (for example, \"kayak\"). Note that this method does not exist in java's String API because it's not very useful. But it is still a good exercise to train yourself to manipulate String objects in java.
  • \r\n
\r\n

Here is the skeleton of the StringUtils (downloadable here):

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n
public class StringUtils {\r\n\r\n\r\n    /*\r\n    * Split the input string 'str' w.r.t the character 'marker' in an array of String\r\n    * for example split("test-test", '-') => {"test", "test"}\r\n    * Must return null if there is no occurrence of 'marker' in 'str'\r\n    */\r\n    public static String [] split(String str, char marker){\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n\r\n    /*\r\n    * Returns the index of the first occurrence of sub in str\r\n    * or -1 if there is no occurrence of sub in str at all.\r\n    * Be careful, we ask you to make CASE SENSITIVE comparison between str and sub.\r\n    */\r\n    public static int indexOf(String str, String sub){\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n    /*\r\n    * Returns a String with the same characters as 'str' except that\r\n    * all upper case characters have been replaced by their lower case equivalent.\r\n    */\r\n    public static String toLowerCase(String str){\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n\r\n    /*\r\n    * Returns true if the string 'str' is a palindrome (a string that reads the same from\r\n    * left to right AND from right to left).\r\n    */\r\n    public static boolean palindrome(String str){\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -3121,7 +3125,7 @@ }, { "title": "Small introduction to threads - Counters", - "description": "In this task, we will ask you to implement the `init` method of this\r\n[Launcher](https://inginious.info.ucl.ac.be/course/LEPL1402/ThreadsIntroduction/Launcher.java) class :\r\n\r\n``` java\r\npublic class Launcher {\r\n\r\n /*\r\n * Instantiate and start each thread from \"t\" with its OWN Counter object,\r\n * then wait for all threads to finish and return the set of Counter objects\r\n * the threads ran on. Each thread must be named according to its index in the\r\n * \"t\" array.\r\n */\r\n public static Counter[] init(Thread [] t) {\r\n // YOUR CODE HERE\r\n }\r\n\r\n}\r\n```\r\n\r\nIn Java, a thread needs an entry point to know where to start when we\r\nwant it to run : this entry point can be any object implementing the\r\n[Runnable](https://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html)\r\ninterface. For this exercise, we give you a small implementation of the\r\n[Runnable](https://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html)\r\ninterface :\r\n[Counter](https://inginious.info.ucl.ac.be/course/LEPL1402/ThreadsIntroduction/Counter.java), a small\r\nclass increasing an int variable `rnd` times.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/ThreadsIntroduction/LEPL1402_ThreadsIntroduction.zip)\r\nthat contains few tests to help you.\r\n\r\n``` java\r\npublic class Counter implements Runnable {\r\n\r\n private int count;\r\n private int rnd;\r\n\r\n public int getCount() {\r\n return count;\r\n }\r\n\r\n public int getRnd(){\r\n return rnd;\r\n }\r\n\r\n public Counter(){\r\n this.count = 0;\r\n this.rnd = (int) ( (Math.random()*100) + 1000);\r\n }\r\n\r\n @Override\r\n public void run() {\r\n for(int i=0; i< getRnd(); i++){\r\n count += 1;\r\n }\r\n }\r\n\r\n}\r\n```\r\n", + "description": "

In this task, we will ask you to implement the init method of this Launcher class :

\r\n
public class Launcher {\r\n\r\n    /*\r\n     * Instantiate and start each thread from "t" with its OWN Counter object,\r\n     * then wait for all threads to finish and return the set of Counter objects\r\n     * the threads ran on. Each thread must be named according to its index in the\r\n     * "t" array.\r\n     */\r\n    public static Counter[] init(Thread [] t) {\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n}
\r\n

In Java, a thread needs an entry point to know where to start when we want it to run : this entry point can be any object implementing the Runnable interface. For this exercise, we give you a small implementation of the Runnable interface : Counter, a small class increasing an int variable rnd times.

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n
public class Counter implements Runnable {\r\n\r\n    private int count;\r\n    private int rnd;\r\n\r\n    public int getCount() {\r\n        return count;\r\n    }\r\n\r\n    public int getRnd(){\r\n        return rnd;\r\n    }\r\n\r\n    public Counter(){\r\n        this.count = 0;\r\n        this.rnd = (int) ( (Math.random()*100) + 1000);\r\n    }\r\n\r\n    @Override\r\n    public void run() {\r\n        for(int i=0; i< getRnd(); i++){\r\n            count += 1;\r\n        }\r\n    }\r\n\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -3180,7 +3184,7 @@ }, { "title": "Binary trees - combineWith", - "description": "Write a method combineWith that could be added to the\r\n[Tree](https://inginious.info.ucl.ac.be/course/LEPL1402/TreeCombineWith/Tree.java) class (Node class can\r\nbe found [here](https://inginious.info.ucl.ac.be/course/LEPL1402/TreeCombineWith/Node.java)).\r\n\r\nThe method accepts another binary tree of integers as a parameter and\r\ncombines the two trees into a new third tree which is returned. The new\r\ntree's structure should be a union of the structures of the two original\r\ntrees.\r\n\r\nIt should have a node in any location where there was a node in either\r\nof the original trees (or both).\r\n\r\nThe nodes of the new tree should store an integer indicating the sum of\r\nthe values at that position of the original trees if possible. (else\r\nonly the value of the not null node)\r\n\r\nFor example, suppose Tree variables t1 and t2 have been initialized and\r\nstore the following trees:\r\n\r\n
\r\n\"\"\r\n
\r\n\r\nThen the following call:\r\n\r\n``` java\r\nTree t3 = t1.combineWith(t2);\r\n```\r\n\r\nWill return a reference to the following tree:\r\n\r\n
\r\n\"\"\r\n
\r\n\r\nYou may define private helper methods to solve this problem but in any\r\ncase, your method should not change the structure or contents of either\r\nof the two trees being compared.\r\n\r\n(This exercise was partialy inspired by this\r\n[source](https://practiceit.cs.washington.edu/problem/view/cs2/exams/finals/final4/combineWith))\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/TreeCombineWith/LEPL1402_TreeCombineWith.zip)\r\nthat contains few tests to help you.\r\n", + "description": "

Write a method combineWith that could be added to the Tree class (Node class can be found here).

\r\n

The method accepts another binary tree of integers as a parameter and combines the two trees into a new third tree which is returned. The new tree's structure should be a union of the structures of the two original trees.

\r\n

It should have a node in any location where there was a node in either of the original trees (or both).

\r\n

The nodes of the new tree should store an integer indicating the sum of the values at that position of the original trees if possible. (else only the value of the not null node)

\r\n

For example, suppose Tree variables t1 and t2 have been initialized and store the following trees:

\r\n
\r\n\"\"\r\n
\r\n

Then the following call:

\r\n
Tree t3 = t1.combineWith(t2);
\r\n

Will return a reference to the following tree:

\r\n
\r\n\"\"\r\n
\r\n

You may define private helper methods to solve this problem but in any case, your method should not change the structure or contents of either of the two trees being compared.

\r\n

(This exercise was partialy inspired by this source)

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3239,7 +3243,7 @@ }, { "title": "Binary trees - Inorder traversal", - "description": "In this task, we ask you to implement two different version of an\r\n\"in-order\" tree traversal : a recursive version and an iterative\r\nversion. Both function will take a `Node` representing the root of the\r\ntree itself and a `List` that you have to fill with the tree\r\nnodes' `val` respecting the \"in-order\" traversal.\r\n\r\n**Example**: the following tree, when explored in an in-order fashion,\r\nwill give `A,B,C,D,E,F,G,H,I`. This type of tree traversal is thus very\r\nuseful to retrieve all nodes from a tree as an ordered list, provided\r\nthat the tree itself is \"sorted\", i.e, for each node, its left subtree\r\nonly contain \"smaller\" nodes and its right subtree only contain\r\n\"greater\" nodes (which is the case in the example, considering the\r\nalphabetical order).\r\n\r\n\"image\"\r\n\r\nHere are the skeleton of the\r\n[Node](https://inginious.info.ucl.ac.be/course/LEPL1402/TreeInorder/Node.java) and\r\n[Traversal](https://inginious.info.ucl.ac.be/course/LEPL1402/TreeInorder/Traversal.java) classes:\r\n\r\n``` java\r\npublic class Node {\r\n\r\n public int val;\r\n\r\n public Node left;\r\n public Node right;\r\n\r\n public Node(int val){\r\n this.val = val;\r\n }\r\n\r\n public boolean isLeaf(){\r\n return this.left == null && this.right == null;\r\n }\r\n}\r\n\r\n\r\nimport java.util.List;\r\nimport java.util.Stack; // this should give you a hint for the iterative version\r\n\r\npublic class Traversal {\r\n\r\n public static void recursiveInorder(Node root, List res) {\r\n // YOUR CODE HERE\r\n }\r\n\r\n\r\n public static void iterativeInorder(Node root, List res){\r\n // YOUR CODE HERE\r\n }\r\n\r\n}\r\n```\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/TreeInorder/LEPL1402_TreeInorder.zip) that\r\ncontains few tests to help you.\r\n", + "description": "

In this task, we ask you to implement two different version of an \"in-order\" tree traversal : a recursive version and an iterative version. Both function will take a Node representing the root of the tree itself and a List<Integer> that you have to fill with the tree nodes' val respecting the \"in-order\" traversal.

\r\n

Example: the following tree, when explored in an in-order fashion, will give A,B,C,D,E,F,G,H,I. This type of tree traversal is thus very useful to retrieve all nodes from a tree as an ordered list, provided that the tree itself is \"sorted\", i.e, for each node, its left subtree only contain \"smaller\" nodes and its right subtree only contain \"greater\" nodes (which is the case in the example, considering the alphabetical order).

\r\n

\"image\"

\r\n

Here are the skeleton of the Node and Traversal classes:

\r\n
public class Node {\r\n\r\n    public int val;\r\n\r\n    public Node left;\r\n    public Node right;\r\n\r\n    public Node(int val){\r\n        this.val = val;\r\n    }\r\n\r\n    public boolean isLeaf(){\r\n        return this.left == null && this.right == null;\r\n    }\r\n}\r\n\r\n\r\nimport java.util.List;\r\nimport java.util.Stack; // this should give you a hint for the iterative version\r\n\r\npublic class Traversal {\r\n\r\n    public static void recursiveInorder(Node root, List<Integer> res) {\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n\r\n    public static void iterativeInorder(Node root, List<Integer> res){\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n}
\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3298,7 +3302,7 @@ }, { "title": "Binary trees - equals", - "description": "In this task, we will ask you to implement the mehtod `equals(Object o)`\r\nfor both classes [Tree](https://inginious.info.ucl.ac.be/course/LEPL1402/TreeSame/Tree.java) and\r\n[Node](https://inginious.info.ucl.ac.be/course/LEPL1402/TreeSame/Node.java). Two instances of `Tree` are\r\nconsidered equal when they both have the exact same structure (same\r\nnumber of nodes, each node at the same place in **both** trees) and when\r\nevery node has the same `val`. Here are the skeleton of both classes:\r\n\r\n``` java\r\npublic class Node {\r\n\r\n public int val;\r\n public Node left;\r\n public Node right;\r\n\r\n public Node(int val){\r\n this.val = val;\r\n }\r\n\r\n public boolean isLeaf(){\r\n return this.left == null && this.right == null;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object o){\r\n // YOUR CODE HERE\r\n }\r\n}\r\n\r\npublic class Tree {\r\n\r\n public Node root;\r\n\r\n public Tree(Node root){\r\n this.root = root;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object o){\r\n // YOUR CODE HERE\r\n }\r\n\r\n}\r\n```\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/TreeSame/LEPL1402_TreeSame.zip) that contains\r\nfew tests to help you.\r\n", + "description": "

In this task, we will ask you to implement the mehtod equals(Object o) for both classes Tree and Node. Two instances of Tree are considered equal when they both have the exact same structure (same number of nodes, each node at the same place in both trees) and when every node has the same val. Here are the skeleton of both classes:

\r\n
public class Node {\r\n\r\n    public int val;\r\n    public Node left;\r\n    public Node right;\r\n\r\n    public Node(int val){\r\n        this.val = val;\r\n    }\r\n\r\n    public boolean isLeaf(){\r\n        return this.left == null && this.right == null;\r\n    }\r\n\r\n    @Override\r\n    public boolean equals(Object o){\r\n        // YOUR CODE HERE\r\n    }\r\n}\r\n\r\npublic class Tree {\r\n\r\n    public Node root;\r\n\r\n    public Tree(Node root){\r\n        this.root = root;\r\n    }\r\n\r\n    @Override\r\n    public boolean equals(Object o){\r\n        // YOUR CODE HERE\r\n    }\r\n\r\n}
\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3357,7 +3361,7 @@ }, { "title": "Longest Valley", - "description": "A geologist is trying to find the deepest valley and the biggest\r\nmountain between 2 locations and he thinks you can help him! He'll give\r\nyou an array of integer like this one:\r\n\r\n\"image\"\r\n\r\nThe negative values mean the slope is negative and the positive ones\r\nmean it's positive. Thus previous array looks like this:\r\n\r\n\"image\"\r\n\r\nYour method will return an array containing the depth of the deepest\r\nvalley at index 0 and the biggest mountain at index 1. In this example,\r\nthe depth is 5 and the summit is at 3.\r\n\r\nWe can define a valley by saying it is sequence of negative number\r\nfollowed by a sequence of positive number with the same amount of\r\nnumbers. The depth is the length of the sequence.\r\n\r\nHere is the mathematical definition:\r\n\r\nGiven *A* an Array of integer ∀*i*, 0 ≤ *i* < |*A*|,*A*\\[*i*\\] ≠ 0,\r\nGiven *v* the length of the longest valley, ∃!*i*, *j* with\r\n0 ≤ *i* < *j* ≤ |*A*| so that ∀*m* , *i* ≤ *m* < (*j* − *i*)/2 ,\r\n*A*\\[*m*\\] < 0 and ∀*n* , (*j* − *i*)/2 < *m* ≤ *j* ,\r\n*A*\\[*n*\\] > 0 , *j* − *i* > *v* \\* 2\r\n\r\nWe can define a mountain by saying it is sequence of positive number\r\nfollowed by a sequence of negative number with the same amount of\r\nnumbers. The height is the length of the sequence.\r\n\r\nHere is the mathematical definition:\r\n\r\nGiven *A* an Array of integer ∀*i*, 0 ≤ *i* < |*A*|,*A*\\[*i*\\] ≠ 0,\r\nGiven *v* the length of the longest valley, ∃!*i*, *j* with\r\n0 ≤ *i* < *j* ≤ |*A*| so that ∀*m* , *i* ≤ *m* < (*j* − *i*)/2 ,\r\n*A*\\[*m*\\] > 0 and ∀*n* , (*j* − *i*)/2 < *m* ≤ *j* ,\r\n*A*\\[*n*\\] < 0 , *j* − *i* > *v* \\* 2\r\n\r\nConsider that the array is never gonna be empty and your method should\r\nhave a theta(n) complexity Here is the class you have to fill:\r\n\r\n``` java\r\npublic class Valley{\r\n /*\r\n * Example:\r\n * [1, 1, 1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, -1, -1]\r\n * Should return\r\n * [5, 3]\r\n */\r\n\r\n public static int[] valley ( int[] array){\r\n //TODO By Student\r\n\r\n }\r\n}\r\n```\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/valley/LEPL1402_valley.zip) that contains few\r\ntests to help you.\r\n", + "description": "

A geologist is trying to find the deepest valley and the biggest mountain between 2 locations and he thinks you can help him! He'll give you an array of integer like this one:

\r\n

\"image\"

\r\n

The negative values mean the slope is negative and the positive ones mean it's positive. Thus previous array looks like this:

\r\n

\"image\"

\r\n

Your method will return an array containing the depth of the deepest valley at index 0 and the biggest mountain at index 1. In this example, the depth is 5 and the summit is at 3.

\r\n

We can define a valley by saying it is sequence of negative number followed by a sequence of positive number with the same amount of numbers. The depth is the length of the sequence.

\r\n

Here is the mathematical definition:

\r\n

Given A an Array of integer i, 0 ≤ i < |A|,A[i] ≠ 0, Given v the length of the longest valley, ∃!i, j with 0 ≤ i < j ≤ |A| so that m , i ≤ m < (j − i)/2 , A[m] < 0 and n , (j − i)/2 < m ≤ j , A[n] > 0 , j − i > v * 2

\r\n

We can define a mountain by saying it is sequence of positive number followed by a sequence of negative number with the same amount of numbers. The height is the length of the sequence.

\r\n

Here is the mathematical definition:

\r\n

Given A an Array of integer i, 0 ≤ i < |A|,A[i] ≠ 0, Given v the length of the longest valley, ∃!i, j with 0 ≤ i < j ≤ |A| so that m , i ≤ m < (j − i)/2 , A[m] > 0 and n , (j − i)/2 < m ≤ j , A[n] < 0 , j − i > v * 2

\r\n

Consider that the array is never gonna be empty and your method should have a theta(n) complexity Here is the class you have to fill:

\r\n
public class Valley{\r\n    /*\r\n     * Example:\r\n     * [1, 1, 1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, -1, -1]\r\n     * Should return\r\n     * [5, 3]\r\n     */\r\n\r\n     public static int[] valley ( int[] array){\r\n     //TODO By Student\r\n\r\n    }\r\n}
\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3416,7 +3420,7 @@ }, { "title": "Value Or Reference", - "description": "Try to answer the following question without actually testing the shown\r\ncode on your computer.\r\n", + "description": "

Try to answer the following question without actually testing the shown code on your computer.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3470,7 +3474,7 @@ }, { "title": "Visitor design pattern - Calculator", - "description": "In this task, we will ask you to implement a basic calculator (+,-,\\*,/)\r\nusing the visitor design pattern. Every expression you will compute will\r\nbe represented as a tree. A tree contains at least one node and every\r\nnode of the tree is either :\r\n\r\n- a parent node containing two sub nodes (an operand)\r\n- a leaf (a value)\r\n\r\nHere is an example of how your code is supposed to run:\r\n\r\n``` java\r\nNode root = new Add( //((6-2)/(1+1))+(5*2)\r\n new Div( //(6-2)/(1+1)\r\n new Sub(new Leaf(6),new Leaf(2)) //6-2\r\n new Add(new Leaf(1), new Leaf(1))), //1+1\r\n new Mult(new Leaf(5), new Leaf(2))); //5*2\r\nVisitor calculator = new Evaluation();\r\n\r\ncalculator.visit((Add)root); // 12\r\n```\r\n\r\n**We provide you a set of class you have to complete**\r\n[here](https://inginious.info.ucl.ac.be/course/LEPL1402/Visitor/source.zip)\r\n\r\nThere are a lot of classes but please don't panick, this exercise\r\nshouldn't require more than 50ish lines of code from you.\r\n\r\nA special case needs you to throw an `IllegalArgumentException`.\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/Visitor/LEPL1402_Visitor.zip) that contains\r\nfew tests to help you.\r\n", + "description": "

In this task, we will ask you to implement a basic calculator (+,-,*,/) using the visitor design pattern. Every expression you will compute will be represented as a tree. A tree contains at least one node and every node of the tree is either :

\r\n
    \r\n
  • a parent node containing two sub nodes (an operand)
  • \r\n
  • a leaf (a value)
  • \r\n
\r\n

Here is an example of how your code is supposed to run:

\r\n
Node root = new Add(                                            //((6-2)/(1+1))+(5*2)\r\n                    new Div(                                   //(6-2)/(1+1)\r\n                        new Sub(new Leaf(6),new Leaf(2))         //6-2\r\n                        new Add(new Leaf(1), new Leaf(1))),      //1+1\r\n                    new Mult(new Leaf(5), new Leaf(2)));         //5*2\r\nVisitor calculator = new Evaluation();\r\n\r\ncalculator.visit((Add)root); // 12
\r\n

We provide you a set of class you have to complete here

\r\n

There are a lot of classes but please don't panick, this exercise shouldn't require more than 50ish lines of code from you.

\r\n

A special case needs you to throw an IllegalArgumentException.

\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3529,7 +3533,7 @@ }, { "title": "Visitor design pattern - List Filtering", - "description": "In this task, we will ask you to implement a list filtering using the\r\nvisitor design pattern. More precisely, your visitor will need to\r\ntraverse a list full of objects of different kind. At the end of its\r\ntraversal, your observer should have a filtered list containing only\r\n`Integer` elements from the original list. To succeed this task, you'll\r\nhave to give us the implementation of these two classes :\r\n\r\n``` java\r\npublic class VisitorList extends Visitor {\r\n // YOUR CODE HERE\r\n}\r\n\r\npublic class VisitableList extends Visitable {\r\n // YOUR CODE HERE\r\n}\r\n```\r\n\r\nThese two classes must extends\r\n[Visitable](https://inginious.info.ucl.ac.be/course/LEPL1402/VisitorBasic/Visitable.java) and\r\n[Visitor](https://inginious.info.ucl.ac.be/course/LEPL1402/VisitorBasic/Visitor.java). These are\r\nabstract classes, pay attention to implement all abstract methods these\r\nclasses contain.\r\n\r\nHere is an example of how your code is supposed to run:\r\n\r\n``` java\r\nVisitor visitor = new VisitorList(Integer.class);\r\nVisitable visitable = new VisitableList(new Object[]{1, 2, 3, 3.1, 4, \"HELLO\"});\r\n\r\nvisitor.visit(visitable);\r\n\r\nList lst = visitor.getFiltered(); // [1, 2, 3, 4]\r\n```\r\n\r\nYou can download the [IntelliJ\r\nProject](https://inginious.info.ucl.ac.be/course/LEPL1402/VisitorBasic/LEPL1402_VisitorBasic.zip) that\r\ncontains few tests to help you.\r\n", + "description": "

In this task, we will ask you to implement a list filtering using the visitor design pattern. More precisely, your visitor will need to traverse a list full of objects of different kind. At the end of its traversal, your observer should have a filtered list containing only Integer elements from the original list. To succeed this task, you'll have to give us the implementation of these two classes :

\r\n
public class VisitorList extends Visitor {\r\n    // YOUR CODE HERE\r\n}\r\n\r\npublic class VisitableList extends Visitable {\r\n    // YOUR CODE HERE\r\n}
\r\n

These two classes must extends Visitable and Visitor. These are abstract classes, pay attention to implement all abstract methods these classes contain.

\r\n

Here is an example of how your code is supposed to run:

\r\n
Visitor visitor = new VisitorList(Integer.class);\r\nVisitable visitable = new VisitableList(new Object[]{1, 2, 3, 3.1, 4, "HELLO"});\r\n\r\nvisitor.visit(visitable);\r\n\r\nList<Object> lst = visitor.getFiltered(); // [1, 2, 3, 4]
\r\n

You can download the IntelliJ Project that contains few tests to help you.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3592,6 +3596,6 @@ "1": "Misconception", "2": "autres" }, - "extraction_date": "2019-12-18T16:15:33.173Z", + "extraction_date": "2020-03-04T17:49:41.436Z", "url": "https://github.com/UCL-INGI/LEPL1402" } \ No newline at end of file diff --git a/results/results3.json b/results/results3.json index 34a0fdc..9fd7b9a 100644 --- a/results/results3.json +++ b/results/results3.json @@ -488,7 +488,7 @@ }, { "title": "Question supplémentaire : Ordonne", - "description": "`a`, `b` et `c` sont des variables contenant un entier. Ecrivez le code\r\npermettant de placer la valeur `true` dans la variabe booléenne\r\n`ordonne` si `a < b < c` et `false` sinon.\r\n\r\n``` java\r\nboolean ordonne; // la variable à changer (true/false)\r\nint a;\r\nint b;\r\nint c;\r\n```\r\n", + "description": "

a, b et c sont des variables contenant un entier. Ecrivez le code permettant de placer la valeur true dans la variabe booléenne ordonne si a < b < c et false sinon.

\r\n
boolean ordonne; // la variable à changer (true/false)\r\nint a;\r\nint b;\r\nint c;
\r\n", "tags": [ { "text": "INGINIOUS", @@ -547,7 +547,7 @@ }, { "title": "Question supplémentaire : Moyenne", - "description": "Les variables `a`, `b` et `c` contiennent des nombres réels. Placez dans\r\nla variable `moyenne` la moyenne arithmétique entre ces trois nombres.\r\nSi vous avez un doute sur la définition de cette moyenne, consultez [sa\r\npage sur\r\nwikipédia](https://fr.wikipedia.org/wiki/Moyenne_arithm%C3%A9tique)\r\n\r\n``` java\r\ndouble moyenne; // le résultat de la moyenne\r\ndouble a;\r\ndouble b;\r\ndouble c;\r\n```\r\n", + "description": "

Les variables a, b et c contiennent des nombres réels. Placez dans la variable moyenne la moyenne arithmétique entre ces trois nombres. Si vous avez un doute sur la définition de cette moyenne, consultez sa page sur wikipédia

\r\n
double moyenne; // le résultat de la moyenne\r\ndouble a;\r\ndouble b;\r\ndouble c;
\r\n", "tags": [ { "text": "INGINIOUS", @@ -606,7 +606,7 @@ }, { "title": "Question supplémentaire : Maximum", - "description": "Les variables `a`, `b` et `c` contiennent un entier. Ecrivez le code\r\nJava permettant de stocker dans la variable `maximum` le plus grand de\r\nces trois nombres.\r\n\r\n``` java\r\nint a;\r\nint b;\r\nint c;\r\nint maximum; // le plus grand parmi a, b, c\r\n```\r\n", + "description": "

Les variables a, b et c contiennent un entier. Ecrivez le code Java permettant de stocker dans la variable maximum le plus grand de ces trois nombres.

\r\n
int a;\r\nint b;\r\nint c;\r\nint maximum; // le plus grand parmi a, b, c
\r\n", "tags": [ { "text": "INGINIOUS", @@ -665,7 +665,7 @@ }, { "title": "Question supplémentaire : Minimum", - "description": "Les variables `a`, `b`, `c` et `d` contiennent chacune un nombre entier.\r\nEcrivez le code permettant de placer dans la variable `min` le minimum\r\nentre ces quatre nombres.\r\n\r\n``` java\r\nint a;\r\nint b;\r\nint c;\r\nint d;\r\nint min; // le plus petit parmi a, b, c, d\r\n```\r\n", + "description": "

Les variables a, b, c et d contiennent chacune un nombre entier. Ecrivez le code permettant de placer dans la variable min le minimum entre ces quatre nombres.

\r\n
int a;\r\nint b;\r\nint c;\r\nint d;\r\nint min; // le plus petit parmi a, b, c, d
\r\n", "tags": [ { "text": "INGINIOUS", @@ -724,7 +724,7 @@ }, { "title": "Question supplémentaire : Compteur de différence", - "description": "Les variables `a`,`b` et `c` contiennent des entiers. Placez dans la\r\nvariable `count` le nombre d'entiers distincts.\r\n\r\nPar exemple, si `a` vaut `3`, `b` vaut `5` et `c` vaut `3`, alors\r\n`count` contiendra la valeur `2`. Lorsque toutes les variables\r\ncontiennent la même valeur, `count` doit valoir `1`.\r\n\r\n``` java\r\nint count; // le nombre d'entiers différents\r\nint a;\r\nint b;\r\nint c;\r\n```\r\n", + "description": "

Les variables a,b et c contiennent des entiers. Placez dans la variable count le nombre d'entiers distincts.

\r\n

Par exemple, si a vaut 3, b vaut 5 et c vaut 3, alors count contiendra la valeur 2. Lorsque toutes les variables contiennent la même valeur, count doit valoir 1.

\r\n
int count; // le nombre d'entiers différents\r\nint a;\r\nint b;\r\nint c;
\r\n", "tags": [ { "text": "INGINIOUS", @@ -783,7 +783,7 @@ }, { "title": "Question supplémentaire : Sélecteur de saison", - "description": "Connaissant une date (`jour`/`mois`) de l'année 2016, placez dans la\r\nvariable `saison` le nom de la saison correspondante. Pour rappel, en\r\n2016 les saisons officielles commençaient aux dates suivantes :\r\n\r\n- le printemps le dimanche 20 mars 2016\r\n- l’été le lundi 20 juin 2016\r\n- l’automne le jeudi 22 septembre 2016\r\n- l’hiver le mercredi 21 décembre 2016\r\n\r\n\r\n\r\n``` java\r\nint jour; // le jour\r\nint mois; // le mois\r\nString saison; // le nom de la saison (automne, hiver, printemps, été)\r\n```\r\n", + "description": "

Connaissant une date (jour/mois) de l'année 2016, placez dans la variable saison le nom de la saison correspondante. Pour rappel, en 2016 les saisons officielles commençaient aux dates suivantes :

\r\n
    \r\n
  • le printemps le dimanche 20 mars 2016
  • \r\n
  • l’été le lundi 20 juin 2016
  • \r\n
  • l’automne le jeudi 22 septembre 2016
  • \r\n
  • l’hiver le mercredi 21 décembre 2016
  • \r\n
\r\n
int jour; // le jour\r\nint mois; // le mois\r\nString saison; // le nom de la saison (automne, hiver, printemps, été)
\r\n", "tags": [ { "text": "INGINIOUS", @@ -842,7 +842,7 @@ }, { "title": "Question supplémentaire : Nombre de secondes depuis minuit", - "description": "Dans un programme gérant une horloge, vous devez calculer le nombre de\r\nsecondes qui se sont écoulées depuis minuit. Placer le résultat de votre\r\ncalcul dans la variable `total`.\r\n\r\nExemple : 22h14m12s = 80052s\r\n\r\n``` java\r\nint heure; // le nombre d'heures\r\nint minute; // le nombre de minutes\r\nint seconde; // le nombre de secondes\r\nint total = 0; // le nombre de secondes depuis minuit\r\n```\r\n", + "description": "

Dans un programme gérant une horloge, vous devez calculer le nombre de secondes qui se sont écoulées depuis minuit. Placer le résultat de votre calcul dans la variable total.

\r\n

Exemple : 22h14m12s = 80052s

\r\n
int heure; // le nombre d'heures\r\nint minute; // le nombre de minutes\r\nint seconde; // le nombre de secondes\r\nint total = 0; // le nombre de secondes depuis minuit
\r\n", "tags": [ { "text": "INGINIOUS", @@ -901,7 +901,7 @@ }, { "title": "Question supplémentaire : Année bissextile", - "description": "Ecrivez un programme qui place la valeur `true` dans la variable\r\n`resultat` si `annee` correspond à une année bissextile et `false`\r\nsinon.\r\n\r\nPour rappel, une année sera [bissextile](https://fr.wikipedia.org/wiki/Année_bissextile) : \r\n- si l'année est divisible par 4 et non divisible par 100, ou\r\n- si l'année est divisible par 400.\r\n\r\n\r\n\r\n``` java\r\nint annee; // l'année à vérifier\r\nboolean resultat;\r\n```\r\n", + "description": "

Ecrivez un programme qui place la valeur true dans la variable resultat si annee correspond à une année bissextile et false sinon.

\r\n
\r\n
Pour rappel, une année sera bissextile :
\r\n
    \r\n
  • si l'année est divisible par 4 et non divisible par 100, ou
  • \r\n
  • si l'année est divisible par 400.
  • \r\n
\r\n
\r\n
\r\n
int annee; // l'année à vérifier\r\nboolean resultat;
\r\n", "tags": [ { "text": "INGINIOUS", @@ -960,7 +960,7 @@ }, { "title": "Question supplémentaire : Siècle", - "description": "Créer un programme permettant de déterminer le siècle d'une année.\r\nPlacez le résultat de votre calcul dans la variable `siecle`.\r\n\r\n``` java\r\nint annee; // l'année à vérifier\r\nint siecle; // le siècle de l'année\r\n```\r\n", + "description": "

Créer un programme permettant de déterminer le siècle d'une année. Placez le résultat de votre calcul dans la variable siecle.

\r\n
int annee;  // l'année à vérifier\r\nint siecle; // le siècle de l'année
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1014,7 +1014,7 @@ }, { "title": "Question supplémentaire : Calcul d'amende", - "description": "La police vous engage pour développer un programme permettant de\r\ncalculer l'amende qu'un conducteur de voiture devra payer en cas\r\nd'infraction. La loi stipule que le conducteur devra payer 5 euros par\r\nkm/h au-dessus de la vitesse maximale autorisée, avec un minimum de\r\n12.5€.\r\n\r\nPour tout dépassement de plus de 10 km/h, l'amende est doublée !\r\n\r\nVotre programme reçoit la vitesse maximale autorisée et la vitesse\r\nréelle de la voiture. Il calcule l'éventuelle amende.\r\n\r\n*Exemple* :\r\n\r\n- Si la vitesse maximum est de 50km/h et que le véhicule roule à\r\n 62km/h, l'amende sera de 12\\*5\\*2=120€.\r\n- Si la vitesse maximum est de 50km/h et que le véhicule roule à\r\n 56km/h, l'amende sera de 6\\*5=30€.\r\n- Si la vitesse maximum est de 50km/h et que le véhicule roule à\r\n 51km/h, l'amende sera de 12.5€.\r\n\r\n\r\n\r\n``` java\r\ndouble vitesseMaximale = // valeur réelle positive\r\ndouble vitesseVehicule = // valeur réelle positive\r\ndouble amende = 0; // modifié par votre programme et renvoie la valeur de l'amende\r\n```\r\n", + "description": "

La police vous engage pour développer un programme permettant de calculer l'amende qu'un conducteur de voiture devra payer en cas d'infraction. La loi stipule que le conducteur devra payer 5 euros par km/h au-dessus de la vitesse maximale autorisée, avec un minimum de 12.5€.

\r\n

Pour tout dépassement de plus de 10 km/h, l'amende est doublée !

\r\n

Votre programme reçoit la vitesse maximale autorisée et la vitesse réelle de la voiture. Il calcule l'éventuelle amende.

\r\n

Exemple :

\r\n
    \r\n
  • Si la vitesse maximum est de 50km/h et que le véhicule roule à 62km/h, l'amende sera de 12*5*2=120€.
  • \r\n
  • Si la vitesse maximum est de 50km/h et que le véhicule roule à 56km/h, l'amende sera de 6*5=30€.
  • \r\n
  • Si la vitesse maximum est de 50km/h et que le véhicule roule à 51km/h, l'amende sera de 12.5€.
  • \r\n
\r\n
double vitesseMaximale = // valeur réelle positive\r\ndouble vitesseVehicule = // valeur réelle positive\r\ndouble amende = 0; // modifié par votre programme et renvoie la valeur de l'amende
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1078,7 +1078,7 @@ }, { "title": "Question supplémentaire : Caractère", - "description": "La variable `carac` contient un caractère (chiffre ou lettre minuscule).\r\nEcrivez le code Java qui place dans la variable `retour`, la chaîne de\r\ncaractères :\r\n\r\n- `chiffre` si `carac` contient un chiffre\r\n- `voyelle` si `carac` contient une voyelle\r\n- `consonne` sinon\r\n\r\n\r\n\r\n``` java\r\nchar carac; // le caractère à vérifier\r\nString retour; // chiffre, voyelle ou consonne\r\n```\r\n", + "description": "

La variable carac contient un caractère (chiffre ou lettre minuscule). Ecrivez le code Java qui place dans la variable retour, la chaîne de caractères :

\r\n
    \r\n
  • chiffre si carac contient un chiffre
  • \r\n
  • voyelle si carac contient une voyelle
  • \r\n
  • consonne sinon
  • \r\n
\r\n
char carac; // le caractère à vérifier\r\nString retour; // chiffre, voyelle ou consonne
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1132,7 +1132,7 @@ }, { "title": "Question supplémentaire : Indice de Quételet", - "description": "L'[indice de\r\nQuételet](https://fr.wikipedia.org/wiki/Indice_de_masse_corporelle),\r\nutilisé par les diététiciens, est révélateur de l'état d'’une personne.\r\n\r\nUne personne normale devrait avoir un indice compris entre 20 et 25. En\r\ndessous de 20, elle est considérée comme mince, au dessus de 25, elle a\r\nun embonpoint. Au-delà de 30, elle est obèse!\r\n\r\nCet indice est calculé comme étant le rapport entre le poids d'une\r\npersonne, exprimé en kg et le carré de sa taille, exprimé en mètre.\r\n\r\nComplétez le programme ci-dessous pour calculer l'indice de Quételet\r\nd'un personne et stocker dans la chaîne de caractères `etat` la valeur\r\n`mince` pour une personne ayant un indice strictement inférieur à 20,\r\n`normal` pour une personne dont l'indice est compris entre 20 et 25,\r\n`embonpoint` si l'indice est strictement supérieur à 25 et inférieur ou\r\négal à 30 et `obèse` lorsqu'il est strictement supérieur à 30 ...\r\n\r\n``` java\r\ndouble taille; // taille d'une personne en m\r\nint poids; // poids d'une personne en kg\r\nString etat; // état de la personne (mince, normal, embonpoint, obèse)\r\n```\r\n", + "description": "

L'indice de Quételet, utilisé par les diététiciens, est révélateur de l'état d'’une personne.

\r\n

Une personne normale devrait avoir un indice compris entre 20 et 25. En dessous de 20, elle est considérée comme mince, au dessus de 25, elle a un embonpoint. Au-delà de 30, elle est obèse!

\r\n

Cet indice est calculé comme étant le rapport entre le poids d'une personne, exprimé en kg et le carré de sa taille, exprimé en mètre.

\r\n

Complétez le programme ci-dessous pour calculer l'indice de Quételet d'un personne et stocker dans la chaîne de caractères etat la valeur mince pour une personne ayant un indice strictement inférieur à 20, normal pour une personne dont l'indice est compris entre 20 et 25, embonpoint si l'indice est strictement supérieur à 25 et inférieur ou égal à 30 et obèse lorsqu'il est strictement supérieur à 30 ...

\r\n
double taille; // taille d'une personne en m\r\nint poids; // poids d'une personne en kg\r\nString etat; // état de la personne (mince, normal, embonpoint, obèse)
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1196,7 +1196,7 @@ }, { "title": "Question supplémentaire : Calcul de prix", - "description": "Une autoroute à péage est divisée en sections. Chaque section est\r\nidentifiée par un entier. La première section a le numéro 1, le suivante\r\nle 2, ... Les véhicules doivent **entrer en début de section** et\r\n**sortir et fin de section**.\r\n\r\nLe prix à payer pour un véhicule dépend du nombre de sections parcourues\r\n: la première section coûte 1 euro et les suivantes coûtent 50 centimes.\r\n\r\nÉcrivez un programme qui reçoit la section d'entrée et la section de\r\nsortie d'une voiture. Il place ensuite dans la variable `prix` le\r\nmontant du payage.\r\n\r\n``` java\r\nint sectionEntree = // le point d'entrée\r\nint sectionSortie = // le point de sortie\r\ndouble prix = 0; // le prix à payer\r\n```\r\n\r\nExemples :\r\n\r\n- Si `sectionEntree` vaut 3 et `sectionSortie` vaut 5, la voiture a\r\n parcouru 3 sections (les section 3, 4 et 5), donc le prix est 2.0€\r\n (1€ + 0.5€ + 0.5€).\r\n- Si `sectionEntree` vaut 2 et `sectionSortie` vaut 2, la voiture a\r\n parcouru 1 section (la section 2), donc le prix est 1€.\r\n", + "description": "

Une autoroute à péage est divisée en sections. Chaque section est identifiée par un entier. La première section a le numéro 1, le suivante le 2, ... Les véhicules doivent entrer en début de section et sortir et fin de section.

\r\n

Le prix à payer pour un véhicule dépend du nombre de sections parcourues : la première section coûte 1 euro et les suivantes coûtent 50 centimes.

\r\n

Écrivez un programme qui reçoit la section d'entrée et la section de sortie d'une voiture. Il place ensuite dans la variable prix le montant du payage.

\r\n
int sectionEntree = // le point d'entrée\r\nint sectionSortie = // le point de sortie\r\ndouble prix = 0; // le prix à payer
\r\n

Exemples :

\r\n
    \r\n
  • Si sectionEntree vaut 3 et sectionSortie vaut 5, la voiture a parcouru 3 sections (les section 3, 4 et 5), donc le prix est 2.0€ (1€ + 0.5€ + 0.5€).
  • \r\n
  • Si sectionEntree vaut 2 et sectionSortie vaut 2, la voiture a parcouru 1 section (la section 2), donc le prix est 1€.
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1260,7 +1260,7 @@ }, { "title": "Question supplémentaire : OU exclusif", - "description": "Le [OU exclusif](https://fr.wikipedia.org/wiki/Fonction_OU_exclusif)\r\n(XOR en anglais) est un opérateur logique à l'instar du \"et\" et du \"ou\".\r\nIl vous est demandé d'implémenter ce XOR, sachant que, pour `a` et `b`\r\ndeux booléens, le résultat de `a XOR b` est `true` si un et un seul des\r\nbooléens est `true`, et `false` sinon.\r\n\r\nPour cette question, il est conseillé d'utiliser les instructions\r\nconditionelles et les expressions `&&`, `||` et la négation logique `!`.\r\n\r\nPour rappel, les expressions booléennes sont décrites dans la section\r\n2.5 : Details of Expressions\\_ du livre\r\net l'instruction conditionelle dans la section [3.1 : Blocks, Loops, and\r\nBranches](http://math.hws.edu/javanotes/c3/s1.html)\r\n\r\n``` java\r\nboolean a;\r\nboolean b;\r\nboolean xor; // placer dans cette variable votre résultat\r\n```\r\n", + "description": "

Le OU exclusif (XOR en anglais) est un opérateur logique à l'instar du \"et\" et du \"ou\". Il vous est demandé d'implémenter ce XOR, sachant que, pour a et b deux booléens, le résultat de a XOR b est true si un et un seul des booléens est true, et false sinon.

\r\n

Pour cette question, il est conseillé d'utiliser les instructions conditionelles et les expressions &&, || et la négation logique !.

\r\n

Pour rappel, les expressions booléennes sont décrites dans la section 2.5 : Details of Expressions_ du livre et l'instruction conditionelle dans la section 3.1 : Blocks, Loops, and Branches

\r\n
boolean a;\r\nboolean b;\r\nboolean xor; // placer dans cette variable votre résultat
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1319,7 +1319,7 @@ }, { "title": "Question supplémentaire : Fizzbuzz", - "description": "Écrivez un programme qui permet de jouer au jeu du\r\n[fizzbuzz](https://en.wikipedia.org/wiki/Fizz_buzz)\r\n\r\nVous recevez un nombre (stocké dans la variable `i`).\r\n\r\nNous allons ici implémenter une version simplifiée du jeu. Pour l'entier\r\n`i`, le jeu consiste en :\r\n\r\n- On stocke `fizz` dans la variable `temp` si le nombre est divisible\r\n par 3.\r\n- On stocke `buzz` dans la variable `temp` si le nombre est divisible\r\n par 5.\r\n- On stocke `fizzbuzz` dans la variable `temp` si le nombre est\r\n divisible par 3 et par 5.\r\n- On stocke `non` dans la variable `temp` s'il n'est divisible ni par\r\n 3 ni par 5.\r\n\r\n\r\n\r\n``` java\r\nint i = // le nombre à vérifier (i >= 1)\r\nString temp = \"\" // fizz, buzz, fizzbuzz, non\r\n```\r\n", + "description": "

Écrivez un programme qui permet de jouer au jeu du fizzbuzz

\r\n

Vous recevez un nombre (stocké dans la variable i).

\r\n

Nous allons ici implémenter une version simplifiée du jeu. Pour l'entier i, le jeu consiste en :

\r\n
    \r\n
  • On stocke fizz dans la variable temp si le nombre est divisible par 3.
  • \r\n
  • On stocke buzz dans la variable temp si le nombre est divisible par 5.
  • \r\n
  • On stocke fizzbuzz dans la variable temp si le nombre est divisible par 3 et par 5.
  • \r\n
  • On stocke non dans la variable temp s'il n'est divisible ni par 3 ni par 5.
  • \r\n
\r\n
int i = // le nombre à vérifier (i >= 1)\r\nString temp = "" // fizz, buzz, fizzbuzz, non
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1383,7 +1383,7 @@ }, { "title": "Question supplémentaire : Somme d'entiers pairs", - "description": "On vous demande d'écrire un programme permettant de calculer la somme\r\ndes entiers pairs entre 1 et `n` (inclus).\r\n\r\n*Exemple* : pour `n=5` votre programme retourner 6 (2+4)\r\n\r\nPour vous aider dans cette tâche, il vous est possible d'utiliser le\r\nsymbole `%` qui calcule un modulo.\r\n\r\nVotre code utilisera la variable `n` et placera son résultat dans la\r\nvariable `sum`.\r\n\r\n``` java\r\nint n = // n peut prendre n'importe quelle valeur supérieure à zéro\r\nint sum = 0; // sum est la variable dans laquelle vous devez écrire le résultat final\r\n```\r\n", + "description": "

On vous demande d'écrire un programme permettant de calculer la somme des entiers pairs entre 1 et n (inclus).

\r\n

Exemple : pour n=5 votre programme retourner 6 (2+4)

\r\n

Pour vous aider dans cette tâche, il vous est possible d'utiliser le symbole % qui calcule un modulo.

\r\n

Votre code utilisera la variable n et placera son résultat dans la variable sum.

\r\n
int n = // n peut prendre n'importe quelle valeur supérieure à zéro\r\nint sum = 0; // sum est la variable dans laquelle vous devez écrire le résultat final
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1442,7 +1442,7 @@ }, { "title": "Question supplémentaire : Médiane", - "description": "Considérons un programme utilisant trois variables entières : `int a`,\r\n`int b`, `int c`.\r\n\r\nComment feriez-vous, en utilisant uniquement des instructions\r\nconditionelles (`if (...) {...} else {...}` pour calculer la\r\n[médiane](https://fr.wikipedia.org/wiki/Médiane_(statistiques)) de ces\r\ntrois valeurs.\r\n\r\nPour rappel, la médiane est la valeur qui est telle qu’il y a exactement\r\nune valeurs inférieure à elle et une valeur supérieure à elle. Les\r\ninstructions conditionelles sont décrites dans la section\r\n[3.1](http://math.hws.edu/javanotes/c3/s1.html) du livre.\r\n\r\n``` java\r\nint a, int b, int c; // Les valeurs entières à comparer\r\nint mediane; // La médiane à déterminer\r\n```\r\n", + "description": "

Considérons un programme utilisant trois variables entières : int a, int b, int c.

\r\n

Comment feriez-vous, en utilisant uniquement des instructions conditionelles (if (...) {...} else {...} pour calculer la médiane de ces trois valeurs.

\r\n

Pour rappel, la médiane est la valeur qui est telle qu’il y a exactement une valeurs inférieure à elle et une valeur supérieure à elle. Les instructions conditionelles sont décrites dans la section 3.1 du livre.

\r\n
int a, int b, int c; // Les valeurs entières à comparer\r\nint mediane; // La médiane à déterminer
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1506,7 +1506,7 @@ }, { "title": "Question supplémentaire : IN/OUT", - "description": "Mettre la variable `in` à la valeur `true` si `x` se trouve dans\r\nl’intervalle fermé \\[*a*, *b*\\] et `false` sinon.\r\n\r\n``` java\r\nboolean in; // résultat de votre calcul à placer ici\r\nint x; // la valeur à vérifier\r\nint a; // borne inférieure de l'intervalle\r\nint b; // borne supérieure de l'intervalle\r\n```\r\n", + "description": "

Mettre la variable in à la valeur true si x se trouve dans l’intervalle fermé [a, b] et false sinon.

\r\n
boolean in; // résultat de votre calcul à placer ici\r\nint x; // la valeur à vérifier\r\nint a; // borne inférieure de l'intervalle\r\nint b; // borne supérieure de l'intervalle
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1560,7 +1560,7 @@ }, { "title": "Phase de réalisation: Soumission", - "description": "Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour\r\nla Mission 1.\r\n\r\nVous attendons une archive **.zip** contenant uniquement les fichiers :\r\n\r\n- MiseEnRoute.java\r\n- README.txt\r\n", + "description": "

Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour la Mission 1.

\r\n

Vous attendons une archive .zip contenant uniquement les fichiers :

\r\n
    \r\n
  • MiseEnRoute.java
  • \r\n
  • README.txt
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1609,7 +1609,7 @@ }, { "title": "Question de Bilan Final", - "description": "La [suite de\r\nSyracuse](https://fr.wikipedia.org/wiki/Conjecture_de_Syracuse) est une\r\nsuite de naturels, définie de la manière suivante. Le premier naturel de\r\nla suite est n'importe quel naturel non-nul, que nous noterons\r\n*s*0. On peut ensuite calculer les éléments suivants de la\r\nsuite en appliquant la formule suivante :\r\n\r\n$$u\\_{n+1}= \\\\dfrac{u\\_n}{2} \\\\mbox{ si } u\\_n \\\\mbox{ est pair,}$$\r\n*u**n* + 1 = 3*u**n* + 1 si *u**n* est impair.\r\n\r\nPar exemple, en partant de 11, on obtient : 11 34 17 52 26 13 40 20 10 5\r\n16 8 4 2 1 4 2…\r\n\r\nRemarquez qu'une fois que le nombre 1 est atteint, la suite 1 4 2 1 4 2…\r\nse répète indéfiniment. La conjecture de Collatz est l'hypothèse\r\nmathématique selon laquelle toutes les suites de Syracuse atteignent\r\ntoujours 1, peu importe le naturel *s*0 choisi. Il s'agit\r\nactuellement d’un conjecture, c’est-à-dire qu’aucune preuve mathématique\r\nn’a pu être élaborée. Tous les tests effectués actuellement n'ont\r\nnéanmoins pas permis de trouver un *s*0 tel que la suite de\r\nSyracuse en découlant n'atteigne pas 1.\r\n\r\nAfin d'aider les mathématiciens à éventuellement trouver un\r\ncontre-exemple, écrivez un programme Java qui permet de calculer la\r\nsuite de Syracuse pour n’importe quel naturel non-nul *s*0.\r\nLe programme s'arrête bien entendu lorsque le naturel 1 est atteint.\r\n\r\nVous devez afficher chaque élément de la suite sur la sortie standard,\r\navec `System.out.println()`. La valeur de départ vous est déjà fournie\r\net se trouve dans une variable de type `int` nommée `s0`.\r\n", + "description": "

La suite de Syracuse est une suite de naturels, définie de la manière suivante. Le premier naturel de la suite est n'importe quel naturel non-nul, que nous noterons s0. On peut ensuite calculer les éléments suivants de la suite en appliquant la formule suivante :

\r\n


$$u_{n+1}= \\dfrac{u_n}{2} \\mbox{ si } u_n \\mbox{ est pair,}$$

un + 1 = 3un + 1 si un est impair.

\r\n

Par exemple, en partant de 11, on obtient : 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 4 2…

\r\n

Remarquez qu'une fois que le nombre 1 est atteint, la suite 1 4 2 1 4 2… se répète indéfiniment. La conjecture de Collatz est l'hypothèse mathématique selon laquelle toutes les suites de Syracuse atteignent toujours 1, peu importe le naturel s0 choisi. Il s'agit actuellement d’un conjecture, c’est-à-dire qu’aucune preuve mathématique n’a pu être élaborée. Tous les tests effectués actuellement n'ont néanmoins pas permis de trouver un s0 tel que la suite de Syracuse en découlant n'atteigne pas 1.

\r\n

Afin d'aider les mathématiciens à éventuellement trouver un contre-exemple, écrivez un programme Java qui permet de calculer la suite de Syracuse pour n’importe quel naturel non-nul s0. Le programme s'arrête bien entendu lorsque le naturel 1 est atteint.

\r\n

Vous devez afficher chaque élément de la suite sur la sortie standard, avec System.out.println(). La valeur de départ vous est déjà fournie et se trouve dans une variable de type int nommée s0.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1668,7 +1668,7 @@ }, { "title": "QCM", - "description": "Mission 1 : Mise en Route\r\n=========================\r\n\r\nCes questions ont pour objectif de vous permettre de tester vous-même\r\nvotre compréhension de la matière couverte par cette mission de mise en\r\nroute.\r\n\r\nCes questions supposent que vous avez lu les sections suivantes du livre\r\nde référence JavaNotes\\_ :\r\n\r\n> - 1 : Overview: The Mental\r\n> Landscape\\_\r\n> - 1.1 : The Fetch and Execute Cycle:\r\n> Machine Language\\_\r\n> - 1.2 : Asynchronous Events: Polling\r\n> Loops and Interrupts\\_\r\n> - 1.3 : The Java Virtual\r\n> Machine\\_\r\n> - 1.4 : Fundamental Building Blocks of\r\n> Programs\\_\r\n> - 1.5 : Objects and Object-oriented\r\n> Programming\\_\r\n> - 1.7 : The Internet and Beyond\\_\r\n> - 2 : Programming in the Small I: Names and\r\n> Things\\_\r\n> - 2.1 : The Basic Java\r\n> Application\\_\r\n> - 2.2 : Variables and the Primitive\r\n> Types\\_\r\n> - 2.3 : Strings, Objects, Enums, and\r\n> Subroutines\\_ (sauf 2.3.3 :\r\n> Introduction to Enums\\_)\r\n> - 2.5 : Details of Expressions\\_\r\n> (sauf 2.5.7 : Type Conversion of\r\n> Strings\\_)\r\n> - 2.6 : Programming\r\n> Environments\\_ (sauf 2.6.3 :\r\n> IDEs and Eclipse\\_)\r\n> - 3 : Programming in the Small II:\r\n> Control\\_\r\n> - 3.1 : Blocks, Loops, and\r\n> Branches\\_\r\n", + "description": "

Mission 1 : Mise en Route

\r\n

Ces questions ont pour objectif de vous permettre de tester vous-même votre compréhension de la matière couverte par cette mission de mise en route.

\r\n

Ces questions supposent que vous avez lu les sections suivantes du livre de référence JavaNotes_ :

\r\n
\r\n
    \r\n
  • 1 : Overview: The Mental Landscape_\r\n
      \r\n
    • 1.1 : The Fetch and Execute Cycle: Machine Language_
    • \r\n
    • 1.2 : Asynchronous Events: Polling Loops and Interrupts_
    • \r\n
    • 1.3 : The Java Virtual Machine_
    • \r\n
    • 1.4 : Fundamental Building Blocks of Programs_
    • \r\n
    • 1.5 : Objects and Object-oriented Programming_
    • \r\n
    • 1.7 : The Internet and Beyond_
    • \r\n
  • \r\n
  • 2 : Programming in the Small I: Names and Things_\r\n
      \r\n
    • 2.1 : The Basic Java Application_
    • \r\n
    • 2.2 : Variables and the Primitive Types_
    • \r\n
    • 2.3 : Strings, Objects, Enums, and Subroutines_ (sauf 2.3.3 : Introduction to Enums_)
    • \r\n
    • 2.5 : Details of Expressions_ (sauf 2.5.7 : Type Conversion of Strings_)
    • \r\n
    • 2.6 : Programming Environments_ (sauf 2.6.3 : IDEs and Eclipse_)
    • \r\n
  • \r\n
  • 3 : Programming in the Small II: Control_\r\n
      \r\n
    • 3.1 : Blocks, Loops, and Branches_
    • \r\n
  • \r\n
\r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1717,7 +1717,7 @@ }, { "title": "Question de démarrage 1: Les bases", - "description": "Voici quelques questions QCM pour vérifier votre compréhension de la\r\nMission 2 du cours, après lecture du livre de référence.\r\n", + "description": "

Voici quelques questions QCM pour vérifier votre compréhension de la Mission 2 du cours, après lecture du livre de référence.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1766,7 +1766,7 @@ }, { "title": "Question de démarrage 2 : Somme d'entiers", - "description": "Les boucles, notamment les boucles `for`, sont un concept clé en\r\nprogrammation. Pour vous entraîner à l'utilisation de boucles `for`,\r\nécrivez une boucle for qui permettra de calculer la somme des n premiers\r\nentier PAIRS supérieurs à zéro, en fonction de la variable n, déjà\r\ndéfinie à une valeur supérieure ou égale à zéro. Le résultat final doit\r\nêtre stocké dans la variable `sum` à la fin de la boucle, elle aussi\r\ndéjà définie. Lorsque n est négatif, le résultat doit valoir zéro.\r\n\r\n``` java\r\nint n = // n peut prendre n'importe quelle valeur\r\nint sum = 0;\r\n```\r\n", + "description": "

Les boucles, notamment les boucles for, sont un concept clé en programmation. Pour vous entraîner à l'utilisation de boucles for, écrivez une boucle for qui permettra de calculer la somme des n premiers entier PAIRS supérieurs à zéro, en fonction de la variable n, déjà définie à une valeur supérieure ou égale à zéro. Le résultat final doit être stocké dans la variable sum à la fin de la boucle, elle aussi déjà définie. Lorsque n est négatif, le résultat doit valoir zéro.

\r\n
int n = // n peut prendre n'importe quelle valeur\r\nint sum = 0;
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1830,7 +1830,7 @@ }, { "title": "Question de démarrage 3 : Puissances", - "description": "Les langages de programmation sont souvent utilisés à des fins\r\nmathématiques et il est intéressant de savoir implémenter certaines\r\nfonctions mathématiques simples.\r\n\r\nDans cet exercice, il vous est demandé d'implémenter à l'aide d'une\r\nboucle une portion de programme qui permet de calculer un entier `a`\r\nélevé à la puissance `n`.\r\n\r\nNotez que `n` est plus grand ou égal à zéro et vous ne devez donc pas\r\ngérer le cas où `n` est négatif. Le résultat final doit être stocké dans\r\nla variable `valeur`, qui est déjà initialisée à 1 pour vous.\r\n\r\n``` java\r\nint n = // n est non-négatif\r\nint a = // a peut prendre n'importe quelle valeur\r\nint valeur = 1;\r\n```\r\n", + "description": "

Les langages de programmation sont souvent utilisés à des fins mathématiques et il est intéressant de savoir implémenter certaines fonctions mathématiques simples.

\r\n

Dans cet exercice, il vous est demandé d'implémenter à l'aide d'une boucle une portion de programme qui permet de calculer un entier a élevé à la puissance n.

\r\n

Notez que n est plus grand ou égal à zéro et vous ne devez donc pas gérer le cas où n est négatif. Le résultat final doit être stocké dans la variable valeur, qui est déjà initialisée à 1 pour vous.

\r\n
int n = // n est non-négatif\r\nint a = // a peut prendre n'importe quelle valeur\r\nint valeur = 1;
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1889,7 +1889,7 @@ }, { "title": "Question de démarrage 4 : Plus grand diviseur", - "description": "En programmation, il est souvent intéressant de connaitre le reste de la\r\ndivison euclidienne de deux nombres, notamment pour savoir si un nombre\r\nest pair ou non. En java, pour connaître le reste d'une division, on\r\nutilise l'instruction \"modulo\" (se note \"`%`\"), ainsi `5 % 3` vaut `2`.\r\nEn sachant cela, utilisez une boucle `for` pour déterminer le plus grand\r\ndiviseur entier de n (hormis lui-même).\r\n\r\nPensez aux cas \"border lines\" : quand `n` vaut `0` ou `1`, on attend une\r\nréponse égale à `0`. La réponse finale doit-être stockée dans la\r\nvariable `biggest`.\r\n\r\n``` java\r\nint n = // n est plus grand ou égal à 0\r\nint biggest = 0;\r\n```\r\n", + "description": "

En programmation, il est souvent intéressant de connaitre le reste de la divison euclidienne de deux nombres, notamment pour savoir si un nombre est pair ou non. En java, pour connaître le reste d'une division, on utilise l'instruction \"modulo\" (se note \"%\"), ainsi 5 % 3 vaut 2. En sachant cela, utilisez une boucle for pour déterminer le plus grand diviseur entier de n (hormis lui-même).

\r\n

Pensez aux cas \"border lines\" : quand n vaut 0 ou 1, on attend une réponse égale à 0. La réponse finale doit-être stockée dans la variable biggest.

\r\n
int n = // n est plus grand ou égal à 0\r\nint biggest = 0;
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1948,7 +1948,7 @@ }, { "title": "Question de démarrage 5 : Nombres premiers", - "description": "Les nombres premiers sont un concept important en mathématiques. Un\r\nnombre premier est un nombre entier qui n'a pour diviseurs que 1 et\r\nlui-même. Notez que 0 et 1 ne sont pas des nombres premiers. En\r\nutilisant une boucle for, écrivez un petit bout de code permettant de\r\nvérifier si le nombre n est premier ou non. Vous devez stocker votre\r\nréponse dans la variable booléenne `prime` une fois la boucle terminée,\r\ndéjà initialisée à `true` pour vous. Une fois votre programme terminé,\r\nprime vaudra `true` si n est premier, et `false` si n n'est pas premier.\r\n\r\n``` java\r\nint n = // n est plus grand ou égal à zéro\r\nboolean prime = true;\r\n```\r\n", + "description": "

Les nombres premiers sont un concept important en mathématiques. Un nombre premier est un nombre entier qui n'a pour diviseurs que 1 et lui-même. Notez que 0 et 1 ne sont pas des nombres premiers. En utilisant une boucle for, écrivez un petit bout de code permettant de vérifier si le nombre n est premier ou non. Vous devez stocker votre réponse dans la variable booléenne prime une fois la boucle terminée, déjà initialisée à true pour vous. Une fois votre programme terminé, prime vaudra true si n est premier, et false si n n'est pas premier.

\r\n
int n = // n est plus grand ou égal à zéro\r\nboolean prime = true;
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2007,7 +2007,7 @@ }, { "title": "Exercice complémentaire 1 : Exercice rapide", - "description": "Pouvez-vous prédire la sortie du code suivant en moins de 5 secondes?\r\n\r\n``` java\r\nfor( int i = 0 ; i < 5; i++)\r\n{\r\n System.out.println(\"∗∗∗∗∗\") ;\r\n}\r\n```\r\n", + "description": "

Pouvez-vous prédire la sortie du code suivant en moins de 5 secondes?

\r\n
for( int i = 0 ; i < 5; i++)\r\n{\r\n    System.out.println("∗∗∗∗∗") ;\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2056,7 +2056,7 @@ }, { "title": "Exercice supplémentaire : Calculer le reste d'une division entière", - "description": "Calculez le reste de la division entière entre `a` et `b` en utilisant\r\nuniquement une boucle `for` et des soustractions. On supposera `a>0` et\r\n`b>0`.\r\n\r\nExemple : Le reste de la division entière de 5 par 3 vaut 2\r\n\r\n``` java\r\nint a; //a un entier strictement positif\r\nint b; //b un entier strictement positif\r\nint reste; // le reste de la division entière.\r\n```\r\n", + "description": "

Calculez le reste de la division entière entre a et b en utilisant uniquement une boucle for et des soustractions. On supposera a>0 et b>0.

\r\n

Exemple : Le reste de la division entière de 5 par 3 vaut 2

\r\n
int a; //a un entier strictement positif\r\nint b; //b un entier strictement positif\r\nint reste; // le reste de la division entière.
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2115,7 +2115,7 @@ }, { "title": "Question supplémentaire : Calcul du nombre diviseurs distincts", - "description": "Calculer le *nombre* de diviseurs distincts d'un entier strictement\r\npositif.\r\n\r\n``` java\r\nint a; // l'entier a\r\nint resultat = 0;\r\n```\r\n", + "description": "

Calculer le nombre de diviseurs distincts d'un entier strictement positif.

\r\n
int a; // l'entier a\r\nint resultat = 0;
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2174,7 +2174,7 @@ }, { "title": "Question supplémentaire : Dessin d'un triangle", - "description": "En utilisant des boucle(s) `for`, écrivez le code permettant d'afficher\r\nun triangle rectangle isocèle dont la longueur du côté vous est fournié.\r\n\r\nPour rappel, `System.out.print('0')` permet d'afficher le caractère `0`\r\nà l'écran et `System.out.println()` permet d'aller à la ligne.\r\n\r\nA titre d'exemple, voici un triangle dont le côté est de `4` :\r\n\r\n``` console\r\n0\r\n00\r\n000\r\n0000\r\n```\r\n\r\n``` java\r\nint cote = // la longueur du cote\r\n```\r\n", + "description": "

En utilisant des boucle(s) for, écrivez le code permettant d'afficher un triangle rectangle isocèle dont la longueur du côté vous est fournié.

\r\n

Pour rappel, System.out.print('0') permet d'afficher le caractère 0 à l'écran et System.out.println() permet d'aller à la ligne.

\r\n

A titre d'exemple, voici un triangle dont le côté est de 4 :

\r\n
0\r\n00\r\n000\r\n0000
\r\n
int cote = // la longueur du cote
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2233,7 +2233,7 @@ }, { "title": "Question supplémentaire : Dessin de H", - "description": "Dessiner la lettre H en utilisant de l'ASCII-art avec le caractère `*`.\r\nVotre programme reçoit comme entrée la hauteur de la lettre à dessiner\r\n(supposée impaire) et sa largeur. N'affichez pas d'espaces inutiles à\r\ndroite de votre lettre.\r\n\r\nA titre d'exemple, si `hauteur` vaut 5 et `largeur` 3, vous devez\r\nafficher.\r\n\r\n``` console\r\n* *\r\n* *\r\n***\r\n* *\r\n* *\r\n```\r\n\r\n``` java\r\nint hauteur; // la hauteur du H\r\nint largeur; // la largeur du H\r\n```\r\n", + "description": "

Dessiner la lettre H en utilisant de l'ASCII-art avec le caractère *. Votre programme reçoit comme entrée la hauteur de la lettre à dessiner (supposée impaire) et sa largeur. N'affichez pas d'espaces inutiles à droite de votre lettre.

\r\n

A titre d'exemple, si hauteur vaut 5 et largeur 3, vous devez afficher.

\r\n
* *\r\n* *\r\n***\r\n* *\r\n* *
\r\n
int hauteur; // la hauteur du H\r\nint largeur; // la largeur du H
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2292,7 +2292,7 @@ }, { "title": "Question supplémentaire : Dessin de X", - "description": "En utilisant le caractère `*`, dessinez une lettre `X` dont on vous\r\ndonne la hauteur (supposée impaire). N'affichez pas d'espaces inutiles à\r\ndroite de votre lettre.\r\n\r\nExemple avec une hauteur de 5, avec \"-\" symbolisant un espace :\r\n\r\n``` console\r\n*---*\r\n-*-*\r\n--*\r\n-*-*\r\n*---*\r\n```\r\n\r\n``` java\r\nint hauteur; // la hauteur du X\r\n```\r\n\r\nNB: Même un retour à la ligne est un caractère de trop!\r\n", + "description": "

En utilisant le caractère *, dessinez une lettre X dont on vous donne la hauteur (supposée impaire). N'affichez pas d'espaces inutiles à droite de votre lettre.

\r\n

Exemple avec une hauteur de 5, avec \"-\" symbolisant un espace :

\r\n
*---*\r\n-*-*\r\n--*\r\n-*-*\r\n*---*
\r\n
int hauteur; // la hauteur du X
\r\n

NB: Même un retour à la ligne est un caractère de trop!

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2351,7 +2351,7 @@ }, { "title": "Question supplémentaire : Dessin de S", - "description": "Dessinez la lettre S en utilisant le caractère `*` lorsque l'on vous\r\ndonne la `hauteur`. La largeur du S sera toujours de 3 caractères. Les\r\nespaces ne sont nécéssaires que s'il y a une étoile après.\r\n\r\nExemple avec une hauteur de 5, avec \"-\" symbolisant un espace:\r\n\r\n``` console\r\n***\r\n*\r\n***\r\n--*\r\n***\r\n```\r\n\r\n``` java\r\nint hauteur; // la hauteur du S\r\n```\r\n", + "description": "

Dessinez la lettre S en utilisant le caractère * lorsque l'on vous donne la hauteur. La largeur du S sera toujours de 3 caractères. Les espaces ne sont nécéssaires que s'il y a une étoile après.

\r\n

Exemple avec une hauteur de 5, avec \"-\" symbolisant un espace:

\r\n
***\r\n*\r\n***\r\n--*\r\n***
\r\n
int hauteur; // la hauteur du S
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2410,7 +2410,7 @@ }, { "title": "Question supplémentaire : Calcul d'intérêts", - "description": "Vous avez aujourd'hui `base` € sur votre livret d'épargne. Si vous le\r\nlaissez `x` années à un taux d'intérêt supposé fixe de `y` pourcents,\r\nquel sera le solde de votre livret après ces `x` années ?\r\n\r\n``` java\r\nint x; // le nombre d'années\r\ndouble y; // le pourcentage\r\ndouble base; // l'argent sur le compte sans les intérêts\r\ndouble resultat; // le resultat du calcul\r\n```\r\n", + "description": "

Vous avez aujourd'hui base € sur votre livret d'épargne. Si vous le laissez x années à un taux d'intérêt supposé fixe de y pourcents, quel sera le solde de votre livret après ces x années ?

\r\n
int x; // le nombre d'années\r\ndouble y; // le pourcentage\r\ndouble base; // l'argent sur le compte sans les intérêts\r\ndouble resultat; // le resultat du calcul
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2464,7 +2464,7 @@ }, { "title": "Question supplémentaire : Calcul de factorielle", - "description": "En mathématiques, la factorielle d'un entier `x`, notée *x*! strictement\r\npositif est le produit des entiers strictement positifs inférieurs ou\r\négaux à `x`. Calculer la factorielle d'un entier et stocker la valeur\r\ndans la variable `resultat`.\r\n\r\nExemple : 5! = 5 × 4 × 3 × 2 × 1 = 120\r\n\r\n``` java\r\nint x; // l'entier\r\nint resultat = 0;\r\n```\r\n\r\nTip : faites attention à la valeur de la variable resultat !\r\n", + "description": "

En mathématiques, la factorielle d'un entier x, notée x! strictement positif est le produit des entiers strictement positifs inférieurs ou égaux à x. Calculer la factorielle d'un entier et stocker la valeur dans la variable resultat.

\r\n

Exemple : 5! = 5 × 4 × 3 × 2 × 1 = 120

\r\n
int x; // l'entier\r\nint resultat = 0;
\r\n

Tip : faites attention à la valeur de la variable resultat !

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2523,7 +2523,7 @@ }, { "title": "Question supplémentaire : Somme des entiers entre a et b", - "description": "`a` et `b` sont deux entiers tels que *a* < *b*. Calculez la somme\r\ndes entiers se trouvant dans l'intervalle fermé \\[*a*, *b*\\] en\r\nutilisant une boucle `for`.\r\n\r\n``` java\r\nint a; // l'entier a\r\nint b; // l'entier b\r\nint resultat = 0;\r\n```\r\n", + "description": "

a et b sont deux entiers tels que a < b. Calculez la somme des entiers se trouvant dans l'intervalle fermé [a, b] en utilisant une boucle for.

\r\n
int a; // l'entier a\r\nint b; // l'entier b\r\nint resultat = 0;
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2582,7 +2582,7 @@ }, { "title": "Phase de réalisation: Soumission", - "description": "Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour\r\nla Mission 2.\r\n\r\nVous attendons une archive **.zip** contenant uniquement les fichiers :\r\n\r\n- Equation.java\r\n- EquationSimple.java\r\n- TextIO.java\r\n- README.txt\r\n", + "description": "

Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour la Mission 2.

\r\n

Vous attendons une archive .zip contenant uniquement les fichiers :

\r\n
    \r\n
  • Equation.java
  • \r\n
  • EquationSimple.java
  • \r\n
  • TextIO.java
  • \r\n
  • README.txt
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2631,7 +2631,7 @@ }, { "title": "Question de Bilan Final", - "description": "Soit un naturel non-nul *x*, le naturel non-nul *d* est un **diviseur\r\npropre** de *x* s'il est compris entre *x* (exclus) et qu'il divise *x*.\r\n\r\nCe qui va nous intéresser dans le cadre de cette question de bilan\r\nfinal, c'est le nombre de diviseurs propres. Vous devez écrire un\r\nprogramme qui va, étant donné un naturel non-nul `n`, afficher à l'écran\r\nle nombre de diviseurs propres que possède chacun des naturels compris\r\nentre 1 et *n* (tous les deux inclus).\r\n\r\nPar exemple, si la variable `n` vaut 7, votre programme doit afficher\r\nsur la sortie standard, grâce à `System.out.println()`, ceci :\r\n\r\n``` console\r\n1:0\r\n2:1\r\n3:1\r\n4:2\r\n5:1\r\n6:3\r\n7:1\r\n```\r\n\r\nVotre programme doit afficher son résultat exactement comme présenté\r\ndans l'exemple ci-dessus. Vous ne devez pas déclarer, ni initialiser la\r\nvariable de type `int` nommée `n`, elle vous sera fournie.\r\n", + "description": "

Soit un naturel non-nul x, le naturel non-nul d est un diviseur propre de x s'il est compris entre x (exclus) et qu'il divise x.

\r\n

Ce qui va nous intéresser dans le cadre de cette question de bilan final, c'est le nombre de diviseurs propres. Vous devez écrire un programme qui va, étant donné un naturel non-nul n, afficher à l'écran le nombre de diviseurs propres que possède chacun des naturels compris entre 1 et n (tous les deux inclus).

\r\n

Par exemple, si la variable n vaut 7, votre programme doit afficher sur la sortie standard, grâce à System.out.println(), ceci :

\r\n
1:0\r\n2:1\r\n3:1\r\n4:2\r\n5:1\r\n6:3\r\n7:1
\r\n

Votre programme doit afficher son résultat exactement comme présenté dans l'exemple ci-dessus. Vous ne devez pas déclarer, ni initialiser la variable de type int nommée n, elle vous sera fournie.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2690,7 +2690,7 @@ }, { "title": "QCM", - "description": "Mission 2. Les bases de Java\r\n============================\r\n\r\nCette mission a pour objectif de renforcer vos connaissances des\r\nconcepts de base de la programmation en Java.\r\n\r\nCes questions supposent que vous avez lu les sections suivantes du livre\r\nde référence JavaNotes\\_ :\r\n\r\n> - 2 : Programming in the Small I: Names and\r\n> Things\\_\r\n>\r\n> > - 2.4 : Text Input and Output\\_\r\n> > (sauf 2.4.2 : Text Output\\_,\r\n> > 2.4.4 : Formatted Output\\_,\r\n> > 2.4.5 : Introduction to File\r\n> > I/O\\_, et 2.4.6 : Using\r\n> > Scanner for Input\\_).\r\n>\r\n> - 3 : Programming in the Small II:\r\n> Control\\_\r\n>\r\n> > - 3.2 : Algorithm Development\\_\r\n> > - 3.3 : The while and do..while\r\n> > Statements\\_ (sauf 3.3.3 :\r\n> > break and continue\\_)\r\n> > - 3.4 : The for Statement\\_\r\n> > (sauf 3.4.4 : Enums and for-each\r\n> > Loops\\_)\r\n> > - 3.5 : The if Statement\\_\r\n", + "description": "

Mission 2. Les bases de Java

\r\n

Cette mission a pour objectif de renforcer vos connaissances des concepts de base de la programmation en Java.

\r\n

Ces questions supposent que vous avez lu les sections suivantes du livre de référence JavaNotes_ :

\r\n
\r\n
    \r\n
  • 2 : Programming in the Small I: Names and Things_

    \r\n
    \r\n
      \r\n
    • 2.4 : Text Input and Output_ (sauf 2.4.2 : Text Output_, 2.4.4 : Formatted Output_, 2.4.5 : Introduction to File I/O_, et 2.4.6 : Using Scanner for Input_).
    • \r\n
    \r\n
  • \r\n
  • 3 : Programming in the Small II: Control_

    \r\n
    \r\n
      \r\n
    • 3.2 : Algorithm Development_
    • \r\n
    • 3.3 : The while and do..while Statements_ (sauf 3.3.3 : break and continue_)
    • \r\n
    • 3.4 : The for Statement_ (sauf 3.4.4 : Enums and for-each Loops_)
    • \r\n
    • 3.5 : The if Statement_
    • \r\n
    \r\n
  • \r\n
\r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2739,7 +2739,7 @@ }, { "title": "Question de Démarrage 1: Conversions", - "description": "Considérez les déclaratons suivantes :\r\n\r\nL'on souhaite faire en sorte que d'une part la valeur le la variable\r\n*money* se retrouve dans la variable *wallet\\_i* et que d'autre part la\r\nvaleur de la variable *euro* se retrouve dans la variable *wallet\\_d*.\r\n", + "description": "

Considérez les déclaratons suivantes :

\r\n

L'on souhaite faire en sorte que d'une part la valeur le la variable money se retrouve dans la variable wallet_i et que d'autre part la valeur de la variable euro se retrouve dans la variable wallet_d.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2783,7 +2783,7 @@ }, { "title": "Question de Démarrage 2 : Le Nombre Maximum", - "description": "Ecrivez *la signature* et *le corps* d’une methode baptisée `afficheMax`\r\nqui prend deux nombres entiers comme arguments et **affiche** le plus\r\ngrand de ces nombres. La spécification de cette méthode est :\r\n", + "description": "

Ecrivez la signature et le corps d’une methode baptisée afficheMax qui prend deux nombres entiers comme arguments et affiche le plus grand de ces nombres. La spécification de cette méthode est :

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2842,7 +2842,7 @@ }, { "title": "Question de Démarrage 3 : Nombres impairs", - "description": "Ecrivez la signature et le corps d'une méthode baptisée `impair` qui\r\nprend comme argument un entier **n** positif et retourne `true` si **n**\r\nest impair et `false` sinon. Pour rappel, si **n** est un entier positif\r\n`n % 2` vaut le reste de la division entière de **n** par 2. La\r\nspécification de cette méthode est:\r\n", + "description": "

Ecrivez la signature et le corps d'une méthode baptisée impair qui prend comme argument un entier n positif et retourne true si n est impair et false sinon. Pour rappel, si n est un entier positif n % 2 vaut le reste de la division entière de n par 2. La spécification de cette méthode est:

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2901,7 +2901,7 @@ }, { "title": "Question de démarrage 4 : Lettre L", - "description": "Un étudiant montre à son tuteur la méthode main ci-dessous :\r\n\r\nLors de son exécution elle affiche les caractères suivants à l'écran:\r\n\r\n> Hauteur du L\r\n> 7\r\n> Largeur du L\r\n> 5\r\n>\r\n> X\r\n> X\r\n> X\r\n> X\r\n> X\r\n> X\r\n> XXXXX\r\n", + "description": "

Un étudiant montre à son tuteur la méthode main ci-dessous :

\r\n

Lors de son exécution elle affiche les caractères suivants à l'écran:

\r\n
\r\n
Hauteur du L\r\n7\r\nLargeur du L\r\n5\r\n\r\nX\r\nX\r\nX\r\nX\r\nX\r\nX\r\nXXXXX
\r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2960,7 +2960,7 @@ }, { "title": "Question de Démarage 5 : Diviseurs Entiers", - "description": "La section *3.4.2* du livre présente un programme qui permet de calculer\r\net d’afficher le nombre de diviseurs entiers d’un nombre entier.\r\nRéutilisez ce code de façon à construire la méthode `nDiv` répondant à\r\nla spécification et la signature suivante :\r\n", + "description": "

La section 3.4.2 du livre présente un programme qui permet de calculer et d’afficher le nombre de diviseurs entiers d’un nombre entier. Réutilisez ce code de façon à construire la méthode nDiv répondant à la spécification et la signature suivante :

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3019,7 +3019,7 @@ }, { "title": "Q* intervalle fermé", - "description": "On vous demande d'écrire une méthode permettant de dire si un nombre se\r\ntrouve dans l'intervalle fermé \\[*a*, *b*\\] dont les spécifications sont\r\nles suivantes:\r\n\r\n``` java\r\n/*\r\n * @pre a < b\r\n * @post retourne true si x est dans [a,b] false sinon\r\n */\r\n```\r\n\r\nVotre méthode devra s'appeler `intervalle` et prendra comme premier\r\nargument `a`, la borne inférieure de l'intervalle, comme deuxième\r\nargument, `b`, la borne supérieure et comme dernier argument la valeur à\r\ntester. Ces trois arguments sont des entiers.\r\n", + "description": "

On vous demande d'écrire une méthode permettant de dire si un nombre se trouve dans l'intervalle fermé [a, b] dont les spécifications sont les suivantes:

\r\n
/*\r\n * @pre a < b\r\n * @post retourne true si x est dans [a,b] false sinon\r\n */
\r\n

Votre méthode devra s'appeler intervalle et prendra comme premier argument a, la borne inférieure de l'intervalle, comme deuxième argument, b, la borne supérieure et comme dernier argument la valeur à tester. Ces trois arguments sont des entiers.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3073,7 +3073,7 @@ }, { "title": "Q* Calculer la surface d'un rectangle", - "description": "On vous demande d'écrire la méthode `surface` qui permet de calculer la\r\nsurface d'un rectangle. On supposera que la `longueur` et la `largeur`\r\nqui sont passées en arguments sont des entiers positifs.\r\n\r\n``` java\r\n/*\r\n * @pre largeur > 0, longueur > 0\r\n * @post retourne la surface du rectangle dont les\r\n * largeur et longueur sont données.\r\n */\r\n```\r\n", + "description": "

On vous demande d'écrire la méthode surface qui permet de calculer la surface d'un rectangle. On supposera que la longueur et la largeur qui sont passées en arguments sont des entiers positifs.

\r\n
/*\r\n * @pre largeur > 0, longueur > 0\r\n * @post retourne la surface du rectangle dont les\r\n *       largeur et longueur sont données.\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -3127,7 +3127,7 @@ }, { "title": "Q* Maximum", - "description": "Ecrivez la signature et le corps de la méthode `max` qui prend comme\r\nparamètres les entiers `a`, `b` , `c` qui retourne le maximum de 3\r\nnombres et dont la spécification est:\r\n\r\n``` java\r\n/*\r\n * @pre\r\n * @post retourne le maximum entre les entiers a, b et c\r\n */\r\n```\r\n\r\nVous pouvez réutiliser votre code de la question supplémentaire maximum\r\nde la mission 1.\r\n", + "description": "

Ecrivez la signature et le corps de la méthode max qui prend comme paramètres les entiers a, b , c qui retourne le maximum de 3 nombres et dont la spécification est:

\r\n
/*\r\n * @pre\r\n * @post retourne le maximum entre les entiers a, b et c\r\n */
\r\n

Vous pouvez réutiliser votre code de la question supplémentaire maximum de la mission 1.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3186,7 +3186,7 @@ }, { "title": "Q** Médiane", - "description": "Ecrivez la méthode `mediane` qui prend comme arguments trois entiers et\r\nretourne la\r\n[médiane](https://fr.wikipedia.org/wiki/Médiane_(statistiques)) entre\r\nces nombres.\r\n\r\nPour vous aider on vous donne les méthodes\r\n`public static int min(int x, int y)` et\r\n`public static int max(int x, int y)` que vous pouvez utiliser dans\r\nvotre code. Leurs spécifications sont :\r\n\r\n``` java\r\n/*\r\n * @pre -\r\n * @post retourne le minimum entre a et b\r\n */\r\npublic static int min(int a, int b);\r\n\r\n/*\r\n * @pre -\r\n * @post retourne le maximum entre a et b\r\n */\r\npublic static int max(int a, int b);\r\n```\r\n", + "description": "

Ecrivez la méthode mediane qui prend comme arguments trois entiers et retourne la médiane entre ces nombres.

\r\n

Pour vous aider on vous donne les méthodes public static int min(int x, int y) et public static int max(int x, int y) que vous pouvez utiliser dans votre code. Leurs spécifications sont :

\r\n
/*\r\n * @pre -\r\n * @post retourne le minimum entre a et b\r\n */\r\npublic static int min(int a, int b);\r\n\r\n/*\r\n * @pre -\r\n * @post retourne le maximum entre a et b\r\n */\r\npublic static int max(int a, int b);
\r\n", "tags": [ { "text": "INGINIOUS", @@ -3245,7 +3245,7 @@ }, { "title": "Q* Calcul du volume d'une sphère", - "description": "Ecrivez la méthode `volume` qui calcule le volume d'une\r\n[sphère](https://fr.wikipedia.org/wiki/Sphère). Elle prend en paramètre\r\nle rayon de la sphère (nombre réel).\r\n\r\nPour rappel, le volume d'une sphère de rayon r est\r\n$\\\\frac{4\\\\times\\\\pi\\\\times{r^{3}}}{3}$\r\n\r\nEn Java, la constante *π* est définie dans la classe\r\n[Math](https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html)\r\ncomme la constante `Math.PI`\r\n", + "description": "

Ecrivez la méthode volume qui calcule le volume d'une sphère. Elle prend en paramètre le rayon de la sphère (nombre réel).

\r\n

Pour rappel, le volume d'une sphère de rayon r est $\\frac{4\\times\\pi\\times{r^{3}}}{3}$

\r\n

En Java, la constante π est définie dans la classe Math comme la constante Math.PI

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3304,7 +3304,7 @@ }, { "title": "Q** Calcul de la factorielle", - "description": "La [factorielle](https://fr.wikipedia.org/wiki/Factorielle) d'un entier\r\n`n` est le produit des nombres entiers strictement positifs inférieurs\r\nou égaux à `n`.\r\n\r\nEcrivez la signature et le corps de la méthode `fact` dont les\r\nspécifications sont :\r\n\r\n``` java\r\n/*\r\n * @pre n > 0\r\n * @post retourne la valeur de la factorielle de n\r\n */\r\n```\r\n", + "description": "

La factorielle d'un entier n est le produit des nombres entiers strictement positifs inférieurs ou égaux à n.

\r\n

Ecrivez la signature et le corps de la méthode fact dont les spécifications sont :

\r\n
/*\r\n * @pre n > 0\r\n * @post retourne la valeur de la factorielle de n\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -3363,7 +3363,7 @@ }, { "title": "Q** Carré parfait", - "description": "En mathématiques, un nombre entier est un [carré\r\nparfait](https://fr.wikipedia.org/wiki/Carré_parfait) si il est le carré\r\nd'un autre nombre entier.\r\n\r\nEcrivez la méthode `carparf` dont les spécifications sont (`x` est un\r\nentier) :\r\n", + "description": "

En mathématiques, un nombre entier est un carré parfait si il est le carré d'un autre nombre entier.

\r\n

Ecrivez la méthode carparf dont les spécifications sont (x est un entier) :

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3422,7 +3422,7 @@ }, { "title": "Phase de réalisation: Soumission", - "description": "Soumettez l'archive zip contenant le fichier LibMath.java et README.txt\r\n", + "description": "

Soumettez l'archive zip contenant le fichier LibMath.java et README.txt

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3471,7 +3471,7 @@ }, { "title": "Question de Bilan Final", - "description": "Un étudiant a écrit le programme Java suivant qui permet de compter le\r\nnombre de chiffres de la représentation décimale d'un nombre naturel\r\ndonné.\r\n\r\nVous devez définir la méthode `chiffresPairs` qui renvoie `true` si le\r\nnombre de chiffres de son paramètre est pair et `false` sinon. N'hésitez\r\npas à décomposer le problème en sous-problèmes et de définir des\r\nméthodes privées complémentaires.\r\n\r\nVoici un exemple :\r\n\r\n- `chiffresPairs(5555)` doit retourner `true`\r\n- `chiffresPairs(555)` doit retourner `false`\r\n- `chiffresPairs(-555)` doit retourner `false`\r\n", + "description": "

Un étudiant a écrit le programme Java suivant qui permet de compter le nombre de chiffres de la représentation décimale d'un nombre naturel donné.

\r\n

Vous devez définir la méthode chiffresPairs qui renvoie true si le nombre de chiffres de son paramètre est pair et false sinon. N'hésitez pas à décomposer le problème en sous-problèmes et de définir des méthodes privées complémentaires.

\r\n

Voici un exemple :

\r\n
    \r\n
  • chiffresPairs(5555) doit retourner true
  • \r\n
  • chiffresPairs(555) doit retourner false
  • \r\n
  • chiffresPairs(-555) doit retourner false
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -3525,7 +3525,7 @@ }, { "title": "QCM", - "description": "Mission 3. Méthodes et sous-routines\r\n====================================\r\n\r\nCes questions supposent que vous avez lu les sections suivantes du livre\r\nde référence JavaNotes\\_\r\n\r\n> - 4 : Programming in the Large I:\r\n> Subroutines\\_\r\n>\r\n> > - 4.1 : Black Boxes\\_\r\n> >\r\n> > - 4.2 : Static Subroutines and Static\r\n> > Variables\\_\r\n> >\r\n> > - 4.2.1: Subroutine\r\n> > Definitions\\_\r\n> >\r\n> > - 4.2.2 : Calling Subroutines\\_\r\n> >\r\n> > - 4.2.3 : Subroutines in\r\n> > Programs\\_\r\n> >\r\n> > - 4.2.4 : Member Variables\\_\r\n> >\r\n> > - 4.3 : Parameters\\_\r\n> >\r\n> > > - 4.3.1 : Using\r\n> > > Parameters\\_\r\n> > > - 4.3.2 : Formal and Actual\r\n> > > Parameters\\_\r\n> > > - 4.3.3 : Overloading\\_\r\n> > > - 4.3.4 : Subroutine\r\n> > > Examples\\_\r\n> > > - 4.3.6 : Global and Local\r\n> > > Variables\\_\r\n> >\r\n> > - 4.4 : Return Values\\_\r\n> >\r\n> > > - 4.4.1 : The return\r\n> > > statement\\_\r\n> > > - 4.4.2 : Function\r\n> > > Examples\\_\r\n> > > - 4.4.3 : 3N+1\r\n> > > Revisited\\_\r\n> >\r\n> > - 4.6 : More on Program\r\n> > Design\\_\r\n> >\r\n> > - 4.6.1 : Preconditions and\r\n> > Postconditions\\_\r\n", + "description": "

Mission 3. Méthodes et sous-routines

\r\n

Ces questions supposent que vous avez lu les sections suivantes du livre de référence JavaNotes_

\r\n
\r\n
    \r\n
  • 4 : Programming in the Large I: Subroutines_

    \r\n
    \r\n
      \r\n
    • 4.1 : Black Boxes_

    • \r\n
    • 4.2 : Static Subroutines and Static Variables_

    • \r\n
    • 4.2.1: Subroutine Definitions_

    • \r\n
    • 4.2.2 : Calling Subroutines_

    • \r\n
    • 4.2.3 : Subroutines in Programs_

    • \r\n
    • 4.2.4 : Member Variables_

    • \r\n
    • 4.3 : Parameters_

      \r\n
      \r\n
        \r\n
      • 4.3.1 : Using Parameters_
      • \r\n
      • 4.3.2 : Formal and Actual Parameters_
      • \r\n
      • 4.3.3 : Overloading_
      • \r\n
      • 4.3.4 : Subroutine Examples_
      • \r\n
      • 4.3.6 : Global and Local Variables_
      • \r\n
      \r\n
    • \r\n
    • 4.4 : Return Values_

      \r\n
      \r\n
        \r\n
      • 4.4.1 : The return statement_
      • \r\n
      • 4.4.2 : Function Examples_
      • \r\n
      • 4.4.3 : 3N+1 Revisited_
      • \r\n
      \r\n
    • \r\n
    • 4.6 : More on Program Design_

    • \r\n
    • 4.6.1 : Preconditions and Postconditions_

    • \r\n
    \r\n
  • \r\n
\r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -3574,7 +3574,7 @@ }, { "title": "Questions de démarrage 1 : La classe Character", - "description": "La classe `Character` de l'API Java\r\n()\r\ncontient un bon nombre de méthodes qui pourront vous être utiles pour\r\nmanipuler des caractères. Avec ces exercices, vous serez un peu plus\r\nfamiliers avec certaines méthodes qui vous seront certainement utiles\r\ndans le futur.\r\n\r\n``` java\r\nchar c = // un caractère, représentant un chiffre ou non\r\nchar d = // un caractère de a à z, en majuscule ou non\r\nboolean b; // à assigner dans la Question 1\r\nchar e; // à assigner dans la Question 2\r\n```\r\n", + "description": "

La classe Character de l'API Java (https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html) contient un bon nombre de méthodes qui pourront vous être utiles pour manipuler des caractères. Avec ces exercices, vous serez un peu plus familiers avec certaines méthodes qui vous seront certainement utiles dans le futur.

\r\n
char c = // un caractère, représentant un chiffre ou non\r\nchar d = // un caractère de a à z, en majuscule ou non\r\nboolean b; // à assigner dans la Question 1\r\nchar e;    // à assigner dans la Question 2
\r\n", "tags": [ { "text": "INGINIOUS", @@ -3628,7 +3628,7 @@ }, { "title": "Question de démarrage 2 : Concaténation", - "description": "En java, on retrouve des types de variables primitifs comme `int`,\r\n`char`, `double`, qui commencent par une minuscule, mais aussi des\r\nobjets, dont les `String` font partie. Cependant, les `String` sont des\r\nobjets un peu particuliers qui permettent certaines opérations qui les\r\ndifférencient des objets, comme la concaténation des `String`. La\r\nconcaténation de deux `String` consiste à former un nouveau `String` qui\r\ncontient le contenu du premier et du deuxième mis bout à bout. Ainsi,\r\nconcaténer le `String` `\"Harry\"` et le `String` `\"gateau\"` nous donne le\r\n`String` `\"Harrygateau\"`.\r\n\r\nNous allons maintenant vous demander d'implémenter le corps de la\r\nméthode `cat`, qui permet de renvoyer la concaténation de deux `String`,\r\n`s1` et `s2`. Voici les signatures de la méthode `cat`. Veillez bien à\r\nrespecter scrupuleusement les spécifications\r\n", + "description": "

En java, on retrouve des types de variables primitifs comme int, char, double, qui commencent par une minuscule, mais aussi des objets, dont les String font partie. Cependant, les String sont des objets un peu particuliers qui permettent certaines opérations qui les différencient des objets, comme la concaténation des String. La concaténation de deux String consiste à former un nouveau String qui contient le contenu du premier et du deuxième mis bout à bout. Ainsi, concaténer le String \"Harry\" et le String \"gateau\" nous donne le String \"Harrygateau\".

\r\n

Nous allons maintenant vous demander d'implémenter le corps de la méthode cat, qui permet de renvoyer la concaténation de deux String, s1 et s2. Voici les signatures de la méthode cat. Veillez bien à respecter scrupuleusement les spécifications

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3687,7 +3687,7 @@ }, { "title": "Question de démarrage 3 : Longueur d'un String", - "description": "Comme dit précédemment, le type `String` est un type quelque peu\r\nparticulier en Java. Pour faire des opérations sur des `String`, on a\r\ntrès souvent besoin de leur longueur. En vous référant à l'API Java de\r\nla classe `String`\r\n(),\r\nécrivez en une seule ligne le corps de la méthode `showLength()`, qui\r\naffiche sur la sortie standard la longueur de l'argument `s`. La méthode\r\ndoit être implémenté de sorte que lorsqu'on l'appelle trois fois de\r\nsuite avec comme argument `\"Popol\"`, `\"Jeanjean\"` et `\"abc\"`, de\r\nlongueurs 5, 8 et 3, on retrouve la sortie standard dans cet état :\r\n\r\n 5\r\n 8\r\n 3\r\n\r\nVoici la signature de la méthode `showLength()`. Veillez à bien\r\nrespecter les spécifications :\r\n\r\n``` java\r\n/*\r\n * @pre -\r\n * @post affiche la longueur de s sur la sortie standard\r\n */\r\n public static void showLength(String s) {\r\n // à compléter\r\n }\r\n```\r\n", + "description": "

Comme dit précédemment, le type String est un type quelque peu particulier en Java. Pour faire des opérations sur des String, on a très souvent besoin de leur longueur. En vous référant à l'API Java de la classe String (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html), écrivez en une seule ligne le corps de la méthode showLength(), qui affiche sur la sortie standard la longueur de l'argument s. La méthode doit être implémenté de sorte que lorsqu'on l'appelle trois fois de suite avec comme argument \"Popol\", \"Jeanjean\" et \"abc\", de longueurs 5, 8 et 3, on retrouve la sortie standard dans cet état :

\r\n
5\r\n8\r\n3
\r\n

Voici la signature de la méthode showLength(). Veillez à bien respecter les spécifications :

\r\n
/*\r\n * @pre -\r\n * @post affiche la longueur de s sur la sortie standard\r\n */\r\n public static void showLength(String s) {\r\n     // à compléter\r\n }
\r\n", "tags": [ { "text": "INGINIOUS", @@ -3746,7 +3746,7 @@ }, { "title": "Question de démarrage 4 : toUpper", - "description": "Il est parfois utile de s'assurer qu'un String est en majuscule. La\r\nméthode `Character.toUpperCase()` de la classe `Character` de l'API Java\r\npermet de récupérer la majuscule d'un caractère qu'on lui passe en\r\nargument. En utilisant cette méthode, implémentez la méthode `toUpper`\r\nqui retourne un `String` identique à celui passé en argument, mais en\r\nmajuscule. Attention à ne pas utiliser une autre méthode que\r\n`Character.toUpperCase()`.\r\n\r\nVoici la signature de la méthode `toUpper` à implémenter. Respectez bien\r\nles spécifications :\r\n\r\n``` java\r\n/*\r\n * @pre s non vide\r\n * @post retourne s en majuscules\r\n */\r\n public static String toUpper(String s) {\r\n // À implémenter\r\n }\r\n```\r\n", + "description": "

Il est parfois utile de s'assurer qu'un String est en majuscule. La méthode Character.toUpperCase() de la classe Character de l'API Java permet de récupérer la majuscule d'un caractère qu'on lui passe en argument. En utilisant cette méthode, implémentez la méthode toUpper qui retourne un String identique à celui passé en argument, mais en majuscule. Attention à ne pas utiliser une autre méthode que Character.toUpperCase().

\r\n

Voici la signature de la méthode toUpper à implémenter. Respectez bien les spécifications :

\r\n
/*\r\n *    @pre  s non vide\r\n *    @post retourne s en majuscules\r\n */\r\n public static String toUpper(String s) {\r\n     // À implémenter\r\n }
\r\n", "tags": [ { "text": "INGINIOUS", @@ -3805,7 +3805,7 @@ }, { "title": "Question de démarrage 5 : La méthode containsChar()", - "description": "Écrivez le corps de la méthode de la méthode `containsChar()` qui prend\r\ndeux arguments, `s1` et `s2`, et qui vérifie si tous les caractères\r\nprésents dans `s1` sont aussi présents dans `s2`. Si c'est le cas, la\r\nméthode retourne `true`. Le cas des `String` vides ne doit pas être\r\ngéré.\r\n\r\nVoici les spécifications de la méthode `containsChar()` :\r\n\r\n``` java\r\n/**\r\n * @pre s1 et s2 non-vides\r\n * @post Retourne true si s1 contient uniquement des\r\n * caractères qui sont aussi dans s2.\r\n * Retourne false sinon.\r\n */\r\n public static boolean containsChar(String s1, String s2){\r\n // À implémenter\r\n }\r\n```\r\n", + "description": "

Écrivez le corps de la méthode de la méthode containsChar() qui prend deux arguments, s1 et s2, et qui vérifie si tous les caractères présents dans s1 sont aussi présents dans s2. Si c'est le cas, la méthode retourne true. Le cas des String vides ne doit pas être géré.

\r\n

Voici les spécifications de la méthode containsChar() :

\r\n
/**\r\n *    @pre  s1 et s2 non-vides\r\n *    @post Retourne true si s1 contient uniquement des\r\n *          caractères qui sont aussi dans s2.\r\n *          Retourne false sinon.\r\n */\r\n public static boolean containsChar(String s1, String s2){\r\n         // À implémenter\r\n }
\r\n", "tags": [ { "text": "INGINIOUS", @@ -3859,7 +3859,7 @@ }, { "title": "Question supplémentaire : Occurences de c dans s", - "description": "Ecrivez la méthode `int countChar(String s, char c)` permettant de\r\ncompter le nombre d'occurences du caractère `c` dans `s` et dont la\r\nspécification est :\r\n\r\n``` java\r\n/*\r\n * @pre s != null\r\n * @post retourne le nombre d’occurrences du caractère c dans la chaîne s\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode int countChar(String s, char c) permettant de compter le nombre d'occurences du caractère c dans s et dont la spécification est :

\r\n
/*\r\n * @pre s != null\r\n * @post retourne le nombre d’occurrences du caractère c dans la chaîne s\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -3913,7 +3913,7 @@ }, { "title": "Q** représentation entière", - "description": "Ecrivez la méthode `int d2i(String s)` qui retourne la représentation\r\nentière d'un nombre entier fourni sous la forme d'un String. Par\r\nexemple, \"012345\" doit renvoyer 1235. N'utilisez pas de méthode de\r\nparsing comme `parseInt` ou `parseDouble`.\r\n\r\nLa spécification est:\r\n\r\n``` java\r\n/*\r\n * @pre s != null et s est la représentation d'un nombre entier dans le \r\n * système décimal (il contient uniquement des chiffres)\r\n * @post retourne la représentation du nombre sous forme d'un entier\r\n */\r\n```\r\n\r\nLa méthode ci-dessous pourrait vous aider à résoudre facilement cette\r\nquestion :\r\n\r\n", + "description": "

Ecrivez la méthode int d2i(String s) qui retourne la représentation entière d'un nombre entier fourni sous la forme d'un String. Par exemple, \"012345\" doit renvoyer 1235. N'utilisez pas de méthode de parsing comme parseInt ou parseDouble.

\r\n

La spécification est:

\r\n
/*\r\n * @pre s != null et s est la représentation d'un nombre entier dans le \r\n *      système décimal (il contient uniquement des chiffres)\r\n * @post retourne la représentation du nombre sous forme d'un entier\r\n */
\r\n

La méthode ci-dessous pourrait vous aider à résoudre facilement cette question : http://docs.oracle.com/javase/6/docs/api/java/lang/Character.html#getNumericValue(char)

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3972,7 +3972,7 @@ }, { "title": "Q*** Caractère le plus fréquent", - "description": "Ecrivez la méthode `char plusFrequent(String s)` qui permet de\r\ndéterminer le caractère le plus présent dans la chaine de caractères\r\n`s`.\r\n\r\nA titre d'exemple, le caractère le plus fréquent de la chaîne `abbDDaa`\r\nest `a`. Si la chaîne contient des caractères avec le même nombre\r\nd'occurences maximal, renvoyez le premier trouvé de gauche à droite.\r\n\r\nLa spécification est:\r\n\r\n``` java\r\n/*\r\n * @pre s!=null\r\n * @post retourne le caractère qui se trouve le plus grand\r\n * nombre de fois dans la chaîne s\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode char plusFrequent(String s) qui permet de déterminer le caractère le plus présent dans la chaine de caractères s.

\r\n

A titre d'exemple, le caractère le plus fréquent de la chaîne abbDDaa est a. Si la chaîne contient des caractères avec le même nombre d'occurences maximal, renvoyez le premier trouvé de gauche à droite.

\r\n

La spécification est:

\r\n
/*\r\n * @pre s!=null\r\n * @post retourne le caractère qui se trouve le plus grand\r\n *      nombre de fois dans la chaîne s\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -4031,7 +4031,7 @@ }, { "title": "Q* Caractère dans String", - "description": "Ecrivez la méthode `boolean isIn(char c, String s)` dont la\r\nspécification est :\r\n\r\n``` java\r\n/*\r\n * @pre s!=null\r\n * @post retourne true si le caractère c est dans s, false sinon\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode boolean isIn(char c, String s) dont la spécification est :

\r\n
/*\r\n * @pre s!=null\r\n * @post retourne true si le caractère c est dans s, false sinon\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -4085,7 +4085,7 @@ }, { "title": "Q* chaîne composée de chiffres", - "description": "Ecrivez la méthode `boolean entierValide(String s)` permettant de\r\nretourner `true` uniquement si la chaine de caractères `s` ne contient\r\nque des chiffres. la spécification est :\r\n\r\n``` java\r\n/*\r\n * @pre s != null\r\n * @post retourne true uniquement si la chaine de caractères\r\n * s ne contient que des chiffres\r\n */\r\n```\r\n\r\nIl y a une méthode dans la classe Character qui devrait vous aider à\r\nvérifier qu'un caractère est un chiffre, voir\r\n\r\n", + "description": "

Ecrivez la méthode boolean entierValide(String s) permettant de retourner true uniquement si la chaine de caractères s ne contient que des chiffres. la spécification est :

\r\n
/*\r\n  * @pre s != null\r\n  * @post retourne true uniquement si la chaine de caractères\r\n  *       s ne contient que des chiffres\r\n  */
\r\n

Il y a une méthode dans la classe Character qui devrait vous aider à vérifier qu'un caractère est un chiffre, voir https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4139,7 +4139,7 @@ }, { "title": "Q** Vérification de mot de passe", - "description": "De nombreux sites web imposent des contraintes sur les mots de passe que\r\nles utilisateurs peuvent utiliser. L'objectif est généralement de forcer\r\nles utilisateurs à choisir des mots de passe difficiles à trouver par\r\ndes attaquants éventuels.\r\n\r\nEcrivez la méthode `boolean motDePasseValide(String s)` permettant de\r\nvérifier la validité d'un mot de passe `s`. La contrainte imposée à un\r\ntel mot de passe est qu'il doit au moins contenir 8 caractères, un\r\nchiffre. La spécification de cette méthode est :\r\n\r\n``` java\r\n/*\r\n * @pre s!=null\r\n * @post retourne true uniquement si la chaine de caractères\r\n * s est un mot de passe valide, c-a-d qu'elle\r\n * contient au moins 8 caractères, au moins une lettre\r\n * minuscule, au moins un chiffre et au moins une lettre majuscule\r\n */\r\n```\r\n\r\nVous trouverez dans la classe\r\n[Character](https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html)\r\ndes méthodes utiles pour cette tâche.\r\n", + "description": "

De nombreux sites web imposent des contraintes sur les mots de passe que les utilisateurs peuvent utiliser. L'objectif est généralement de forcer les utilisateurs à choisir des mots de passe difficiles à trouver par des attaquants éventuels.

\r\n

Ecrivez la méthode boolean motDePasseValide(String s) permettant de vérifier la validité d'un mot de passe s. La contrainte imposée à un tel mot de passe est qu'il doit au moins contenir 8 caractères, un chiffre. La spécification de cette méthode est :

\r\n
/*\r\n * @pre s!=null\r\n * @post retourne true uniquement si la chaine de caractères\r\n *       s est un mot de passe valide, c-a-d qu'elle\r\n *       contient au moins 8 caractères, au moins une lettre\r\n *       minuscule, au moins un chiffre et au moins une lettre majuscule\r\n */
\r\n

Vous trouverez dans la classe Character des méthodes utiles pour cette tâche.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4193,7 +4193,7 @@ }, { "title": "Question supplémentaire : binaire", - "description": "Ecrivez la méthode `boolean binaire(String s)` qui retourne `true`\r\nuniquement si la chaine de caractères `s` ne contient que les caractères\r\n`0` ou `1`\r\n\r\nLa spécification est :\r\n\r\n``` java\r\n/*\r\n * @pre s != null, s.length() >= 1\r\n * @post retourne true uniquement si la chaine de caractères\r\n * s ne contient que les caractères 0 ou 1\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode boolean binaire(String s) qui retourne true uniquement si la chaine de caractères s ne contient que les caractères 0 ou 1

\r\n

La spécification est :

\r\n
/*\r\n * @pre s != null, s.length() >= 1\r\n * @post retourne true uniquement si la chaine de caractères\r\n *       s ne contient que les caractères 0 ou 1\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -4247,7 +4247,7 @@ }, { "title": "Q** containsOnly", - "description": "Ecrivez la méthode `boolean containsOnly(String s, String c)` qui\r\nretourne `true` si la chaine `s` contient uniquement des caractères se\r\ntrouvant dans la chaine `c`, `false` sinon.\r\n\r\nLa spécification est :\r\n\r\n``` java\r\n/*\r\n * @pre s != null, c != null, tous les caractères de la chaine c sont différents\r\n * @post retourne true si la chaine s contient uniquement des\r\n * caracteres se trouvant la chaine c, false sinon\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode boolean containsOnly(String s, String c) qui retourne true si la chaine s contient uniquement des caractères se trouvant dans la chaine c, false sinon.

\r\n

La spécification est :

\r\n
/*\r\n * @pre s != null, c != null, tous les caractères de la chaine c sont différents\r\n * @post retourne true si la chaine s contient uniquement des\r\n *       caracteres se trouvant la chaine c, false sinon\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -4301,7 +4301,7 @@ }, { "title": "Question supplémentaire : le palindrome", - "description": "Ecrivez la méthode `boolean palindrome(String s)` qui vérifie si une\r\nchaine de caractères `s` est un palindrome. Pour rappel, vous trouverez\r\nplus d'informations sur les palindromes sur\r\n[Wikipedia](https://en.wikipedia.org/wiki/Palindrome).\r\n\r\nPour simplifier les choses, votre programme prend en compte les signes\r\ndiacritiques (accents, trémas, cédilles) et les espaces. Par exemple\r\n\"camilleellimaç\" ou encore \"la mariée ira mal\" ne doivent pas être\r\nconsidérés comme des palindromes.\r\n\r\nLa spécification de cette méthode est :\r\n\r\n``` java\r\n/*\r\n * @pre s != null\r\n * @post retourne true si s est un palindrome, false sinon\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode boolean palindrome(String s) qui vérifie si une chaine de caractères s est un palindrome. Pour rappel, vous trouverez plus d'informations sur les palindromes sur Wikipedia.

\r\n

Pour simplifier les choses, votre programme prend en compte les signes diacritiques (accents, trémas, cédilles) et les espaces. Par exemple \"camilleellimaç\" ou encore \"la mariée ira mal\" ne doivent pas être considérés comme des palindromes.

\r\n

La spécification de cette méthode est :

\r\n
/*\r\n * @pre s != null\r\n * @post retourne true si s est un palindrome, false sinon\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -4360,7 +4360,7 @@ }, { "title": "Q* méthode contains", - "description": "Ecrivez la méthode `boolean contains(String s, String in)` qui retourne\r\ntrue si la chaine de caractère `in` se trouve dans la chaine de\r\ncaractères `s`. N'utilisez pas la méthode `contains()` ou `indexOf()` de\r\nString. La spécification est :\r\n\r\n``` java\r\n/*\r\n * @pre s != null, in != null\r\n * @post retourne true si la chaine de caractère in se trouve\r\n * dans la chaîne de caractères s\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode boolean contains(String s, String in) qui retourne true si la chaine de caractère in se trouve dans la chaine de caractères s. N'utilisez pas la méthode contains() ou indexOf() de String. La spécification est :

\r\n
/*\r\n * @pre s != null, in != null\r\n * @post retourne true si la chaine de caractère in se trouve\r\n *     dans la chaîne de caractères s\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -4414,7 +4414,7 @@ }, { "title": "Q* notation binaire", - "description": "Les ordinateurs manipulent les nombres en utilisant le [système\r\nbinaire](https://fr.wikipedia.org/wiki/Système_binaire).\r\n\r\nEcrivez la méthode `int b2i(String s)` qui permet de transformer un\r\nnombre en notation binaire en sa représentation sous forme d'entier .\r\n\r\nLa spécification de cette méthode est :\r\n\r\n``` java\r\n/*\r\n * @pre s != null\r\n * s est la représentation d'un nombre binaire\r\n * s contient uniquement des 1 et des 0\r\n * @post retourne la représentation entière du nombre binaire\r\n * correspondant à cette chaîne\r\n */\r\n```\r\n", + "description": "

Les ordinateurs manipulent les nombres en utilisant le système binaire.

\r\n

Ecrivez la méthode int b2i(String s) qui permet de transformer un nombre en notation binaire en sa représentation sous forme d'entier .

\r\n

La spécification de cette méthode est :

\r\n
/*\r\n * @pre s != null\r\n *      s est la représentation d'un nombre binaire\r\n *      s contient uniquement des 1 et des 0\r\n * @post retourne la représentation entière du nombre binaire\r\n *      correspondant à cette chaîne\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -4468,7 +4468,7 @@ }, { "title": "Phase de réalisation: Soumission", - "description": "Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour\r\nla mission 4.\r\n\r\nVous attendons une archive **.zip** contenant uniquement les fichiers :\r\n\r\n- BioInfo.java\r\n- README.txt\r\n", + "description": "

Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour la mission 4.

\r\n

Vous attendons une archive .zip contenant uniquement les fichiers :

\r\n
    \r\n
  • BioInfo.java
  • \r\n
  • README.txt
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -4517,7 +4517,7 @@ }, { "title": "Question de bilan final", - "description": "La classe **String** contient de nombreuses méthodes permettant de\r\nmanipuler les chaînes de caractères. Parmi celles-ci, on peut citer\r\n`length()` qui retourne la longueur de la chaîne de caractères,\r\n`charAt(int i)` qui retourne le caractère de la ième position ou\r\n`substring(int begin, int end)` qui retourne la sous-chaîne de\r\ncaractères démarrant à la position `begin` et se terminant à la position\r\n`end - 1`.\r\n\r\nEn utilisant ces méthodes, vous devez écrire une méthode dont la\r\nspécification est la suivante :\r\n\r\n``` java\r\n/*\r\n * @pre - p != null, s != null\r\n * - p est un pattern, c’est-à-dire une chaîne de caractères composées de\r\n * lettres, de chiffres et de zéro, une ou plusieurs fois le caractère ?\r\n * - s contient des lettres et des chiffres, mais pas le caractère ?\r\n * @post - retourne le nombre d’occurrences du pattern p à l’intérieur de la chaîne\r\n * de caractères s.\r\n * - Une occurrence est une sous-chaîne de s de même longueur\r\n * que p qui contient les mêmes caractères que p à toutes les positions\r\n * où p ne contient pas de caractère ?\r\n */\r\npublic static int count (String p, String s);\r\n```\r\n\r\nÀ titre d’exemple, le code ci-dessous :\r\n\r\n``` java\r\nSystem.out.println(count(\"AB\",\"CDEF\"));\r\nSystem.out.println(count(\"?B\",\"CABDEF\"));\r\nSystem.out.println(count(\"A?\",\"CABDEACF\"));\r\nSystem.out.println(count(\"AA\",\"CAAABDEAAF\"));\r\nSystem.out.println(count(\"??\",\"CAAAB\"));\r\n```\r\n\r\nAffiche les valeurs 0, 1, 2, 3 et 4.\r\n\r\nPour résoudre ce problème, pensez à la découper en sous-problèmes et\r\nn’hésitez pas à utiliser une ou plusieurs méthodes privées\r\nsupplémentaires.\r\n", + "description": "

La classe String contient de nombreuses méthodes permettant de manipuler les chaînes de caractères. Parmi celles-ci, on peut citer length() qui retourne la longueur de la chaîne de caractères, charAt(int i) qui retourne le caractère de la ième position ou substring(int begin, int end) qui retourne la sous-chaîne de caractères démarrant à la position begin et se terminant à la position end - 1.

\r\n

En utilisant ces méthodes, vous devez écrire une méthode dont la spécification est la suivante :

\r\n
/*\r\n * @pre - p != null, s != null\r\n *      - p est un pattern, c’est-à-dire une chaîne de caractères composées de\r\n *        lettres, de chiffres et de zéro, une ou plusieurs fois le caractère ?\r\n *      - s contient des lettres et des chiffres, mais pas le caractère ?\r\n * @post - retourne le nombre d’occurrences du pattern p à l’intérieur de la chaîne\r\n *         de caractères s.\r\n *       - Une occurrence est une sous-chaîne de s de même longueur\r\n *         que p qui contient les mêmes caractères que p à toutes les positions\r\n *         où p ne contient pas de caractère ?\r\n */\r\npublic static int count (String p, String s);
\r\n

À titre d’exemple, le code ci-dessous :

\r\n
System.out.println(count("AB","CDEF"));\r\nSystem.out.println(count("?B","CABDEF"));\r\nSystem.out.println(count("A?","CABDEACF"));\r\nSystem.out.println(count("AA","CAAABDEAAF"));\r\nSystem.out.println(count("??","CAAAB"));
\r\n

Affiche les valeurs 0, 1, 2, 3 et 4.

\r\n

Pour résoudre ce problème, pensez à la découper en sous-problèmes et n’hésitez pas à utiliser une ou plusieurs méthodes privées supplémentaires.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4576,7 +4576,7 @@ }, { "title": "QCM", - "description": "Mission 4. Manipulation de chaînes de caractères\r\n================================================\r\n\r\nCes questions supposent que vous avez lu les sections suivantes du livre\r\nde référence JavaNotes\\_\r\n\r\n> - 2.3 : Strings, Objects, Enums, and\r\n> Subroutines\\_\r\n> - 2.3.1 : Built-in Subroutines and\r\n> Functions\\_\r\n> - 2.3.2 : Operations on Strings\\_\r\n> - 2.3.3 : Introduction to Enums\\_\r\n> n'est pas vu dans le cadre de ce cours\r\n> - 4.7 : The Truth About\r\n> Declarations\\_\r\n> - 4.7.1 : Initialization in\r\n> Declarations\\_\r\n> - 4.7.2 : Named Constants\\_\r\n> - 4.7.3 : Naming and Scope\r\n> Rules\\_\r\n\r\nLes sections vues précédemment restent bien entendu d'actualité.\r\n", + "description": "

Mission 4. Manipulation de chaînes de caractères

\r\n

Ces questions supposent que vous avez lu les sections suivantes du livre de référence JavaNotes_

\r\n
\r\n
    \r\n
  • 2.3 : Strings, Objects, Enums, and Subroutines_\r\n
      \r\n
    • 2.3.1 : Built-in Subroutines and Functions_
    • \r\n
    • 2.3.2 : Operations on Strings_
    • \r\n
    • 2.3.3 : Introduction to Enums_ n'est pas vu dans le cadre de ce cours
    • \r\n
  • \r\n
  • 4.7 : The Truth About Declarations_\r\n
      \r\n
    • 4.7.1 : Initialization in Declarations_
    • \r\n
    • 4.7.2 : Named Constants_
    • \r\n
    • 4.7.3 : Naming and Scope Rules_
    • \r\n
  • \r\n
\r\n
\r\n

Les sections vues précédemment restent bien entendu d'actualité.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4625,7 +4625,7 @@ }, { "title": "Question de démarrage 1 : Syntaxe et Tableaux", - "description": "Répondez aux questions simples suivantes au sujet de la syntaxe des\r\ntableaux. Vous *devez* respecter les noms de variables suggérés. (Nous\r\nutilisons le type `int` pour les entiers et le type `double` pour les\r\nréels.)\r\n", + "description": "

Répondez aux questions simples suivantes au sujet de la syntaxe des tableaux. Vous devez respecter les noms de variables suggérés. (Nous utilisons le type int pour les entiers et le type double pour les réels.)

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4674,7 +4674,7 @@ }, { "title": "Question de démarrage 2 : Compararer des tableaux", - "description": "Un étudiant utilise des tableaux de réels pour représenter des vecteurs\r\nmathématiques. Ces tableaux sont définis comme suit :\r\n\r\nL'étudiant propose la méthode suivante pour tester que deux vecteurs\r\nsont identiques :\r\n\r\nIl teste sa méthode sur les deux tableaux ci-dessus et conclut que sa\r\nméthode est correcte. Qu'en pensez-vous ?\r\n", + "description": "

Un étudiant utilise des tableaux de réels pour représenter des vecteurs mathématiques. Ces tableaux sont définis comme suit :

\r\n

L'étudiant propose la méthode suivante pour tester que deux vecteurs sont identiques :

\r\n

Il teste sa méthode sur les deux tableaux ci-dessus et conclut que sa méthode est correcte. Qu'en pensez-vous ?

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4733,7 +4733,7 @@ }, { "title": "Question de démarrage 3 : Matrice unité", - "description": "Ecrivez la méthode suivante :\r\n", + "description": "

Ecrivez la méthode suivante :

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4792,7 +4792,7 @@ }, { "title": "Question de démarrage 4 : Sommes de Matrices", - "description": "Ecrivez en appliquant la *programmation défensive*, une version de la\r\nméthode dont la spécification est la suivante :\r\n", + "description": "

Ecrivez en appliquant la programmation défensive, une version de la méthode dont la spécification est la suivante :

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4851,7 +4851,7 @@ }, { "title": "Question de Démarrage 5 : Méthode Main", - "description": "Dans une classe, on trouve une méthode dont la signature est :\r\n", + "description": "

Dans une classe, on trouve une méthode dont la signature est :

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4910,7 +4910,7 @@ }, { "title": "Q* : Tous la même valeur", - "description": "Ecrivez la méthode `boolean allSame(double [] v)` qui retourne vrai si\r\ntous les éléments du tableau ont la même valeur, false sinon. la\r\nspécification est :\r\n\r\n``` java\r\n/*\r\n * @pre v != null, v contient au moins 2 éléments\r\n * @post retourne vrai si tous les éléments du tableau ont la même valeur, false sinon\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode boolean allSame(double [] v) qui retourne vrai si tous les éléments du tableau ont la même valeur, false sinon. la spécification est :

\r\n
/*\r\n * @pre v != null, v contient au moins 2 éléments\r\n * @post retourne vrai si tous les éléments du tableau ont la même valeur, false sinon\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -4969,7 +4969,7 @@ }, { "title": "Q** : Somme", - "description": "Ecrivez la méthode `double[] somme(double[] a, double[] b)` qui retourne\r\nun tableau dont chaque élément est la somme des éléments des tableaux a\r\net b au même indice. la spécification est :\r\n\r\n``` java\r\n/*\r\n * @pre a != null, b != null, a.length == b.lenght\r\n * @post retourne un tableau dont chaque élément est la somme des éléments\r\n * des tableaux a et b au même indice\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode double[] somme(double[] a, double[] b) qui retourne un tableau dont chaque élément est la somme des éléments des tableaux a et b au même indice. la spécification est :

\r\n
/*\r\n * @pre a != null, b != null, a.length == b.lenght\r\n * @post retourne un tableau dont chaque élément est la somme des éléments\r\n *       des tableaux a et b au même indice\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -5028,7 +5028,7 @@ }, { "title": "Q*** : Top", - "description": "Ecrivez la méthode `int[] top(int n, int[] v)` qui retourne un tableau\r\nde longueur `n` dont les éléments sont dans l'ordre croissant et qui\r\ncontient les `n` plus grands entiers du tableau `v` .\r\n\r\nPar exemple :\r\n\r\n- `top(3, {5,0,4,1,2})` doit retourner `{2,4,5}`\r\n- `top(1, {5,3})` doit retourner `{3}`\r\n- `top(2, {5,1,3})` doit retourner `{3,5}`\r\n\r\nLa spécification est :\r\n\r\n``` java\r\n/*\r\n * @pre v != null, n < v.length\r\n * @post retourne un tableau de longueur n\r\n * dont les éléments sont dans l'ordre croissant\r\n * et qui contient les n plus grands entiers du tableau v\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode int[] top(int n, int[] v) qui retourne un tableau de longueur n dont les éléments sont dans l'ordre croissant et qui contient les n plus grands entiers du tableau v .

\r\n

Par exemple :

\r\n
    \r\n
  • top(3, {5,0,4,1,2}) doit retourner {2,4,5}
  • \r\n
  • top(1, {5,3}) doit retourner {3}
  • \r\n
  • top(2, {5,1,3}) doit retourner {3,5}
  • \r\n
\r\n

La spécification est :

\r\n
/*\r\n * @pre v != null, n < v.length\r\n * @post retourne un tableau de longueur n\r\n *       dont les éléments sont dans l'ordre croissant\r\n *       et qui contient les n plus grands entiers du tableau v\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -5087,7 +5087,7 @@ }, { "title": "Q* : Oppose", - "description": "Ecrivez les méthodes `oppose` et `oppose2` dont les spécifications et\r\nsignatures sont :\r\n", + "description": "

Ecrivez les méthodes oppose et oppose2 dont les spécifications et signatures sont :

\r\n", "tags": [ { "text": "INGINIOUS", @@ -5141,7 +5141,7 @@ }, { "title": "Q* : Valeur max du tableau", - "description": "Ecrivez la méthode `double max(double[] v)` qui retourne le maximum du\r\ntableau de réels v. la spécification est :\r\n\r\n``` java\r\n/*\r\n * @pre v != null\r\n * @post retourne le maximum du tableau de réels v\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode double max(double[] v) qui retourne le maximum du tableau de réels v. la spécification est :

\r\n
/*\r\n * @pre v != null\r\n * @post retourne le maximum du tableau de réels v\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -5200,7 +5200,7 @@ }, { "title": "Q* : Valeur moyenne du tableau", - "description": "Ecrivez la méthode `double mean(double[] v)` qui retourne la moyenne\r\narithmétique du tableau de réels v. la spécification est :\r\n\r\n``` java\r\n/*\r\n * @pre v != null\r\n * @post retourne la moyenne arithmétique du tableau de réels v\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode double mean(double[] v) qui retourne la moyenne arithmétique du tableau de réels v. la spécification est :

\r\n
/*\r\n * @pre v != null\r\n * @post retourne la moyenne arithmétique du tableau de réels v\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -5259,7 +5259,7 @@ }, { "title": "Q* : Tableau croissant", - "description": "Ecrivez la méthode `boolean croissant(int[] t)` qui retourne true si les\r\néléments du tableau `t` sont croissants, false sinon. la spécification\r\nest :\r\n\r\n``` java\r\n/*\r\n * @pre t != null\r\n * @post retourne true si les éléments du tableau t sont croissants, false sinon\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode boolean croissant(int[] t) qui retourne true si les éléments du tableau t sont croissants, false sinon. la spécification est :

\r\n
/*\r\n * @pre t != null\r\n * @post retourne true si les éléments du tableau t sont croissants, false sinon\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -5318,7 +5318,7 @@ }, { "title": "Q** : Vecteur", - "description": "Ecrivez la méthode `double[] initVector(int n, double i)` qui retourne\r\nun vecteur de n éléments tous initialisés à la valeur i. la\r\nspécification est :\r\n\r\n``` java\r\n/*\r\n * @pre n > 0\r\n * @post retourne un vecteur de n éléments tous initialisés à la valeur i\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode double[] initVector(int n, double i) qui retourne un vecteur de n éléments tous initialisés à la valeur i. la spécification est :

\r\n
/*\r\n * @pre n > 0\r\n * @post retourne un vecteur de n éléments tous initialisés à la valeur i\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -5377,7 +5377,7 @@ }, { "title": "Q** : Matrice identité", - "description": "Ecrivez la méthode `double[][] matriceIdentite(int n)` qui retourne la\r\nmatrice identité de taille n×n. la spécification est :\r\n\r\n``` java\r\n/*\r\n * @pre n > 0\r\n * @post retourne la matrice identité de taille n×n\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode double[][] matriceIdentite(int n) qui retourne la matrice identité de taille n×n. la spécification est :

\r\n
/*\r\n * @pre n > 0\r\n * @post retourne la matrice identité de taille n×n\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -5436,7 +5436,7 @@ }, { "title": "Q** : Count", - "description": "Ecrivez la méthode `int count(int v, int[][] m)` qui compte le nombre\r\nd'occurences de la valeur `v` dans `int[][] m`. la spécification est :\r\n\r\n``` java\r\n/*\r\n * @pre m != null\r\n * @post compte le nombre d'occurences de la valeur v dans int[][] m\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode int count(int v, int[][] m) qui compte le nombre d'occurences de la valeur v dans int[][] m. la spécification est :

\r\n
/*\r\n * @pre m != null\r\n * @post compte le nombre d'occurences de la valeur v dans int[][] m\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -5495,7 +5495,7 @@ }, { "title": "Q** : replace", - "description": "Ecrivez la méthode `void replace(int v, int w, int[][] m)` qui remplace\r\ntoutes les d'occurences de la valeur `v` dans `int[][] m` par la valeur\r\n`w`. la spécification est :\r\n\r\n``` java\r\n/*\r\n * @pre m != null\r\n * @post remplace toutes les d'occurences de la valeur v\r\n * dans le tableau int[][] m par la valeur w.\r\n * Modifie la matrice m.\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode void replace(int v, int w, int[][] m) qui remplace toutes les d'occurences de la valeur v dans int[][] m par la valeur w. la spécification est :

\r\n
/*\r\n * @pre m != null\r\n * @post remplace toutes les d'occurences de la valeur v\r\n *       dans le tableau int[][] m par la valeur w.\r\n *       Modifie la matrice m.\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -5554,7 +5554,7 @@ }, { "title": "Q** : Decale", - "description": "Ecrivez la méthode `void decaleDroite(char[] v)` qui modifie le tableau\r\n`v` en décalant tous les caractères d'une position vers la droite et\r\n`v[0]` a été mis à la valeur `*` (étoile). Par exemple, si\r\n`v = ['a', 'b', 'c']`, le résultat attendu est `['*', 'a', 'b']`. La\r\nspécification est :\r\n\r\n``` java\r\n/*\r\n * @pre v != null\r\n * @post Modifie le tableau v en décalant tous les caractères\r\n * d'une position vers la droite\r\n * et v[0] est mis à la valeur '*' (étoile)\r\n */\r\n```\r\n", + "description": "

Ecrivez la méthode void decaleDroite(char[] v) qui modifie le tableau v en décalant tous les caractères d'une position vers la droite et v[0] a été mis à la valeur * (étoile). Par exemple, si v = ['a', 'b', 'c'], le résultat attendu est ['*', 'a', 'b']. La spécification est :

\r\n
/*\r\n * @pre v != null\r\n * @post Modifie le tableau v en décalant tous les caractères\r\n *       d'une position vers la droite\r\n *       et v[0] est mis à la valeur '*' (étoile)\r\n */
\r\n", "tags": [ { "text": "INGINIOUS", @@ -5613,7 +5613,7 @@ }, { "title": "Phase de réalisation: Soumission", - "description": "Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour\r\nla mission 5.\r\n\r\nNous attendons une archive **.zip** contenant uniquement les fichiers :\r\n\r\n- ImageGray.java\r\n- LibrairieImage.java\r\n- LibrairieIO.java\r\n- Test.java\r\n- TestRescale.java\r\n- TestBrighten.java\r\n- TestContains.java\r\n- TestSubtract.java\r\n- README.txt\r\n", + "description": "

Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour la mission 5.

\r\n

Nous attendons une archive .zip contenant uniquement les fichiers :

\r\n
    \r\n
  • ImageGray.java
  • \r\n
  • LibrairieImage.java
  • \r\n
  • LibrairieIO.java
  • \r\n
  • Test.java
  • \r\n
  • TestRescale.java
  • \r\n
  • TestBrighten.java
  • \r\n
  • TestContains.java
  • \r\n
  • TestSubtract.java
  • \r\n
  • README.txt
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -5662,7 +5662,7 @@ }, { "title": "(a) : Question de Bilan Final", - "description": "Dans cette question de bilan final, on va s'intéresser à l'écriture de\r\nméthodes dont le but est de modifier les éléments d'un tableau passé en\r\nparamètre. Le but de ces méthodes est de déplacer tous les éléments du\r\ntableau d'un certain nombre de cases vers la droite.\r\n\r\nCommençons par la méthode `rotateRightOne`. Elle va décaler tous les\r\néléments du tableau passé en paramètre, d'une case vers la droite. Voici\r\nsa spécification précise :\r\n\r\n``` java\r\n/*\r\n * @pre tab != null\r\n * @post Le tableau tab a été modifié et tous ses éléments sont décalés\r\n * d'une position vers la droite (le dernier élément revenant\r\n * en première position)\r\n */\r\n public static void rotateRightOne(int[] tab) {\r\n // Question 1\r\n }\r\n```\r\n\r\nEnsuite, vous devez écrire une méthode `rotateRight` qui déplace tous\r\nles éléments d'un tableau, vers la droite, d'un certain nombre `n` de\r\npositions. Voici sa spécification précise :\r\n\r\n``` java\r\n/*\r\n * @pre tab != null\r\n * @post Le tableau tab a été modifié et tous ses éléments sont décalés\r\n * de n positions vers la droite, c'est-à-dire que les éléments\r\n * qui se trouvaient en i se retrouvent en (i + n) % tab.length\r\n */\r\npublic static void rotateRight(int[] tab, int n) {\r\n // Question 2\r\n}\r\n```\r\n\r\nN'oubliez pas d'éviter la duplication de code, et d'éventuellement\r\nréutiliser l'une des deux méthodes dans l'autre.\r\n", + "description": "

Dans cette question de bilan final, on va s'intéresser à l'écriture de méthodes dont le but est de modifier les éléments d'un tableau passé en paramètre. Le but de ces méthodes est de déplacer tous les éléments du tableau d'un certain nombre de cases vers la droite.

\r\n

Commençons par la méthode rotateRightOne. Elle va décaler tous les éléments du tableau passé en paramètre, d'une case vers la droite. Voici sa spécification précise :

\r\n
/*\r\n * @pre tab != null\r\n * @post Le tableau tab a été modifié et tous ses éléments sont décalés\r\n *       d'une position vers la droite (le dernier élément revenant\r\n *       en première position)\r\n */\r\n public static void rotateRightOne(int[] tab) {\r\n     // Question 1\r\n }
\r\n

Ensuite, vous devez écrire une méthode rotateRight qui déplace tous les éléments d'un tableau, vers la droite, d'un certain nombre n de positions. Voici sa spécification précise :

\r\n
/*\r\n * @pre tab != null\r\n * @post Le tableau tab a été modifié et tous ses éléments sont décalés\r\n *       de n positions vers la droite, c'est-à-dire que les éléments\r\n *       qui se trouvaient en i se retrouvent en (i + n) % tab.length\r\n */\r\npublic static void rotateRight(int[] tab, int n) {\r\n    // Question 2\r\n}
\r\n

N'oubliez pas d'éviter la duplication de code, et d'éventuellement réutiliser l'une des deux méthodes dans l'autre.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -5716,7 +5716,7 @@ }, { "title": "QCM", - "description": "Mission 5. Tableaux\r\n===================\r\n\r\nCes questions supposent que vous avez lu les sections suivantes du livre\r\nde référence JavaNotes\\_\r\n\r\n> - 2 : Programming in the Small I: Names and\r\n> Things\\_\r\n>\r\n> > - 2.5 : Details of Expressions\\_\r\n> > - 2.5.7 : Type Conversion of\r\n> > Strings\\_\r\n>\r\n> - 7 : Arrays\\_\r\n>\r\n> > - 7.1 : Creating and Using Arrays\\_\r\n> > - 7.1.1 : Arrays\\_\r\n> > - 7.1.2 : Using Arrays\\_\r\n> > - 7.1.3 : Array\r\n> > Initialization\\_\r\n> > - 7.2 : Programming With Arrays\\_\r\n> > - 7.2.1 : Arrays and for\r\n> > Loops\\_\r\n> > - 7.2.3 : Array Types in\r\n> > Subroutines\\_\r\n> > - 7.2.4 : Random Access\\_\r\n> > - 7.2.6 : Variable Arity\r\n> > Methods\\_\r\n> > - 7.4 : Searching and Sorting\\_\r\n> > - 7.4.1 : Searching\\_\r\n> > - 7.5 : Multi-dimensional Arrays\\_\r\n> > - 7.5.1 : Creating Two-dimensional\r\n> > Arrays\\_\r\n> > - 7.5.2 : Using Two-dimensional\r\n> > Arrays\\_\r\n>\r\n> - 8 : Correctness, Robustness,\r\n> Efficiency\\_\r\n>\r\n> > - 8.4 : Assertions and\r\n> > Annotations\\_\r\n> > - 8.4.1 : Assertions\\_\r\n\r\nLes sections vues précédemment restent bien entendu d'actualité.\r\n", + "description": "

Mission 5. Tableaux

\r\n

Ces questions supposent que vous avez lu les sections suivantes du livre de référence JavaNotes_

\r\n
\r\n
    \r\n
  • 2 : Programming in the Small I: Names and Things_
  • \r\n
\r\n
\r\n
    \r\n
  • 2.5 : Details of Expressions_\r\n
      \r\n
    • 2.5.7 : Type Conversion of Strings_
    • \r\n
  • \r\n
\r\n
\r\n
    \r\n
  • 7 : Arrays_
  • \r\n
\r\n
\r\n
    \r\n
  • 7.1 : Creating and Using Arrays_\r\n
      \r\n
    • 7.1.1 : Arrays_
    • \r\n
    • 7.1.2 : Using Arrays_
    • \r\n
    • 7.1.3 : Array Initialization_
    • \r\n
  • \r\n
  • 7.2 : Programming With Arrays_\r\n
      \r\n
    • 7.2.1 : Arrays and for Loops_
    • \r\n
    • 7.2.3 : Array Types in Subroutines_
    • \r\n
    • 7.2.4 : Random Access_
    • \r\n
    • 7.2.6 : Variable Arity Methods_
    • \r\n
  • \r\n
  • 7.4 : Searching and Sorting_\r\n
      \r\n
    • 7.4.1 : Searching_
    • \r\n
  • \r\n
  • 7.5 : Multi-dimensional Arrays_\r\n
      \r\n
    • 7.5.1 : Creating Two-dimensional Arrays_
    • \r\n
    • 7.5.2 : Using Two-dimensional Arrays_
    • \r\n
  • \r\n
\r\n
\r\n
    \r\n
  • 8 : Correctness, Robustness, Efficiency_
  • \r\n
\r\n
\r\n
    \r\n
  • 8.4 : Assertions and Annotations_\r\n
      \r\n
    • 8.4.1 : Assertions_
    • \r\n
  • \r\n
\r\n
\r\n
\r\n

Les sections vues précédemment restent bien entendu d'actualité.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -5765,7 +5765,7 @@ }, { "title": "Question de démarrage 1 : Pair.opposite()", - "description": "Maintenant que les objets sont une notion un peu plus familière, nous\r\nallons vous demander de travailler avec des classes en Java, qui ne sont\r\nmaintenant plus de simple conteneurs à méthodes `static`.\r\n\r\nConsidérez la classe `Pair` suivante :\r\n\r\n``` java\r\npublic static class Pair{\r\n private int a; // le premier élément de la paire\r\n private int b; // le second élément de la paire\r\n\r\n /**\r\n * @pre -\r\n * @post crée une paire avec a et b non-initialisés\r\n */\r\n public Pair(){\r\n\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post crée une paire composée de x et y\r\n */\r\n public Pair(int x, int y){\r\n a = x;\r\n b = y;\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post donne au premier élément de la paire la valeur nA\r\n */\r\n public void setA(int nA){\r\n a = nA;\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post donne au second élément de la paire la valeur nB\r\n */\r\n public void setB(int nB){\r\n b = nB;\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post retourne le premier élément de la paire\r\n */\r\n public int getA(){\r\n return a;\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post retourne le second élément de la paire\r\n */\r\n public int getB(){\r\n return b;\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post retourne une nouvelle instance de Pair dont les deux\r\n * éléments sont les opposés de ceux de cette paire-ci.\r\n * L'instance appelante reste inchangée.\r\n */\r\n public Pair opposite(){\r\n // À implémenter\r\n }\r\n}\r\n```\r\n\r\nPrenez le temps d'analyser cette classe, puis, une fois que vous l'aurez\r\nbien comprise, implémentez le corps de la méthode `opposite` de la\r\nclasse pair. Cette méthode renvoie une nouvelle instance de la classe\r\n`Pair` telle que ses variables d'instance, `a` et `b`, valent l'opposé\r\ndes variables `a` et `b` de l'instance qui y fait appel. Voici un\r\nexemple de l'utilisation de cette méthode :\r\n\r\n``` java\r\nPair p,q;\r\np = new Pair();\r\np.setA(10);\r\np.setB(-2);\r\nq = p.opposite();\r\nSystem.out.println(q.getA() + \", \" + q.getB()); // affiche \"-10, 2\"\r\n```\r\n", + "description": "

Maintenant que les objets sont une notion un peu plus familière, nous allons vous demander de travailler avec des classes en Java, qui ne sont maintenant plus de simple conteneurs à méthodes static.

\r\n

Considérez la classe Pair suivante :

\r\n
public static class Pair{\r\n    private int a;    // le premier élément de la paire\r\n    private int b;    // le second élément de la paire\r\n\r\n    /**\r\n     *     @pre     -\r\n     *     @post    crée une paire avec a et b non-initialisés\r\n     */\r\n     public Pair(){\r\n\r\n     }\r\n\r\n    /**\r\n     * @pre    -\r\n     * @post    crée une paire composée de x et y\r\n     */\r\n     public Pair(int x, int y){\r\n        a = x;\r\n        b = y;\r\n     }\r\n\r\n    /**\r\n     * @pre    -\r\n     * @post    donne au premier élément de la paire la valeur nA\r\n     */\r\n     public void setA(int nA){\r\n        a = nA;\r\n     }\r\n\r\n    /**\r\n     * @pre    -\r\n     * @post    donne au second élément de la paire la valeur nB\r\n     */\r\n     public void setB(int nB){\r\n        b = nB;\r\n     }\r\n\r\n    /**\r\n     * @pre     -\r\n     * @post    retourne le premier élément de la paire\r\n     */\r\n     public int getA(){\r\n        return a;\r\n     }\r\n\r\n    /**\r\n     * @pre    -\r\n     * @post    retourne le second élément de la paire\r\n     */\r\n     public int getB(){\r\n        return b;\r\n     }\r\n\r\n    /**\r\n     * @pre        -\r\n     * @post    retourne une nouvelle instance de Pair dont les deux\r\n     *             éléments sont les opposés de ceux de cette paire-ci.\r\n     *            L'instance appelante reste inchangée.\r\n     */\r\n     public Pair opposite(){\r\n         // À implémenter\r\n     }\r\n}
\r\n

Prenez le temps d'analyser cette classe, puis, une fois que vous l'aurez bien comprise, implémentez le corps de la méthode opposite de la classe pair. Cette méthode renvoie une nouvelle instance de la classe Pair telle que ses variables d'instance, a et b, valent l'opposé des variables a et b de l'instance qui y fait appel. Voici un exemple de l'utilisation de cette méthode :

\r\n
Pair p,q;\r\np = new Pair();\r\np.setA(10);\r\np.setB(-2);\r\nq = p.opposite();\r\nSystem.out.println(q.getA() +  ", " + q.getB());    // affiche "-10, 2"
\r\n", "tags": [ { "text": "INGINIOUS", @@ -5819,7 +5819,7 @@ }, { "title": "Question de démarrage 2 : OrderedPair", - "description": "Considérez maintenant la classe `OrderedPair`, qui prend comme variable\r\nd'instance un objet de type `Pair` dont la classe se trouve dans la\r\nqueston précédente. Voici la classe `OrderedPair` :\r\n\r\n``` java\r\npublic class OrderedPair {\r\n\r\n private boolean ordered; /* vrai si p est ordonnée */\r\n /* p.getA() <= p.getB() */\r\n private Pair p;\r\n\r\n /**\r\n * @pre -\r\n * @post crée un paire ordonnée (0,0)\r\n */\r\n public OrderedPair() {\r\n p = new Pair(0, 0);\r\n ordered = true;\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post donne au premier élément de la paire la valeur nA\r\n */\r\n public void setA(int nA) {\r\n // À implémenter\r\n }\r\n /**\r\n * @pre -\r\n * @post donne au second élément de la paire la valeur nB\r\n */\r\n public void setB(int nB) {\r\n // À implémenter\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post donne à la variable ordered la valeur nOrdered\r\n */\r\n public void setOrdered(boolean nOrdered){\r\n /* Pas donné */\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post retourne vrai si la paire est ordonnée, faux sinon\r\n */\r\n public boolean getOrdered() {\r\n return ordered;\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post retourne le premier élément de la paire\r\n */\r\n public int getA() {\r\n return p.getA();\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post retourne le second élément de la paire\r\n */\r\n public int getB() {\r\n return p.getB();\r\n }\r\n}\r\n```\r\n\r\nLe but de l'exercice est d'implémenter les méthodes `setA()` et `setB()`\r\nsans oublier de mettre à jour `ordered` en fonction des nouvelles\r\nvaleurs des nombres dans la paire.\r\n", + "description": "

Considérez maintenant la classe OrderedPair, qui prend comme variable d'instance un objet de type Pair dont la classe se trouve dans la queston précédente. Voici la classe OrderedPair :

\r\n
public class OrderedPair {\r\n\r\n    private boolean ordered;  /* vrai si p est ordonnée */\r\n                            /* p.getA() <= p.getB() */\r\n    private Pair p;\r\n\r\n    /**\r\n     * @pre -\r\n     * @post crée un paire ordonnée (0,0)\r\n     */\r\n    public OrderedPair() {\r\n      p = new Pair(0, 0);\r\n      ordered = true;\r\n    }\r\n\r\n    /**\r\n     * @pre -\r\n     * @post donne au premier élément de la paire la valeur nA\r\n     */\r\n    public void setA(int nA) {\r\n      // À implémenter\r\n    }\r\n    /**\r\n     * @pre -\r\n     * @post donne au second élément de la paire la valeur nB\r\n     */\r\n    public void setB(int nB) {\r\n      // À implémenter\r\n    }\r\n\r\n    /**\r\n     * @pre    -\r\n     * @post donne à la variable ordered la valeur nOrdered\r\n     */\r\n     public void setOrdered(boolean nOrdered){\r\n         /* Pas donné */\r\n     }\r\n\r\n    /**\r\n     * @pre -\r\n     * @post retourne vrai si la paire est ordonnée, faux sinon\r\n     */\r\n    public boolean getOrdered() {\r\n      return ordered;\r\n    }\r\n\r\n    /**\r\n     * @pre -\r\n     * @post retourne le premier élément de la paire\r\n     */\r\n    public int getA() {\r\n      return p.getA();\r\n    }\r\n\r\n    /**\r\n     * @pre -\r\n     * @post retourne le second élément de la paire\r\n     */\r\n    public int getB() {\r\n      return p.getB();\r\n    }\r\n}
\r\n

Le but de l'exercice est d'implémenter les méthodes setA() et setB() sans oublier de mettre à jour ordered en fonction des nouvelles valeurs des nombres dans la paire.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -5873,7 +5873,7 @@ }, { "title": "Question de démarrage 3 : Drapeau.same()", - "description": "Un étudiant a écrit la classe `Drapeau` ci-dessous. Il aimerait y\r\najouter la méthode `same` permettant de savoir si deux objets `Drapeau`\r\nsont dans le même état, mais il ne sait pas bien comment s'y prendre et\r\nvous demande votre aide pour y arriver.\r\n\r\nVoici la classe `Drapeau` :\r\n\r\n``` java\r\n/**\r\n * Une classe simple avec un objet contenant un booleen\r\n */\r\n\r\npublic static class Drapeau {\r\n private boolean drapeau; // la valeur du drapeau\r\n\r\n // Constructeur\r\n /**\r\n * @pre : -\r\n * @post : un objet de type Drapeau est cree et\r\n * represente le booleen passe en argument\r\n */\r\n public Drapeau(boolean b) {\r\n drapeau = b;\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post le drapeau vaut b\r\n */\r\n public void set(boolean b) {\r\n drapeau = b;\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post retourne la valeur du drapeau\r\n */\r\n public boolean get() {\r\n return drapeau;\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post Retourne true si d.get() == this.get().\r\n * Retourne false sinon\r\n */\r\n public boolean same(Drapeau d){\r\n // À implémenter\r\n }\r\n}\r\n```\r\n\r\nAidez cet étudiant en détresse et implémentez la méthode `same` dont les\r\nspécifications sont fournies ci-dessus. Pensez à gérer le cas où\r\n`d == null`, car les préconditions ne font aucune supposition.\r\n", + "description": "

Un étudiant a écrit la classe Drapeau ci-dessous. Il aimerait y ajouter la méthode same permettant de savoir si deux objets Drapeau sont dans le même état, mais il ne sait pas bien comment s'y prendre et vous demande votre aide pour y arriver.

\r\n

Voici la classe Drapeau :

\r\n
/**\r\n * Une classe simple avec un objet contenant un booleen\r\n */\r\n\r\npublic static class Drapeau {\r\n    private boolean drapeau; // la valeur du drapeau\r\n\r\n    // Constructeur\r\n    /**\r\n     * @pre : -\r\n     * @post : un objet de type Drapeau est cree et\r\n     *            represente le booleen passe en argument\r\n     */\r\n    public Drapeau(boolean b) {\r\n        drapeau = b;\r\n    }\r\n\r\n    /**\r\n     * @pre -\r\n     * @post le drapeau vaut b\r\n     */\r\n    public void set(boolean b) {\r\n        drapeau = b;\r\n    }\r\n\r\n    /**\r\n     * @pre -\r\n     * @post retourne la valeur du drapeau\r\n     */\r\n    public boolean get() {\r\n        return drapeau;\r\n    }\r\n\r\n    /**\r\n     *    @pre     -\r\n     *    @post     Retourne true si d.get() == this.get().\r\n     *            Retourne false sinon\r\n     */\r\n    public boolean same(Drapeau d){\r\n        // À implémenter\r\n    }\r\n}
\r\n

Aidez cet étudiant en détresse et implémentez la méthode same dont les spécifications sont fournies ci-dessus. Pensez à gérer le cas où d == null, car les préconditions ne font aucune supposition.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -5927,7 +5927,7 @@ }, { "title": "Question de démarrage 4 : Lecture de fichiers", - "description": "Depuis le début du cours, la librairie `TextIO`\r\n() vous\r\npermet de lire des messages sur l'entrée standard. Cependant, `TextIO`\r\npermet aussi de lire des fichiers. En analysant la librairie `TextIO`,\r\ncomplétez les deux lignes incomplètes de manière à lire complètement le\r\nfichier `cotes.txt` qui contient les cotes de plusieurs personnes.\r\n\r\nVoici le code à compléter :\r\n\r\n``` java\r\npublic static void lireCotes() {\r\n /*1*/\r\n while (/*2*/) {\r\n String prenom = TextIO.getWord();\r\n String nom = TextIO.getWord();\r\n int cote = TextIO.getInt();\r\n TextIO.getln();\r\n System.out.println(nom + \", \" + prenom + \": \" + cote);\r\n }\r\n System.out.println(\"Le fichier a été lu entièrement.\");\r\n}\r\n```\r\n", + "description": "

Depuis le début du cours, la librairie TextIO (http://math.hws.edu/eck/cs124/javanotes6/source/TextIO.java) vous permet de lire des messages sur l'entrée standard. Cependant, TextIO permet aussi de lire des fichiers. En analysant la librairie TextIO, complétez les deux lignes incomplètes de manière à lire complètement le fichier cotes.txt qui contient les cotes de plusieurs personnes.

\r\n

Voici le code à compléter :

\r\n
public static void lireCotes() {\r\n    /*1*/\r\n    while (/*2*/) {\r\n        String prenom = TextIO.getWord();\r\n        String nom = TextIO.getWord();\r\n        int cote = TextIO.getInt();\r\n        TextIO.getln();\r\n        System.out.println(nom + ", " + prenom + ": " + cote);\r\n    }\r\n    System.out.println("Le fichier a été lu entièrement.");\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -5976,7 +5976,7 @@ }, { "title": "Q* constructeur Date", - "description": "Dans un programme Java, on écrit une classe permettant de représenter\r\nune date. Les variables d'instant de cette classe sont définies comme\r\nsuite :\r\n\r\n``` java\r\n/**\r\n * Une classe pour encoder une date\r\n *\r\n * @author Olivier Bonaventure\r\n * @version Oct. 2016\r\n */\r\npublic class Date{\r\n public int jour; // le jour du mois\r\n public int mois; // le mois\r\n public int annee; // l'année\r\n //...\r\n}\r\n```\r\n\r\nLe constructeur de cette classe a comme spécification :\r\n\r\n``` java\r\n/*\r\n * @pre 1 <= jour <= 31, 1 <= mois <= 12\r\n * @post retourne une date, les mois commencent à 1 pour janvier\r\n * On ne gère pas les années bissextiles, février est supposé toujours\r\n * contenir 28 jours\r\n */\r\n```\r\n\r\nVoici quelques exemples d'utilisation du constructeur :\r\n\r\n``` java\r\nDate poisson = new Date(1,4,2017); // 1er avril 2017\r\nDate noel = new Date(25,12,2016); // 25 décembre 2016\r\n```\r\n\r\nEcrivez le constructeur de cette classe `Date`.\r\n", + "description": "

Dans un programme Java, on écrit une classe permettant de représenter une date. Les variables d'instant de cette classe sont définies comme suite :

\r\n
/**\r\n * Une classe pour encoder une date\r\n *\r\n * @author Olivier Bonaventure\r\n * @version Oct. 2016\r\n */\r\npublic class Date{\r\n  public int jour; // le jour du mois\r\n  public int mois; // le mois\r\n  public int annee; // l'année\r\n  //...\r\n}
\r\n

Le constructeur de cette classe a comme spécification :

\r\n
/*\r\n * @pre 1 <= jour <= 31, 1 <= mois <= 12\r\n * @post retourne une date, les mois commencent à 1 pour janvier\r\n *       On ne gère pas les années bissextiles, février est supposé toujours\r\n *       contenir 28 jours\r\n */
\r\n

Voici quelques exemples d'utilisation du constructeur :

\r\n
Date poisson = new Date(1,4,2017); // 1er avril 2017\r\nDate noel = new Date(25,12,2016); // 25 décembre 2016
\r\n

Ecrivez le constructeur de cette classe Date.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -6030,7 +6030,7 @@ }, { "title": "Q* memeSurface", - "description": "Considérons la classe `Rectangle`:\r\n\r\n``` java\r\n/**\r\n * Un objet Java représentant un rectangle\r\n *\r\n * @author O. Bonaventure\r\n * @version Oct. 2016\r\n */\r\n public class Rectangle{\r\n private double longueur;\r\n private double largeur;\r\n\r\n /**\r\n * @pre long, larg > 0\r\n * @post a construit un rectangle de longueur lon et de largeur larg\r\n */\r\n public Rectangle(double lon, double larg){\r\n longueur = lon;\r\n largeur = larg;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la longueur du rectangle\r\n */\r\n public double getLongueur(){\r\n return longueur;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la largeur du rectangle\r\n */\r\n public double getLargeur(){\r\n return largeur;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la surface du rectangle\r\n */\r\n public double surface(){\r\n // non fourni\r\n }\r\n\r\n /*\r\n * @pre r != null\r\n * @post return true si this et r ont la même surface, false sinon\r\n */\r\n // A compléter\r\n }\r\n```\r\n", + "description": "

Considérons la classe Rectangle:

\r\n
/**\r\n  * Un objet Java représentant un rectangle\r\n  *\r\n  * @author O. Bonaventure\r\n  * @version Oct. 2016\r\n  */\r\n public class Rectangle{\r\n     private double longueur;\r\n     private double largeur;\r\n\r\n     /**\r\n      * @pre long, larg > 0\r\n      * @post a construit un rectangle de longueur lon et de largeur larg\r\n      */\r\n     public Rectangle(double lon, double larg){\r\n         longueur = lon;\r\n         largeur = larg;\r\n     }\r\n\r\n     /*\r\n      * @pre -\r\n      * @post retourne la longueur du rectangle\r\n      */\r\n     public double getLongueur(){\r\n         return longueur;\r\n     }\r\n\r\n     /*\r\n      * @pre -\r\n      * @post retourne la largeur du rectangle\r\n      */\r\n     public double getLargeur(){\r\n         return largeur;\r\n     }\r\n\r\n     /*\r\n      * @pre -\r\n      * @post retourne la surface du rectangle\r\n      */\r\n      public double surface(){\r\n        // non fourni\r\n      }\r\n\r\n     /*\r\n      * @pre r != null\r\n      * @post return true si this et r ont la même surface, false sinon\r\n      */\r\n      // A compléter\r\n }
\r\n", "tags": [ { "text": "INGINIOUS", @@ -6084,7 +6084,7 @@ }, { "title": "Q* rectangle identique", - "description": "Considérons la classe `Rectangle`:\r\n\r\n``` java\r\n/**\r\n * Un objet Java représentant un rectangle\r\n *\r\n * @author O. Bonaventure\r\n * @version Oct. 2016\r\n */\r\n public class Rectangle{\r\n private double longueur;\r\n private double largeur;\r\n\r\n /**\r\n * @pre long, larg > 0\r\n * @post a construit un rectangle de longueur lon et de largeur larg\r\n */\r\n public Rectangle(double lon, double larg){\r\n longueur = lon;\r\n largeur = larg;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la longueur du rectangle\r\n */\r\n public double getLongueur(){\r\n return longueur;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la largeur du rectangle\r\n */\r\n\r\n public double getLargeur(){\r\n return largeur;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la surface du rectangle\r\n */\r\n public double surface(){\r\n // non fourni\r\n }\r\n\r\n /*\r\n * @pre r != null\r\n * @post return true si this et r ont la même surface, false sinon\r\n */\r\n public boolean memeSurface(Rectangle r){\r\n // non fourni\r\n }\r\n\r\n /*\r\n * @pre r != null\r\n * @post return true si this et r sont identiques, false sinon\r\n */\r\n // A compléter\r\n }\r\n```\r\n", + "description": "

Considérons la classe Rectangle:

\r\n
/**\r\n  * Un objet Java représentant un rectangle\r\n  *\r\n  * @author O. Bonaventure\r\n  * @version Oct. 2016\r\n  */\r\n public class Rectangle{\r\n     private double longueur;\r\n     private double largeur;\r\n\r\n     /**\r\n      * @pre long, larg > 0\r\n      * @post a construit un rectangle de longueur lon et de largeur larg\r\n      */\r\n     public Rectangle(double lon, double larg){\r\n         longueur = lon;\r\n         largeur = larg;\r\n     }\r\n\r\n     /*\r\n      * @pre -\r\n      * @post retourne la longueur du rectangle\r\n      */\r\n     public double getLongueur(){\r\n         return longueur;\r\n     }\r\n\r\n     /*\r\n      * @pre -\r\n      * @post retourne la largeur du rectangle\r\n      */\r\n\r\n     public double getLargeur(){\r\n         return largeur;\r\n     }\r\n\r\n     /*\r\n      * @pre -\r\n      * @post retourne la surface du rectangle\r\n      */\r\n     public double surface(){\r\n        // non fourni\r\n     }\r\n\r\n     /*\r\n      * @pre r != null\r\n      * @post return true si this et r ont la même surface, false sinon\r\n      */\r\n     public boolean memeSurface(Rectangle r){\r\n        // non fourni\r\n     }\r\n\r\n     /*\r\n      * @pre r != null\r\n      * @post return true si this et r sont identiques, false sinon\r\n      */\r\n     // A compléter\r\n }
\r\n", "tags": [ { "text": "INGINIOUS", @@ -6138,7 +6138,7 @@ }, { "title": "Q* getters Date", - "description": "Considérons à nouveau la classe `Date` qui permet de représenter une\r\ndate. Le squelette du code de cette classe est le suivant :\r\n\r\n``` java\r\n/**\r\n * Une classe pour encoder une date\r\n *\r\n * @author Olivier Bonaventure\r\n * @version Oct. 2016\r\n */\r\npublic class Date\r\n{\r\n public int jour; // le jour du mois\r\n public int mois; // le mois\r\n public int annee; // l'année\r\n\r\n /*\r\n * @pre 1<= jour <=31, 1<= mois <=12\r\n * @post retourne une date, les mois commencent à 1 pour janvier\r\n * On ne gère pas les années bissextiles, février est supposé toujours\r\n * contenir 28 jours\r\n */\r\n\r\n public Date(int jour, int mois, int annee){\r\n // code non fourni\r\n }\r\n\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le jour\r\n */\r\n public int getJour(){\r\n // a compléter\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le mois (1=janvier, 2=février, ...\r\n */\r\n public int getMois(){\r\n // a compléter\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne l'année\r\n */\r\n public int getAnnee(){\r\n // a compléter\r\n }\r\n```\r\n", + "description": "

Considérons à nouveau la classe Date qui permet de représenter une date. Le squelette du code de cette classe est le suivant :

\r\n
/**\r\n * Une classe pour encoder une date\r\n *\r\n * @author Olivier Bonaventure\r\n * @version Oct. 2016\r\n */\r\npublic class Date\r\n{\r\n public int jour; // le jour du mois\r\n public int mois; // le mois\r\n public int annee; // l'année\r\n\r\n /*\r\n  * @pre 1<= jour <=31, 1<= mois <=12\r\n  * @post retourne une date, les mois commencent à 1 pour janvier\r\n  *       On ne gère pas les années bissextiles, février est supposé toujours\r\n  *       contenir 28 jours\r\n  */\r\n\r\n public Date(int jour, int mois, int annee){\r\n   // code non fourni\r\n }\r\n\r\n\r\n /*\r\n  * @pre -\r\n  * @post retourne le jour\r\n  */\r\n public int getJour(){\r\n    // a compléter\r\n }\r\n\r\n /*\r\n  * @pre -\r\n  * @post retourne le mois (1=janvier, 2=février, ...\r\n  */\r\n public int getMois(){\r\n    // a compléter\r\n }\r\n\r\n /*\r\n  * @pre -\r\n  * @post retourne l'année\r\n  */\r\n public int getAnnee(){\r\n    // a compléter\r\n }
\r\n", "tags": [ { "text": "INGINIOUS", @@ -6192,7 +6192,7 @@ }, { "title": "Q* identique", - "description": "La classe `Date` représente une date. Dans cette classe, écrivez la\r\nméthode `identique` qui permet de tester l'égalité entre deux dates.\r\n\r\n``` java\r\n/**\r\n * Une classe pour encoder une date\r\n *\r\n * @author Olivier Bonaventure\r\n * @version Oct. 2016\r\n */\r\npublic class Date {\r\n public int jour; // le jour du mois\r\n public int mois; // le mois\r\n public int annee; // l'année\r\n\r\n /*\r\n * @pre 1<= jour <=31, 1<= mois <=12\r\n * @post retourne une date, les mois commencent à 1 pour janvier\r\n * On ne gère pas les années bissextiles, février est supposé toujours\r\n * contenir 28 jours\r\n */\r\n\r\n public Date(int jour, int mois, int annee) {\r\n // code non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le jour\r\n */\r\n public int getJour() {\r\n // code non fourni\r\n }\r\n\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le mois (1=janvier, 2=février, ...\r\n */\r\n public int getMois() {\r\n // code non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne l'année\r\n */\r\n public int getAnnee() {\r\n // code non fourni\r\n }\r\n\r\n\r\n /*\r\n * @pre d!=null\r\n * @post retourne true si this et d correspondent à la même date, false sinon\r\n */\r\n public boolean identique(Date d) {\r\n // à compléter\r\n }\r\n // ...\r\n}\r\n```\r\n", + "description": "

La classe Date représente une date. Dans cette classe, écrivez la méthode identique qui permet de tester l'égalité entre deux dates.

\r\n
/**\r\n * Une classe pour encoder une date\r\n *\r\n * @author Olivier Bonaventure\r\n * @version Oct. 2016\r\n */\r\npublic class Date {\r\n public int jour; // le jour du mois\r\n public int mois; // le mois\r\n public int annee; // l'année\r\n\r\n /*\r\n  * @pre 1<= jour <=31, 1<= mois <=12\r\n  * @post retourne une date, les mois commencent à 1 pour janvier\r\n  *       On ne gère pas les années bissextiles, février est supposé toujours\r\n  *       contenir 28 jours\r\n  */\r\n\r\n public Date(int jour, int mois, int annee) {\r\n     // code non fourni\r\n }\r\n\r\n /*\r\n  * @pre -\r\n  * @post retourne le jour\r\n  */\r\n public int getJour() {\r\n     // code non fourni\r\n }\r\n\r\n\r\n /*\r\n  * @pre -\r\n  * @post retourne le mois (1=janvier, 2=février, ...\r\n  */\r\n public int getMois() {\r\n     // code non fourni\r\n }\r\n\r\n /*\r\n  * @pre -\r\n  * @post retourne l'année\r\n  */\r\n public int getAnnee() {\r\n     // code non fourni\r\n }\r\n\r\n\r\n /*\r\n  * @pre d!=null\r\n  * @post retourne true si this et d correspondent à la même date, false sinon\r\n  */\r\n public boolean identique(Date d) {\r\n   // à compléter\r\n }\r\n // ...\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -6246,7 +6246,7 @@ }, { "title": "Q* demain", - "description": "La classe `Date` représente une date. Dans cette classe, écrivez la\r\nméthode `demain` qui permet de retourner la date qui suit celle-ci.\r\n\r\n``` java\r\n/**\r\n * Une classe pour encoder une date\r\n *\r\n * @author Olivier Bonaventure\r\n * @version Oct. 2016\r\n */\r\npublic class Date\r\n{\r\n public int jour; // le jour du mois\r\n public int mois; // le mois\r\n public int annee; // l'année\r\n\r\n /*\r\n * @pre 1<= jour <=31, 1<= mois <=12\r\n * @post retourne une date, les mois commencent à 1 pour janvier\r\n * On ne gère pas les années bissextiles, février est supposé toujours\r\n * contenir 28 jours\r\n */\r\n\r\n public Date(int jour, int mois, int annee)\r\n {\r\n // code non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le jour\r\n */\r\n public int getJour()\r\n {\r\n // code non fourni\r\n }\r\n\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le mois (1=janvier, 2=février, ...\r\n */\r\n public int getMois()\r\n {\r\n // code non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne l'année\r\n */\r\n public int getAnnee()\r\n {\r\n // code non fourni\r\n }\r\n\r\n\r\n /*\r\n * @pre d!=null\r\n * @post retourne true si this et d correspondent à la même date, false sinon\r\n */\r\n public boolean identique(Date d) {\r\n // code non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la date correspondant au jour qui suit this. Cette méthode\r\n * ne supporte pas les années bissextiles, février est supposé avoir toujours\r\n * 28 jours.\r\n */\r\n public Date demain() {\r\n // à compléter\r\n }\r\n}\r\n```\r\n", + "description": "

La classe Date représente une date. Dans cette classe, écrivez la méthode demain qui permet de retourner la date qui suit celle-ci.

\r\n
/**\r\n * Une classe pour encoder une date\r\n *\r\n * @author Olivier Bonaventure\r\n * @version Oct. 2016\r\n */\r\npublic class Date\r\n{\r\n public int jour; // le jour du mois\r\n public int mois; // le mois\r\n public int annee; // l'année\r\n\r\n /*\r\n  * @pre 1<= jour <=31, 1<= mois <=12\r\n  * @post retourne une date, les mois commencent à 1 pour janvier\r\n  *       On ne gère pas les années bissextiles, février est supposé toujours\r\n  *       contenir 28 jours\r\n  */\r\n\r\n public Date(int jour, int mois, int annee)\r\n {\r\n     // code non fourni\r\n }\r\n\r\n /*\r\n  * @pre -\r\n  * @post retourne le jour\r\n  */\r\n public int getJour()\r\n {\r\n     // code non fourni\r\n }\r\n\r\n\r\n /*\r\n  * @pre -\r\n  * @post retourne le mois (1=janvier, 2=février, ...\r\n  */\r\n public int getMois()\r\n {\r\n     // code non fourni\r\n }\r\n\r\n /*\r\n  * @pre -\r\n  * @post retourne l'année\r\n  */\r\n public int getAnnee()\r\n {\r\n     // code non fourni\r\n }\r\n\r\n\r\n /*\r\n  * @pre d!=null\r\n  * @post retourne true si this et d correspondent à la même date, false sinon\r\n  */\r\n public boolean identique(Date d) {\r\n   // code non fourni\r\n }\r\n\r\n /*\r\n  * @pre -\r\n  * @post retourne la date correspondant au jour qui suit this. Cette méthode\r\n  *       ne supporte pas les années bissextiles, février est supposé avoir toujours\r\n  *       28 jours.\r\n  */\r\n public Date demain() {\r\n // à compléter\r\n }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -6300,7 +6300,7 @@ }, { "title": "Q* getter", - "description": "Considérons la classe `Fraction` qui permet de représenter une date. Le\r\nsquelette du code de cette classe est le suivant :\r\n\r\n``` java\r\n/**\r\n * Une classe représentant une fraction\r\n *\r\n * @author O. Bonaventure\r\n * @version Oct. 2016\r\n */\r\npublic class Fraction{\r\n private int num; // numerateur\r\n private int den; // denominateur\r\n\r\n /**\r\n * @pre num>=0, den>0\r\n * @post construit la fraction num/den\r\n */\r\n public Fraction(int num, int den){\r\n //code non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le dénominateur de la fraction\r\n */\r\n public int getDen(){\r\n //à compléter\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le numérateur de la fraction\r\n */\r\n public int getNum(){\r\n //à compléter\r\n }\r\n //...\r\n}\r\n```\r\n", + "description": "

Considérons la classe Fraction qui permet de représenter une date. Le squelette du code de cette classe est le suivant :

\r\n
/**\r\n * Une classe représentant une fraction\r\n *\r\n * @author O. Bonaventure\r\n * @version Oct. 2016\r\n */\r\npublic class Fraction{\r\n    private int num; // numerateur\r\n    private int den; // denominateur\r\n\r\n    /**\r\n     * @pre num>=0, den>0\r\n     * @post construit la fraction num/den\r\n     */\r\n    public Fraction(int num, int den){\r\n        //code non fourni\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le dénominateur de la fraction\r\n     */\r\n    public int getDen(){\r\n        //à compléter\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le numérateur de la fraction\r\n     */\r\n    public int getNum(){\r\n        //à compléter\r\n    }\r\n    //...\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -6354,7 +6354,7 @@ }, { "title": "Q* entier", - "description": "Considérons la classe `Fraction` qui permet de représenter une fraction.\r\nLe squelette du code de cette classe est le suivant :\r\n\r\n``` java\r\n/**\r\n * Une classe représentant une fraction\r\n *\r\n * @author O. Bonaventure\r\n * @version Oct. 2016\r\n */\r\npublic class Fraction{\r\n private int num; // numerateur\r\n private int den; // denominateur\r\n\r\n /**\r\n * @pre num>=0, den>0\r\n * @post construit la fraction num/den\r\n */\r\n public Fraction(int num, int den){\r\n //code non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le dénominateur de la fraction\r\n */\r\n public int getDen(){\r\n //code non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le numérateur de la fraction\r\n */\r\n public int getNum(){\r\n //code non fourni\r\n }\r\n /*\r\n * @pre -\r\n * @post retourne true si la valeur numérique de la fraction est égale à une valeur entière\r\n */\r\n //Code à compléter\r\n\r\n}\r\n```\r\n", + "description": "

Considérons la classe Fraction qui permet de représenter une fraction. Le squelette du code de cette classe est le suivant :

\r\n
/**\r\n * Une classe représentant une fraction\r\n *\r\n * @author O. Bonaventure\r\n * @version Oct. 2016\r\n */\r\npublic class Fraction{\r\n    private int num; // numerateur\r\n    private int den; // denominateur\r\n\r\n    /**\r\n     * @pre num>=0, den>0\r\n     * @post construit la fraction num/den\r\n     */\r\n    public Fraction(int num, int den){\r\n        //code non fourni\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le dénominateur de la fraction\r\n     */\r\n    public int getDen(){\r\n        //code non fourni\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le numérateur de la fraction\r\n     */\r\n    public int getNum(){\r\n        //code non fourni\r\n    }\r\n    /*\r\n     * @pre -\r\n     * @post retourne true si la valeur numérique de la fraction est égale à une valeur entière\r\n     */\r\n    //Code à compléter\r\n\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -6408,7 +6408,7 @@ }, { "title": "Q* getters Point", - "description": "Considérons la classe `Point` qui permet de représenter une point. Le\r\nsquelette du code de cette classe est le suivant :\r\n\r\n``` java\r\npublic class Point{\r\n private double x;\r\n private double y;\r\n\r\n /*\r\n * @pre -\r\n * @post a construit le point de coordonnée x,y\r\n */\r\n Point(double x, double y) {\r\n //code non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la coordonnée x du Point this\r\n */\r\n //à compléter\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la coordonnée y du Point this\r\n */\r\n //à compléter\r\n}\r\n```\r\n", + "description": "

Considérons la classe Point qui permet de représenter une point. Le squelette du code de cette classe est le suivant :

\r\n
public class Point{\r\n   private double x;\r\n   private double y;\r\n\r\n   /*\r\n    * @pre -\r\n    * @post a construit le point de coordonnée x,y\r\n    */\r\n   Point(double x, double y) {\r\n    //code non fourni\r\n   }\r\n\r\n   /*\r\n    * @pre -\r\n    * @post retourne la coordonnée x du Point this\r\n    */\r\n   //à compléter\r\n\r\n   /*\r\n    * @pre -\r\n    * @post retourne la coordonnée y du Point this\r\n    */\r\n   //à compléter\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -6462,7 +6462,7 @@ }, { "title": "Q* distance", - "description": "Considérons la classe `Point` qui permet de représenter une point. Le\r\nsquelette du code de cette classe est le suivant :\r\n\r\n``` java\r\npublic class Point{\r\n private double x;\r\n private double y;\r\n\r\n /*\r\n * @pre -\r\n * @post a construit le point de coordonnée x,y\r\n */\r\n Point(double x, double y) {\r\n //code non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la coordonnée x du Point this\r\n *\r\n */\r\n public double getX() {\r\n //code non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la coordonnée y du Point this\r\n */\r\n public double getY() {\r\n //code non fourni\r\n }\r\n\r\n /*\r\n * @pre p!=null\r\n * @post retourne la distance entre this et p\r\n *\r\n * Voir https://fr.wikipedia.org/wiki/Coordonnées_cartésiennes\r\n * pour le rappel de la distance entre deux points\r\n */\r\n //A compléter\r\n}\r\n```\r\n", + "description": "

Considérons la classe Point qui permet de représenter une point. Le squelette du code de cette classe est le suivant :

\r\n
public class Point{\r\n   private double x;\r\n   private double y;\r\n\r\n   /*\r\n    * @pre -\r\n    * @post a construit le point de coordonnée x,y\r\n    */\r\n   Point(double x, double y) {\r\n    //code non fourni\r\n   }\r\n\r\n   /*\r\n    * @pre -\r\n    * @post retourne la coordonnée x du Point this\r\n    *\r\n    */\r\n   public double getX() {\r\n       //code non fourni\r\n   }\r\n\r\n   /*\r\n    * @pre -\r\n    * @post retourne la coordonnée y du Point this\r\n    */\r\n   public double getY() {\r\n       //code non fourni\r\n   }\r\n\r\n   /*\r\n    * @pre p!=null\r\n    * @post retourne la distance entre this et p\r\n    *\r\n    * Voir https://fr.wikipedia.org/wiki/Coordonnées_cartésiennes\r\n    * pour le rappel de la distance entre deux points\r\n    */\r\n    //A compléter\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -6516,7 +6516,7 @@ }, { "title": "Q* surface", - "description": "Considérons la classe `Rectangle`:\r\n\r\n``` java\r\n/**\r\n * Un objet Java représentant un rectangle\r\n *\r\n * @author O. Bonaventure\r\n * @version Oct. 2016\r\n */\r\n public class Rectangle{\r\n private double longueur;\r\n private double largeur;\r\n\r\n /**\r\n * @pre long, larg >0\r\n * @post a construit un rectangle de longueur lon et de largeur larg\r\n */\r\n public Rectangle(double lon, double larg){\r\n longueur = lon;\r\n largeur = larg;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la longueur du rectangle\r\n */\r\n public double getLongueur(){\r\n return longueur;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la largeur du rectangle\r\n */\r\n public double getLargeur(){\r\n return largeur;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la surface du rectangle\r\n */\r\n // A compléter\r\n }\r\n```\r\n", + "description": "

Considérons la classe Rectangle:

\r\n
/**\r\n  * Un objet Java représentant un rectangle\r\n  *\r\n  * @author O. Bonaventure\r\n  * @version Oct. 2016\r\n  */\r\n public class Rectangle{\r\n     private double longueur;\r\n     private double largeur;\r\n\r\n     /**\r\n      * @pre long, larg >0\r\n      * @post a construit un rectangle de longueur lon et de largeur larg\r\n      */\r\n     public Rectangle(double lon, double larg){\r\n         longueur = lon;\r\n         largeur = larg;\r\n     }\r\n\r\n     /*\r\n      * @pre -\r\n      * @post retourne la longueur du rectangle\r\n      */\r\n     public double getLongueur(){\r\n         return longueur;\r\n     }\r\n\r\n     /*\r\n      * @pre -\r\n      * @post retourne la largeur du rectangle\r\n      */\r\n     public double getLargeur(){\r\n         return largeur;\r\n     }\r\n\r\n     /*\r\n      * @pre -\r\n      * @post retourne la surface du rectangle\r\n      */\r\n     // A compléter\r\n }
\r\n", "tags": [ { "text": "INGINIOUS", @@ -6570,7 +6570,7 @@ }, { "title": "Phase de réalisation: Soumission", - "description": "Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour\r\nla Mission 6.\r\n\r\nVous attendons une archive **.zip** contenant uniquement les fichiers :\r\n\r\n- TestChanson.java\r\n- TestTemps.java\r\n- TextIO.java\r\n- Chanson.java\r\n- Temps.java\r\n- Programme.java\r\n- README.txt\r\n", + "description": "

Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour la Mission 6.

\r\n

Vous attendons une archive .zip contenant uniquement les fichiers :

\r\n
    \r\n
  • TestChanson.java
  • \r\n
  • TestTemps.java
  • \r\n
  • TextIO.java
  • \r\n
  • Chanson.java
  • \r\n
  • Temps.java
  • \r\n
  • Programme.java
  • \r\n
  • README.txt
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -6619,7 +6619,7 @@ }, { "title": "Question de Bilan Final", - "description": "Écrivez une classe complète `Employe` dont les instances représentent un\r\nemployé d’entreprise. Un employé est caractérisé par son nom (un string)\r\net son salaire (un entier positif). Il doit être possible de créer un\r\nnouvel employé avec un nom et un salaire et d’effectuer les opérations\r\nsuivantes sur un objet Employe :\r\n\r\n- obtenir le nom de l’employé\r\n- obtenir le salaire de l'employé\r\n- obtenir un texte descriptif représentant l’employé sous la forme\r\n `nom : salaire`\r\n- augmenter le salaire de l'employé d'un certain pourcentage\r\n\r\nVous devez donc définir la classe `Employe` qui contiendra les méthodes\r\nsuivantes :\r\n\r\n``` java\r\n/*\r\n * @pre -\r\n * @post Un employé est créé avec le nom et le salaire indiqués en paramètres\r\n */\r\npublic Employe(String n, float s);\r\n\r\n/*\r\n * @pre -\r\n * @post Renvoie le nom de l'employé\r\n */\r\npublic String getNom();\r\n\r\n/*\r\n * @pre -\r\n * @post Renvoie le salaire de l'employé\r\n */\r\npublic float getSalaire();\r\n\r\n/*\r\n * @pre -\r\n * @post Renvoie une représentation textuelle de l'employé\r\n * au format nom : salaire\r\n */\r\npublic String toString();\r\n\r\n/*\r\n * @pre s est un entier représentant le pourcentage d'augmentation\r\n * @post Le salaire de l'employé est augmenté du pourcentage spécifié\r\n * (ex : un pourcentage de 100% double le salaire)\r\n */\r\npublic void augmente(float pourcentage);\r\n```\r\n", + "description": "

Écrivez une classe complète Employe dont les instances représentent un employé d’entreprise. Un employé est caractérisé par son nom (un string) et son salaire (un entier positif). Il doit être possible de créer un nouvel employé avec un nom et un salaire et d’effectuer les opérations suivantes sur un objet Employe :

\r\n
    \r\n
  • obtenir le nom de l’employé
  • \r\n
  • obtenir le salaire de l'employé
  • \r\n
  • obtenir un texte descriptif représentant l’employé sous la forme nom : salaire
  • \r\n
  • augmenter le salaire de l'employé d'un certain pourcentage
  • \r\n
\r\n

Vous devez donc définir la classe Employe qui contiendra les méthodes suivantes :

\r\n
/*\r\n * @pre -\r\n * @post Un employé est créé avec le nom et le salaire indiqués en paramètres\r\n */\r\npublic Employe(String n, float s);\r\n\r\n/*\r\n * @pre -\r\n * @post Renvoie le nom de l'employé\r\n */\r\npublic String getNom();\r\n\r\n/*\r\n * @pre -\r\n * @post Renvoie le salaire de l'employé\r\n */\r\npublic float getSalaire();\r\n\r\n/*\r\n * @pre -\r\n * @post Renvoie une représentation textuelle de l'employé\r\n *       au format nom : salaire\r\n */\r\npublic String toString();\r\n\r\n/*\r\n * @pre s est un entier représentant le pourcentage d'augmentation\r\n * @post Le salaire de l'employé est augmenté du pourcentage spécifié\r\n *       (ex : un pourcentage de 100% double le salaire)\r\n */\r\npublic void augmente(float pourcentage);
\r\n", "tags": [ { "text": "INGINIOUS", @@ -6673,7 +6673,7 @@ }, { "title": "QCM", - "description": "Mission 6. Classes et Objets\r\n============================\r\n\r\nCes questions supposent que vous avez lu les sections suivantes du livre\r\nde référence JavaNotes\\_\r\n\r\n> - 5.1 : Objects, Instance Methods, and\r\n> Instance Variables\\_\r\n> - 5.1.1 : Objects, Classes, and\r\n> Instances\\_\r\n> - 5.1.2 : Fundamentals of\r\n> Objects\\_\r\n> - 5.1.3 : Getters and Setters\\_\r\n> - 5.2 : Constructors and Object\r\n> Initialization\\_\r\n> - 5.2.1 : Initializing Instance\r\n> Variables\\_\r\n> - 5.2.2 : Constructors\\_\r\n> - 5.2.3 : Garbage Collection\\_\r\n> - 5.4 : Programming Example: Card, Hand,\r\n> Deck\\_\r\n> - 5.4.1 : Designing the classes\\_\r\n> - 5.4.2 : The Card Class\\_\r\n> - 5.4.3 : Example: A Simple Card\r\n> Game\\_\r\n\r\nainsi que l'API de la classe `TextIO`\\_. Les sections vues précédemment\r\nrestent bien entendu d'actualité.\r\n", + "description": "

Mission 6. Classes et Objets

\r\n

Ces questions supposent que vous avez lu les sections suivantes du livre de référence JavaNotes_

\r\n
\r\n
    \r\n
  • 5.1 : Objects, Instance Methods, and Instance Variables_\r\n
      \r\n
    • 5.1.1 : Objects, Classes, and Instances_
    • \r\n
    • 5.1.2 : Fundamentals of Objects_
    • \r\n
    • 5.1.3 : Getters and Setters_
    • \r\n
  • \r\n
  • 5.2 : Constructors and Object Initialization_\r\n
      \r\n
    • 5.2.1 : Initializing Instance Variables_
    • \r\n
    • 5.2.2 : Constructors_
    • \r\n
    • 5.2.3 : Garbage Collection_
    • \r\n
  • \r\n
  • 5.4 : Programming Example: Card, Hand, Deck_\r\n
      \r\n
    • 5.4.1 : Designing the classes_
    • \r\n
    • 5.4.2 : The Card Class_
    • \r\n
    • 5.4.3 : Example: A Simple Card Game_
    • \r\n
  • \r\n
\r\n
\r\n

ainsi que l'API de la classe TextIO_. Les sections vues précédemment restent bien entendu d'actualité.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -6722,7 +6722,7 @@ }, { "title": "Question de Démarrage 1 : Paire d'entiers", - "description": "Considérez la classe `Pair` suivante :\r\n\r\nDéfinissez une méthode `equals` pour cette classe, **qui re-définit\r\ncelle de la classe**\r\n[Object](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html)\r\ntelle que deux paires sont égales si leur deux composantes sont égales.\r\n", + "description": "

Considérez la classe Pair suivante :

\r\n

Définissez une méthode equals pour cette classe, qui re-définit celle de la classe Object telle que deux paires sont égales si leur deux composantes sont égales.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -6776,7 +6776,7 @@ }, { "title": "Question de Démarrage 2 : Tickets de Parking", - "description": "> Complétez la classe `Ticket` ci-dessous :\r\n", + "description": "
\r\n

Complétez la classe Ticket ci-dessous :

\r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -6830,7 +6830,7 @@ }, { "title": "Q* Employe - Méthode equals", - "description": "On vous donne la classe Employe dont voici le corps :\r\n\r\n``` java\r\npublic class Employe{\r\n private String nom ;\r\n private double salaire ;\r\n\r\n /*\r\n * Constructeur\r\n * @pre nom != null, salaire > 0\r\n * @post a construit une instance de la classe Employe avec nom et salaire\r\n */\r\n public Employe ( String nom, double salaire){\r\n this.nom = nom ;\r\n this.salaire = salaire ;\r\n }\r\n /*\r\n * @pre -\r\n * @post retourne le nom de l'employé this\r\n */\r\n public String getNom(){\r\n return nom ;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le salaire de l'employé this\r\n */\r\n public double getSalaire() {\r\n return salaire ;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne un String décrivant l'employé this\r\n */\r\n public String toString() {\r\n //Non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true si this et other sont deux employés qui ont le même nom et le même salaire\r\n */\r\n public boolean equals(Object other){\r\n //A compléter\r\n }\r\n}\r\n```\r\n", + "description": "

On vous donne la classe Employe dont voici le corps :

\r\n
public class Employe{\r\n  private String nom ;\r\n  private double salaire ;\r\n\r\n  /*\r\n   * Constructeur\r\n   * @pre nom != null, salaire > 0\r\n   * @post a construit une instance de la classe Employe avec nom et salaire\r\n   */\r\n  public Employe ( String nom, double salaire){\r\n      this.nom = nom ;\r\n      this.salaire = salaire ;\r\n  }\r\n  /*\r\n   * @pre -\r\n   * @post retourne le nom de l'employé this\r\n   */\r\n  public String getNom(){\r\n      return nom ;\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne le salaire de l'employé this\r\n   */\r\n  public double getSalaire() {\r\n      return salaire ;\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne un String décrivant l'employé this\r\n   */\r\n  public String toString() {\r\n      //Non fourni\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne true si this et other sont deux employés qui ont le même nom et le même salaire\r\n   */\r\n  public boolean equals(Object other){\r\n      //A compléter\r\n  }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -6884,7 +6884,7 @@ }, { "title": "Q* DeStats - toString", - "description": "On vous donne la classe DeStats dont voici le corps:\r\n\r\n``` java\r\npublic class DeStats extends De {\r\n\r\n private int lances;\r\n private int[] resultats;\r\n\r\n /*\r\n * @pre s != null;\r\n * @post Crée une instance de la classe DeStats\r\n * avec comme nom s\r\n */\r\n public DeStats(String s) {\r\n /* Code non fourni */\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le tableau des résultats du dé this\r\n */\r\n public int[] getResultats() {\r\n // A complèter\r\n }\r\n\r\n /*\r\n * @pre 1 <= n <= 6\r\n * @post retourne le nombre de fois que le dé\r\n * a donné comme résultat n\r\n */\r\n public int statistique(int n) {\r\n return this.resultat[n-1];\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post incrémente le nombre de lancés et le\r\n * nombre de fois qu'un chiffre est sorti.\r\n * Retourne le chiffre que le dé a donné.\r\n */\r\n public int lance() {\r\n /* Code non fourni */\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le nombre de lancés du dé this\r\n */\r\n public int getLances() {\r\n return this.lances;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne une description du dé sous forme\r\n * d'un String. Le format retourné est le nom du\r\n * dé suivi des statistique.\r\n * Par exemple, le dé avec le nom \"Dé\", 10 lancés\r\n * et 10 fois le 2 aurait comme représentation en String\r\n * \"Dé 10 [0, 10, 0, 0, 0, 0]\"\r\n */\r\n public String toString() {\r\n // A complèter\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true si this et o sont deux DeStats identiques\r\n */\r\n public boolean equals(Object o) {\r\n /* Code non fourni */\r\n }\r\n}\r\n```\r\n\r\nPour information, la classe De ressemble à ceci :\r\n\r\n``` java\r\nimport java.util.Random;\r\n\r\npublic class De {\r\n private String nom; // le nom de ce dé (par exemple sa couleur)\r\n protected Random r; // nombre aléatoire\r\n\r\n /*\r\n * @pre nom != null\r\n * @post crée l'instance de la classe De ayant comme nom la chaine n\r\n * initilisé le générateur de nombres aléatoires\r\n */\r\n public De(String n) {\r\n nom = n;\r\n r = new Random();\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post lance le dé et retourne la valeur du dé\r\n */\r\n public int lance() {\r\n return r.nextInt(6)+1;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le générateur de nombres aléatoires utilisé par le dé\r\n */\r\n public Random getRandom() {\r\n return r;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le nom du dé\r\n */\r\n public String getNom(){\r\n return nom;\r\n }\r\n\r\n /*\r\n * @pre n != null\r\n * @post modifie le nom du dé qui est maintenant n\r\n */\r\n public void setNom(String n){\r\n this.nom = n;\r\n }\r\n\r\n /*\r\n * @pre r != null\r\n * @post modifie le générateur de nombres aléatoires du dé qui est maintenant r\r\n */\r\n public void setRandom(Random r){\r\n this.r = r;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne une chaîne de caractères représentant le dé\r\n */\r\n public String toString(){\r\n return this.nom;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true ssi other est un dé identique à celui-ci (même nom et même générateur aléatoire)\r\n */\r\n public boolean equals(Object other) {\r\n /* Code non fourni */\r\n }\r\n}\r\n```\r\n", + "description": "

On vous donne la classe DeStats dont voici le corps:

\r\n
public class DeStats extends De {\r\n\r\n    private int lances;\r\n    private int[] resultats;\r\n\r\n    /*\r\n     * @pre s != null;\r\n     * @post Crée une instance de la classe DeStats\r\n     *       avec comme nom s\r\n     */\r\n    public DeStats(String s) {\r\n        /* Code non fourni */\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le tableau des résultats du dé this\r\n     */\r\n    public int[] getResultats() {\r\n        // A complèter\r\n    }\r\n\r\n    /*\r\n     * @pre 1 <= n <= 6\r\n     * @post retourne le nombre de fois que le dé\r\n     *       a donné comme résultat n\r\n     */\r\n    public int statistique(int n) {\r\n        return this.resultat[n-1];\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post incrémente le nombre de lancés et le\r\n     *       nombre de fois qu'un chiffre est sorti.\r\n     *       Retourne le chiffre que le dé a donné.\r\n     */\r\n    public int lance() {\r\n        /* Code non fourni */\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le nombre de lancés du dé this\r\n     */\r\n    public int getLances() {\r\n        return this.lances;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne une description du dé sous forme\r\n     *       d'un String. Le format retourné est le nom du\r\n     *       dé suivi des statistique.\r\n     *       Par exemple, le dé avec le nom "Dé", 10 lancés\r\n     *       et 10 fois le 2 aurait comme représentation en String\r\n     *       "Dé 10 [0, 10, 0, 0, 0, 0]"\r\n     */\r\n    public String toString() {\r\n        // A complèter\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne true si this et o sont deux DeStats identiques\r\n     */\r\n    public boolean equals(Object o) {\r\n        /* Code non fourni */\r\n    }\r\n}
\r\n

Pour information, la classe De ressemble à ceci :

\r\n
import java.util.Random;\r\n\r\npublic class De {\r\n    private String nom; // le nom de ce dé (par exemple sa couleur)\r\n    protected Random r; // nombre aléatoire\r\n\r\n    /*\r\n     * @pre nom != null\r\n     * @post crée l'instance de la classe De ayant comme nom la chaine n\r\n     *      initilisé le générateur de nombres aléatoires\r\n     */\r\n    public De(String n) {\r\n        nom = n;\r\n        r = new Random();\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post lance le dé et retourne la valeur du dé\r\n     */\r\n    public int lance() {\r\n        return r.nextInt(6)+1;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le générateur de nombres aléatoires utilisé par le dé\r\n     */\r\n    public Random getRandom() {\r\n        return r;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le nom du dé\r\n     */\r\n    public String getNom(){\r\n        return nom;\r\n    }\r\n\r\n    /*\r\n     * @pre n != null\r\n     * @post modifie le nom du dé qui est maintenant n\r\n     */\r\n    public void setNom(String n){\r\n        this.nom = n;\r\n    }\r\n\r\n    /*\r\n     * @pre r != null\r\n     * @post modifie le générateur de nombres aléatoires du dé qui est maintenant r\r\n     */\r\n    public void setRandom(Random r){\r\n        this.r = r;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne une chaîne de caractères représentant le dé\r\n     */\r\n    public String toString(){\r\n        return this.nom;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne true ssi other est un dé identique à celui-ci (même nom et même générateur aléatoire)\r\n     */\r\n    public boolean equals(Object other) {\r\n        /* Code non fourni */\r\n    }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -6938,7 +6938,7 @@ }, { "title": "Q* DeStats - equals", - "description": "On vous donne la classe DeStats dont voici le corps:\r\n\r\n``` java\r\npublic class DeStats extends De {\r\n\r\n private int lances;\r\n private int[] resultats;\r\n\r\n /*\r\n * @pre s != null;\r\n * @post Crée une instance de la classe DeStats\r\n * avec comme nom s\r\n */\r\n public DeStats(String s) {\r\n /* Code non fourni */\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le tableau des résultats du dé this\r\n */\r\n public int[] getResultats() {\r\n /* Code non fourni */\r\n }\r\n\r\n /*\r\n * @pre 1 <= n <= 6\r\n * @post retourne le nombre de fois que le dé\r\n * a donné comme résultat n\r\n */\r\n public int statistique(int n) {\r\n return this.resultat[n-1];\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post incrémente le nombre de lancés et le\r\n * nombre de fois qu'un chiffre est sorti.\r\n * Retourne le chiffre que le dé a donné.\r\n */\r\n public int lance() {\r\n /* Code non fourni */\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le nombre de lancés du dé this\r\n */\r\n public int getLances() {\r\n return this.lances;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne une description du dé sous forme\r\n * d'un String. Le format retourné est le nom du\r\n * dé suivi des statistique sous forme de tableau\r\n */\r\n public String toString() {\r\n /* Code non fourni */\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true si this et o sont deux DeStats identiques\r\n */\r\n public boolean equals(Object o) {\r\n // A complèter\r\n }\r\n}\r\n```\r\n\r\nPour information, la classe De ressemble à ceci :\r\n\r\n``` java\r\nimport java.util.Random;\r\n\r\npublic class De {\r\n private String nom; // le nom de ce dé (par exemple sa couleur)\r\n protected Random r; // nombre aléatoire\r\n\r\n /*\r\n * @pre nom != null\r\n * @post crée l'instance de la classe De ayant comme nom la chaine n\r\n * initilisé le générateur de nombres aléatoires\r\n */\r\n public De(String n) {\r\n nom = n;\r\n r = new Random();\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post lance le dé et retourne la valeur du dé\r\n */\r\n public int lance() {\r\n return r.nextInt(6)+1;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le générateur de nombres aléatoires utilisé par le dé\r\n */\r\n public Random getRandom() {\r\n return r;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le nom du dé\r\n */\r\n public String getNom(){\r\n return nom;\r\n }\r\n\r\n /*\r\n * @pre n != null\r\n * @post modifie le nom du dé qui est maintenant n\r\n */\r\n public void setNom(String n){\r\n this.nom = n;\r\n }\r\n\r\n /*\r\n * @pre r != null\r\n * @post modifie le générateur de nombres aléatoires du dé qui est maintenant r\r\n */\r\n public void setRandom(Random r){\r\n this.r = r;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne une chaîne de caractères représentant le dé\r\n */\r\n public String toString(){\r\n return this.nom;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true ssi other est un dé identique à celui-ci (même nom et même générateur aléatoire)\r\n */\r\n public boolean equals(Object other) {\r\n /* Code non fourni */\r\n }\r\n}\r\n```\r\n", + "description": "

On vous donne la classe DeStats dont voici le corps:

\r\n
public class DeStats extends De {\r\n\r\n    private int lances;\r\n    private int[] resultats;\r\n\r\n    /*\r\n     * @pre s != null;\r\n     * @post Crée une instance de la classe DeStats\r\n     *       avec comme nom s\r\n     */\r\n    public DeStats(String s) {\r\n        /* Code non fourni */\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le tableau des résultats du dé this\r\n     */\r\n    public int[] getResultats() {\r\n        /* Code non fourni */\r\n    }\r\n\r\n    /*\r\n     * @pre 1 <= n <= 6\r\n     * @post retourne le nombre de fois que le dé\r\n     *       a donné comme résultat n\r\n     */\r\n    public int statistique(int n) {\r\n        return this.resultat[n-1];\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post incrémente le nombre de lancés et le\r\n     *       nombre de fois qu'un chiffre est sorti.\r\n     *       Retourne le chiffre que le dé a donné.\r\n     */\r\n    public int lance() {\r\n        /* Code non fourni */\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le nombre de lancés du dé this\r\n     */\r\n    public int getLances() {\r\n        return this.lances;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne une description du dé sous forme\r\n     *       d'un String. Le format retourné est le nom du\r\n     *       dé suivi des statistique sous forme de tableau\r\n     */\r\n    public String toString() {\r\n        /* Code non fourni */\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne true si this et o sont deux DeStats identiques\r\n     */\r\n    public boolean equals(Object o) {\r\n        // A complèter\r\n    }\r\n}
\r\n

Pour information, la classe De ressemble à ceci :

\r\n
import java.util.Random;\r\n\r\npublic class De {\r\n    private String nom; // le nom de ce dé (par exemple sa couleur)\r\n    protected Random r; // nombre aléatoire\r\n\r\n    /*\r\n     * @pre nom != null\r\n     * @post crée l'instance de la classe De ayant comme nom la chaine n\r\n     *      initilisé le générateur de nombres aléatoires\r\n     */\r\n    public De(String n) {\r\n        nom = n;\r\n        r = new Random();\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post lance le dé et retourne la valeur du dé\r\n     */\r\n    public int lance() {\r\n        return r.nextInt(6)+1;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le générateur de nombres aléatoires utilisé par le dé\r\n     */\r\n    public Random getRandom() {\r\n        return r;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le nom du dé\r\n     */\r\n    public String getNom(){\r\n        return nom;\r\n    }\r\n\r\n    /*\r\n     * @pre n != null\r\n     * @post modifie le nom du dé qui est maintenant n\r\n     */\r\n    public void setNom(String n){\r\n        this.nom = n;\r\n    }\r\n\r\n    /*\r\n     * @pre r != null\r\n     * @post modifie le générateur de nombres aléatoires du dé qui est maintenant r\r\n     */\r\n    public void setRandom(Random r){\r\n        this.r = r;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne une chaîne de caractères représentant le dé\r\n     */\r\n    public String toString(){\r\n        return this.nom;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne true ssi other est un dé identique à celui-ci (même nom et même générateur aléatoire)\r\n     */\r\n    public boolean equals(Object other) {\r\n        /* Code non fourni */\r\n    }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -6992,7 +6992,7 @@ }, { "title": "Q* Employe - Méthode toString", - "description": "On vous donne la classe Employe dont voici le corps:\r\n\r\n``` java\r\npublic class Employe{\r\n private String nom ;\r\n private double salaire ;\r\n\r\n /*\r\n * Constructeur\r\n * @pre nom != null, salaire > 0\r\n * @post a construit une instance de la classe Employe avec nom et salaire\r\n */\r\n public Employe ( String nom, double salaire){\r\n this.nom = nom ;\r\n this.salaire = salaire ;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le nom de l'employé this\r\n */\r\n public String getNom(){\r\n return nom ;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le salaire de l'employé this\r\n */\r\n public double getSalaire() {\r\n return salaire ;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne un String décrivant l'employé this\r\n */\r\n public String toString() {\r\n // A compléter\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true si this et other sont deux employés qui ont le même nom et le même salaire\r\n */\r\n public boolean equals(Object other){\r\n // Non fourni\r\n }\r\n}\r\n```\r\n", + "description": "

On vous donne la classe Employe dont voici le corps:

\r\n
public class Employe{\r\n  private String nom ;\r\n  private double salaire ;\r\n\r\n  /*\r\n   * Constructeur\r\n   * @pre nom != null, salaire > 0\r\n   * @post a construit une instance de la classe Employe avec nom et salaire\r\n   */\r\n  public Employe ( String nom, double salaire){\r\n      this.nom = nom ;\r\n      this.salaire = salaire ;\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne le nom de l'employé this\r\n   */\r\n  public String getNom(){\r\n      return nom ;\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne le salaire de l'employé this\r\n   */\r\n  public double getSalaire() {\r\n      return salaire ;\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne un String décrivant l'employé this\r\n   */\r\n  public String toString() {\r\n      // A compléter\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne true si this et other sont deux employés qui ont le même nom et le même salaire\r\n   */\r\n  public boolean equals(Object other){\r\n      // Non fourni\r\n  }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -7046,7 +7046,7 @@ }, { "title": "Q* Dé - Méthode equals", - "description": "On vous donne la classe De dont voici le corps :\r\n\r\n``` java\r\nimport java.util.Random;\r\n\r\npublic class De{\r\n private String nom; // le nom de ce dé (par exemple sa couleur)\r\n protected Random r ; // nombre aléatoire\r\n\r\n /*\r\n * @pre nom != null\r\n * @post a créé l'instance de la classe De ayant comme nom la chaine n, a initilisé\r\n * le générateur de nombres aléatoires\r\n */\r\n public De(String n){\r\n nom = n;\r\n r = new Random();\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post a lance le dé et retourne la valeur du dé\r\n */\r\n public int lance(){\r\n return r.nextInt(6)+1;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le générateur de nombres aléatoires utilisé par le dé\r\n */\r\n public Random getRandom(){\r\n return r;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le nom du dé\r\n */\r\n public String getNom(){\r\n return nom;\r\n }\r\n\r\n /*\r\n * @pre n!=null\r\n * @post a modifié le nom du dé qui est maintenant n\r\n */\r\n public void setNom(String n){\r\n this.nom = n;\r\n }\r\n\r\n /*\r\n * @pre r!=null\r\n * @post a modifié le générateur de nombres aléatoires du dé qui est maintenant r\r\n */\r\n public void setRandom(Random r){\r\n this.r = r;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne une chaîne de caractères représentant le dé\r\n */\r\n public String toString(){\r\n return this.nom;\r\n }\r\n\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true ssi other est un dé identique à celui-ci (même nom et même générateur aléatoire)\r\n */\r\n public boolean equals(Object other) {\r\n // A compléter\r\n }\r\n}\r\n```\r\n", + "description": "

On vous donne la classe De dont voici le corps :

\r\n
import java.util.Random;\r\n\r\npublic class De{\r\n  private String nom; // le nom de ce dé (par exemple sa couleur)\r\n  protected Random r ; // nombre aléatoire\r\n\r\n  /*\r\n   * @pre nom != null\r\n   * @post a créé l'instance de la classe De ayant comme nom la chaine n, a initilisé\r\n   *       le générateur de nombres aléatoires\r\n   */\r\n  public De(String n){\r\n      nom = n;\r\n      r = new Random();\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post a lance le dé et retourne la valeur du dé\r\n   */\r\n  public int lance(){\r\n      return r.nextInt(6)+1;\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne le générateur de nombres aléatoires utilisé par le dé\r\n   */\r\n  public Random getRandom(){\r\n      return r;\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne le nom du dé\r\n   */\r\n  public String getNom(){\r\n      return nom;\r\n  }\r\n\r\n  /*\r\n   * @pre n!=null\r\n   * @post a modifié le nom du dé qui est maintenant n\r\n   */\r\n  public void setNom(String n){\r\n      this.nom = n;\r\n  }\r\n\r\n  /*\r\n   * @pre r!=null\r\n   * @post a modifié le générateur de nombres aléatoires du dé qui est maintenant r\r\n   */\r\n  public void setRandom(Random r){\r\n      this.r = r;\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne une chaîne de caractères représentant le dé\r\n   */\r\n  public String toString(){\r\n      return this.nom;\r\n  }\r\n\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne true ssi other est un dé identique à celui-ci (même nom et même générateur aléatoire)\r\n   */\r\n  public boolean equals(Object other) {\r\n      // A compléter\r\n  }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -7100,7 +7100,7 @@ }, { "title": "Q* Directeur - Constructeur", - "description": "On vous donne la classe Directeur dont voici le corps:\r\n\r\n``` java\r\npublic class Directeur extends Employe{\r\n private double prime; // en pourcents du salaire\r\n\r\n /*\r\n * Constructeur\r\n * @pre nom != null, salaire > 0, 0 <= prime < 1\r\n * @post a construit une instance de la classe Directeur\r\n */\r\n public Directeur(String nom, double salaire, double prime){\r\n //a compléter\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la salaire du directeur. Ce salaire est (1+prime)*salaire\r\n */\r\n public double getSalaire() {\r\n // non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true si this et other sont identiques\r\n * (même nom, même salaire, même prime)\r\n */\r\n public boolean equals(Object other){\r\n // non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la prime de ce directeur\r\n */\r\n public double getPrime() {\r\n // code non fourni\r\n }\r\n}\r\n```\r\n\r\nPour information, la classe Employé ressemble à ceci :\r\n\r\n``` java\r\npublic class Employe{\r\n private String nom ;\r\n private double salaire ;\r\n\r\n /*\r\n * Constructeur\r\n * @pre nom != null, salaire > 0\r\n * @post a construit une instance de la classe Employe avec nom et salaire\r\n */\r\n public Employe (String nom, double salaire){\r\n this.nom = nom ;\r\n this.salaire = salaire ;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le nom de l'employé this\r\n */\r\n public String getNom(){\r\n return nom ;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le salaire de l'employé this\r\n */\r\n public double getSalaire() {\r\n return salaire ;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne un String décrivant l'employé this\r\n */\r\n public String toString() {\r\n // Non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true si this et other sont deux employés\r\n * qui ont le même nom et le même salaire\r\n */\r\n public boolean equals(Object other){\r\n // Non fourni\r\n }\r\n}\r\n```\r\n", + "description": "

On vous donne la classe Directeur dont voici le corps:

\r\n
public class Directeur extends Employe{\r\n  private double prime; // en pourcents du salaire\r\n\r\n /*\r\n  * Constructeur\r\n  * @pre nom != null, salaire > 0, 0 <= prime < 1\r\n  * @post a construit une instance de la classe Directeur\r\n  */\r\n  public Directeur(String nom, double salaire, double prime){\r\n      //a compléter\r\n  }\r\n\r\n /*\r\n  * @pre -\r\n  * @post retourne la salaire du directeur. Ce salaire est (1+prime)*salaire\r\n  */\r\n  public double getSalaire() {\r\n      // non fourni\r\n  }\r\n\r\n /*\r\n  * @pre -\r\n  * @post retourne true si this et other sont identiques\r\n  *      (même nom, même salaire, même prime)\r\n  */\r\n  public boolean equals(Object other){\r\n      // non fourni\r\n  }\r\n\r\n /*\r\n  * @pre -\r\n  * @post retourne la prime de ce directeur\r\n  */\r\n  public double getPrime() {\r\n      // code non fourni\r\n  }\r\n}
\r\n

Pour information, la classe Employé ressemble à ceci :

\r\n
public class Employe{\r\n  private String nom ;\r\n  private double salaire ;\r\n\r\n  /*\r\n   * Constructeur\r\n   * @pre nom != null, salaire > 0\r\n   * @post a construit une instance de la classe Employe avec nom et salaire\r\n   */\r\n  public Employe (String nom, double salaire){\r\n      this.nom = nom ;\r\n      this.salaire = salaire ;\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne le nom de l'employé this\r\n   */\r\n  public String getNom(){\r\n      return nom ;\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne le salaire de l'employé this\r\n   */\r\n  public double getSalaire() {\r\n      return salaire ;\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne un String décrivant l'employé this\r\n   */\r\n  public String toString() {\r\n      // Non fourni\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne true si this et other sont deux employés\r\n   *       qui ont le même nom et le même salaire\r\n   */\r\n  public boolean equals(Object other){\r\n      // Non fourni\r\n  }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -7154,7 +7154,7 @@ }, { "title": "Q* Directeur - getSalaire", - "description": "On vous donne la classe Directeur dont voici le corps :\r\n\r\n``` java\r\npublic class Directeur extends Employe {\r\n\r\n private double prime;\r\n\r\n /*\r\n * Constructeur\r\n * @pre nom != null, salaire > 0, 0 <= prime < 1\r\n * @post a construit une instance de la classe Directeur\r\n */\r\n public Directeur(String nom, double salaire, double prime) {\r\n //non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la salaire du directeur.\r\n * Ce salaire est (1+prime)*salaire\r\n */\r\n public double getSalaire() {\r\n // a compléter\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true si this et other sont identiques\r\n * (même nom, même salaire, même prime)\r\n */\r\n public boolean equals(Object other) {\r\n // non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la prime de ce directeur\r\n */\r\n public double getPrime() {\r\n // code non fourni\r\n }\r\n}\r\n```\r\n\r\nPour information, la classe Employé ressemble à ceci :\r\n\r\n``` java\r\npublic class Employe {\r\n private String nom;\r\n private double salaire;\r\n\r\n /*\r\n * Constructeur\r\n * @pre nom != null, salaire > 0\r\n * @post a construit une instance de la classe Employe avec nom et salaire\r\n */\r\n public Employe(String nom, double salaire){\r\n this.nom = nom;\r\n this.salaire = salaire;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le nom de l'employé this\r\n */\r\n public String getNom(){\r\n return nom ;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le salaire de l'employé this\r\n */\r\n public double getSalaire() {\r\n return salaire ;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne un String décrivant l'employé this\r\n */\r\n public String toString() {\r\n // Non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true si this et other sont deux employés qui ont le même nom et le même salaire\r\n */\r\n public boolean equals(Object other) {\r\n // Non fourni\r\n }\r\n}\r\n```\r\n", + "description": "

On vous donne la classe Directeur dont voici le corps :

\r\n
public class Directeur extends Employe {\r\n\r\n    private double prime;\r\n\r\n    /*\r\n     * Constructeur\r\n     * @pre nom != null, salaire > 0, 0 <= prime < 1\r\n     * @post a construit une instance de la classe Directeur\r\n     */\r\n    public Directeur(String nom, double salaire, double prime) {\r\n        //non fourni\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne la salaire du directeur.\r\n     *       Ce salaire est (1+prime)*salaire\r\n     */\r\n    public double getSalaire() {\r\n        // a compléter\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne true si this et other sont identiques\r\n     *      (même nom, même salaire, même prime)\r\n     */\r\n    public boolean equals(Object other) {\r\n        // non fourni\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne la prime de ce directeur\r\n     */\r\n    public double getPrime() {\r\n        // code non fourni\r\n    }\r\n}
\r\n

Pour information, la classe Employé ressemble à ceci :

\r\n
public class Employe {\r\n    private String nom;\r\n    private double salaire;\r\n\r\n    /*\r\n     * Constructeur\r\n     * @pre nom != null, salaire > 0\r\n     * @post a construit une instance de la classe Employe avec nom et salaire\r\n     */\r\n    public Employe(String nom, double salaire){\r\n        this.nom = nom;\r\n        this.salaire = salaire;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le nom de l'employé this\r\n     */\r\n    public String getNom(){\r\n        return nom ;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le salaire de l'employé this\r\n     */\r\n    public double getSalaire() {\r\n        return salaire ;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne un String décrivant l'employé this\r\n     */\r\n    public String toString() {\r\n        // Non fourni\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne true si this et other sont deux employés qui ont le même nom et le même salaire\r\n     */\r\n    public boolean equals(Object other) {\r\n        // Non fourni\r\n    }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -7208,7 +7208,7 @@ }, { "title": "Q* Directeur - Equals", - "description": "On vous donne la classe Directeur dont voici le corps :\r\n\r\n``` java\r\npublic class Directeur extends Employe {\r\n private double prime; // en pourcents du salaire\r\n\r\n /*\r\n * Constructeur\r\n * @pre nom != null, salaire > 0, 0 <= prime < 1\r\n * @post a construit une instance de la classe Directeur\r\n */\r\n\r\n public Directeur(String nom, double salaire, double prime){\r\n //non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la salaire du directeur.\r\n * Ce salaire est (1+prime)*salaire\r\n */\r\n public double getSalaire() {\r\n //non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true si this et other sont identiques\r\n * (même nom, même salaire, même prime)\r\n */\r\n public boolean equals(Object other){\r\n //a compléter\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la prime de ce directeur\r\n */\r\n public double getPrime() {\r\n // code non fourni\r\n }\r\n }\r\n```\r\n\r\nPour information, la classe Employé ressemble à ceci :\r\n\r\n``` java\r\npublic class Employe{\r\n\r\n private String nom;\r\n private double salaire;\r\n\r\n /*\r\n * Constructeur\r\n * @pre nom != null, salaire > 0\r\n * @post a construit une instance de la classe Employe avec nom et salaire\r\n */\r\n public Employe(String nom, double salaire){\r\n this.nom = nom ;\r\n this.salaire = salaire ;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le nom de l'employé this\r\n */\r\n public String getNom(){\r\n return nom ;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le salaire de l'employé this\r\n */\r\n public double getSalaire() {\r\n return salaire ;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne un String décrivant l'employé this\r\n */\r\n public String toString() {\r\n //Non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true si this et other sont deux employés qui ont le même nom et le même salaire\r\n */\r\n public boolean equals(Object other){\r\n //Non fourni\r\n }\r\n}\r\n```\r\n", + "description": "

On vous donne la classe Directeur dont voici le corps :

\r\n
public class Directeur extends Employe {\r\n   private double prime; // en pourcents du salaire\r\n\r\n  /*\r\n   * Constructeur\r\n   * @pre nom != null, salaire > 0, 0 <= prime < 1\r\n   * @post a construit une instance de la classe Directeur\r\n   */\r\n\r\n   public Directeur(String nom, double salaire, double prime){\r\n       //non fourni\r\n   }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne la salaire du directeur.\r\n   *       Ce salaire est (1+prime)*salaire\r\n   */\r\n   public double getSalaire() {\r\n       //non fourni\r\n   }\r\n\r\n   /*\r\n    * @pre -\r\n    * @post retourne true si this et other sont identiques\r\n    *       (même nom, même salaire, même prime)\r\n    */\r\n   public boolean equals(Object other){\r\n       //a compléter\r\n   }\r\n\r\n   /*\r\n    * @pre -\r\n    * @post retourne la prime de ce directeur\r\n    */\r\n   public double getPrime() {\r\n       // code non fourni\r\n   }\r\n }
\r\n

Pour information, la classe Employé ressemble à ceci :

\r\n
public class Employe{\r\n\r\n  private String nom;\r\n  private double salaire;\r\n\r\n  /*\r\n   * Constructeur\r\n   * @pre nom != null, salaire > 0\r\n   * @post a construit une instance de la classe Employe avec nom et salaire\r\n   */\r\n  public Employe(String nom, double salaire){\r\n      this.nom = nom ;\r\n      this.salaire = salaire ;\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne le nom de l'employé this\r\n   */\r\n  public String getNom(){\r\n      return nom ;\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne le salaire de l'employé this\r\n   */\r\n  public double getSalaire() {\r\n      return salaire ;\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne un String décrivant l'employé this\r\n   */\r\n  public String toString() {\r\n      //Non fourni\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne true si this et other sont deux employés qui ont le même nom et le même salaire\r\n   */\r\n  public boolean equals(Object other){\r\n      //Non fourni\r\n  }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -7262,7 +7262,7 @@ }, { "title": "Q* DeStats - Constructeur", - "description": "On vous donne la classe DeStats dont voici le corps:\r\n\r\n``` java\r\npublic class DeStats extends De {\r\n\r\n private int lances;\r\n private int[] resultats;\r\n\r\n /*\r\n * @pre s != null;\r\n * @post Crée une instance de la classe DeStats\r\n * avec comme nom s\r\n */\r\n public DeStats(String s) {\r\n // A complèter\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le tableau des résultats du dé this\r\n */\r\n public int[] getResultats() {\r\n /* Code non fourni */\r\n }\r\n\r\n /*\r\n * @pre 1 <= n <= 6\r\n * @post retourne le nombre de fois que le dé\r\n * a donné comme résultat n\r\n */\r\n public int statistique(int n) {\r\n return this.resultat[n-1];\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post incrémente le nombre de lancés et le\r\n * nombre de fois qu'un chiffre est sorti.\r\n * Retourne le chiffre que le dé a donné.\r\n */\r\n public int lance() {\r\n /* Code non fourni */\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le nombre de lancés du dé this\r\n */\r\n public int getLances() {\r\n return this.lances;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne une description du dé sous forme\r\n * d'un String. Le format retourné est le nom du\r\n * dé suivi des statistique sous forme de tableau\r\n */\r\n public String toString() {\r\n /* Code non fourni */\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true si this et o sont deux DeStats identiques\r\n */\r\n public boolean equals(Object o) {\r\n /* Code non fourni */\r\n }\r\n}\r\n```\r\n\r\nPour information, la classe De ressemble à ceci :\r\n\r\n``` java\r\nimport java.util.Random;\r\n\r\npublic class De {\r\n private String nom; // le nom de ce dé (par exemple sa couleur)\r\n protected Random r; // nombre aléatoire\r\n\r\n /*\r\n * @pre nom != null\r\n * @post crée l'instance de la classe De ayant comme nom la chaine n\r\n * initilisé le générateur de nombres aléatoires\r\n */\r\n public De(String n) {\r\n nom = n;\r\n r = new Random();\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post lance le dé et retourne la valeur du dé\r\n */\r\n public int lance() {\r\n return r.nextInt(6)+1;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le générateur de nombres aléatoires utilisé par le dé\r\n */\r\n public Random getRandom() {\r\n return r;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le nom du dé\r\n */\r\n public String getNom(){\r\n return nom;\r\n }\r\n\r\n /*\r\n * @pre n != null\r\n * @post modifie le nom du dé qui est maintenant n\r\n */\r\n public void setNom(String n){\r\n this.nom = n;\r\n }\r\n\r\n /*\r\n * @pre r != null\r\n * @post modifie le générateur de nombres aléatoires du dé qui est maintenant r\r\n */\r\n public void setRandom(Random r){\r\n this.r = r;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne une chaîne de caractères représentant le dé\r\n */\r\n public String toString(){\r\n return this.nom;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true ssi other est un dé identique à celui-ci (même nom et même générateur aléatoire)\r\n */\r\n public boolean equals(Object other) {\r\n /* Code non fourni */\r\n }\r\n}\r\n```\r\n", + "description": "

On vous donne la classe DeStats dont voici le corps:

\r\n
public class DeStats extends De {\r\n\r\n    private int lances;\r\n    private int[] resultats;\r\n\r\n    /*\r\n     * @pre s != null;\r\n     * @post Crée une instance de la classe DeStats\r\n     *       avec comme nom s\r\n     */\r\n    public DeStats(String s) {\r\n        // A complèter\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le tableau des résultats du dé this\r\n     */\r\n    public int[] getResultats() {\r\n        /* Code non fourni */\r\n    }\r\n\r\n    /*\r\n     * @pre 1 <= n <= 6\r\n     * @post retourne le nombre de fois que le dé\r\n     *       a donné comme résultat n\r\n     */\r\n    public int statistique(int n) {\r\n        return this.resultat[n-1];\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post incrémente le nombre de lancés et le\r\n     *       nombre de fois qu'un chiffre est sorti.\r\n     *       Retourne le chiffre que le dé a donné.\r\n     */\r\n    public int lance() {\r\n        /* Code non fourni */\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le nombre de lancés du dé this\r\n     */\r\n    public int getLances() {\r\n        return this.lances;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne une description du dé sous forme\r\n     *       d'un String. Le format retourné est le nom du\r\n     *       dé suivi des statistique sous forme de tableau\r\n     */\r\n    public String toString() {\r\n        /* Code non fourni */\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne true si this et o sont deux DeStats identiques\r\n     */\r\n    public boolean equals(Object o) {\r\n        /* Code non fourni */\r\n    }\r\n}
\r\n

Pour information, la classe De ressemble à ceci :

\r\n
import java.util.Random;\r\n\r\npublic class De {\r\n    private String nom; // le nom de ce dé (par exemple sa couleur)\r\n    protected Random r; // nombre aléatoire\r\n\r\n    /*\r\n     * @pre nom != null\r\n     * @post crée l'instance de la classe De ayant comme nom la chaine n\r\n     *      initilisé le générateur de nombres aléatoires\r\n     */\r\n    public De(String n) {\r\n        nom = n;\r\n        r = new Random();\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post lance le dé et retourne la valeur du dé\r\n     */\r\n    public int lance() {\r\n        return r.nextInt(6)+1;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le générateur de nombres aléatoires utilisé par le dé\r\n     */\r\n    public Random getRandom() {\r\n        return r;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le nom du dé\r\n     */\r\n    public String getNom(){\r\n        return nom;\r\n    }\r\n\r\n    /*\r\n     * @pre n != null\r\n     * @post modifie le nom du dé qui est maintenant n\r\n     */\r\n    public void setNom(String n){\r\n        this.nom = n;\r\n    }\r\n\r\n    /*\r\n     * @pre r != null\r\n     * @post modifie le générateur de nombres aléatoires du dé qui est maintenant r\r\n     */\r\n    public void setRandom(Random r){\r\n        this.r = r;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne une chaîne de caractères représentant le dé\r\n     */\r\n    public String toString(){\r\n        return this.nom;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne true ssi other est un dé identique à celui-ci (même nom et même générateur aléatoire)\r\n     */\r\n    public boolean equals(Object other) {\r\n        /* Code non fourni */\r\n    }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -7316,7 +7316,7 @@ }, { "title": "Q* DeStats - lances", - "description": "On vous donne la classe DeStats dont voici le corps:\r\n\r\n``` java\r\npublic class DeStats extends De {\r\n\r\n private int lances;\r\n private int[] resultats;\r\n\r\n /*\r\n * @pre s != null;\r\n * @post Crée une instance de la classe DeStats\r\n * avec comme nom s\r\n */\r\n public DeStats(String s) {\r\n /* Code non fourni */\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le tableau des résultats du dé this\r\n */\r\n public int[] getResultats() {\r\n /* Code non fourni */\r\n }\r\n\r\n /*\r\n * @pre 1 <= n <= 6\r\n * @post retourne le nombre de fois que le dé\r\n * a donné comme résultat n\r\n */\r\n public int statistique(int n) {\r\n return this.resultat[n-1];\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post incrémente le nombre de lancés et le\r\n * nombre de fois qu'un chiffre est sorti.\r\n * Retourne le chiffre que le dé a donné.\r\n */\r\n public int lance() {\r\n // A complèter\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le nombre de lancés du dé this\r\n */\r\n public int getLances() {\r\n return this.lances;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne une description du dé sous forme\r\n * d'un String. Le format retourné est le nom du\r\n * dé suivi des statistique sous forme de tableau\r\n */\r\n public String toString() {\r\n /* Code non fourni */\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true si this et o sont deux DeStats identiques\r\n */\r\n public boolean equals(Object o) {\r\n /* Code non fourni */\r\n }\r\n}\r\n```\r\n\r\nPour information, la classe De ressemble à ceci :\r\n\r\n``` java\r\nimport java.util.Random;\r\n\r\npublic class De {\r\n private String nom; // le nom de ce dé (par exemple sa couleur)\r\n protected Random r; // nombre aléatoire\r\n\r\n /*\r\n * @pre nom != null\r\n * @post crée l'instance de la classe De ayant comme nom la chaine n\r\n * initilisé le générateur de nombres aléatoires\r\n */\r\n public De(String n) {\r\n nom = n;\r\n r = new Random();\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post lance le dé et retourne la valeur du dé\r\n */\r\n public int lance() {\r\n return r.nextInt(6)+1;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le générateur de nombres aléatoires utilisé par le dé\r\n */\r\n public Random getRandom() {\r\n return r;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le nom du dé\r\n */\r\n public String getNom(){\r\n return nom;\r\n }\r\n\r\n /*\r\n * @pre n != null\r\n * @post modifie le nom du dé qui est maintenant n\r\n */\r\n public void setNom(String n){\r\n this.nom = n;\r\n }\r\n\r\n /*\r\n * @pre r != null\r\n * @post modifie le générateur de nombres aléatoires du dé qui est maintenant r\r\n */\r\n public void setRandom(Random r){\r\n this.r = r;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne une chaîne de caractères représentant le dé\r\n */\r\n public String toString(){\r\n return this.nom;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true ssi other est un dé identique à celui-ci (même nom et même générateur aléatoire)\r\n */\r\n public boolean equals(Object other) {\r\n /* Code non fourni */\r\n }\r\n}\r\n```\r\n", + "description": "

On vous donne la classe DeStats dont voici le corps:

\r\n
public class DeStats extends De {\r\n\r\n    private int lances;\r\n    private int[] resultats;\r\n\r\n    /*\r\n     * @pre s != null;\r\n     * @post Crée une instance de la classe DeStats\r\n     *       avec comme nom s\r\n     */\r\n    public DeStats(String s) {\r\n        /* Code non fourni */\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le tableau des résultats du dé this\r\n     */\r\n    public int[] getResultats() {\r\n        /* Code non fourni */\r\n    }\r\n\r\n    /*\r\n     * @pre 1 <= n <= 6\r\n     * @post retourne le nombre de fois que le dé\r\n     *       a donné comme résultat n\r\n     */\r\n    public int statistique(int n) {\r\n        return this.resultat[n-1];\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post incrémente le nombre de lancés et le\r\n     *       nombre de fois qu'un chiffre est sorti.\r\n     *       Retourne le chiffre que le dé a donné.\r\n     */\r\n    public int lance() {\r\n        // A complèter\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le nombre de lancés du dé this\r\n     */\r\n    public int getLances() {\r\n        return this.lances;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne une description du dé sous forme\r\n     *       d'un String. Le format retourné est le nom du\r\n     *       dé suivi des statistique sous forme de tableau\r\n     */\r\n    public String toString() {\r\n        /* Code non fourni */\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne true si this et o sont deux DeStats identiques\r\n     */\r\n    public boolean equals(Object o) {\r\n        /* Code non fourni */\r\n    }\r\n}
\r\n

Pour information, la classe De ressemble à ceci :

\r\n
import java.util.Random;\r\n\r\npublic class De {\r\n    private String nom; // le nom de ce dé (par exemple sa couleur)\r\n    protected Random r; // nombre aléatoire\r\n\r\n    /*\r\n     * @pre nom != null\r\n     * @post crée l'instance de la classe De ayant comme nom la chaine n\r\n     *      initilisé le générateur de nombres aléatoires\r\n     */\r\n    public De(String n) {\r\n        nom = n;\r\n        r = new Random();\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post lance le dé et retourne la valeur du dé\r\n     */\r\n    public int lance() {\r\n        return r.nextInt(6)+1;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le générateur de nombres aléatoires utilisé par le dé\r\n     */\r\n    public Random getRandom() {\r\n        return r;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le nom du dé\r\n     */\r\n    public String getNom(){\r\n        return nom;\r\n    }\r\n\r\n    /*\r\n     * @pre n != null\r\n     * @post modifie le nom du dé qui est maintenant n\r\n     */\r\n    public void setNom(String n){\r\n        this.nom = n;\r\n    }\r\n\r\n    /*\r\n     * @pre r != null\r\n     * @post modifie le générateur de nombres aléatoires du dé qui est maintenant r\r\n     */\r\n    public void setRandom(Random r){\r\n        this.r = r;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne une chaîne de caractères représentant le dé\r\n     */\r\n    public String toString(){\r\n        return this.nom;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne true ssi other est un dé identique à celui-ci (même nom et même générateur aléatoire)\r\n     */\r\n    public boolean equals(Object other) {\r\n        /* Code non fourni */\r\n    }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -7370,7 +7370,7 @@ }, { "title": "Q* DeStats - resultats", - "description": "On vous donne la classe DeStats dont voici le corps:\r\n\r\n``` java\r\npublic class DeStats extends De {\r\n\r\n private int lances;\r\n private int[] resultats;\r\n\r\n /*\r\n * @pre s != null;\r\n * @post Crée une instance de la classe DeStats\r\n * avec comme nom s\r\n */\r\n public DeStats(String s) {\r\n /* Code non fourni */\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le tableau des résultats du dé this\r\n */\r\n public int[] getResultats() {\r\n // A complèter\r\n }\r\n\r\n /*\r\n * @pre 1 <= n <= 6\r\n * @post retourne le nombre de fois que le dé\r\n * a donné comme résultat n\r\n */\r\n public int statistique(int n) {\r\n return this.resultat[n-1];\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post incrémente le nombre de lancés et le\r\n * nombre de fois qu'un chiffre est sorti.\r\n * Retourne le chiffre que le dé a donné.\r\n */\r\n public int lance() {\r\n /* Code non fourni */\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le nombre de lancés du dé this\r\n */\r\n public int getLances() {\r\n return this.lances;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne une description du dé sous forme\r\n * d'un String. Le format retourné est le nom du\r\n * dé suivi des statistique sous forme de tableau\r\n */\r\n public String toString() {\r\n /* Code non fourni */\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true si this et o sont deux DeStats identiques\r\n */\r\n public boolean equals(Object o) {\r\n /* Code non fourni */\r\n }\r\n}\r\n```\r\n\r\nPour information, la classe De ressemble à ceci :\r\n\r\n``` java\r\nimport java.util.Random;\r\n\r\npublic class De {\r\n private String nom; // le nom de ce dé (par exemple sa couleur)\r\n protected Random r; // nombre aléatoire\r\n\r\n /*\r\n * @pre nom != null\r\n * @post crée l'instance de la classe De ayant comme nom la chaine n\r\n * initilisé le générateur de nombres aléatoires\r\n */\r\n public De(String n) {\r\n nom = n;\r\n r = new Random();\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post lance le dé et retourne la valeur du dé\r\n */\r\n public int lance() {\r\n return r.nextInt(6)+1;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le générateur de nombres aléatoires utilisé par le dé\r\n */\r\n public Random getRandom() {\r\n return r;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le nom du dé\r\n */\r\n public String getNom(){\r\n return nom;\r\n }\r\n\r\n /*\r\n * @pre n != null\r\n * @post modifie le nom du dé qui est maintenant n\r\n */\r\n public void setNom(String n){\r\n this.nom = n;\r\n }\r\n\r\n /*\r\n * @pre r != null\r\n * @post modifie le générateur de nombres aléatoires du dé qui est maintenant r\r\n */\r\n public void setRandom(Random r){\r\n this.r = r;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne une chaîne de caractères représentant le dé\r\n */\r\n public String toString(){\r\n return this.nom;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true ssi other est un dé identique à celui-ci (même nom et même générateur aléatoire)\r\n */\r\n public boolean equals(Object other) {\r\n /* Code non fourni */\r\n }\r\n}\r\n```\r\n", + "description": "

On vous donne la classe DeStats dont voici le corps:

\r\n
public class DeStats extends De {\r\n\r\n    private int lances;\r\n    private int[] resultats;\r\n\r\n    /*\r\n     * @pre s != null;\r\n     * @post Crée une instance de la classe DeStats\r\n     *       avec comme nom s\r\n     */\r\n    public DeStats(String s) {\r\n        /* Code non fourni */\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le tableau des résultats du dé this\r\n     */\r\n    public int[] getResultats() {\r\n        // A complèter\r\n    }\r\n\r\n    /*\r\n     * @pre 1 <= n <= 6\r\n     * @post retourne le nombre de fois que le dé\r\n     *       a donné comme résultat n\r\n     */\r\n    public int statistique(int n) {\r\n        return this.resultat[n-1];\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post incrémente le nombre de lancés et le\r\n     *       nombre de fois qu'un chiffre est sorti.\r\n     *       Retourne le chiffre que le dé a donné.\r\n     */\r\n    public int lance() {\r\n        /* Code non fourni */\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le nombre de lancés du dé this\r\n     */\r\n    public int getLances() {\r\n        return this.lances;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne une description du dé sous forme\r\n     *       d'un String. Le format retourné est le nom du\r\n     *       dé suivi des statistique sous forme de tableau\r\n     */\r\n    public String toString() {\r\n        /* Code non fourni */\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne true si this et o sont deux DeStats identiques\r\n     */\r\n    public boolean equals(Object o) {\r\n        /* Code non fourni */\r\n    }\r\n}
\r\n

Pour information, la classe De ressemble à ceci :

\r\n
import java.util.Random;\r\n\r\npublic class De {\r\n    private String nom; // le nom de ce dé (par exemple sa couleur)\r\n    protected Random r; // nombre aléatoire\r\n\r\n    /*\r\n     * @pre nom != null\r\n     * @post crée l'instance de la classe De ayant comme nom la chaine n\r\n     *      initilisé le générateur de nombres aléatoires\r\n     */\r\n    public De(String n) {\r\n        nom = n;\r\n        r = new Random();\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post lance le dé et retourne la valeur du dé\r\n     */\r\n    public int lance() {\r\n        return r.nextInt(6)+1;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le générateur de nombres aléatoires utilisé par le dé\r\n     */\r\n    public Random getRandom() {\r\n        return r;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le nom du dé\r\n     */\r\n    public String getNom(){\r\n        return nom;\r\n    }\r\n\r\n    /*\r\n     * @pre n != null\r\n     * @post modifie le nom du dé qui est maintenant n\r\n     */\r\n    public void setNom(String n){\r\n        this.nom = n;\r\n    }\r\n\r\n    /*\r\n     * @pre r != null\r\n     * @post modifie le générateur de nombres aléatoires du dé qui est maintenant r\r\n     */\r\n    public void setRandom(Random r){\r\n        this.r = r;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne une chaîne de caractères représentant le dé\r\n     */\r\n    public String toString(){\r\n        return this.nom;\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne true ssi other est un dé identique à celui-ci (même nom et même générateur aléatoire)\r\n     */\r\n    public boolean equals(Object other) {\r\n        /* Code non fourni */\r\n    }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -7424,7 +7424,7 @@ }, { "title": "Phase de réalisation: Soumission", - "description": "Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour\r\nla Mission 7.\r\n\r\nVous attendons une archive **.zip** contenant uniquement les fichiers :\r\n\r\n- Article.java\r\n- ArticlePiece.java\r\n- ArticleReparation.java\r\n- Facture.java\r\n- Piece.java\r\n- TestFacture.java\r\n- TestFactureInitial.java\r\n- README.txt\r\n", + "description": "

Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour la Mission 7.

\r\n

Vous attendons une archive .zip contenant uniquement les fichiers :

\r\n
    \r\n
  • Article.java
  • \r\n
  • ArticlePiece.java
  • \r\n
  • ArticleReparation.java
  • \r\n
  • Facture.java
  • \r\n
  • Piece.java
  • \r\n
  • TestFacture.java
  • \r\n
  • TestFactureInitial.java
  • \r\n
  • README.txt
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -7478,7 +7478,7 @@ }, { "title": "Question de Bilan Final", - "description": "Dans le contexte de gestion d'une bibliothèque de média, chacun des\r\nobjets de cette bibliothèque est une instance de la classe Java `Item`\r\nci-dessous :\r\n\r\n``` java\r\npublic class Item {\r\n private final String author, title;\r\n private final int serial;\r\n\r\n /**\r\n * Constructeur\r\n * @pre author != null , title != null , serial > 0\r\n * @post Une instance de la classe est créée, et représente un objet ayant comme\r\n * auteur author, comme titre title et comme numéro de série serial\r\n */\r\n public Item (String author, String title, Integer serial) {\r\n this.author = author;\r\n this.title = title;\r\n this.serial = serial;\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post Retourne l'auteur\r\n */\r\n public String getAuthor(){\r\n return this.author;\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post Retourne le titre\r\n */\r\n public String getAuthor(){\r\n return this.title;\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post Retourne le numéro de série\r\n */\r\n public String getAuthor(){\r\n return this.serial;\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post La valeur renvoyée contient une représentation de cet objet\r\n * sous la forme : [num série] Auteur, Titre\r\n */\r\n public String toString(){\r\n // À compléter\r\n }\r\n}\r\n```\r\n\r\nVous devez tout d'abord compléter la méthode `toString` de la classe\r\n`Item`.\r\n\r\nOn vous demande ensuite d'écrire une classe `CD` permettant de\r\nreprésenter des CD. Un CD est lui même un item de la bibliothèque avec\r\nune information supplémentaire : la durée de l'album en secondes (cette\r\ndurée doit être stockée dans un `int`). On doit pouvoir créer un nouvel\r\nobjet CD par exemple avec l'instruction :\r\n\r\n``` java\r\nCD r = new CD (\"Radiohead\", \"The Bends\", 2917); // auteur, titre et durée en secondes\r\n```\r\n\r\net obtenir une représentation textuelle de ce CD grâce à sa méthode\r\n`toString`, qui renvoie par exemple :\r\n\r\n``` java\r\n[100001] Radiohead, The Bends (2917 s)\r\n```\r\n\r\nRemarquez que chaque `Item` possède un serial qui est un numéro de série\r\nunique propre à l’objet (pour pouvoir différencier plusieurs exemplaires\r\ndu même livre par exemple). Il doit être généré automatiquement et être\r\nsupérieur à 100000 pour un CD.\r\n", + "description": "

Dans le contexte de gestion d'une bibliothèque de média, chacun des objets de cette bibliothèque est une instance de la classe Java Item ci-dessous :

\r\n
public class Item {\r\n   private final String author, title;\r\n   private final int serial;\r\n\r\n   /**\r\n    * Constructeur\r\n    * @pre author != null , title != null , serial > 0\r\n    * @post Une instance de la classe est créée, et représente un objet ayant comme\r\n    *       auteur author, comme titre title et comme numéro de série serial\r\n    */\r\n   public Item (String author, String title, Integer serial) {\r\n      this.author = author;\r\n      this.title = title;\r\n      this.serial = serial;\r\n   }\r\n\r\n   /**\r\n    * @pre -\r\n    * @post Retourne l'auteur\r\n    */\r\n    public String getAuthor(){\r\n        return this.author;\r\n    }\r\n\r\n    /**\r\n    * @pre -\r\n    * @post Retourne le titre\r\n    */\r\n    public String getAuthor(){\r\n        return this.title;\r\n    }\r\n\r\n    /**\r\n    * @pre -\r\n    * @post Retourne le numéro de série\r\n    */\r\n    public String getAuthor(){\r\n        return this.serial;\r\n    }\r\n\r\n   /**\r\n    * @pre -\r\n    * @post La valeur renvoyée contient une représentation de cet objet\r\n    *       sous la forme : [num série] Auteur, Titre\r\n    */\r\n   public String toString(){\r\n      // À compléter\r\n   }\r\n}
\r\n

Vous devez tout d'abord compléter la méthode toString de la classe Item.

\r\n

On vous demande ensuite d'écrire une classe CD permettant de représenter des CD. Un CD est lui même un item de la bibliothèque avec une information supplémentaire : la durée de l'album en secondes (cette durée doit être stockée dans un int). On doit pouvoir créer un nouvel objet CD par exemple avec l'instruction :

\r\n
CD r = new CD ("Radiohead", "The Bends", 2917);  // auteur, titre et durée en secondes
\r\n

et obtenir une représentation textuelle de ce CD grâce à sa méthode toString, qui renvoie par exemple :

\r\n
[100001] Radiohead, The Bends (2917 s)
\r\n

Remarquez que chaque Item possède un serial qui est un numéro de série unique propre à l’objet (pour pouvoir différencier plusieurs exemplaires du même livre par exemple). Il doit être généré automatiquement et être supérieur à 100000 pour un CD.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -7532,7 +7532,7 @@ }, { "title": "QCM", - "description": "Mission 7. Extension et Héritage\r\n================================\r\n\r\nCes questions supposent que vous avez lu les sections suivantes du livre\r\nde référence JavaNotes\\_\r\n\r\n> - 2.4 : Text Input and Output\\_\r\n> - 2.4.4 : Formatted Output\\_\r\n> - 4.3 : Parameters\\_\r\n> - 4.3.3 : Overloading\\_\r\n> - 5.3 : Programming with Objects\\_\r\n> - 5.3.3 : The class \"Object\"\\_\r\n> - 5.5 : Inheritance, Polymorphism, and\r\n> Abstract Classes\\_\r\n> - 5.5.1 : Extending Existing\r\n> Classes\\_\r\n> - 5.5.2 : Inheritance and Class\r\n> Hierarchy\\_\r\n> - 5.5.3 : Example: Vehicles\\_\r\n> - 5.5.4 : Polymorphism\\_\r\n> - 5.6 : this and super\\_\r\n> - 5.6.1 : The Special Variable\r\n> this\\_\r\n> - 5.6.2 : The Special Variable\r\n> super\\_\r\n> - 5.6.3 : Constructors in\r\n> Subclasses\\_\r\n> - 5.7 : Interfaces, Nested Classes, and\r\n> Other Details\\_\r\n> - 5.7.4 : Mixing Static and\r\n> Non-static\\_\r\n", + "description": "

Mission 7. Extension et Héritage

\r\n

Ces questions supposent que vous avez lu les sections suivantes du livre de référence JavaNotes_

\r\n
\r\n
    \r\n
  • 2.4 : Text Input and Output_\r\n
      \r\n
    • 2.4.4 : Formatted Output_
    • \r\n
  • \r\n
  • 4.3 : Parameters_\r\n
      \r\n
    • 4.3.3 : Overloading_
    • \r\n
  • \r\n
  • 5.3 : Programming with Objects_\r\n
      \r\n
    • 5.3.3 : The class \"Object\"_
    • \r\n
  • \r\n
  • 5.5 : Inheritance, Polymorphism, and Abstract Classes_\r\n
      \r\n
    • 5.5.1 : Extending Existing Classes_
    • \r\n
    • 5.5.2 : Inheritance and Class Hierarchy_
    • \r\n
    • 5.5.3 : Example: Vehicles_
    • \r\n
    • 5.5.4 : Polymorphism_
    • \r\n
  • \r\n
  • 5.6 : this and super_\r\n
      \r\n
    • 5.6.1 : The Special Variable this_
    • \r\n
    • 5.6.2 : The Special Variable super_
    • \r\n
    • 5.6.3 : Constructors in Subclasses_
    • \r\n
  • \r\n
  • 5.7 : Interfaces, Nested Classes, and Other Details_\r\n
      \r\n
    • 5.7.4 : Mixing Static and Non-static_
    • \r\n
  • \r\n
\r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -7581,7 +7581,7 @@ }, { "title": "Question de démarrage 1 : Implémenter une interface", - "description": "Les interfaces sont très pratiques en termes de conception orientée\r\nobjet et permettent d'avoir une vision globale cohérente du\r\nfonctionnement d'un programme, de ses différents acteurs et de la\r\nmanière dont ils interagissent. Il est donc important de savoir\r\nimplémenter des interfaces en respectant leurs spécifications. Voici\r\nl'interface `DrapeauIF`:\r\n\r\n``` java\r\n// Une interface simple correspondant à un drapeau\r\npublic interface DrapeauIF {\r\n\r\n /*\r\n * @pre : -\r\n * @post : le drapeau prend la valeur passée en argument\r\n */\r\n public void set(boolean drapeau);\r\n\r\n /*\r\n * @pre : -\r\n * @post : Si l'argument est 'V' ou 'v', le drapeau\r\n * prend la valeur vrai et faux sinon\r\n */\r\n public void set(char c);\r\n\r\n /*\r\n * @pre : -\r\n * @post : retourne le drapeau sous forme d'un booléen\r\n */\r\n public boolean toBoolean();\r\n}\r\n```\r\n\r\nPrenez connaissance de sont fonctionnement et de ses spécifications.\r\nVoici maintenant la classe `Drapeau` qui implémente l'interface\r\n`DrapeauIF`:\r\n\r\n``` java\r\n// Une classe simple avec un objet contenant un booléen\r\npublic class Drapeau implements DrapeauIF {\r\n\r\n private boolean drapeau; // la valeur du drapeau\r\n\r\n // Constructeurs\r\n /*\r\n * @pre : -\r\n * @post : un objet de type Drapeau est créé\r\n * et représente le drapeau 'false'\r\n */\r\n public Drapeau() {\r\n drapeau = false;\r\n }\r\n\r\n /*\r\n * @pre : -\r\n * @post : un objet de type Drapeau est créé et\r\n * représente le booleen passé en argument\r\n */\r\n public Drapeau(boolean drapeau) {\r\n this.drapeau = drapeau;\r\n }\r\n\r\n /*\r\n * @pre : -\r\n * @post : un objet de type Drapeau est créé.\r\n * Si l'argument est 'V' ou 'v', il représente le\r\n * drapeau true.\r\n * Sinon, il représente le drapeau false\r\n */\r\n public Drapeau(char c) {\r\n drapeau = (c == 'V' || c == 'v');\r\n }\r\n\r\n public void set(boolean drapeau) {\r\n // A Complèter\r\n }\r\n\r\n public void set(char c) {\r\n // A Complèter\r\n }\r\n\r\n public boolean toBoolean() {\r\n return drapeau;\r\n }\r\n}\r\n```\r\n\r\nImplémentez les deux alternatives de la méthode `set()` de la classe\r\n`Drapeau` en vous référant aux spécifications énoncées dans l'interface\r\n`DrapeauIF`.\r\n", + "description": "

Les interfaces sont très pratiques en termes de conception orientée objet et permettent d'avoir une vision globale cohérente du fonctionnement d'un programme, de ses différents acteurs et de la manière dont ils interagissent. Il est donc important de savoir implémenter des interfaces en respectant leurs spécifications. Voici l'interface DrapeauIF:

\r\n
// Une interface simple correspondant à un drapeau\r\npublic interface DrapeauIF {\r\n\r\n    /*\r\n     * @pre : -\r\n     * @post : le drapeau prend la valeur passée en argument\r\n     */\r\n    public void set(boolean drapeau);\r\n\r\n    /*\r\n     * @pre : -\r\n     * @post : Si l'argument est 'V' ou 'v', le drapeau\r\n     *         prend la valeur vrai et faux sinon\r\n     */\r\n    public void set(char c);\r\n\r\n    /*\r\n     * @pre : -\r\n     * @post : retourne le drapeau sous forme d'un booléen\r\n     */\r\n    public boolean toBoolean();\r\n}
\r\n

Prenez connaissance de sont fonctionnement et de ses spécifications. Voici maintenant la classe Drapeau qui implémente l'interface DrapeauIF:

\r\n
// Une classe simple avec un objet contenant un booléen\r\npublic class Drapeau implements DrapeauIF {\r\n\r\n    private boolean drapeau; // la valeur du drapeau\r\n\r\n    // Constructeurs\r\n    /*\r\n     * @pre : -\r\n     * @post : un objet de type Drapeau est créé\r\n     *         et représente le drapeau 'false'\r\n     */\r\n    public Drapeau() {\r\n        drapeau = false;\r\n    }\r\n\r\n    /*\r\n     * @pre : -\r\n     * @post : un objet de type Drapeau est créé et\r\n     *         représente le booleen passé en argument\r\n     */\r\n    public Drapeau(boolean drapeau) {\r\n        this.drapeau = drapeau;\r\n    }\r\n\r\n    /*\r\n     * @pre : -\r\n     * @post : un objet de type Drapeau est créé.\r\n     *         Si l'argument est 'V' ou 'v', il représente le\r\n     *         drapeau true.\r\n     *         Sinon, il représente le drapeau false\r\n     */\r\n    public Drapeau(char c) {\r\n        drapeau = (c == 'V' || c == 'v');\r\n    }\r\n\r\n    public void set(boolean drapeau) {\r\n        // A Complèter\r\n    }\r\n\r\n    public void set(char c) {\r\n        // A Complèter\r\n    }\r\n\r\n    public boolean toBoolean() {\r\n        return drapeau;\r\n    }\r\n}
\r\n

Implémentez les deux alternatives de la méthode set() de la classe Drapeau en vous référant aux spécifications énoncées dans l'interface DrapeauIF.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -7635,7 +7635,7 @@ }, { "title": "Question de démarrage 2 : StringBuffer", - "description": "En Java, concaténer des `String` avec l'opérateur `+` implique la\r\ncréation et la desctruction successive d'un grand nombre de `String`. On\r\nutilise en général un `StringBuffer`\r\n()\r\npour éviter ce problème. En utilisant l'API de la classe `StringBuffer`,\r\nimplémentez le corps de la méthode `repeat()` qui permet de répéter un\r\n`String` un certain nombre de fois. Voici la signature de cette méthode\r\n:\r\n\r\n``` java\r\n/*\r\n * @pre -\r\n * @post retourne le String s répété n fois.\r\n * Si s == null ou n == 0, retourne null.\r\n */\r\npublic static String repeat(String s, int n){\r\n // À implémenter\r\n}\r\n```\r\n", + "description": "

En Java, concaténer des String avec l'opérateur + implique la création et la desctruction successive d'un grand nombre de String. On utilise en général un StringBuffer (http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html) pour éviter ce problème. En utilisant l'API de la classe StringBuffer, implémentez le corps de la méthode repeat() qui permet de répéter un String un certain nombre de fois. Voici la signature de cette méthode :

\r\n
/*\r\n * @pre -\r\n * @post retourne le String s répété n fois.\r\n *      Si s == null ou n == 0, retourne null.\r\n */\r\npublic static String repeat(String s, int n){\r\n    // À implémenter\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -7689,7 +7689,7 @@ }, { "title": "Q* MyString - Constructeur", - "description": "On vous donne l'interface `MyString` suivante:\r\n\r\n``` java\r\npublic interface MyString {\r\n /*\r\n * @pre -\r\n * @post retourne la longueur de la chaîne de caractère\r\n */\r\n public int length();\r\n\r\n /*\r\n * @pre 0<=iOn vous donne l'interface MyString suivante:

\r\n
public interface MyString {\r\n  /*\r\n   * @pre -\r\n   * @post retourne la longueur de la chaîne de caractère\r\n   */\r\n  public int length();\r\n\r\n  /*\r\n   * @pre 0<=i<this.length()\r\n   * @post retourne le caractère à l'indice i de this\r\n   */\r\n  public char charAt(int i);\r\n\r\n  /*\r\n   * @pre s!=null\r\n   * @post retourne true si la chaine de caratères s est comprise dans la chaine this, false sinon\r\n   */\r\n  public boolean contains(MyString s);\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne la chaine de caractères qui est la concaténation entre this et le caractère c\r\n   */\r\n  public MyString concat(char c);\r\n}
\r\n

Ainsi que la classe suivante :

\r\n
public class StringTab implements MyString {\r\n  private char[] s;\r\n\r\n  /*\r\n   * @pre -\r\n   * @post construit une instance de la classe StringTab\r\n   */\r\n  public StringTab(char c) {\r\n      // A compléter\r\n      // Constructeur 1\r\n  }\r\n\r\n  public StringTab(char[] c) {\r\n      // A compléter\r\n      // Constructeur 2\r\n  }\r\n\r\n  public MyString concat(char c){\r\n      // Non fourni\r\n  }\r\n  public boolean contains(MyString s) {\r\n      // Non fourni\r\n  }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -7743,7 +7743,7 @@ }, { "title": "Q* MyString - Concat", - "description": "On vous donne l'interface `MyString` suivante :\r\n\r\n``` java\r\npublic interface MyString {\r\n /*\r\n * @pre -\r\n * @post retourne la longueur de la chaîne de caractère\r\n */\r\n public int length();\r\n\r\n\r\n /*\r\n * @pre 0<=iOn vous donne l'interface MyString suivante :

\r\n
public interface MyString {\r\n  /*\r\n   * @pre -\r\n   * @post retourne la longueur de la chaîne de caractère\r\n   */\r\n  public int length();\r\n\r\n\r\n  /*\r\n   * @pre 0<=i<this.length()\r\n   * @post retourne le caractère à l'indice i de this\r\n   */\r\n  public char charAt(int i);\r\n\r\n  /*\r\n   * @pre s != null\r\n   * @post retourne true si la chaine de caratères s est comprise dans la chaine this, false sinon\r\n   */\r\n  public boolean contains(MyString s);\r\n\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne la chaine de caractères qui est la concaténation entre this et le caractère c\r\n   */\r\n   public MyString concat(char c);\r\n}
\r\n

Ainsi que la classe suivante :

\r\n
public class StringTab implements MyString {\r\n  private char[] s;\r\n\r\n  /*\r\n   * @pre -\r\n   * @post construit une instance de la classe StringTab\r\n   */\r\n  public StringTab(char c) {\r\n      // Non fourni\r\n  }\r\n  public StringTab(char[] c) {\r\n      // Non fourni\r\n  }\r\n  //Partie de code non fournie\r\n\r\n  public MyString concat(char c) {\r\n      // A compléter\r\n  }\r\n  public boolean contains(MyString s) {\r\n      // Non fourni\r\n  }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -7797,7 +7797,7 @@ }, { "title": "Q* MyString - Contains", - "description": "On vous donne l'interface `MyString` suivante:\r\n\r\n``` java\r\npublic interface MyString {\r\n /*\r\n * @pre -\r\n * @post retourne la longueur de la chaîne de caractère\r\n */\r\n public int length();\r\n\r\n /*\r\n * @pre 0<=iOn vous donne l'interface MyString suivante:

\r\n
public interface MyString {\r\n  /*\r\n   * @pre -\r\n   * @post retourne la longueur de la chaîne de caractère\r\n   */\r\n  public int length();\r\n\r\n  /*\r\n   * @pre 0<=i<this.length()\r\n   * @post retourne le caractère à l'indice i de this\r\n   */\r\n  public char charAt(int i);\r\n\r\n  /*\r\n   * @pre s != null\r\n   * @post retourne true si la chaine de caratères s est comprise dans la chaine this, false sinon\r\n   */\r\n  public boolean contains(MyString s);\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne la chaine de caractères qui est la concaténation entre this et le caractère c\r\n   */\r\n  public MyString concat(char c);\r\n}
\r\n

Ainsi que la classe suivante :

\r\n
public class StringTab implements MyString {\r\n  private char[] s;\r\n\r\n  /*\r\n   * @pre -\r\n   * @post construit une instance de la classe StringTab\r\n   */\r\n  public StringTab(char c) {\r\n      // Non fourni\r\n  }\r\n  public StringTab(char[] c) {\r\n      // Non fourni\r\n  }\r\n  //Partie de code non fournie\r\n\r\n  public MyString concat(char c) {\r\n      // Non fourni\r\n  }\r\n  public boolean contains(MyString s) {\r\n      // A compléter\r\n  }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -7851,7 +7851,7 @@ }, { "title": "Q* ByteString", - "description": "On vous donne linterface `Byte` suivante :\r\n\r\n``` java\r\npublic interface Byte {\r\n /*\r\n * @pre i est un entier positif et 0<=i<=7\r\n * @post On retourne la valeur du bit à la position i\r\n */\r\n public int getBit(int i);\r\n /*\r\n * @pre i est un entier positif et 0<=i<=7\r\n * @post le bit à la position i est mis à 1\r\n */\r\n public void setBit(int i);\r\n /*\r\n * @pre i est un entier positif et 0<=i<=7\r\n * @post le bit à la position i est remis à 0\r\n */\r\n public void resetBit(int i);\r\n /*\r\n * @pre -\r\n * @post La chaîne est décallée d'un bit vers la droite\r\n * (attention à la structure interne)\r\n * Le bit de poids faible est mis à 0.\r\n */\r\n public void shiftLeft();\r\n /*\r\n * @pre -\r\n * @post La chaîne est décallée d'un bit vers la gauche\r\n * (attention à la structure interne)\r\n * Le bit de poids fort prend la valeur du bit de poids faible avant rotation\r\n */\r\n public void rotateRight();\r\n /*\r\n * @pre -\r\n * @post On effectue un ET logique entre chaque bit de b et b1\r\n */\r\n public Byte and(Byte b1);\r\n}\r\n```\r\n\r\nAinsi que la classe (à compléter) `ByteString` suivante :\r\n\r\n``` java\r\npublic class ByteString implements Byte {\r\n private StringBuilder b; // contient les caractères représentant le byte\r\n\r\n /*\r\n * @pre -\r\n * @post a construit un byte dont les huit bits sont mis à zéro\r\n * le bit de poids fort est en position 7 dans le StringBuilder\r\n */\r\n public ByteString() {\r\n //A COMPLETER\r\n }\r\n\r\n /*\r\n * @pre s.length==8, s ne contient que des caractères 0 et 1\r\n * @post a construit un byte dont la représentation naturelle en String est s\r\n * La représentation naturelle d'un byte sous la forme d'un String est\r\n * le bit de poids fort à gauche. Dans le StringBuilder, on stocke\r\n * le byte de façon à avoir le bit de poids faible (resp. fort)\r\n * en position 0 (resp. 7).\r\n *\r\n * Exemple\r\n *\r\n * 5 en décimal correspond à 00000101 en binaire et\r\n * sera stocké dans le StringBuilder 10100000\r\n */\r\n public ByteString(String s) {\r\n //A COMPLETER\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la représentation naturelle du nombre binaire\r\n * c'est-à-dire celle où le bit de poids fort est à gauche\r\n */\r\n public String toString() {\r\n String r=\"\";\r\n for(int i=b.length()-1; i>=0;i--) {\r\n r=r+b.charAt(i);\r\n }\r\n return r;\r\n }\r\n\r\n //A COMPLETER\r\n}\r\n```\r\n", + "description": "

On vous donne linterface Byte suivante :

\r\n
public interface Byte {\r\n  /*\r\n  * @pre i est un entier positif et 0<=i<=7\r\n  * @post On retourne la valeur du bit à la position i\r\n  */\r\n  public int getBit(int i);\r\n  /*\r\n  * @pre i est un entier positif  et 0<=i<=7\r\n  * @post le bit à la position i est mis à 1\r\n  */\r\n  public void setBit(int i);\r\n  /*\r\n  * @pre i est un entier positif  et 0<=i<=7\r\n  * @post le bit à la position i est remis à 0\r\n  */\r\n  public void resetBit(int i);\r\n  /*\r\n  * @pre -\r\n  * @post La chaîne est décallée d'un bit vers la droite\r\n  * (attention à la structure interne)\r\n  * Le bit de poids faible est mis à 0.\r\n  */\r\n  public void shiftLeft();\r\n  /*\r\n  * @pre -\r\n  * @post La chaîne est décallée d'un bit vers la gauche\r\n  * (attention à la structure interne)\r\n  * Le bit de poids fort prend la valeur du bit de poids faible avant rotation\r\n  */\r\n  public void rotateRight();\r\n  /*\r\n  * @pre -\r\n  * @post On effectue un ET logique entre chaque bit de b et b1\r\n  */\r\n  public Byte and(Byte b1);\r\n}
\r\n

Ainsi que la classe (à compléter) ByteString suivante :

\r\n
public class ByteString implements Byte {\r\n private StringBuilder b; // contient les caractères représentant le byte\r\n\r\n /*\r\n  * @pre -\r\n  * @post a construit un byte dont les huit bits sont mis à zéro\r\n  *       le bit de poids fort est en position 7 dans le StringBuilder\r\n  */\r\n public ByteString() {\r\n     //A COMPLETER\r\n }\r\n\r\n /*\r\n  * @pre s.length==8, s ne contient que des caractères 0 et 1\r\n  * @post a construit un byte dont la représentation naturelle en String est s\r\n  *       La représentation naturelle d'un byte sous la forme d'un String est\r\n  *       le bit de poids fort à gauche. Dans le StringBuilder, on stocke\r\n  *       le byte de façon à avoir le bit de poids faible (resp. fort)\r\n  *       en position 0 (resp. 7).\r\n  *\r\n  *       Exemple\r\n  *\r\n  *       5 en décimal correspond à 00000101 en binaire et\r\n  *       sera stocké dans le StringBuilder 10100000\r\n  */\r\n public ByteString(String s) {\r\n     //A COMPLETER\r\n }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne la représentation naturelle du nombre binaire\r\n   *       c'est-à-dire celle où le bit de poids fort est à gauche\r\n   */\r\n  public String toString() {\r\n      String r="";\r\n      for(int i=b.length()-1; i>=0;i--) {\r\n          r=r+b.charAt(i);\r\n      }\r\n      return r;\r\n  }\r\n\r\n //A COMPLETER\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -7905,7 +7905,7 @@ }, { "title": "Q* ByteTab", - "description": "On vous donne linterface `Byte` suivante :\r\n\r\n``` java\r\npublic interface Byte {\r\n /*\r\n * @pre i est un entier positif et 0<=i<=7\r\n * @post On retourne la valeur du bit à la position i\r\n */\r\n public int getBit(int i);\r\n /*\r\n * @pre i est un entier positif et 0<=i<=7\r\n * @post le bit à la position i est mis à 1\r\n */\r\n public void setBit(int i);\r\n /*\r\n * @pre i est un entier positif et 0<=i<=7\r\n * @post le bit à la position i est remis à 0\r\n */\r\n public void resetBit(int i);\r\n /*\r\n * @pre -\r\n * @post Le tableau est décallée d'un bit vers la droite\r\n * (attention à la structure interne)\r\n * Le bit de poids faible est mis à 0.\r\n */\r\n public void shiftLeft();\r\n /*\r\n * @pre -\r\n * @post Le tableau est décallée d'un bit vers la gauche\r\n * (attention à la structure interne)\r\n * Le bit de poids fort prend la valeur du bit de poids faible avant rotation\r\n */\r\n public void rotateRight();\r\n /*\r\n * @pre -\r\n * @post On effectue un ET logique entre chaque bit de b et b1\r\n */\r\n public Byte and(Byte b1);\r\n}\r\n```\r\n\r\nAinsi que la classe (à compléter) `ByteTab` suivante :\r\n\r\n``` java\r\npublic class ByteTab implements Byte {\r\n private boolean b[];\r\n // true signifie 1\r\n // false signifie 0\r\n\r\n /*\r\n * @pre -\r\n * @post a construit un Byte dont tous les bits sont mis à 0\r\n */\r\n public ByteTab() {\r\n b=new boolean[8];\r\n for(int i=0;i=0;i--) {\r\n if(b[i])\r\n r+='1';\r\n else\r\n r+='0';\r\n }\r\n return r;\r\n }\r\n\r\n //A compléter\r\n}\r\n```\r\n", + "description": "

On vous donne linterface Byte suivante :

\r\n
public interface Byte {\r\n  /*\r\n  * @pre i est un entier positif et 0<=i<=7\r\n  * @post On retourne la valeur du bit à la position i\r\n  */\r\n  public int getBit(int i);\r\n  /*\r\n  * @pre i est un entier positif  et 0<=i<=7\r\n  * @post le bit à la position i est mis à 1\r\n  */\r\n  public void setBit(int i);\r\n  /*\r\n  * @pre i est un entier positif  et 0<=i<=7\r\n  * @post le bit à la position i est remis à 0\r\n  */\r\n  public void resetBit(int i);\r\n  /*\r\n  * @pre -\r\n  * @post Le tableau est décallée d'un bit vers la droite\r\n  * (attention à la structure interne)\r\n  * Le bit de poids faible est mis à 0.\r\n  */\r\n  public void shiftLeft();\r\n  /*\r\n  * @pre -\r\n  * @post Le tableau est décallée d'un bit vers la gauche\r\n  * (attention à la structure interne)\r\n  * Le bit de poids fort prend la valeur du bit de poids faible avant rotation\r\n  */\r\n  public void rotateRight();\r\n  /*\r\n  * @pre -\r\n  * @post On effectue un ET logique entre chaque bit de b et b1\r\n  */\r\n  public Byte and(Byte b1);\r\n}
\r\n

Ainsi que la classe (à compléter) ByteTab suivante :

\r\n
public class ByteTab implements Byte {\r\n  private boolean b[];\r\n  // true signifie 1\r\n  // false signifie 0\r\n\r\n  /*\r\n   * @pre -\r\n   * @post a construit un Byte dont tous les bits sont mis à 0\r\n   */\r\n  public ByteTab() {\r\n      b=new boolean[8];\r\n      for(int i=0;i<b.length;i++) {\r\n          b[i]=false;\r\n      }\r\n  }\r\n\r\n  /*\r\n  * @pre s.length==8, s ne contient que des caractères 0 et 1\r\n  * @post a construit un byte dont la représentation naturelle en String est s\r\n  *       La représentation naturelle d'un byte sous la forme d'un String est\r\n  *       le bit de poids fort à gauche. Dans le tableau de char, on stocke\r\n  *       le byte de façon à avoir le bit de poids faible (resp. fort)\r\n  *       en position 0 (resp. 7).\r\n  *\r\n  *       Exemple\r\n  *\r\n  *       5 en décimal correspond à 00000101 en binaire et\r\n  *       sera stocké dans le tableau 10100000\r\n  */\r\n  public ByteTab(String s) {\r\n      b=new boolean[8];\r\n      for(int i=0;i<s.length();i++) {\r\n          if(s.charAt(i)=='0')\r\n              b[7-i]=false;\r\n          else\r\n              b[7-i]=true;\r\n      }\r\n  }\r\n\r\n  /*\r\n   * @pre -\r\n   * @post retourne la représentation naturelle du nombre binaire\r\n   *       c'est-à-dire celle où le bit de poids fort est à gauche\r\n   */\r\n  public String toString() {\r\n      String r="";\r\n      for(int i=b.length-1;i>=0;i--) {\r\n          if(b[i])\r\n              r+='1';\r\n          else\r\n              r+='0';\r\n      }\r\n      return r;\r\n  }\r\n\r\n  //A compléter\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -7959,7 +7959,7 @@ }, { "title": "Q* Vecteur", - "description": "On vous donne l'interface `Stat` suivante :\r\n\r\n``` java\r\npublic interface Stat {\r\n /*\r\n * @pre -\r\n * @post retourne le plus grand nombre de l'ensemble\r\n */\r\n public double max();\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le plus petit nombre de l'ensemble\r\n */\r\n public double min();\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la moyenne des nombres présents dans l'ensemble\r\n */\r\n public double moyenne();\r\n}\r\n```\r\n\r\nAinsi que la classe (à compléter) `Vecteur` suivante :\r\n\r\n``` java\r\npublic class Vecteur implements Stat {\r\n private double[] v;\r\n\r\n /*\r\n * @pre n > 0\r\n * @post construit un vecteur contenant n réels\r\n *\r\n */\r\n public Vecteur(int n) {\r\n v=new double[n];\r\n }\r\n\r\n /*\r\n * @pre 0 <= i < n\r\n * @post stocke la valeur d en position i du vecteur\r\n */\r\n public void set(int i, double d){\r\n v[i]=d;\r\n }\r\n\r\n /*\r\n * @pre 0 <= i < n\r\n * @post retourne la valeur se trouvant en position i du vecteur\r\n */\r\n public double get(int i) {\r\n return v[i];\r\n }\r\n\r\n //A COMPLETER\r\n}\r\n```\r\n", + "description": "

On vous donne l'interface Stat suivante :

\r\n
public interface Stat {\r\n    /*\r\n     * @pre -\r\n     * @post retourne le plus grand nombre de l'ensemble\r\n     */\r\n    public double max();\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le plus petit nombre de l'ensemble\r\n     */\r\n    public double min();\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne la moyenne des nombres présents dans l'ensemble\r\n     */\r\n    public double moyenne();\r\n}
\r\n

Ainsi que la classe (à compléter) Vecteur suivante :

\r\n
public class Vecteur implements Stat {\r\n    private double[] v;\r\n\r\n    /*\r\n     * @pre n > 0\r\n     * @post construit un vecteur contenant n réels\r\n     *\r\n     */\r\n    public Vecteur(int n) {\r\n        v=new double[n];\r\n    }\r\n\r\n    /*\r\n     * @pre 0 <= i < n\r\n     * @post stocke la valeur d en position i du vecteur\r\n     */\r\n    public void set(int i, double d){\r\n        v[i]=d;\r\n    }\r\n\r\n    /*\r\n     * @pre 0 <= i < n\r\n     * @post retourne la valeur se trouvant en position i du vecteur\r\n     */\r\n    public double get(int i) {\r\n        return v[i];\r\n    }\r\n\r\n    //A COMPLETER\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -8013,7 +8013,7 @@ }, { "title": "Q* Matrice Carrée", - "description": "On vous donne l'interface `Stat` suivante :\r\n\r\n``` java\r\npublic interface Stat {\r\n /*\r\n * @pre -\r\n * @post retourne le plus grand nombre de l'ensemble\r\n */\r\n public double max();\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le plus petit nombre de l'ensemble\r\n */\r\n public double min();\r\n\r\n /*\r\n * @pre -\r\n * @post retourne la moyenne des nombres présents dans l'ensemble\r\n */\r\n public double moyenne();\r\n}\r\n```\r\n\r\nAinsi que la classe (à compléter) `MatriceCarree` suivante :\r\n\r\n``` java\r\npublic class MatriceCarree implements Stat {\r\n\r\n public double[][] m;\r\n\r\n /*\r\n * @pre n > 0\r\n * @post a construit une matrice carrée de taille n*n\r\n */\r\n public MatriceCarree(int n) {\r\n m = new double[n][n];\r\n }\r\n\r\n /*\r\n * @pre 0 <= i < n, 0 <= j < n\r\n * @post stocke la valeur d en position i,j de la matrice\r\n */\r\n public void set(int i, int j, double d) {\r\n m[i][j] = d;\r\n }\r\n\r\n /*\r\n * @pre 0 <= i < n, 0 <= j < n\r\n * @post retourne la valeur se trouvant en position i,j de la matrice\r\n */\r\n public double get(int i, int j){\r\n return m[i][j];\r\n }\r\n\r\n //A COMPLETER\r\n}\r\n```\r\n", + "description": "

On vous donne l'interface Stat suivante :

\r\n
public interface Stat {\r\n    /*\r\n     * @pre -\r\n     * @post retourne le plus grand nombre de l'ensemble\r\n     */\r\n    public double max();\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne le plus petit nombre de l'ensemble\r\n     */\r\n    public double min();\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne la moyenne des nombres présents dans l'ensemble\r\n     */\r\n    public double moyenne();\r\n}
\r\n

Ainsi que la classe (à compléter) MatriceCarree suivante :

\r\n
public class MatriceCarree implements Stat {\r\n\r\n    public double[][] m;\r\n\r\n    /*\r\n     * @pre n > 0\r\n     * @post a construit une matrice carrée de taille n*n\r\n     */\r\n    public MatriceCarree(int n) {\r\n        m = new double[n][n];\r\n    }\r\n\r\n    /*\r\n     * @pre 0 <= i < n, 0 <= j < n\r\n     * @post stocke la valeur d en position i,j de la matrice\r\n     */\r\n    public void set(int i, int j, double d) {\r\n        m[i][j] = d;\r\n    }\r\n\r\n    /*\r\n     * @pre 0 <= i < n, 0 <= j < n\r\n     * @post retourne la valeur se trouvant en position i,j de la matrice\r\n     */\r\n    public double get(int i, int j){\r\n        return m[i][j];\r\n    }\r\n\r\n    //A COMPLETER\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -8067,7 +8067,7 @@ }, { "title": "Phase de réalisation: Soumission", - "description": "Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour\r\nla Mission 8.\r\n\r\nVous attendons une archive **.zip** contenant uniquement les fichiers :\r\n\r\n- Square.java\r\n- Rectangle.java\r\n- DrawPanel.java\r\n- Equilateral.java\r\n- MyShape.java\r\n- Segment.java\r\n- Shape.java\r\n- Triangle.java\r\n- README.txt\r\n", + "description": "

Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour la Mission 8.

\r\n

Vous attendons une archive .zip contenant uniquement les fichiers :

\r\n
    \r\n
  • Square.java
  • \r\n
  • Rectangle.java
  • \r\n
  • DrawPanel.java
  • \r\n
  • Equilateral.java
  • \r\n
  • MyShape.java
  • \r\n
  • Segment.java
  • \r\n
  • Shape.java
  • \r\n
  • Triangle.java
  • \r\n
  • README.txt
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -8116,7 +8116,7 @@ }, { "title": "QCM", - "description": "Mission 8. Interfaces\r\n=====================\r\n\r\nCes questions supposent que vous avez lu les sections suivantes du livre\r\nde référence JavaNotes\\_\r\n\r\n> - 4.5 : APIs, Packages, and Javadoc\\_ \r\n> - 4.5.2 : Toolboxes\\_\r\n> - 4.5.3 : Java's Standard\r\n> Packages\\_\r\n> - 4.5.4 : Using Classes from\r\n> Packages\\_\r\n> - 4.5.4 : Javadoc\\_\r\n>\r\n> - 5.3 : Programming with Objects\\_ \r\n> - 5.3.1 : Some Built-in Classes\\_\r\n> - 5.3.2 : Wrapper Classes and\r\n> Autoboxing\\_\r\n> - 5.3.3 : The class \"Object\"\\_\r\n> - 5.3.4 : Object-oriented Analysis and\r\n> Design\\_\r\n>\r\n> - 5.5 : Inheritance, Polymorphism, and Abstract Classes\\_ \r\n> - 5.5.5 : Abstract Classes\\_\r\n>\r\n> - 5.7 : Interfaces, Nested Classes, and Other Details\\_ \r\n> - 5.7.1 : Interfaces\\_\r\n> - 5.7.2 : Nested Classes\\_\r\n", + "description": "

Mission 8. Interfaces

\r\n

Ces questions supposent que vous avez lu les sections suivantes du livre de référence JavaNotes_

\r\n
\r\n
    \r\n
  • \r\n
    4.5 : APIs, Packages, and Javadoc_
    \r\n
      \r\n
    • 4.5.2 : Toolboxes_
    • \r\n
    • 4.5.3 : Java's Standard Packages_
    • \r\n
    • 4.5.4 : Using Classes from Packages_
    • \r\n
    • 4.5.4 : Javadoc_
    • \r\n
    \r\n
    \r\n
  • \r\n
  • \r\n
    5.3 : Programming with Objects_
    \r\n
      \r\n
    • 5.3.1 : Some Built-in Classes_
    • \r\n
    • 5.3.2 : Wrapper Classes and Autoboxing_
    • \r\n
    • 5.3.3 : The class \"Object\"_
    • \r\n
    • 5.3.4 : Object-oriented Analysis and Design_
    • \r\n
    \r\n
    \r\n
  • \r\n
  • \r\n
    5.5 : Inheritance, Polymorphism, and Abstract Classes_
    \r\n
      \r\n
    • 5.5.5 : Abstract Classes_
    • \r\n
    \r\n
    \r\n
  • \r\n
  • \r\n
    5.7 : Interfaces, Nested Classes, and Other Details_
    \r\n
      \r\n
    • 5.7.1 : Interfaces_
    • \r\n
    • 5.7.2 : Nested Classes_
    • \r\n
    \r\n
    \r\n
  • \r\n
\r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -8165,7 +8165,7 @@ }, { "title": "Question de démarrage 1: Integer.compareTo", - "description": "La classe `Integer` dispose d'une méthode `compareTo()` dont voici la\r\nsignature :\r\n\r\n``` java\r\n/**\r\n * Compares two Integer objects numerically.\r\n * @pre anotherInteger!=null\r\n * @post returns the value 0 if this Integer is equal to\r\n * the argument Integer; a value less than 0 if this\r\n * Integer is numerically less than the argument Integer;\r\n * and a value greater than 0 if this Integer is\r\n * numerically\r\n * greater than the argument Integer (signed comparison).\r\n */\r\n public int compareTo(Integer anotherInteger)\r\n```\r\n\r\nComment feriez-vous pour implémenter une méthode similaire, mais de\r\nsignature :\r\n\r\n``` java\r\npublic int compareTo(Object o)\r\n```\r\n\r\n?\r\n\r\nÉcrivez le corps de cette nouvelle méthode qui prend un argument de type\r\n`Object` au lieu d'un argument de type `Integer`. Écrivez la réponse en\r\nune seule ligne. Notez que l'argument `o` sera toujours du type\r\n`Integer`. Pensez à utiliser des méthodes qui sont déjà à votre\r\ndisposition.\r\n", + "description": "

La classe Integer dispose d'une méthode compareTo() dont voici la signature :

\r\n
/**\r\n * Compares two Integer objects numerically.\r\n * @pre anotherInteger!=null\r\n * @post returns the value 0 if this Integer is equal to\r\n *        the    argument Integer; a value less than 0 if this\r\n *        Integer is numerically less than the argument Integer;\r\n *        and a value greater than 0 if this Integer is\r\n *         numerically\r\n *        greater than the argument Integer (signed comparison).\r\n */\r\n public int compareTo(Integer anotherInteger)
\r\n

Comment feriez-vous pour implémenter une méthode similaire, mais de signature :

\r\n
public int compareTo(Object o)
\r\n

?

\r\n

Écrivez le corps de cette nouvelle méthode qui prend un argument de type Object au lieu d'un argument de type Integer. Écrivez la réponse en une seule ligne. Notez que l'argument o sera toujours du type Integer. Pensez à utiliser des méthodes qui sont déjà à votre disposition.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -8214,7 +8214,7 @@ }, { "title": "Question de démarrage 2 : la méthode premierPrenom()", - "description": "Un étudiant nommé Jean-Complexe vient vers vous et vous dit que lui et\r\nses amis détestent leur prénom car leur prénom est composé, or, ils\r\ntrouvent cela trop long à prononcer. Ils désireraient ne garder que la\r\npremière partie de leur prénom.\r\n\r\nComme la fin d'année approche à grands pas cette histoire vous donne une\r\nidée pour vous entraîner pour l'examen de java et vous décidez\r\nd'implémenter une méthode qui prend un nom de fichier comme argument. Ce\r\nfichier contient sur chaque ligne un prénom composé (les deux parties du\r\nprénom sont séparées par le caractère `'-'`).\r\n\r\nLe but de votre méthode est de lire chaque ligne du fichier et, pour\r\nchaque ligne, afficher sur la sortie standard uniquement la première\r\npartie de ce nom composé, avec un résultat par ligne. En regardant l'API\r\nJava sur les `String`\r\n(), vous\r\nvous êtes rendu compte que la méthode `split` vous sera d'une grande\r\naide.\r\n\r\nBien entendu, vous savez que lire dans des fichier en Java peut\r\nprovoquer des exceptions et votre méthode s'arrangera pour les contenir\r\net retourner la valeur `-1` lorsque l'une d'entre elles apparaîtra.\r\n\r\nPrenons un exemple. Si le contenu du fichier est ci-dessous :\r\n\r\n Saint-François\r\n Jean-Pol\r\n Johnny-Hallyday\r\n\r\nVotre programme affichera ces lignes sur la sortie standard\r\n(`System.out`):\r\n\r\n Saint\r\n Jean\r\n Johnny\r\n\r\nAprès avoir mûrement réfléchi, vous avez décidé de la signature de votre\r\nméthode et il ne vous reste plus qu'à l'implémenter :\r\n\r\n``` java\r\n/**\r\n * @pre filename est le nom d'un fichier.\r\n * si le fichier désigné par filename est lisible,\r\n * chaque ligne du fichier contient un String en deux\r\n * parties, séparées par un \"-\".\r\n *\r\n * @post imprime sur la sortie standard la première partie de\r\n * chaque ligne du fichier désigné par filename, un\r\n * résultat par ligne.\r\n * Retourne -1 si une exception a été lancée.\r\n */\r\npublic static int premierPrenom(String filename){\r\n // À implémenter\r\n}\r\n```\r\n", + "description": "

Un étudiant nommé Jean-Complexe vient vers vous et vous dit que lui et ses amis détestent leur prénom car leur prénom est composé, or, ils trouvent cela trop long à prononcer. Ils désireraient ne garder que la première partie de leur prénom.

\r\n

Comme la fin d'année approche à grands pas cette histoire vous donne une idée pour vous entraîner pour l'examen de java et vous décidez d'implémenter une méthode qui prend un nom de fichier comme argument. Ce fichier contient sur chaque ligne un prénom composé (les deux parties du prénom sont séparées par le caractère '-').

\r\n

Le but de votre méthode est de lire chaque ligne du fichier et, pour chaque ligne, afficher sur la sortie standard uniquement la première partie de ce nom composé, avec un résultat par ligne. En regardant l'API Java sur les String (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html), vous vous êtes rendu compte que la méthode split vous sera d'une grande aide.

\r\n

Bien entendu, vous savez que lire dans des fichier en Java peut provoquer des exceptions et votre méthode s'arrangera pour les contenir et retourner la valeur -1 lorsque l'une d'entre elles apparaîtra.

\r\n

Prenons un exemple. Si le contenu du fichier est ci-dessous :

\r\n
Saint-François\r\nJean-Pol\r\nJohnny-Hallyday
\r\n

Votre programme affichera ces lignes sur la sortie standard (System.out):

\r\n
Saint\r\nJean\r\nJohnny
\r\n

Après avoir mûrement réfléchi, vous avez décidé de la signature de votre méthode et il ne vous reste plus qu'à l'implémenter :

\r\n
/**\r\n *     @pre     filename est le nom d'un fichier.\r\n *              si le fichier désigné par filename est lisible,\r\n *              chaque ligne du fichier contient un String en deux\r\n *              parties, séparées par un "-".\r\n *\r\n *     @post    imprime sur la sortie standard la première partie de\r\n *              chaque ligne du fichier désigné par filename, un\r\n *              résultat par ligne.\r\n *              Retourne -1 si une exception a été lancée.\r\n */\r\npublic static int premierPrenom(String filename){\r\n    // À implémenter\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -8268,7 +8268,7 @@ }, { "title": "Q* Fraction", - "description": "Un étudiant a écrit la classe suivante, mais il lui manque une méthode\r\npour qu'elle puisse être compilée. Pourriez-vous implémenter cette\r\nméthode ?\r\n\r\n``` java\r\npublic class Fraction implements Comparable {\r\n\r\n private int num; // numerateur\r\n private int den; // denominateur\r\n\r\n /**\r\n * @pre num >= 0, den > 0\r\n * @post construit la fraction num/den\r\n */\r\n public Fraction(int num, int den) {\r\n this.num=num;\r\n this.den=den;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le dénominateur de la fraction\r\n */\r\n public int getDen() {\r\n return this.den;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le numérateur de la fraction\r\n */\r\n public int getNum() {\r\n return this.num;\r\n }\r\n\r\n // Insérez le code manquant\r\n}\r\n```\r\n", + "description": "

Un étudiant a écrit la classe suivante, mais il lui manque une méthode pour qu'elle puisse être compilée. Pourriez-vous implémenter cette méthode ?

\r\n
public class Fraction implements Comparable {\r\n\r\n      private int num; // numerateur\r\n      private int den; // denominateur\r\n\r\n      /**\r\n       * @pre num >= 0, den > 0\r\n       * @post construit la fraction num/den\r\n       */\r\n      public Fraction(int num, int den) {\r\n          this.num=num;\r\n          this.den=den;\r\n      }\r\n\r\n      /*\r\n       * @pre -\r\n       * @post retourne le dénominateur de la fraction\r\n       */\r\n      public int getDen() {\r\n          return this.den;\r\n      }\r\n\r\n      /*\r\n       * @pre -\r\n       * @post retourne le numérateur de la fraction\r\n       */\r\n      public int getNum() {\r\n          return this.num;\r\n      }\r\n\r\n      // Insérez le code manquant\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -8322,7 +8322,7 @@ }, { "title": "Q* Employe", - "description": "Un étudiant a écrit la classe suivante, mais il lui manque une méthode\r\npour qu'elle puisse être compilée. Pourriez-vous implémenter cette\r\nméthode ?\r\n\r\n``` java\r\npublic class Employe implements Comparable {\r\n private String nom;\r\n private String prenom;\r\n private double salaire;\r\n\r\n /*\r\n * Constructeur\r\n * @pre nom != null, prenom != null, salaire > 0\r\n * @post a construit une instance de la classe Employe avec nom et salaire\r\n */\r\n public Employe (String nom, String prenom, double salaire){\r\n this.nom = nom;\r\n this.prenom=prenom;\r\n this.salaire = salaire;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le nom de l'employé this\r\n */\r\n public String getNom(){\r\n return nom ;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le prénom de l'employé this\r\n */\r\n public String getPrenom() {\r\n return prenom;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le salaire de l'employé this\r\n */\r\n public double getSalaire() {\r\n return salaire;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne un String décrivant l'employé this\r\n */\r\n public String toString() {\r\n return getPrenom()+\" \"+getNom()+\" (\"+getSalaire()+\")\";\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne true si this et other correspondent au\r\n * même employé (même nom, même prénom, même salaire)\r\n */\r\n public boolean equals(Object other) {\r\n if (other instanceof Employe) {\r\n Employe e = (Employe) other;\r\n return (this.getNom().equals(e.getNom())\r\n && (this.getPrenom().equals(e.getPrenom()))\r\n && (this.getSalaire()==e.getSalaire()));\r\n } else {\r\n return false;\r\n }\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne un entier négatif si l'employé this\r\n * est inférieur dans l'ordre alphabétique à other.\r\n * 0 si this et other correspondent au même employé\r\n * (même nom, même prénom, même salaire)\r\n * Un entier positif si l'employé this est supérieur\r\n * dans l'ordre alphabétique à other.\r\n * Pour tester l'ordre alphabétique, on regarde d'abord\r\n * le nom, ensuite le prénom et enfin le salaire\r\n * (le salaire inférieur étant considéré comme avant\r\n * un salaire supérieur)\r\n */\r\n //Insérez ici le code manquant\r\n}\r\n```\r\n\r\nPour rappel, la documentation de l'interface Comparable est disponible\r\nvia\r\n\r\n", + "description": "

Un étudiant a écrit la classe suivante, mais il lui manque une méthode pour qu'elle puisse être compilée. Pourriez-vous implémenter cette méthode ?

\r\n
public class Employe implements Comparable {\r\n   private String nom;\r\n   private String prenom;\r\n   private double salaire;\r\n\r\n   /*\r\n    * Constructeur\r\n    * @pre nom != null, prenom != null, salaire > 0\r\n    * @post a construit une instance de la classe Employe avec nom et salaire\r\n    */\r\n   public Employe (String nom, String prenom, double salaire){\r\n      this.nom = nom;\r\n      this.prenom=prenom;\r\n      this.salaire = salaire;\r\n   }\r\n\r\n   /*\r\n    * @pre -\r\n    * @post retourne le nom de l'employé this\r\n    */\r\n   public String getNom(){\r\n       return nom ;\r\n   }\r\n\r\n   /*\r\n    * @pre -\r\n    * @post retourne le prénom de l'employé this\r\n    */\r\n   public String getPrenom() {\r\n       return prenom;\r\n   }\r\n\r\n   /*\r\n    * @pre -\r\n    * @post retourne le salaire de l'employé this\r\n    */\r\n   public double getSalaire() {\r\n       return salaire;\r\n   }\r\n\r\n   /*\r\n    * @pre -\r\n    * @post retourne un String décrivant l'employé this\r\n    */\r\n   public String toString() {\r\n       return getPrenom()+" "+getNom()+" ("+getSalaire()+")";\r\n   }\r\n\r\n   /*\r\n    * @pre -\r\n    * @post retourne true si this et other correspondent au\r\n    *       même employé (même nom, même prénom, même salaire)\r\n    */\r\n   public boolean equals(Object other) {\r\n       if (other instanceof Employe) {\r\n            Employe e = (Employe) other;\r\n            return (this.getNom().equals(e.getNom())\r\n                    && (this.getPrenom().equals(e.getPrenom()))\r\n                    && (this.getSalaire()==e.getSalaire()));\r\n        } else {\r\n            return false;\r\n        }\r\n   }\r\n\r\n   /*\r\n    * @pre -\r\n    * @post retourne un entier négatif si l'employé this\r\n    *        est inférieur dans l'ordre alphabétique à other.\r\n    *      0 si this et other correspondent au même employé\r\n    *        (même nom, même prénom, même salaire)\r\n    *      Un entier positif si l'employé this est supérieur\r\n    *        dans l'ordre alphabétique à other.\r\n    *      Pour tester l'ordre alphabétique, on regarde d'abord\r\n    *        le nom, ensuite le prénom et enfin le salaire\r\n    *        (le salaire inférieur étant considéré comme avant\r\n    *            un salaire supérieur)\r\n    */\r\n   //Insérez ici le code manquant\r\n}
\r\n

Pour rappel, la documentation de l'interface Comparable est disponible via https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

\r\n", "tags": [ { "text": "INGINIOUS", @@ -8376,7 +8376,7 @@ }, { "title": "Q* Fichiers", - "description": "La classe `Fichiers` est une classe permettant de réaliser quelques\r\ntâches sur un fichier. On vous demande ici d'écrire la méthodes\r\n`countLines` dont les spécifications et la signature sont :\r\n\r\n``` java\r\n/*\r\n * @pre -\r\n * @post ouvre le fichier filename et retourne le nombre\r\n * de lignes présentes dans ce fichier.\r\n * Retourne -1 en cas d'erreur de lecture ou d'accès au fichier\r\n */\r\n public int countLines(String fileName);\r\n```\r\n\r\nPour lire le fichier, nous vous demandons d'utilisez un\r\n`BufferedReader`.\r\n", + "description": "

La classe Fichiers est une classe permettant de réaliser quelques tâches sur un fichier. On vous demande ici d'écrire la méthodes countLines dont les spécifications et la signature sont :

\r\n
/*\r\n * @pre -\r\n * @post ouvre le fichier filename et retourne le nombre\r\n *       de lignes présentes dans ce fichier.\r\n *       Retourne -1 en cas d'erreur de lecture ou d'accès au fichier\r\n */\r\n  public int countLines(String fileName);
\r\n

Pour lire le fichier, nous vous demandons d'utilisez un BufferedReader.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -8430,7 +8430,7 @@ }, { "title": "Q* Fichiers : Contains", - "description": "La classe `Fichiers` est une classe permettant de réaliser quelques\r\ntâches sur un fichier. On vous demande ici d'écrire la méthodes\r\n`contains` dont les spécifications et la signature sont :\r\n\r\n``` java\r\n/*\r\n * @pre fileName != null\r\n * @post retourne true si le fichier de nom fileName contient\r\n * au moins une occurence de la chaîne s,\r\n * false sinon et en cas d'erreur également\r\n */\r\n public boolean contains(String s, String fileName)\r\n```\r\n\r\nOn vous demande d'utiliser un `BufferedReader` pour lire le fichier\r\n", + "description": "

La classe Fichiers est une classe permettant de réaliser quelques tâches sur un fichier. On vous demande ici d'écrire la méthodes contains dont les spécifications et la signature sont :

\r\n
/*\r\n * @pre fileName != null\r\n * @post retourne true si le fichier de nom fileName contient\r\n *       au moins une occurence de la chaîne s,\r\n *       false sinon et en cas d'erreur également\r\n */\r\n public boolean contains(String s, String fileName)
\r\n

On vous demande d'utiliser un BufferedReader pour lire le fichier

\r\n", "tags": [ { "text": "INGINIOUS", @@ -8484,7 +8484,7 @@ }, { "title": "Q* Fichiers:Accessible", - "description": "La classe `Fichiers` est une classe permettant de réaliser quelques\r\ntâches sur un fichier. On vous demande ici d'écrire la méthodes\r\n`accessible` dont les spécifications et la signature sont :\r\n\r\n``` java\r\n/*\r\n * @pre -\r\n * @post retourne true si le fichier de nom fileName est accessible (c'est-à-dire qu'il peut être ouvert)\r\n * false sinon\r\n */\r\n public static boolean accessible(String fileName)\r\n```\r\n\r\nOn vous demande d'utiliser un `BufferedReader` si vous devez lire le\r\nfichier.\r\n", + "description": "

La classe Fichiers est une classe permettant de réaliser quelques tâches sur un fichier. On vous demande ici d'écrire la méthodes accessible dont les spécifications et la signature sont :

\r\n
/*\r\n * @pre -\r\n * @post retourne true si le fichier de nom fileName est accessible (c'est-à-dire qu'il peut être ouvert)\r\n *       false sinon\r\n */\r\n public static boolean accessible(String fileName)
\r\n

On vous demande d'utiliser un BufferedReader si vous devez lire le fichier.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -8538,7 +8538,7 @@ }, { "title": "Q* Fichiers:saveVector", - "description": "La classe `Fichiers` est une classe permettant de réaliser quelques\r\ntâches sur un fichier. On vous demande ici d'écrire la méthodes\r\n`saveVector` dont les spécifications et la signature sont :\r\n\r\n``` java\r\n/*\r\n * @pre v!=null, fileName!=null\r\n * @post sauve dans le fichier dont le nom est fileName le contenu du vecteur v\r\n * le format du fichier est :\r\n * première ligne : nombre d'éléments du vecteur\r\n * lignes suivantes : un élément par ligne en commençant par v[0] ...\r\n */\r\n public void saveVector(int [] v, String fileName)\r\n```\r\n", + "description": "

La classe Fichiers est une classe permettant de réaliser quelques tâches sur un fichier. On vous demande ici d'écrire la méthodes saveVector dont les spécifications et la signature sont :

\r\n
/*\r\n * @pre v!=null, fileName!=null\r\n * @post sauve dans le fichier dont le nom est fileName le contenu du vecteur v\r\n *       le format du fichier est :\r\n *     première ligne : nombre d'éléments du vecteur\r\n *     lignes suivantes : un élément par ligne en commençant par v[0] ...\r\n */\r\n public void saveVector(int [] v, String fileName)
\r\n", "tags": [ { "text": "INGINIOUS", @@ -8592,7 +8592,7 @@ }, { "title": "Q* Fichiers:readVector", - "description": "La classe `Fichiers` est une classe permettant de réaliser quelques\r\ntâches sur un fichier. On vous demande ici d'écrire la méthodes\r\n`readVector` dont les spécifications et la signature sont :\r\n\r\n``` java\r\n/*\r\n * @pre fileName!=null\r\n * @post lit dans le fichier dont le nom est fileName le contenu du vecteur v\r\n * le format du fichier est :\r\n * première ligne : nombre d'éléments du vecteur\r\n * lignes suivantes : un élément par ligne en commençant par v[0] ...\r\n *\r\n * En cas d'erreur (exception, fichier non lisible, nombre incorrect d'éléments\r\n * dans le fichier, format de nombre incorrect, ...), retourne null\r\n */\r\n public int[] readVector(String fileName)\r\n```\r\n\r\nPour lire le fichier, nous vous demandons d'utiliser un\r\n`BufferedReader`.\r\n", + "description": "

La classe Fichiers est une classe permettant de réaliser quelques tâches sur un fichier. On vous demande ici d'écrire la méthodes readVector dont les spécifications et la signature sont :

\r\n
/*\r\n * @pre fileName!=null\r\n * @post lit dans le fichier dont le nom est fileName le contenu du vecteur v\r\n *       le format du fichier est :\r\n *     première ligne : nombre d'éléments du vecteur\r\n *     lignes suivantes : un élément par ligne en commençant par v[0] ...\r\n *\r\n *     En cas d'erreur (exception, fichier non lisible, nombre incorrect d'éléments\r\n *     dans le fichier, format de nombre incorrect, ...), retourne null\r\n */\r\n public  int[] readVector(String fileName)
\r\n

Pour lire le fichier, nous vous demandons d'utiliser un BufferedReader.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -8646,7 +8646,7 @@ }, { "title": "Phase de réalisation: Soumission", - "description": "Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour\r\nla Mission 9.\r\n\r\nVous attendons une archive **.zip** contenant uniquement les fichiers :\r\n\r\n- Dico.java\r\n- Dictionary.java\r\n- Word.java\r\n- README.txt\r\n", + "description": "

Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour la Mission 9.

\r\n

Vous attendons une archive .zip contenant uniquement les fichiers :

\r\n
    \r\n
  • Dico.java
  • \r\n
  • Dictionary.java
  • \r\n
  • Word.java
  • \r\n
  • README.txt
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -8700,7 +8700,7 @@ }, { "title": "Question de Bilan Final", - "description": "Vous devez implémenter une méthode `getMax` dont le but est de\r\nretrouver, dans un fichier, la ligne contenant le nombre flottant avec\r\nla plus grande valeur. Si un tel nombre n'existe pas, la méthode doit\r\nrenvoyer -∞. En cas d'erreur lors de la lecture du fichier, le programme\r\ndoit se quitter et afficher exactement `ERREUR` sur `System.err`.\r\n\r\nVoici la spécification préçise de la méthode :\r\n\r\n``` java\r\n/**\r\n * @pre filename != null, filename est le nom d’un fichier de texte.\r\n * Chaque ligne valide du fichier représente un seul nombre réel.\r\n * @post - La valeur renvoyée contient le nombre flottant avec la plus grande valeur\r\n * parmi tous les nombres flottants valides du fichier.\r\n * S'il n'y a aucun nombre valide, la valeur renvoyée contient -∞.\r\n * - Si le fichier n’existe pas ou si une erreur d'entrée/sortie survient,\r\n * le programme se termine en affichant ERREUR System.err.\r\n *\r\n * Par exemple, la méthode renvoie 10.0 pour le contenu de fichier suivant :\r\n * 0.345.67\r\n * hello\r\n * -543.0\r\n * 500.0 1000.0 2000.0\r\n * 10.0\r\n * 3.1416\r\n */\r\npublic static double getMax (String filename)\r\n```\r\n", + "description": "

Vous devez implémenter une méthode getMax dont le but est de retrouver, dans un fichier, la ligne contenant le nombre flottant avec la plus grande valeur. Si un tel nombre n'existe pas, la méthode doit renvoyer -∞. En cas d'erreur lors de la lecture du fichier, le programme doit se quitter et afficher exactement ERREUR sur System.err.

\r\n

Voici la spécification préçise de la méthode :

\r\n
/**\r\n * @pre filename != null, filename est le nom d’un fichier de texte.\r\n *      Chaque ligne valide du fichier représente un seul nombre réel.\r\n * @post - La valeur renvoyée contient le nombre flottant avec la plus grande valeur\r\n *         parmi tous les nombres flottants valides du fichier.\r\n *         S'il n'y a aucun nombre valide, la valeur renvoyée contient -∞.\r\n *       - Si le fichier n’existe pas ou si une erreur d'entrée/sortie survient,\r\n *         le programme se termine en affichant ERREUR System.err.\r\n *\r\n *       Par exemple, la méthode renvoie 10.0 pour le contenu de fichier suivant :\r\n *          0.345.67\r\n *          hello\r\n *          -543.0\r\n *          500.0 1000.0 2000.0\r\n *          10.0\r\n *          3.1416\r\n */\r\npublic static double getMax (String filename)
\r\n", "tags": [ { "text": "INGINIOUS", @@ -8759,7 +8759,7 @@ }, { "title": "QCM", - "description": "Mission 9. Fichiers\r\n===================\r\n\r\nCes questions supposent que vous avez lu les sections suivantes du livre\r\nde référence JavaNotes\\_\r\n\r\n> - 3.7 : Introduction to Exceptions and try..catch\\_ \r\n> - 3.7.1 : Exceptions\\_\r\n> - 3.7.2 : try..catch\\_\r\n>\r\n> - 8.1 : Introduction to Correctness and Robustness\\_ \r\n> - 8.1.1 : Horror Stories\\_\r\n> - 8.1.2 : Java to the Rescue\\_\r\n> - 8.1.3 : Problems Remain in\r\n> Java\\_\r\n>\r\n> - 8.3 : Exceptions and try..catch\\_ \r\n> - 8.3.1 : Exceptions and Exception\r\n> Classes\\_\r\n> - 8.3.2 : The try Statement\\_\r\n>\r\n> - 11.1 : Streams, Readers, and Writers\\_ \r\n> - 11.1.1 : Character and Byte\r\n> Streams\\_\r\n> - 11.1.2 : PrintWriter\\_\r\n> - 11.1.3 : Data Streams\\_\r\n> - 11.1.4 : Reading Text\\_\r\n> - 11.1.5 : The Scanner Class\\_\r\n>\r\n> - 11.2 : Files\\_ \r\n> - 11.2.1 : Reading and Writing\r\n> Files\\_\r\n\r\nainsi que l'API de la classe `java.util.Arrays`\\_.\r\n", + "description": "

Mission 9. Fichiers

\r\n

Ces questions supposent que vous avez lu les sections suivantes du livre de référence JavaNotes_

\r\n
\r\n
    \r\n
  • \r\n
    3.7 : Introduction to Exceptions and try..catch_
    \r\n
      \r\n
    • 3.7.1 : Exceptions_
    • \r\n
    • 3.7.2 : try..catch_
    • \r\n
    \r\n
    \r\n
  • \r\n
  • \r\n
    8.1 : Introduction to Correctness and Robustness_
    \r\n
      \r\n
    • 8.1.1 : Horror Stories_
    • \r\n
    • 8.1.2 : Java to the Rescue_
    • \r\n
    • 8.1.3 : Problems Remain in Java_
    • \r\n
    \r\n
    \r\n
  • \r\n
  • \r\n
    8.3 : Exceptions and try..catch_
    \r\n
      \r\n
    • 8.3.1 : Exceptions and Exception Classes_
    • \r\n
    • 8.3.2 : The try Statement_
    • \r\n
    \r\n
    \r\n
  • \r\n
  • \r\n
    11.1 : Streams, Readers, and Writers_
    \r\n
      \r\n
    • 11.1.1 : Character and Byte Streams_
    • \r\n
    • 11.1.2 : PrintWriter_
    • \r\n
    • 11.1.3 : Data Streams_
    • \r\n
    • 11.1.4 : Reading Text_
    • \r\n
    • 11.1.5 : The Scanner Class_
    • \r\n
    \r\n
    \r\n
  • \r\n
  • \r\n
    11.2 : Files_
    \r\n
      \r\n
    • 11.2.1 : Reading and Writing Files_
    • \r\n
    \r\n
    \r\n
  • \r\n
\r\n
\r\n

ainsi que l'API de la classe java.util.Arrays_.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -8808,7 +8808,7 @@ }, { "title": "Question de démarrage 1 : Traitement des exceptions", - "description": "En Java, les exceptions sont un concept clé qui vous permet de gérer le\r\ncomportement de votre programme dans des cas extraordinaires. Voici la\r\nclasse `RevisedRatio` :\r\n\r\n``` java\r\npublic static class RevisedRatio {\r\n /**\r\n * @pre n1 et n2 sont des chaînes de caractères != null\r\n * @post après conversion de n1 et n2 en entier, retourne n1/n2, peut lancer une NumberFormatException si un des strings n'est pas un nombre\r\n */\r\n public static int divise(String n1, String n2) {\r\n int n = Integer.parseInt(n1);\r\n int d = Integer.parseInt(n2);\r\n return doDivise(n, d);\r\n }\r\n\r\n /**\r\n * @pre n et d sont des entiers\r\n * @post retourne n/d si d!=0, sinon throws AritmeticException\r\n */\r\n public static int doDivise(int n, int d) {\r\n return (n/d);\r\n }\r\n\r\n /**\r\n * @pre args contient un tableau de String passés en ligne\r\n * de commande\r\n * @post si args contient seulement un String, affiche un\r\n * message d'erreur sinon affiche le résultat de la\r\n * division de args[0] par args[i] pour tout\r\n * 0 < i < args.length, un résultat par ligne\r\n */\r\n public static int div(String[] args) {\r\n if(args.length < 2) {\r\n System.out.println(\"Erreur : la ligne de commande doit être :\");\r\n System.out.println(\"java ratio num1 num2 num3... \");\r\n System.exit(-1);\r\n }\r\n else {\r\n for(int i=1; iEn Java, les exceptions sont un concept clé qui vous permet de gérer le comportement de votre programme dans des cas extraordinaires. Voici la classe RevisedRatio :

\r\n
public static class RevisedRatio {\r\n    /**\r\n     * @pre n1 et n2 sont des chaînes de caractères != null\r\n     * @post après conversion de n1 et n2 en entier, retourne n1/n2, peut lancer une NumberFormatException si un des strings n'est pas un nombre\r\n     */\r\n    public static int divise(String n1, String n2) {\r\n        int n = Integer.parseInt(n1);\r\n        int d = Integer.parseInt(n2);\r\n        return doDivise(n, d);\r\n    }\r\n\r\n    /**\r\n     * @pre  n et d sont des entiers\r\n     * @post retourne n/d si d!=0, sinon throws AritmeticException\r\n     */\r\n    public static int doDivise(int n, int d) {\r\n        return (n/d);\r\n    }\r\n\r\n    /**\r\n     * @pre  args contient un tableau de String passés en ligne\r\n     *         de commande\r\n     * @post si args contient seulement un String, affiche un\r\n     *         message d'erreur sinon affiche le résultat de la\r\n     *         division de args[0] par args[i] pour tout\r\n     *         0 < i < args.length, un résultat par ligne\r\n     */\r\n    public static int div(String[] args) {\r\n        if(args.length < 2) {\r\n            System.out.println("Erreur : la ligne de commande doit être :");\r\n            System.out.println("java ratio num1 num2 num3... ");\r\n            System.exit(-1);\r\n        }\r\n        else {\r\n            for(int i=1; i<args.length;i++) {\r\n                /*1*/    // À réécrire\r\n                System.out.println(args[0] + "/" + args[i] +\r\n                    " = " + divise(args[0], args[i]));\r\n            }\r\n        }\r\n        return 0;\r\n    }\r\n\r\n    public static void main(String[] args){\r\n        if(div(args) != -1){\r\n            System.out.println("Tout s'est bien passé");\r\n            System.exit(0);\r\n        }\r\n        else{\r\n            System.out.println("Veuillez donner des arguments "\r\n                                +"corrects la prochaine fois.");\r\n            System.exit(-1);\r\n        }\r\n    }\r\n}
\r\n

La méthode div récupère les arguments de la méthode main qui l'appelle et traite la division de args[0] par args[i] pour tout 0 < i < args.length. La méthode affiche la réponse sous la forme \"args[0]/args[i] = reponse\". Par exemple, quand on l'appelle avec les arguments \"20\", \"5\" et \"10\", la méthode affiche sur la sortie standard :

\r\n
20/5 = 4\r\n20/10 = 2
\r\n

Pour le moment, l'appel à cette méthode avec de mauvais arguments pourrait faire crasher le programme en lançant une NumberFormatException ou une ArithmeticException.

\r\n

Réécrivez entièrement l'intérieur de la boucle for de manière à ce que lorsqu'une de ces deux exceptions est lancée, la méthode affiche le message d'erreur Vous ne pouvez pas diviser par 0. pour la division par 0 et le message La chaîne de caractères passée à parseInt() ne contient pas que des chiffres. pour l'erreur de parsing, sur la sortie d'erreur standard et retourne directement la valeur -2. Sur la sortie d'erreur standard, on doit pouvoir voir par exemple, en cas de NumberFormatException:

\r\n
La chaîne de caractères passée à parseInt() ne contient pas que des chiffres.
\r\n", "tags": [ { "text": "INGINIOUS", @@ -8867,7 +8867,7 @@ }, { "title": "Question de démarrage 2 : Écriture dans des fichiers", - "description": "Écrivez le corps de la méthode `write`, qui prend en argument un entier\r\n`n` et un nom de fichier `filename` et qui écrit les `n` premiers\r\nentiers strictement positifs dans un fichier dont le nom est contenu\r\ndans `filename`, en affichant un seul nombre par ligne. Voici la\r\nsignature de la méthode `write` :\r\n\r\n``` java\r\n/**\r\n * @pre n>0, filename != null\r\n * @post crée le fichier dont le nom est filename et écrit dans\r\n * ce fichier les n premiers entiers strictement positifs,\r\n * un entier par ligne.\r\n * En cas d'erreur d'I/O, retourne -1.\r\n * Retourne 0 si tout s'est bien déroulé.\r\n */\r\npublic static int write(int n, String filename)\r\n```\r\n\r\nFaites bien attention à gérer les erreurs d'I/O.\r\n", + "description": "

Écrivez le corps de la méthode write, qui prend en argument un entier n et un nom de fichier filename et qui écrit les n premiers entiers strictement positifs dans un fichier dont le nom est contenu dans filename, en affichant un seul nombre par ligne. Voici la signature de la méthode write :

\r\n
/**\r\n *    @pre    n>0, filename != null\r\n *    @post    crée le fichier dont le nom est filename et écrit dans\r\n *            ce fichier les n premiers entiers strictement positifs,\r\n *            un entier par ligne.\r\n *            En cas d'erreur d'I/O, retourne -1.\r\n *            Retourne 0 si tout s'est bien déroulé.\r\n */\r\npublic static int write(int n, String filename)
\r\n

Faites bien attention à gérer les erreurs d'I/O.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -8926,7 +8926,7 @@ }, { "title": "Q* Fraction", - "description": "Un étudiant a écrit la classe suivante, mais il lui manque une méthode\r\npour qu'elle puisse être compilée. Pourriez-vous implémenter cette\r\nméthode ?\r\n\r\n``` java\r\npublic class Fraction implements Comparable {\r\n private int num; // numerateur\r\n private int den; // denominateur\r\n\r\n /**\r\n * @pre num >= 0, den > 0\r\n * @post construit la fraction num/den\r\n */\r\n public Fraction(int num, int den) {\r\n this.num = num;\r\n this.den = den;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le dénominateur de la fraction\r\n */\r\n public int getDen() {\r\n return this.den;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le numérateur de la fraction\r\n */\r\n public int getNum() {\r\n return this.num;\r\n }\r\n\r\n // Insérez le code manquant\r\n}\r\n```\r\n\r\nTel qu'il est écrit, ce code ne compile pas. Il manque une méthode.\r\nPourriez-vous l'ajouter (signature et corps) ?\r\n", + "description": "

Un étudiant a écrit la classe suivante, mais il lui manque une méthode pour qu'elle puisse être compilée. Pourriez-vous implémenter cette méthode ?

\r\n
public class Fraction implements Comparable<Fraction> {\r\n      private int num; // numerateur\r\n      private int den; // denominateur\r\n\r\n      /**\r\n       * @pre num >= 0, den > 0\r\n       * @post construit la fraction num/den\r\n       */\r\n      public Fraction(int num, int den) {\r\n          this.num = num;\r\n          this.den = den;\r\n      }\r\n\r\n      /*\r\n       * @pre -\r\n       * @post retourne le dénominateur de la fraction\r\n       */\r\n      public int getDen() {\r\n          return this.den;\r\n      }\r\n\r\n      /*\r\n       * @pre -\r\n       * @post retourne le numérateur de la fraction\r\n       */\r\n      public int getNum() {\r\n          return this.num;\r\n      }\r\n\r\n      // Insérez le code manquant\r\n}
\r\n

Tel qu'il est écrit, ce code ne compile pas. Il manque une méthode. Pourriez-vous l'ajouter (signature et corps) ?

\r\n", "tags": [ { "text": "INGINIOUS", @@ -8980,7 +8980,7 @@ }, { "title": "Q* Fraction - Constructeur", - "description": "Revenons à la classe Fraction. Pour faciliter la création de fractions\r\nsur base de données lues depuis le clavier ou dans un fichier, on vous\r\ndemande d'ajouter à cette classe un constructeur qui prend comme\r\nargument un String. Si ce String a comme format x/y avec x et y qui sont\r\ndes entiers, il crée l'instance de la classe Fraction ayant x comme\r\nnumérateur et y comme dénominateur. Pour les cas de String null / qui ne\r\nrespectent pas le format demandé/ qui génère une division par zéro,\r\nlancez une NumberFormatException.\r\n\r\n``` java\r\npublic class Fraction implements Comparable {\r\n private int num; // numerateur\r\n private int den; // denominateur\r\n\r\n /**\r\n * @pre den>0\r\n * @post construit la fraction num/den\r\n */\r\n public Fraction(int num, int den) {\r\n this.num=num;\r\n this.den=den;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post construit une fraction sur base d'une chaine caractère de la\r\n * forme num/den où num est un entier et den un entier non nul\r\n * lance une exception lorsque la chaîne de caractères passée\r\n * en argument ne respecte pas ce format ou que le dénominateur est nul\r\n */\r\n public Fraction(String s) throws NumberFormatException {\r\n // à compléter\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le dénominateur de la fraction\r\n */\r\n public int getDen() {\r\n return this.den;\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne le numérateur de la fraction\r\n */\r\n public int getNum() {\r\n return this.num;\r\n }\r\n}\r\n```\r\n", + "description": "

Revenons à la classe Fraction. Pour faciliter la création de fractions sur base de données lues depuis le clavier ou dans un fichier, on vous demande d'ajouter à cette classe un constructeur qui prend comme argument un String. Si ce String a comme format x/y avec x et y qui sont des entiers, il crée l'instance de la classe Fraction ayant x comme numérateur et y comme dénominateur. Pour les cas de String null / qui ne respectent pas le format demandé/ qui génère une division par zéro, lancez une NumberFormatException.

\r\n
public class Fraction implements Comparable<Fraction> {\r\n  private int num; // numerateur\r\n  private int den; // denominateur\r\n\r\n  /**\r\n  * @pre den>0\r\n  * @post construit la fraction num/den\r\n  */\r\n  public Fraction(int num, int den) {\r\n      this.num=num;\r\n      this.den=den;\r\n  }\r\n\r\n  /*\r\n  * @pre -\r\n  * @post construit une fraction sur base d'une chaine caractère de la\r\n  * forme num/den  où num est un entier et den un entier non nul\r\n  * lance une exception lorsque la chaîne de caractères passée\r\n  * en argument ne respecte pas ce format ou que le dénominateur est nul\r\n  */\r\n  public Fraction(String s) throws NumberFormatException {\r\n      // à compléter\r\n  }\r\n\r\n  /*\r\n  * @pre -\r\n  * @post retourne le dénominateur de la fraction\r\n  */\r\n  public int getDen() {\r\n      return this.den;\r\n  }\r\n\r\n  /*\r\n  * @pre -\r\n  * @post retourne le numérateur de la fraction\r\n  */\r\n  public int getNum() {\r\n      return this.num;\r\n  }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -9039,7 +9039,7 @@ }, { "title": "Q* Student - Constructeur", - "description": "Dans la classe `Student`, implémentez le second `constructeur` qui prend\r\ncomme argument un `String`.\r\n\r\n``` java\r\n/**\r\n * Une classe décrivant un étudiant\r\n *\r\n * @author O. Bonaventure\r\n * @version Novembre 2016\r\n */\r\nimport java.util.Arrays;\r\npublic class Student {\r\n public String nom;\r\n public double[] cotes;\r\n\r\n /**\r\n * @pre nom != null, cotes != null\r\n * @post a construit une instance de la classe Student\r\n * lance une exception StudentFormatException si une des\r\n * cotes est invalide (non comprise entre 0 et 20)\r\n */\r\n public Student(String nom, double[] cotes) throws StudentFormatException {\r\n //code non fourni\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post construit une instance de la classe Student\r\n * en supposant que le String s a le format suivant\r\n * nom; 2.5, 3.0, 6.7\r\n * Le nom est suivi de ; et une virgule sépare les cotes.\r\n * Celles-ci doivent être entre 0 et 20\r\n * Il faut au moins une cote\r\n * Si le format n'est pas respecté, le constructeur\r\n * lance une StudentFormatException\r\n * avec comme argument le String passé\r\n */\r\n public Student(String s) throws StudentFormatException {\r\n // Question\r\n }\r\n}\r\n```\r\n", + "description": "

Dans la classe Student, implémentez le second constructeur qui prend comme argument un String.

\r\n
/**\r\n * Une classe décrivant un étudiant\r\n *\r\n * @author O. Bonaventure\r\n * @version Novembre 2016\r\n */\r\nimport java.util.Arrays;\r\npublic class Student {\r\n    public String nom;\r\n    public double[] cotes;\r\n\r\n    /**\r\n     * @pre nom != null, cotes != null\r\n     * @post a construit une instance de la classe Student\r\n     *       lance une exception StudentFormatException si une des\r\n     *       cotes est invalide (non comprise entre 0 et 20)\r\n     */\r\n    public Student(String nom, double[] cotes) throws StudentFormatException {\r\n        //code non fourni\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post construit une instance de la classe Student\r\n     *      en supposant que le String s a le format suivant\r\n     *      nom; 2.5, 3.0, 6.7\r\n     *      Le nom est suivi de ; et une virgule sépare les cotes.\r\n     *       Celles-ci doivent être entre 0 et 20\r\n     *       Il faut au moins une cote\r\n     *       Si le format n'est pas respecté, le constructeur\r\n     *       lance une StudentFormatException\r\n     *       avec comme argument le String passé\r\n     */\r\n    public Student(String s) throws StudentFormatException {\r\n        // Question\r\n    }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -9093,7 +9093,7 @@ }, { "title": "Q* AList", - "description": "La classe AList contient une implémentation simple d'un ArrayList sur\r\nbase d'un tableau dont la taille augmente au fur et à mesure que l'on\r\nmodifie la liste. Ecrivez le code des principales méthodes de cette\r\nclasse:\r\n\r\n``` java\r\n/**\r\n * Une implémentation partielle d'une ArrayList en utilisant un tableau\r\n *\r\n * Cette implémentation supporte les méthodes suivantes :\r\n *\r\n * Constructeur : crée une liste vide • AList()\r\n * Insère d’un élément à la position index • void add (int index, Object obj)\r\n * Renvoie l’objet en position index • Object get (int index)\r\n * Remplace l’élément en position index • void set (int index, Object obj)\r\n * Retire et renvoie l’élément en position index • Object remove (int index)\r\n * Renvoie true si obj appartient à la liste • boolean contains (Object obj)\r\n *\r\n * @author O; Bonaventure\r\n * @version Novembre 2016\r\n */\r\npublic class AList {\r\n private Object[] l;\r\n\r\n public static final int INIT_SIZE = 5; // taille initiale d'un AList\r\n\r\n /*\r\n * @pre -\r\n * @post a créé une AList initialement vide\r\n * permettant de stocker 5 références\r\n */\r\n public AList() {\r\n l = new Object[INIT_SIZE];\r\n }\r\n\r\n /*\r\n * @pre o != null\r\n * @post retourne true si l'objet o se trouve dans l'AList\r\n */\r\n public boolean contains(Object o) {\r\n // Question\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post retourne l'objet se trouvant à la position index\r\n * et null si rien n'est stocké à cette position\r\n * ou si index >= length\r\n */\r\n public Object get(int index) {\r\n // Question\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @retourne la taille actuelle de la liste\r\n */\r\n public int length() {\r\n return l.length;\r\n }\r\n\r\n /*\r\n * @pre 0 <= index < this.length()\r\n * @post remplace la référence se trouvant à l'index dans\r\n * la liste par la référence à o\r\n */\r\n public void set(int index, Object o) {\r\n // Question\r\n }\r\n\r\n /*\r\n * @pre -\r\n * @post remplace l'objet o dans la liste en position index\r\n * Si index >= length, augmente d'abord la taille\r\n * de la liste en créant un nouveau tableau et\r\n * en y recopiant toutes les références de la liste\r\n * this avant de remplacer l'objet o à l'indice index\r\n */\r\n public void add(int index, Object o) {\r\n // Question\r\n }\r\n}\r\n```\r\n\r\nVous pouvez tester vos méthodes individuellement.\r\n", + "description": "

La classe AList contient une implémentation simple d'un ArrayList sur base d'un tableau dont la taille augmente au fur et à mesure que l'on modifie la liste. Ecrivez le code des principales méthodes de cette classe:

\r\n
/**\r\n * Une implémentation partielle d'une ArrayList en utilisant un tableau\r\n *\r\n * Cette implémentation supporte les méthodes suivantes :\r\n *\r\n * Constructeur : crée une liste vide  •  AList()\r\n * Insère d’un élément à la position index  •  void add (int index, Object obj)\r\n * Renvoie l’objet en position index  •  Object get (int index)\r\n * Remplace l’élément en position index  •  void set (int index, Object obj)\r\n * Retire et renvoie l’élément en position index  •  Object remove (int index)\r\n * Renvoie true si obj appartient à la liste  •  boolean contains (Object obj)\r\n *\r\n * @author O; Bonaventure\r\n * @version Novembre 2016\r\n */\r\npublic class AList {\r\n    private Object[] l;\r\n\r\n    public static final int INIT_SIZE = 5; // taille initiale d'un AList\r\n\r\n    /*\r\n     * @pre -\r\n     * @post a créé une AList initialement vide\r\n     *       permettant de stocker 5 références\r\n     */\r\n    public AList() {\r\n        l = new Object[INIT_SIZE];\r\n    }\r\n\r\n    /*\r\n     * @pre o != null\r\n     * @post retourne true si l'objet o se trouve dans l'AList\r\n     */\r\n    public boolean contains(Object o) {\r\n        // Question\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post retourne l'objet se trouvant à la position index\r\n     *       et null si rien n'est stocké à cette position\r\n     *       ou si index >= length\r\n     */\r\n    public Object get(int index) {\r\n        // Question\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @retourne la taille actuelle de la liste\r\n     */\r\n    public int length() {\r\n        return l.length;\r\n    }\r\n\r\n    /*\r\n     * @pre 0 <= index < this.length()\r\n     * @post remplace la référence se trouvant à l'index dans\r\n     *       la liste par la référence à o\r\n     */\r\n    public void set(int index, Object o) {\r\n        // Question\r\n    }\r\n\r\n    /*\r\n     * @pre -\r\n     * @post remplace l'objet o dans la liste en position index\r\n     *       Si index >= length, augmente d'abord la taille\r\n     *       de la liste en créant un nouveau tableau et\r\n     *       en y recopiant toutes les références de la liste\r\n     *       this avant de remplacer l'objet o à l'indice index\r\n     */\r\n    public void add(int index, Object o) {\r\n        // Question\r\n    }\r\n}
\r\n

Vous pouvez tester vos méthodes individuellement.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -9152,7 +9152,7 @@ }, { "title": "Q* Vecteur", - "description": "On vous fournit une classe `Vector` contenant uniquement une méthode\r\n`loadVector` prenant en paramètre un `String` appelé filename. La\r\nméthode à les spécifications suivantes:\r\n\r\n``` java\r\nimport java.io.BufferedReader;\r\nimport java.io.FileReader;\r\nimport java.io.IOException;\r\nimport java.io.FileNotFoundException;\r\nimport java.util.ArrayList;\r\n\r\n/**\r\n *\r\n * @author ogoletti\r\n * @version 29/11/16\r\n */\r\npublic class Vector {\r\n\r\n /**\r\n * @pre filename != null\r\n * @post lit dans le fichier dont le nom est fileName le contenu du vecteur v\r\n * le format du fichier est : un élément par ligne en commençant par v[0] ...\r\n * Les lignes à un format incorrect sont ignorées.\r\n * En cas d'erreur d'entrée/sortie (exception, fichier non lisible,\r\n * nombre incorrect d'éléments ) retourne null\r\n */\r\n public static double[] loadVector(String filename) {\r\n // Question\r\n }\r\n}\r\n```\r\n\r\nOn vous demande d'utiliser `BufferedReader` pour répondre à cette\r\nquestion.\r\n", + "description": "

On vous fournit une classe Vector contenant uniquement une méthode loadVector prenant en paramètre un String appelé filename. La méthode à les spécifications suivantes:

\r\n
import java.io.BufferedReader;\r\nimport java.io.FileReader;\r\nimport java.io.IOException;\r\nimport java.io.FileNotFoundException;\r\nimport java.util.ArrayList;\r\n\r\n/**\r\n *\r\n * @author ogoletti\r\n * @version 29/11/16\r\n */\r\npublic class Vector {\r\n\r\n    /**\r\n     * @pre filename != null\r\n     * @post lit dans le fichier dont le nom est fileName le     contenu du vecteur v\r\n     *       le format du fichier est : un élément par ligne     en commençant par v[0] ...\r\n     *     Les lignes à un format incorrect sont ignorées.\r\n     *     En cas d'erreur d'entrée/sortie (exception,     fichier non lisible,\r\n     *     nombre incorrect d'éléments ) retourne null\r\n     */\r\n    public static double[] loadVector(String filename) {\r\n            // Question\r\n        }\r\n}
\r\n

On vous demande d'utiliser BufferedReader pour répondre à cette question.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -9206,7 +9206,7 @@ }, { "title": "Q* Matrix", - "description": "On vous fournit une classe `Matrix` contenant uniquement une méthode\r\n`loadMatrix` prenant en paramètre un `String` appelé filename. La\r\nméthode à les spécifications suivantes:\r\n\r\n``` java\r\nimport java.io.BufferedReader;\r\nimport java.io.FileReader;\r\nimport java.io.IOException;\r\nimport java.io.FileNotFoundException;\r\n\r\npublic class Matrix {\r\n /**\r\n * @pre filename != null\r\n * @post lit dans le fichier dont le nom est fileName le contenu d'une matrice mxn\r\n * le format du fichier est :\r\n * première ligne : l'entier m\r\n * deuxième ligne : l'entier n\r\n * lignes suivantes : une chaîne du format i,j val\r\n * où 0<=iOn vous fournit une classe Matrix contenant uniquement une méthode loadMatrix prenant en paramètre un String appelé filename. La méthode à les spécifications suivantes:

\r\n
import java.io.BufferedReader;\r\nimport java.io.FileReader;\r\nimport java.io.IOException;\r\nimport java.io.FileNotFoundException;\r\n\r\npublic class Matrix {\r\n    /**\r\n     * @pre     filename != null\r\n     * @post    lit dans le fichier dont le nom est fileName le contenu d'une matrice mxn\r\n     *          le format du fichier est :\r\n     *          première ligne : l'entier m\r\n     *          deuxième ligne : l'entier n\r\n     *          lignes suivantes : une chaîne du format i,j val\r\n     *                             où 0<=i<m et 0<=j<n et val est un réel\r\n     *          En cas d'erreur d'entrée/sortie (exception, fichier non lisible,\r\n     *          nombre incorrect d'éléments, mauvais format) retourne null\r\n     */\r\n    public static double[][] loadMatrix(String filename) {\r\n        //A compléter\r\n    }\r\n}
\r\n

On vous demande d'utiliser BufferedReader pour répondre à cette question.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -9260,7 +9260,7 @@ }, { "title": "Phase de réalisation: Soumission", - "description": "Vous soumettrez votre soumission de la phase de réalisation de la\r\nMission 10 soit ici, soit directement via BlueJ.\r\n\r\nVeuillez soumettre une archive **zip** contenant uniquement les fichiers\r\n**.java** utilisés pour votre mission, ainsi qu'n fichier nommé\r\n\"README.TXT\".\r\n", + "description": "

Vous soumettrez votre soumission de la phase de réalisation de la Mission 10 soit ici, soit directement via BlueJ.

\r\n

Veuillez soumettre une archive zip contenant uniquement les fichiers .java utilisés pour votre mission, ainsi qu'n fichier nommé \"README.TXT\".

\r\n", "tags": [ { "text": "INGINIOUS", @@ -9309,7 +9309,7 @@ }, { "title": "QCM", - "description": "Mission 10. ArrayList\r\n=====================\r\n\r\nCes questions supposent que vous avez lu les sections suivantes du livre\r\nde référence JavaNotes\\_\r\n\r\n> - 8.3 : Exceptions and try..catch\\_ \r\n> - 8.3.3 : Throwing Exceptions\\_\r\n> - 8.3.4 : Mandatory Exception\r\n> Handling\\_\r\n> - 8.3.5 : Programming with\r\n> Exceptions\\_\r\n>\r\n> - 10.1 : Generic Programming\\_ \r\n> - 10.1.3 : Generic Programming in\r\n> Java\\_\r\n> - 10.1.4 : The Java Collection\r\n> Framework\\_\r\n> - 10.1.5 : Iterators and for-each\r\n> Loops\\_\r\n> - 10.1.6 : Equality and\r\n> Comparison\\_\r\n> - 10.1.7 : Generics and Wrapper\r\n> Classes\\_\r\n>\r\n> - 10.2 : Lists and Sets\\_ \r\n> - 10.2.1 : ArrayList and\r\n> LinkedList\\_\r\n> - 10.2.2 : Sorting\\_\r\n>\r\n> - 11.4 : Networking\\_ \r\n> - 11.4.1 : URLs and\r\n> URLConnections\\_\r\n", + "description": "

Mission 10. ArrayList

\r\n

Ces questions supposent que vous avez lu les sections suivantes du livre de référence JavaNotes_

\r\n
\r\n
    \r\n
  • \r\n
    8.3 : Exceptions and try..catch_
    \r\n
      \r\n
    • 8.3.3 : Throwing Exceptions_
    • \r\n
    • 8.3.4 : Mandatory Exception Handling_
    • \r\n
    • 8.3.5 : Programming with Exceptions_
    • \r\n
    \r\n
    \r\n
  • \r\n
  • \r\n
    10.1 : Generic Programming_
    \r\n
      \r\n
    • 10.1.3 : Generic Programming in Java_
    • \r\n
    • 10.1.4 : The Java Collection Framework_
    • \r\n
    • 10.1.5 : Iterators and for-each Loops_
    • \r\n
    • 10.1.6 : Equality and Comparison_
    • \r\n
    • 10.1.7 : Generics and Wrapper Classes_
    • \r\n
    \r\n
    \r\n
  • \r\n
  • \r\n
    10.2 : Lists and Sets_
    \r\n
      \r\n
    • 10.2.1 : ArrayList and LinkedList_
    • \r\n
    • 10.2.2 : Sorting_
    • \r\n
    \r\n
    \r\n
  • \r\n
  • \r\n
    11.4 : Networking_
    \r\n
      \r\n
    • 11.4.1 : URLs and URLConnections_
    • \r\n
    \r\n
    \r\n
  • \r\n
\r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -9358,7 +9358,7 @@ }, { "title": "Question de Démarrage 1 : JUnit (partie1)", - "description": "Dans la phase de réalisation, vous devez utiliser des méthodes provenant\r\ndu framework de test **JUnit** afin de tester votre implémentation dans\r\nBlueJ. L'objectif de cet exercice est d'utiliser les méthodes de JUnit\r\npour vérifier le bon fonctionnement de la classe `DList`. ci-après :\r\n\r\nIl vous est proposé une classe de test comme exemple dans laquelle les\r\nassertions JUnit ne sont que partiellement écrites. Lisez attentivement\r\nle code de cette classe afin de remplacer les blocs de commentaires du\r\ntype `/*(numero)???*/` par le code qui convient. Si cela est fait\r\ncorrectement, JUnit pourra détecter l'erreur contenue dans\r\nl'implémentation de la classe `DList`.\r\n", + "description": "

Dans la phase de réalisation, vous devez utiliser des méthodes provenant du framework de test JUnit afin de tester votre implémentation dans BlueJ. L'objectif de cet exercice est d'utiliser les méthodes de JUnit pour vérifier le bon fonctionnement de la classe DList. ci-après :

\r\n

Il vous est proposé une classe de test comme exemple dans laquelle les assertions JUnit ne sont que partiellement écrites. Lisez attentivement le code de cette classe afin de remplacer les blocs de commentaires du type /*(numero)???*/ par le code qui convient. Si cela est fait correctement, JUnit pourra détecter l'erreur contenue dans l'implémentation de la classe DList.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -9407,7 +9407,7 @@ }, { "title": "Question de Démarrage 2 : JUnit (partie 2)", - "description": "Suite de la question de démarrage 1.\r\n\r\nLa classe sous test:\r\n\r\nLa partie de la classe test à compléter:\r\n", + "description": "

Suite de la question de démarrage 1.

\r\n

La classe sous test:

\r\n

La partie de la classe test à compléter:

\r\n", "tags": [ { "text": "INGINIOUS", @@ -9456,7 +9456,7 @@ }, { "title": "Question de Démarrage 3 : JUnit (partie3) une DList correcte", - "description": "A la suite de l'écriture de la classe `DListTest` faite aux questions\r\nprécédentes, vous avez réussi à découvrir à l'aide de JUnit l'erreur\r\ncontenue dans la classe testée. Soumettez pour finir une version\r\ncorrigée de cette classe `DList`.\r\n\r\n**Attention, vous devez soumettre la classe DList entière avec\r\nexactement les mêmes attributs et les mêmes méthodes. Seul le corps des\r\nméthodes et les valeurs des attributs peuvent être différents.**\r\n", + "description": "

A la suite de l'écriture de la classe DListTest faite aux questions précédentes, vous avez réussi à découvrir à l'aide de JUnit l'erreur contenue dans la classe testée. Soumettez pour finir une version corrigée de cette classe DList.

\r\n

Attention, vous devez soumettre la classe DList entière avec exactement les mêmes attributs et les mêmes méthodes. Seul le corps des méthodes et les valeurs des attributs peuvent être différents.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -9510,7 +9510,7 @@ }, { "title": "Q* PileInt", - "description": "Une pile d'entiers est une structure de données qui permet d'empiler des\r\nentiers. Les entiers sont ajoutés à la pile via son sommet. La pile\r\ngarantit un fonctionnement Last-In First-Out (LIFO, dernier entré,\r\npremier sorti). On vous donne la classe `PileInt` incomplète suivante :\r\n\r\n``` java\r\n/**\r\n * Une pile d'entiers représentée sous la forme d'une structure chaînée\r\n *\r\n * @author O. Bonaventure\r\n * @version Décembre 2016\r\n */\r\n public class PileInt {\r\n\r\n // une classe interne représentant un noeud de la pile\r\n private class Noeud {\r\n int element;\r\n Noeud suivant;\r\n\r\n public Noeud(int i, Noeud n) {\r\n element = i;\r\n suivant = n;\r\n }\r\n }\r\n\r\n private Noeud sommet; // le sommet de la pile\r\n private int profondeur; // le nombre d'entiers dans la pile\r\n\r\n /**\r\n * @pre -\r\n * @post initialise une pile vide\r\n */\r\n public PileInt() {\r\n sommet = null;\r\n profondeur = 0;\r\n }\r\n\r\n /**\r\n * @pre\r\n * @post ajoute l'entier i au sommet de la pile\r\n */\r\n public void push(int i) {\r\n // Première question\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post retourne l'entier au sommet de la pile et le retire de la pile\r\n * lance l'exception IllegalStateException si la pile est vide\r\n */\r\n public int pop() throws IllegalStateException {\r\n // Deuxième question\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post retourne la profondeur,\r\n * c'est-à-dire le nombre d'éléments dans la pile.\r\n * Retourne 0 pour une pile vide.\r\n */\r\n public int depth() {\r\n return profondeur;\r\n }\r\n }\r\n```\r\n\r\nComplétez cette classe.\r\n", + "description": "

Une pile d'entiers est une structure de données qui permet d'empiler des entiers. Les entiers sont ajoutés à la pile via son sommet. La pile garantit un fonctionnement Last-In First-Out (LIFO, dernier entré, premier sorti). On vous donne la classe PileInt incomplète suivante :

\r\n
/**\r\n * Une pile d'entiers représentée sous la forme d'une structure chaînée\r\n *\r\n * @author O. Bonaventure\r\n * @version Décembre 2016\r\n */\r\n  public class PileInt {\r\n\r\n     // une classe interne représentant un noeud de la pile\r\n      private class Noeud {\r\n          int element;\r\n          Noeud suivant;\r\n\r\n          public Noeud(int i, Noeud n) {\r\n              element = i;\r\n              suivant = n;\r\n          }\r\n      }\r\n\r\n      private Noeud sommet; // le sommet de la pile\r\n      private int profondeur; // le nombre d'entiers dans la pile\r\n\r\n     /**\r\n      * @pre -\r\n      * @post initialise une pile vide\r\n      */\r\n      public PileInt() {\r\n          sommet = null;\r\n          profondeur = 0;\r\n      }\r\n\r\n      /**\r\n       * @pre\r\n       * @post ajoute l'entier i au sommet de la pile\r\n       */\r\n      public void push(int i) {\r\n          // Première question\r\n      }\r\n\r\n      /**\r\n       * @pre -\r\n       * @post retourne l'entier au sommet de la pile et le retire de la pile\r\n       *       lance l'exception IllegalStateException si la pile est vide\r\n       */\r\n      public int pop() throws IllegalStateException {\r\n          // Deuxième question\r\n      }\r\n\r\n      /**\r\n       * @pre -\r\n       * @post retourne la profondeur,\r\n       *      c'est-à-dire le nombre d'éléments dans la pile.\r\n       *      Retourne 0 pour une pile vide.\r\n       */\r\n      public int depth() {\r\n          return profondeur;\r\n      }\r\n  }
\r\n

Complétez cette classe.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -9569,7 +9569,7 @@ }, { "title": "Q* Pile", - "description": "Une pile est une structure de données qui permet d'empiler les éléments.\r\nLes objets sont ajoutés à la pile via son sommet. La pile garantit un\r\nfonctionnement Last-In First-Out (LIFO, dernier entré, premier sorti) On\r\nvous donne la classe `Pile` incomplète suivante :\r\n\r\n``` java\r\n/**\r\n * Une pile représentée sous la forme d'une structure chaînée\r\n *\r\n * @author O. Bonaventure\r\n * @version Novembre 2016\r\n */\r\n public class Pile {\r\n\r\n // une classe interne représentant un noeud de la queue\r\n private class Noeud {\r\n Object element;\r\n Noeud suivant;\r\n\r\n public Noeud(Object o, Noeud n) {\r\n element = o;\r\n suivant = n;\r\n }\r\n }\r\n\r\n private Noeud sommet; // le sommet de la pile\r\n\r\n /*\r\n * @pre -\r\n * @post a initialisé une pile vide\r\n */\r\n public Pile() {\r\n sommet = null;\r\n }\r\n\r\n /**\r\n * @pre o != null\r\n * @post ajoute l'objet o au sommet de la pile\r\n */\r\n public void push(Object o) {\r\n // code non fourni\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post retourne l'élément au sommet de la pile et le supprime\r\n * null si la pile est vide\r\n */\r\n public Object pop() {\r\n // Question 1\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post retourne la profondeur,\r\n * c'est-à-dire le nombre d'éléments dans la pile.\r\n * 0 pour une pile vide.\r\n */\r\n public int depth() {\r\n // Question 2\r\n }\r\n }\r\n```\r\n\r\nComplétez cette classe.\r\n", + "description": "

Une pile est une structure de données qui permet d'empiler les éléments. Les objets sont ajoutés à la pile via son sommet. La pile garantit un fonctionnement Last-In First-Out (LIFO, dernier entré, premier sorti) On vous donne la classe Pile incomplète suivante :

\r\n
/**\r\n * Une pile représentée sous la forme d'une structure chaînée\r\n *\r\n * @author O. Bonaventure\r\n * @version Novembre 2016\r\n */\r\n  public class Pile {\r\n\r\n      // une classe interne représentant un noeud de la queue\r\n      private class Noeud {\r\n          Object element;\r\n          Noeud suivant;\r\n\r\n          public Noeud(Object o, Noeud n) {\r\n              element = o;\r\n              suivant = n;\r\n          }\r\n     }\r\n\r\n     private Noeud sommet; // le sommet de la pile\r\n\r\n     /*\r\n      * @pre -\r\n      * @post a initialisé une pile vide\r\n      */\r\n      public Pile() {\r\n          sommet = null;\r\n      }\r\n\r\n     /**\r\n      * @pre o != null\r\n      * @post ajoute l'objet o au sommet de la pile\r\n      */\r\n      public void push(Object o) {\r\n          // code non fourni\r\n      }\r\n\r\n     /**\r\n      * @pre -\r\n      * @post retourne l'élément au sommet de la pile et le supprime\r\n      *       null si la pile est vide\r\n      */\r\n      public Object pop() {\r\n          // Question 1\r\n      }\r\n\r\n     /**\r\n      * @pre -\r\n      * @post retourne la profondeur,\r\n      *      c'est-à-dire le nombre d'éléments dans la pile.\r\n      *      0 pour une pile vide.\r\n      */\r\n      public int depth() {\r\n          // Question 2\r\n      }\r\n  }
\r\n

Complétez cette classe.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -9628,7 +9628,7 @@ }, { "title": "Q* FIFOQueue", - "description": "Une queue est une structure de donnée qui dispose d'une entrée et d'une\r\nsortie. Les objets sont ajoutés à la queue via son entrée et sont\r\nretirés via sa sortie. La queue garantit un fonctionnement First-In\r\nFirst-Out (FIFO, premier entré, premier sorti) On vous donne la classe\r\n`FIFOQueue` incomplète suivante :\r\n\r\n``` java\r\n/**\r\n * Une FIFO queue représentée sous la forme d'une structure chaînée\r\n *\r\n * @author O. Bonaventure\r\n * @version Novembre 2016\r\n */\r\n public class FIFOQueue {\r\n\r\n // une classe interne représentant un noeud de la queue\r\n private class Noeud {\r\n Object element;\r\n Noeud suivant;\r\n\r\n public Noeud(Object o, Noeud n) {\r\n element = o;\r\n suivant = n;\r\n }\r\n }\r\n\r\n private Noeud entree; // correspond à tout moment à l'entrée de la queue\r\n private Noeud sortie; // correspond à tout moment à la sortie de la queue\r\n\r\n /*\r\n * @pre -\r\n * @post a initialisé une queue vide\r\n */\r\n public FIFOQueue() {\r\n entree = null;\r\n sortie = null;\r\n }\r\n\r\n /**\r\n * @pre o != null\r\n * @post ajoute l'objet à la queue via le noeud entree\r\n */\r\n public void ajoute(Object o) {\r\n Noeud ajout;\r\n ajout = new Noeud(o, entree);\r\n entree = ajout;\r\n if(sortie == null) {\r\n sortie = ajout;\r\n }\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post retourne le plus ancien objet de la queue via le noeud sortie et\r\n * le retire de la queue\r\n * null si la queue est vide\r\n */\r\n public Object retire () {\r\n // A compléter\r\n }\r\n }\r\n```\r\n\r\nComplétez cette classe.\r\n", + "description": "

Une queue est une structure de donnée qui dispose d'une entrée et d'une sortie. Les objets sont ajoutés à la queue via son entrée et sont retirés via sa sortie. La queue garantit un fonctionnement First-In First-Out (FIFO, premier entré, premier sorti) On vous donne la classe FIFOQueue incomplète suivante :

\r\n
/**\r\n * Une FIFO queue représentée sous la forme d'une structure chaînée\r\n *\r\n * @author O. Bonaventure\r\n * @version Novembre 2016\r\n */\r\n  public class FIFOQueue {\r\n\r\n     // une classe interne représentant un noeud de la queue\r\n      private class Noeud {\r\n          Object element;\r\n          Noeud suivant;\r\n\r\n          public Noeud(Object o, Noeud n) {\r\n              element = o;\r\n              suivant = n;\r\n          }\r\n      }\r\n\r\n     private Noeud entree; // correspond à tout moment à l'entrée de la queue\r\n     private Noeud sortie; // correspond à tout moment à la sortie de la queue\r\n\r\n     /*\r\n      * @pre -\r\n      * @post a initialisé une queue vide\r\n      */\r\n      public FIFOQueue() {\r\n          entree = null;\r\n          sortie = null;\r\n      }\r\n\r\n     /**\r\n      * @pre o != null\r\n      * @post ajoute l'objet à la queue via le noeud entree\r\n      */\r\n      public void ajoute(Object o) {\r\n          Noeud ajout;\r\n          ajout = new Noeud(o, entree);\r\n          entree = ajout;\r\n          if(sortie == null) {\r\n               sortie = ajout;\r\n          }\r\n     }\r\n\r\n     /**\r\n      * @pre -\r\n      * @post retourne le plus ancien objet de la queue via le noeud sortie et\r\n      *       le retire de la queue\r\n      *       null si la queue est vide\r\n      */\r\n     public Object retire () {\r\n        // A compléter\r\n     }\r\n  }
\r\n

Complétez cette classe.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -9687,7 +9687,7 @@ }, { "title": "Q** Queue", - "description": "Une queue est une structure de données qui dispose d'une entrée et d'une\r\nsortie. Les objets sont ajoutés à la queue via son entrée et sont\r\nretirés via sa sortie. La queue garantit un fonctionnement First-In\r\nFirst-Out (FIFO, premier entré, premier sorti) On vous donne la classe\r\n`Queue` incomplète suivante :\r\n\r\n``` java\r\n/**\r\n * Une queue représentée sous la forme d'une structure chaînée\r\n *\r\n * @author O. Bonaventure\r\n * @version Novembre 2016\r\n */\r\n public class Queue {\r\n\r\n // une classe interne représentant un noeud de la queue\r\n private class Noeud {\r\n Object element;\r\n Noeud suivant;\r\n Noeud precedent;\r\n\r\n public Noeud(Object o, Noeud n, Noeud p) {\r\n element = o;\r\n suivant = n;\r\n precedent = p;\r\n }\r\n }\r\n\r\n private Noeud entree; // l'entrée de la queue\r\n private Noeud sortie; // la sortie de la queue\r\n\r\n /*\r\n * @pre -\r\n * @post initialise une queue vide\r\n */\r\n public Queue() {\r\n entree = null;\r\n sortie = null;\r\n }\r\n\r\n /**\r\n * @pre o != null\r\n * @post ajoute l'objet à la queue\r\n */\r\n public void ajoute(Object o) {\r\n // Question 1\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post retourne le plus ancien objet de la queue via le noeud sortie et\r\n * le retire de la queue.\r\n * Retourne null si la queue est vide\r\n */\r\n public Object retire() {\r\n // Question 2\r\n }\r\n }\r\n```\r\n\r\nComplétez cette classe.\r\n", + "description": "

Une queue est une structure de données qui dispose d'une entrée et d'une sortie. Les objets sont ajoutés à la queue via son entrée et sont retirés via sa sortie. La queue garantit un fonctionnement First-In First-Out (FIFO, premier entré, premier sorti) On vous donne la classe Queue incomplète suivante :

\r\n
/**\r\n * Une queue représentée sous la forme d'une structure chaînée\r\n *\r\n * @author O. Bonaventure\r\n * @version Novembre 2016\r\n */\r\n  public class Queue {\r\n\r\n      // une classe interne représentant un noeud de la queue\r\n      private class Noeud {\r\n          Object element;\r\n          Noeud suivant;\r\n          Noeud precedent;\r\n\r\n          public Noeud(Object o, Noeud n, Noeud p) {\r\n              element = o;\r\n              suivant = n;\r\n              precedent = p;\r\n          }\r\n       }\r\n\r\n      private Noeud entree; // l'entrée de la queue\r\n      private Noeud sortie; // la sortie de la queue\r\n\r\n     /*\r\n      * @pre -\r\n      * @post initialise une queue vide\r\n      */\r\n      public Queue() {\r\n          entree = null;\r\n          sortie = null;\r\n      }\r\n\r\n     /**\r\n      * @pre o != null\r\n      * @post ajoute l'objet à la queue\r\n      */\r\n      public void ajoute(Object o) {\r\n          // Question 1\r\n      }\r\n\r\n     /**\r\n      * @pre -\r\n      * @post retourne le plus ancien objet de la queue via le noeud sortie et\r\n      *       le retire de la queue.\r\n      *       Retourne null si la queue est vide\r\n      */\r\n      public Object retire() {\r\n          // Question 2\r\n      }\r\n  }
\r\n

Complétez cette classe.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -9746,7 +9746,7 @@ }, { "title": "Q** OrderedList", - "description": "Une queue ordonnée est une structure de données qui dispose d'une\r\nréférence min et d'une référence max. Les réels sont ajoutés à la queue\r\nvia son entrée et sont retirés via sa sortie. A tout moment, la queue\r\nest telle que l'élément le plus petit est accessible via la référence\r\nmin et le plus grand via la référence max. On vous donne la classe\r\n`OrderedList` incomplète suivante :\r\n\r\n``` java\r\n/**\r\n * Une liste qui contient des réels dans l'odre croissant\r\n *\r\n * @author O. Bonaventure\r\n * @version Dec. 2016\r\n */\r\n public class OrderedList {\r\n\r\n // une classe interne représentant un noeud de la queue\r\n private static class Noeud {\r\n double d;\r\n Noeud suivant;\r\n Noeud precedent;\r\n\r\n public Noeud(double d, Noeud n, Noeud p) {\r\n this.d = d;\r\n suivant = n;\r\n precedent = p;\r\n }\r\n }\r\n\r\n private Noeud min; // le plus petit nombre de la liste\r\n private Noeud max; // le plus grand nombre de la liste\r\n\r\n /*\r\n * @pre -\r\n * @post initialise une liste vide\r\n */\r\n public OrderedList() {\r\n min = null;\r\n max = null;\r\n }\r\n\r\n /**\r\n * @pre\r\n * @post ajoute le nombre n à la liste ordonnée. Après ajout, la liste est\r\n * ordonnée, le nombre le plus petit est à la référence min et\r\n * le plus grand à la référence max\r\n */\r\n public void ajoute(double n) {\r\n // Question 1\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post retourne le plus grand élément de la queue et le retire de la queue\r\n * lance un exception IllegalStateException si la queue est vide\r\n */\r\n public double retireMax() throws IllegalStateException {\r\n // Question 2\r\n }\r\n }\r\n```\r\n\r\nComplétez cette classe.\r\n", + "description": "

Une queue ordonnée est une structure de données qui dispose d'une référence min et d'une référence max. Les réels sont ajoutés à la queue via son entrée et sont retirés via sa sortie. A tout moment, la queue est telle que l'élément le plus petit est accessible via la référence min et le plus grand via la référence max. On vous donne la classe OrderedList incomplète suivante :

\r\n
/**\r\n * Une liste qui contient des réels dans l'odre croissant\r\n *\r\n * @author O. Bonaventure\r\n * @version Dec. 2016\r\n */\r\n  public class OrderedList {\r\n\r\n     // une classe interne représentant un noeud de la queue\r\n      private static class Noeud {\r\n          double d;\r\n          Noeud suivant;\r\n          Noeud precedent;\r\n\r\n          public Noeud(double d, Noeud n, Noeud p) {\r\n              this.d = d;\r\n              suivant = n;\r\n              precedent = p;\r\n          }\r\n      }\r\n\r\n      private Noeud min; // le plus petit nombre de la liste\r\n      private Noeud max; // le plus grand nombre de la liste\r\n\r\n     /*\r\n      * @pre -\r\n      * @post initialise une liste vide\r\n      */\r\n      public OrderedList() {\r\n          min = null;\r\n          max = null;\r\n      }\r\n\r\n     /**\r\n      * @pre\r\n      * @post ajoute le nombre n à la liste ordonnée. Après ajout, la liste est\r\n      *       ordonnée, le nombre le plus petit est à la référence min et\r\n      *       le plus grand à la référence max\r\n      */\r\n      public void ajoute(double n) {\r\n          // Question 1\r\n      }\r\n\r\n     /**\r\n      * @pre -\r\n      * @post retourne le plus grand élément de la queue et le retire de la queue\r\n      *       lance un exception IllegalStateException si la queue est vide\r\n      */\r\n      public double retireMax() throws IllegalStateException {\r\n          // Question 2\r\n      }\r\n  }
\r\n

Complétez cette classe.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -9800,7 +9800,7 @@ }, { "title": "Q** List", - "description": "Une liste est une structure de données permettant de stocker des objets.\r\nLes objets sont ajoutés à la liste via sa tete. Elle supporte trois\r\ncommandes : ajout pour ajouter un objet à la liste retire pour retirer\r\nun élément se trouvant dans la liste contient pour voir si un objet se\r\ntrouve dans la liste\r\n\r\nOn vous donne la classe `Liste` incomplète suivante :\r\n\r\n``` java\r\n/**\r\n * Une liste représentée sous la forme d'une structure chaînée\r\n *\r\n * @author O. Bonaventure\r\n * @version Décembre 2016\r\n */\r\npublic class Liste {\r\n\r\n // une classe interne représentant un noeud de la liste\r\n private class Noeud {\r\n Object element;\r\n Noeud suivant;\r\n\r\n public Noeud(Object o, Noeud n) {\r\n element = o;\r\n suivant = n;\r\n }\r\n }\r\n\r\n private Noeud tete; // le début de la liste\r\n\r\n /*\r\n * @pre -\r\n * @post a initialisé une liste vide\r\n */\r\n public Liste() {\r\n tete = null;\r\n }\r\n\r\n /**\r\n * @pre o != null\r\n * @post ajoute l'objet à la liste\r\n */\r\n public void ajoute(Object o) {\r\n // Code non fourni\r\n }\r\n\r\n /*\r\n * @pre o != null\r\n * @post retourne true si l'objet o se trouve dans la liste, false sinon\r\n */\r\n public boolean contient(Object o) {\r\n // Question 1\r\n }\r\n\r\n /**\r\n * @pre o != null\r\n * @post retire toutes les copies de l'objet o de la liste.\r\n * Retourne le nombre d'objets qui ont été retiré de la liste\r\n * (0 si l'objet o n'était pas présent dans la liste)\r\n */\r\n public int retire(Object o) {\r\n // Question 2\r\n }\r\n}\r\n```\r\n\r\nComplétez cette classe.\r\n", + "description": "

Une liste est une structure de données permettant de stocker des objets. Les objets sont ajoutés à la liste via sa tete. Elle supporte trois commandes : ajout pour ajouter un objet à la liste retire pour retirer un élément se trouvant dans la liste contient pour voir si un objet se trouve dans la liste

\r\n

On vous donne la classe Liste incomplète suivante :

\r\n
/**\r\n * Une liste représentée sous la forme d'une structure chaînée\r\n *\r\n * @author O. Bonaventure\r\n * @version Décembre 2016\r\n */\r\npublic class Liste {\r\n\r\n   // une classe interne représentant un noeud de la liste\r\n    private class Noeud {\r\n        Object element;\r\n        Noeud suivant;\r\n\r\n        public Noeud(Object o, Noeud n) {\r\n            element = o;\r\n            suivant = n;\r\n        }\r\n    }\r\n\r\n    private Noeud tete; // le début de la liste\r\n\r\n   /*\r\n    * @pre -\r\n    * @post a initialisé une liste vide\r\n    */\r\n    public Liste() {\r\n        tete = null;\r\n    }\r\n\r\n   /**\r\n    * @pre o != null\r\n    * @post ajoute l'objet à la liste\r\n    */\r\n    public void ajoute(Object o) {\r\n        // Code non fourni\r\n    }\r\n\r\n   /*\r\n    * @pre o != null\r\n    * @post retourne true si l'objet o se trouve dans la liste, false sinon\r\n    */\r\n    public boolean contient(Object o) {\r\n        // Question 1\r\n    }\r\n\r\n   /**\r\n    * @pre o != null\r\n    * @post retire toutes les copies de l'objet o de la liste.\r\n    *       Retourne le nombre d'objets qui ont été retiré de la liste\r\n    *       (0 si l'objet o n'était pas présent dans la liste)\r\n    */\r\n    public int retire(Object o) {\r\n        // Question 2\r\n    }\r\n}
\r\n

Complétez cette classe.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -9859,7 +9859,7 @@ }, { "title": "Phase de réalisation: Soumission", - "description": "Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour\r\nla Mission 11.\r\n\r\nVous attendons une archive **.zip** contenant uniquement les fichiers :\r\n\r\n- Classement.java\r\n- ClassementTemps.java\r\n- Coureur.java\r\n- Dlist.java\r\n- DListTest.java\r\n- Main.java\r\n- Resultat.java\r\n- Temps.java\r\n- README.txt\r\n", + "description": "

Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour la Mission 11.

\r\n

Vous attendons une archive .zip contenant uniquement les fichiers :

\r\n
    \r\n
  • Classement.java
  • \r\n
  • ClassementTemps.java
  • \r\n
  • Coureur.java
  • \r\n
  • Dlist.java
  • \r\n
  • DListTest.java
  • \r\n
  • Main.java
  • \r\n
  • Resultat.java
  • \r\n
  • Temps.java
  • \r\n
  • README.txt
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -9913,7 +9913,7 @@ }, { "title": "QCM", - "description": "Mission 11. Structures chaînées\r\n===============================\r\n\r\nCes questions supposent que vous avez lu les sections suivantes du livre\r\nde référence JavaNotes\\_\r\n\r\n> - 5.7 : Interfaces, Nested Classes, and Other Details\\_ \r\n> - 5.7.2 : Nested Classes\\_\r\n>\r\n> - 9.1 : Recursion\\_\r\n>\r\n> - 9.2 : Linked Data Structures\\_ \r\n> - 9.2.1 : Recursive Linking\\_\r\n> - 9.2.2 : Linked Lists\\_\r\n> - 9.2.3 : Basic Linked List\r\n> Processing\\_\r\n> - 9.2.4 : Inserting into a Linked\r\n> List\\_\r\n> - 9.2.5 : Deleting from a Linked\r\n> List\\_\r\n>\r\n> - 9.3 : Stacks, Queues, and ADTs\\_ \r\n> - 9.3.1 : Stacks\\_\r\n> - 9.3.2 : Queues\\_\r\n\r\nPlusieurs questions se basent sur la classe `StackOfInt` de la section\r\n9.3.1, partiellement reproduite et traduite ici\r\n\r\n``` java\r\n/**\r\n * Une pile d'entiers sous forme de chaîne simplement liée.\r\n * Le sommet de la pile est la tête de la chaîne.\r\n */\r\npublic class StackOfInts {\r\n /**\r\n * Un noeud de la liste.\r\n */\r\n private static class Node {\r\n int item; // donnée\r\n Node next; // le noeud suivant\r\n }\r\n\r\n private Node top; // le sommet de la pile\r\n\r\n /**\r\n * @pre -\r\n * @post Ajoute N au sommet de la pile.\r\n */\r\n public void push( int N ) {\r\n ...\r\n }\r\n\r\n\r\n /**\r\n * @pre -\r\n * @post Retire et retourne l'élément au sommet de la pile.\r\n * Lance une IllegalStateException si la pile est vide.\r\n */\r\n public int pop() {\r\n ...\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post retourne true si la pile est vide, false sinon.\r\n */\r\n public boolean isEmpty() {\r\n return (top == null);\r\n }\r\n\r\n}\r\n```\r\n", + "description": "

Mission 11. Structures chaînées

\r\n

Ces questions supposent que vous avez lu les sections suivantes du livre de référence JavaNotes_

\r\n
\r\n
    \r\n
  • \r\n
    5.7 : Interfaces, Nested Classes, and Other Details_
    \r\n
      \r\n
    • 5.7.2 : Nested Classes_
    • \r\n
    \r\n
    \r\n
  • \r\n
  • 9.1 : Recursion_
  • \r\n
  • \r\n
    9.2 : Linked Data Structures_
    \r\n
      \r\n
    • 9.2.1 : Recursive Linking_
    • \r\n
    • 9.2.2 : Linked Lists_
    • \r\n
    • 9.2.3 : Basic Linked List Processing_
    • \r\n
    • 9.2.4 : Inserting into a Linked List_
    • \r\n
    • 9.2.5 : Deleting from a Linked List_
    • \r\n
    \r\n
    \r\n
  • \r\n
  • \r\n
    9.3 : Stacks, Queues, and ADTs_
    \r\n
      \r\n
    • 9.3.1 : Stacks_
    • \r\n
    • 9.3.2 : Queues_
    • \r\n
    \r\n
    \r\n
  • \r\n
\r\n
\r\n

Plusieurs questions se basent sur la classe StackOfInt de la section 9.3.1, partiellement reproduite et traduite ici

\r\n
/**\r\n * Une pile d'entiers sous forme de chaîne simplement liée.\r\n * Le sommet de la pile est la tête de la chaîne.\r\n */\r\npublic class StackOfInts {\r\n   /**\r\n    * Un noeud de la liste.\r\n    */\r\n   private static class Node {\r\n      int item;     // donnée\r\n      Node next;    // le noeud suivant\r\n   }\r\n\r\n   private Node top;   // le sommet de la pile\r\n\r\n   /**\r\n    * @pre  -\r\n    * @post Ajoute N au sommet de la pile.\r\n    */\r\n   public void push( int N ) {\r\n      ...\r\n   }\r\n\r\n\r\n   /**\r\n    * @pre  -\r\n    * @post Retire et retourne l'élément au sommet de la pile.\r\n    *       Lance une IllegalStateException si la pile est vide.\r\n    */\r\n   public int pop() {\r\n      ...\r\n   }\r\n\r\n   /**\r\n    * @pre  -\r\n    * @post retourne true si la pile est vide, false sinon.\r\n    */\r\n   public boolean isEmpty() {\r\n      return (top == null);\r\n   }\r\n\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -9962,7 +9962,7 @@ }, { "title": "Examen Juin 2011 online : Enoncé", - "description": "Contexte\r\n========\r\n\r\nUne *grappe d'ordinateurs* (computer cluster) est un ensemble\r\nd'ordinateurs connectés entre eux et organisés de manière à apparaître\r\ncomme une large ressource de calcul sur laquelle peuvent s'exécuter\r\nsimultanément de nombreuses tâches, la répartition des tâches entre les\r\ndifférents ordinateurs étant gérée par le système de manière\r\ntransparente pour l'utilisateur. On appelle *processus* (process) une\r\ntâche individuelle dont un utilisateur peut demander l'exécution sur la\r\ngrappe.\r\n\r\n\"image\"\r\n\r\nLe programme que vous devez compléter permet de représenter la gestion\r\ndes processus sur une grappe d'ordinateurs. La grappe est décrite par la\r\nclasse `Cluster`. Une grappe contient la liste des ordinateurs de la\r\ngrappe, organisée sous forme de **liste chaînée circulaire** : les\r\nnoeuds de la liste sont connectés en boucle, de sorte que la liste n'a\r\npas de début ni de fin. Cette organisation est utilisée pour ajouter les\r\nnouveaux processus à chaque ordinateur à tour de rôle, dans la mesure\r\ndes ressources disponibles.\r\n\r\n\"image\"\r\n\r\nLe fonctionnement de la liste est documenté dans la classe `Cluster`. La\r\ntête de liste se décale à chaque ajout de processus pour assurer une\r\nrépartition plus équitable. Par exemple, dans la situation illustrée\r\nci-dessus, l'ordinateur 1 est en tête de liste. Si on désire ajouter un\r\nprocessus, et que ni l'ordinateur 1 ni le 2 ne disposent des ressources\r\nsuffisantes, le processus sera ajouté à l'ordinateur 3, et l'ordinateur\r\n4 deviendra la nouvelle tête de liste.\r\n\r\nUne grappe peut contenir plusieurs types d'ordinateurs, dont les\r\nfonctionnalités communes sont décrites dans l'interface `ComputerIF`.\r\nDeux implémentations de cette interface sont fournies :\r\n\r\n- `BasicComputer` qui supporte un seul processus à la fois, et\r\n- `FullComputer` qui supporte un nombre maximum déterminé de\r\n processus, gérés dans un tableau.\r\n\r\nUn processus est décrit par la classe `Process`, que vous devez écrire à\r\nla question 3. Le programme utilise aussi sa propre classe d'exceptions,\r\ndéfinie dans `UnavailableException`.\r\n\r\nRappelons qu'il convient d'utiliser la méthode `equals` pour comparer\r\ndes objets, même si cette méthode n'est pas explicitement re-définie\r\ndans les classes correspondantes.\r\n\r\nRessources\r\n==========\r\n\r\n- [The Java API](http://docs.oracle.com/javase/8/docs/api/)\r\n- [Introduction to Programming Using Java\r\n (JavaNotes)](http://math.hws.edu/javanotes/)\r\n\r\nAnnexes\r\n=======\r\n\r\nVous trouverez ci-après les sources (incomplètes) du programme auquel se\r\nrapportent les questions :\r\n\r\n- [ComputerIF.java](https://inginious.org/course/uclouvain-cs1-java/#computerif.java)\r\n- [BasicComputer.java](https://inginious.org/course/uclouvain-cs1-java/#basiccomputer.java)\r\n- [Process.java](https://inginious.org/course/uclouvain-cs1-java/#process.java)\r\n- [UnavailableException.java](https://inginious.org/course/uclouvain-cs1-java/#unavailableexception.java)\r\n- [FullComputer.java](https://inginious.org/course/uclouvain-cs1-java/#fullcomputer.java)\r\n- [Cluster.java](https://inginious.org/course/uclouvain-cs1-java/#cluster.java)\r\n\r\n------------------------------------------------------------------------\r\n\r\nComputerIF.java\r\n---------------\r\n\r\n``` java\r\n/**\r\n * Un ordinateur, sur lequel on peut ajouter et retirer des processus.\r\n * L'ordinateur dispose de ressources (nombre de processus, volume de stockage)\r\n * éventuellement limitées, et donc peut refuser l'ajout de processus supplémentaires.\r\n * Un ordinateur a un nom.\r\n *\r\n * @author O. Bonaventure, Ch. Pecheur\r\n * @version Juin 2011\r\n */\r\n\r\npublic interface ComputerIF\r\n{\r\n /**\r\n * @pre p != null, p ne se trouve pas déjà sur cet ordinateur\r\n * @post le processus p a été ajouté à cet ordinateur, si les ressources\r\n * nécessaires sont disponibles. Retourne true si le processus\r\n * a été ajouté, false sinon.\r\n */\r\n public boolean addProcess(Process p);\r\n\r\n /**\r\n * @pre p != null\r\n * @post le processus p a été retiré de cet ordinateur, si ce processus\r\n * se trouve sur cet ordinateur. Retourne true si le processus\r\n * a été supprimé, false sinon.\r\n */\r\n public boolean removeProcess(Process p);\r\n\r\n /**\r\n * @pre -\r\n * @post Tous les processus de cet ordinateur ont été retirés.\r\n */\r\n public void removeAllProcesses();\r\n\r\n /**\r\n * @pre -\r\n * @post retourne le nom de l'ordinateur.\r\n */\r\n public String getName();\r\n\r\n /**\r\n * @pre -\r\n * @post Retourne la liste des processus de cet ordinateur sous forme de texte,\r\n * avec une ligne par processus, chaque ligne comprenant le nom du processus\r\n * et sa taille de stockage, séparés par un espace, et se termine par\r\n * un passage à la ligne. Par exemple:\r\n *\r\n * process1 0\r\n * bigprocess 200\r\n * smallprocess 20\r\n */\r\n public String getState();\r\n }\r\n```\r\n\r\nBasicComputer.java\r\n------------------\r\n\r\n``` java\r\n/**\r\n * Un ordinateur de base, supportant un seul processus et sans capacité de stockage.\r\n *\r\n * @author O. Bonaventure, Ch. Pecheur\r\n * @version Juin 2011\r\n */\r\n public class BasicComputer implements ComputerIF\r\n {\r\n private String name; // Nom de l'ordinateur\r\n private Process proc; // processus éventuel, null si absent\r\n\r\n /**\r\n * @pre name != null\r\n * @post Construit un BasicComputer de nom name.\r\n */\r\n public BasicComputer(String name)\r\n {\r\n this.name = name;\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post retourne le nom de l'ordinateur.\r\n */\r\n public String getName()\r\n {\r\n return name;\r\n }\r\n\r\n /**\r\n * @pre p != null, p ne se trouve pas déjà sur cet ordinateur\r\n * @post le processus p a été ajouté à cet ordinateur, si aucun processus\r\n * n'est présent et si p ne demande pas de stockage. Retourne true si\r\n * le processus a été ajouté, false sinon.\r\n */\r\n public boolean addProcess(Process p)\r\n {\r\n if (proc == null && p.getRequiredStorage() == 0) {\r\n proc = p;\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * @pre p != null\r\n * @post le processus p a été retiré de cet ordinateur, s'il s'agit bien du\r\n * processus présent. Retourne true si le processus a été supprimé,\r\n * false sinon.\r\n */\r\n public boolean removeProcess(Process p)\r\n\r\n QUESTION 1\r\n\r\n\r\n /**\r\n * @pre -\r\n * @post Tous les processus de cet ordinateur ont été retirés. Retire proc\r\n * s'il est actif.\r\n */\r\n public void removeAllProcesses()\r\n {\r\n proc = null;\r\n }\r\n\r\n /**\r\n * @pre -\r\n * @post Retourne la liste des processus de cet ordinateur sous forme de texte,\r\n * avec une ligne par processus, chaque ligne comprenant le nom du processus\r\n * et sa taille de stockage, séparés par un espace, et se termine par\r\n * un passage à la ligne. Par exemple:\r\n *\r\n * process1 0\r\n * bigprocess 200\r\n * smallprocess 20\r\n */\r\n public String getState() {\r\n if (proc != null) {\r\n return proc.getDescr() + \"\\n\";\r\n } else {\r\n return \"\";\r\n }\r\n }\r\n }\r\n```\r\n\r\nProcess.java\r\n------------\r\n\r\n``` java\r\nQUESTION 3\r\n```\r\n\r\nUnavailableException.java\r\n-------------------------\r\n\r\n``` java\r\n/**\r\n * Une exception utilisée lorsqu'une opération ne peut être effectuée\r\n * par manque de ressources.\r\n *\r\n * @author O. Bonaventure, Ch. Pecheur\r\n * @version Juin 2011\r\n */\r\npublic class UnavailableException extends Exception\r\n{\r\n public UnavailableException()\r\n {\r\n super();\r\n }\r\n}\r\n```\r\n\r\nFullComputer.java\r\n-----------------\r\n\r\n``` java\r\n/**\r\n * Un ordinateur avec capacité de stockage limitée et nombre de processus limité.\r\n *\r\n * @author O. Bonaventure, Ch. Pecheur\r\n * @version Juin 2011\r\n */\r\npublic class FullComputer extends BasicComputer\r\n{\r\n /**\r\n * Les processus présents sur cet ordinateur. Les processus sont dans\r\n * procs[0] .. procs[count-1], et procs[i] == null pour i >= count.\r\n */\r\n private Process[] procs;\r\n private int count; // nombre de processus présents\r\n private int storage; // capacité de stockage totale\r\n private int availStorage; // capacit?é de stockage restante\r\n\r\n /**\r\n * @pre n > 0, name != null, storage >= 0\r\n * @post Construit un FullComputer de nom name, supportant n processus\r\n * et avec une capacité de stockage égale à storage\r\n */\r\n\r\n QUESTION 2\r\n\r\n /**\r\n * @pre p != null, p ne se trouve pas déjà sur cet ordinateur\r\n * @post le processus p a été ajouté à cet ordinateur, si (1) le nombre de\r\n * processus maximal n'est pas atteint et (2) la capacité de stockage\r\n * nécessaire pour p est disponible. Retourne true si le processus a\r\n * été ajouté, false sinon.\r\n */\r\n public boolean addProcess(Process p)\r\n\r\n QUESTION 4\r\n\r\n\r\n RESTE DU CODE NON FOURNI\r\n\r\n}\r\n```\r\n\r\nCluster.java\r\n------------\r\n\r\n``` java\r\n/**\r\n * Une grappe (cluster) d'ordinateurs formant une ressource commune pour\r\n * l'exécution de processus. Les ordinateurs du cluster sont gérés comme\r\n * une liste circulaire, de telle manière que les processus soient distribués\r\n * à tour de rôle à chaque ordinateur, dans la limite de leurs ressources disponibles.\r\n * La tête de la liste correspond prochain ordinateur à recevoir un nouveau processus,\r\n * pour autant qu'il ait les ressources nécessaires.\r\n *\r\n * @author O. Bonaventure, Ch. Pecheur\r\n * @version Juin 2011\r\n */\r\n\r\nimport java.io.*;\r\n\r\npublic class Cluster\r\n{\r\n // classe interne: un noeud de la liste circulaire des ordinateurs du cluster\r\n private class ListNode {\r\n ListNode next;\r\n ComputerIF elem;\r\n }\r\n\r\n /**\r\n * La tête courante de la liste des ordinateurs. Les noeuds suivants sont\r\n * chaînés de manière circulaire: la chaîne finit toujours par revenir à\r\n * current.\r\n */\r\n private ListNode current;\r\n private int count; // nombre d'ordinateurs dans le cluster\r\n\r\n /**\r\n * Constructeur\r\n */\r\n public Cluster()\r\n {\r\n count = 0;\r\n current = null;\r\n }\r\n\r\n /**\r\n * @pre p != null, p ne se trouve pas déjà sur un ordinateur du cluster.\r\n * @post Le processus p a été ajouté au premier ordinateur, à partir de la\r\n * tête de la liste, disposant des ressources nécessaires. La nouvelle\r\n * tête de liste est le noeud qui suit celui de l'ordinateur où p a\r\n * été ajouté. Si aucun ordinateur ne dispose de ressources\r\n * suffisantes, la tête de liste est inchangée et une\r\n * UnavailableException est lancée.\r\n */\r\n\r\n QUESTION 5\r\n\r\n\f /**\r\n * @pre p != null\r\n * @post Le processus p a été retiré du premier ordinateur du cluster\r\n * sur lequel il se trouvait, à partir de la tête de la liste.\r\n * Si p n'est pas trouvé, lance UnavailableException.\r\n */\r\n public void removeProcess(Process p) throws UnavailableException\r\n\r\n CODE NON FOURNI\r\n\r\n\r\n /**\r\n * @pre -\r\n * @post Tous les processus de tous les ordinateurs ont été retirés.\r\n */\r\n public void removeAllProcesses()\r\n\r\n CODE NON FOURNI\r\n\r\n /**\r\n * @pre comp != null, comp ne fait pas déjà partie du cluster.\r\n * @post L'ordinateur comp est ajouté à la liste des ordinateurs.\r\n */\r\n public void addComputer(ComputerIF comp)\r\n {\r\n ListNode l = new ListNode();\r\n l.elem = comp;\r\n if(count == 0)\r\n {\r\n l.next = l;\r\n current = l;\r\n }\r\n else\r\n {\r\n l.next = current.next;\r\n current.next = l;\r\n }\r\n count++;\r\n }\r\n\r\n /**\r\n * @pre comp != null\r\n * @post L'ordinateur comp a été retiré du cluster, s'il s'y trouvait. Si\r\n * comp est en tête de liste, la tête de liste passe au noeud suivant,\r\n * sinon elle est inchangée. Retourne true si comp a été retiré, false\r\n * sinon.\r\n */\r\n\r\n QUESTION 6\r\n\r\n /**\r\n * @pre filename est un nom de fichier\r\n * @post Le fichier filename contient l'état du cluster sous forme de texte.\r\n * Pour chaque processus de chaque ordinateur du cluster, le fichier\r\n * contient une ligne composée du nom et de la capacité demandée,\r\n * séparés par un espace. Par exemple :\r\n *\r\n * process1 0\r\n * bigprocess 200\r\n * smallprocess 20\r\n *\r\n * Le nom des ordinateurs sur lesquels se trouvent les processus n'est\r\n * pas sauvegardé. Arrête le programme si une erreur d'I/O se produit.\r\n */\r\n public void saveState(String filename)\r\n\r\n CODE NON FOURNI\r\n\r\n\r\n /**\r\n * @pre filename le nom d'un fichier sauvegardé par saveState\r\n * @post Retire tous les processus présents dans le cluster, puis ajoute au\r\n * cluster les processus dont les noms et capacités sont donnés dans\r\n * le fichier, selon le format généré par saveState. Arrête le\r\n * programme si une erreur d'I/O se produit ou si la capacité du\r\n * cluster est insuffisante.\r\n */\r\n public void loadState(String fileName)\r\n\r\n QUESTION 7\r\n\r\n}\r\n```\r\n", + "description": "

Contexte

\r\n

Une grappe d'ordinateurs (computer cluster) est un ensemble d'ordinateurs connectés entre eux et organisés de manière à apparaître comme une large ressource de calcul sur laquelle peuvent s'exécuter simultanément de nombreuses tâches, la répartition des tâches entre les différents ordinateurs étant gérée par le système de manière transparente pour l'utilisateur. On appelle processus (process) une tâche individuelle dont un utilisateur peut demander l'exécution sur la grappe.

\r\n

\"image\"

\r\n

Le programme que vous devez compléter permet de représenter la gestion des processus sur une grappe d'ordinateurs. La grappe est décrite par la classe Cluster. Une grappe contient la liste des ordinateurs de la grappe, organisée sous forme de liste chaînée circulaire : les noeuds de la liste sont connectés en boucle, de sorte que la liste n'a pas de début ni de fin. Cette organisation est utilisée pour ajouter les nouveaux processus à chaque ordinateur à tour de rôle, dans la mesure des ressources disponibles.

\r\n

\"image\"

\r\n

Le fonctionnement de la liste est documenté dans la classe Cluster. La tête de liste se décale à chaque ajout de processus pour assurer une répartition plus équitable. Par exemple, dans la situation illustrée ci-dessus, l'ordinateur 1 est en tête de liste. Si on désire ajouter un processus, et que ni l'ordinateur 1 ni le 2 ne disposent des ressources suffisantes, le processus sera ajouté à l'ordinateur 3, et l'ordinateur 4 deviendra la nouvelle tête de liste.

\r\n

Une grappe peut contenir plusieurs types d'ordinateurs, dont les fonctionnalités communes sont décrites dans l'interface ComputerIF. Deux implémentations de cette interface sont fournies :

\r\n
    \r\n
  • BasicComputer qui supporte un seul processus à la fois, et
  • \r\n
  • FullComputer qui supporte un nombre maximum déterminé de processus, gérés dans un tableau.
  • \r\n
\r\n

Un processus est décrit par la classe Process, que vous devez écrire à la question 3. Le programme utilise aussi sa propre classe d'exceptions, définie dans UnavailableException.

\r\n

Rappelons qu'il convient d'utiliser la méthode equals pour comparer des objets, même si cette méthode n'est pas explicitement re-définie dans les classes correspondantes.

\r\n

Ressources

\r\n\r\n

Annexes

\r\n

Vous trouverez ci-après les sources (incomplètes) du programme auquel se rapportent les questions :

\r\n\r\n
\r\n

ComputerIF.java

\r\n
/**\r\n * Un ordinateur, sur lequel on peut ajouter et retirer des processus.\r\n * L'ordinateur dispose de ressources (nombre de processus, volume de stockage)\r\n * éventuellement limitées, et donc peut refuser l'ajout de processus supplémentaires.\r\n * Un ordinateur a un nom.\r\n *\r\n * @author O. Bonaventure, Ch. Pecheur\r\n * @version Juin 2011\r\n */\r\n\r\npublic interface ComputerIF\r\n{\r\n    /**\r\n     * @pre  p != null, p ne se trouve pas déjà sur cet ordinateur\r\n     * @post le processus p a été ajouté à cet ordinateur, si les ressources\r\n     *       nécessaires sont disponibles.  Retourne true si le processus\r\n     *       a été ajouté, false sinon.\r\n     */\r\n    public boolean addProcess(Process p);\r\n\r\n    /**\r\n     * @pre p != null\r\n     * @post le processus p a été retiré de cet ordinateur, si ce processus\r\n     *       se trouve sur cet ordinateur.  Retourne true si le processus\r\n     *       a été supprimé, false sinon.\r\n     */\r\n    public boolean removeProcess(Process p);\r\n\r\n    /**\r\n     * @pre -\r\n     * @post Tous les processus de cet ordinateur ont été retirés.\r\n     */\r\n    public void removeAllProcesses();\r\n\r\n    /**\r\n     * @pre -\r\n     * @post retourne le nom de l'ordinateur.\r\n     */\r\n    public String getName();\r\n\r\n    /**\r\n     * @pre -\r\n     * @post Retourne la liste des processus de cet ordinateur sous forme de texte,\r\n     *       avec une ligne par processus, chaque ligne comprenant le nom du processus\r\n     *       et sa taille de stockage, séparés par un espace, et se termine par\r\n     *       un passage à la ligne.  Par exemple:\r\n     *\r\n     *       process1 0\r\n     *       bigprocess 200\r\n     *       smallprocess 20\r\n     */\r\n    public String getState();\r\n }
\r\n

BasicComputer.java

\r\n
/**\r\n  * Un ordinateur de base, supportant un seul processus et sans capacité de stockage.\r\n  *\r\n  * @author O. Bonaventure, Ch. Pecheur\r\n  * @version Juin 2011\r\n  */\r\n public class BasicComputer implements ComputerIF\r\n {\r\n     private String name; // Nom de l'ordinateur\r\n     private Process proc; // processus éventuel, null si absent\r\n\r\n     /**\r\n      * @pre name != null\r\n      * @post Construit un BasicComputer de nom name.\r\n      */\r\n     public BasicComputer(String name)\r\n     {\r\n         this.name = name;\r\n     }\r\n\r\n     /**\r\n      * @pre -\r\n      * @post retourne le nom de l'ordinateur.\r\n      */\r\n     public String getName()\r\n     {\r\n         return name;\r\n     }\r\n\r\n     /**\r\n      * @pre  p != null, p ne se trouve pas déjà sur cet ordinateur\r\n      * @post le processus p a été ajouté à cet ordinateur, si aucun processus\r\n      *       n'est présent et si p ne demande pas de stockage. Retourne true si\r\n      *       le processus a été ajouté, false sinon.\r\n      */\r\n     public boolean addProcess(Process p)\r\n     {\r\n         if (proc == null && p.getRequiredStorage() == 0) {\r\n             proc = p;\r\n             return true;\r\n         } else {\r\n             return false;\r\n         }\r\n     }\r\n\r\n     /**\r\n      * @pre p != null\r\n      * @post le processus p a été retiré de cet ordinateur, s'il s'agit bien du\r\n      *       processus présent. Retourne true si le processus a été supprimé,\r\n      *       false sinon.\r\n      */\r\n     public boolean removeProcess(Process p)\r\n\r\n          QUESTION 1\r\n\r\n\r\n     /**\r\n      * @pre -\r\n      * @post Tous les processus de cet ordinateur ont été retirés. Retire proc\r\n      *       s'il est actif.\r\n      */\r\n     public void removeAllProcesses()\r\n     {\r\n         proc = null;\r\n     }\r\n\r\n     /**\r\n      * @pre -\r\n      * @post Retourne la liste des processus de cet ordinateur sous forme de texte,\r\n      *       avec une ligne par processus, chaque ligne comprenant le nom du processus\r\n      *       et sa taille de stockage, séparés par un espace, et se termine par\r\n      *       un passage à la ligne.  Par exemple:\r\n      *\r\n      *       process1 0\r\n      *       bigprocess 200\r\n      *       smallprocess 20\r\n      */\r\n     public String getState() {\r\n         if (proc != null) {\r\n             return proc.getDescr() + "\\n";\r\n         } else {\r\n             return "";\r\n         }\r\n     }\r\n }
\r\n

Process.java

\r\n
QUESTION 3
\r\n

UnavailableException.java

\r\n
/**\r\n * Une exception utilisée lorsqu'une opération ne peut être effectuée\r\n * par manque de ressources.\r\n *\r\n * @author O. Bonaventure, Ch. Pecheur\r\n * @version Juin 2011\r\n */\r\npublic class UnavailableException extends Exception\r\n{\r\n    public UnavailableException()\r\n    {\r\n        super();\r\n    }\r\n}
\r\n

FullComputer.java

\r\n
/**\r\n * Un ordinateur avec capacité de stockage limitée et nombre de processus limité.\r\n *\r\n * @author O. Bonaventure, Ch. Pecheur\r\n * @version Juin 2011\r\n */\r\npublic class FullComputer extends BasicComputer\r\n{\r\n    /**\r\n     * Les processus présents sur cet ordinateur.  Les processus sont dans\r\n     * procs[0] .. procs[count-1], et procs[i] == null pour i >= count.\r\n     */\r\n    private Process[] procs;\r\n    private int count;         // nombre de processus présents\r\n    private int storage;       // capacité de stockage totale\r\n    private int availStorage;  // capacit?é de stockage restante\r\n\r\n    /**\r\n     * @pre n > 0, name != null, storage >= 0\r\n     * @post Construit un FullComputer de nom name, supportant n processus\r\n     *       et avec une capacité de stockage égale à storage\r\n     */\r\n\r\n         QUESTION 2\r\n\r\n    /**\r\n     * @pre  p != null, p ne se trouve pas déjà sur cet ordinateur\r\n     * @post le processus p a été ajouté à cet ordinateur, si (1) le nombre de\r\n     *       processus maximal n'est pas atteint et (2) la capacité de stockage\r\n     *       nécessaire pour p est disponible. Retourne true si le processus a\r\n     *       été ajouté, false sinon.\r\n     */\r\n    public boolean addProcess(Process p)\r\n\r\n         QUESTION 4\r\n\r\n\r\n     RESTE DU CODE NON FOURNI\r\n\r\n}
\r\n

Cluster.java

\r\n
/**\r\n * Une grappe (cluster) d'ordinateurs formant une ressource commune pour\r\n * l'exécution de processus.  Les ordinateurs du cluster sont gérés comme\r\n * une liste circulaire, de telle manière que les processus soient distribués\r\n * à tour de rôle à chaque ordinateur, dans la limite de leurs ressources disponibles.\r\n * La tête de la liste correspond prochain ordinateur à recevoir un nouveau processus,\r\n * pour autant qu'il ait les ressources nécessaires.\r\n *\r\n * @author O. Bonaventure, Ch. Pecheur\r\n * @version Juin 2011\r\n */\r\n\r\nimport java.io.*;\r\n\r\npublic class Cluster\r\n{\r\n    // classe interne: un noeud de la liste circulaire des ordinateurs du cluster\r\n    private class ListNode {\r\n        ListNode next;\r\n        ComputerIF elem;\r\n    }\r\n\r\n    /**\r\n     * La tête courante de la liste des ordinateurs. Les noeuds suivants sont\r\n     * chaînés de manière circulaire: la chaîne finit toujours par revenir à\r\n     * current.\r\n     */\r\n    private ListNode current;\r\n    private int count; // nombre d'ordinateurs dans le cluster\r\n\r\n    /**\r\n     * Constructeur\r\n     */\r\n    public Cluster()\r\n    {\r\n        count = 0;\r\n        current = null;\r\n    }\r\n\r\n    /**\r\n     * @pre p != null, p ne se trouve pas déjà sur un ordinateur du cluster.\r\n     * @post Le processus p a été ajouté au premier ordinateur, à partir de la\r\n     *       tête de la liste, disposant des ressources nécessaires. La nouvelle\r\n     *       tête de liste est le noeud qui suit celui de l'ordinateur où p a\r\n     *       été ajouté. Si aucun ordinateur ne dispose de ressources\r\n     *       suffisantes, la tête de liste est inchangée et une\r\n     *       UnavailableException est lancée.\r\n     */\r\n\r\n         QUESTION 5\r\n\r\n\f    /**\r\n     * @pre p != null\r\n     * @post Le processus p a été retiré du premier ordinateur du cluster\r\n     *       sur lequel il se trouvait, à partir de la tête de la liste.\r\n     *       Si p n'est pas trouvé, lance UnavailableException.\r\n     */\r\n    public void removeProcess(Process p) throws UnavailableException\r\n\r\n         CODE NON FOURNI\r\n\r\n\r\n    /**\r\n     * @pre -\r\n     * @post Tous les processus de tous les ordinateurs ont été retirés.\r\n     */\r\n    public void removeAllProcesses()\r\n\r\n         CODE NON FOURNI\r\n\r\n    /**\r\n     * @pre  comp != null, comp ne fait pas déjà partie du cluster.\r\n     * @post L'ordinateur comp est ajouté à la liste des ordinateurs.\r\n     */\r\n    public void addComputer(ComputerIF comp)\r\n    {\r\n        ListNode l = new ListNode();\r\n        l.elem = comp;\r\n       if(count == 0)\r\n        {\r\n           l.next = l;\r\n           current = l;\r\n        }\r\n        else\r\n        {\r\n            l.next = current.next;\r\n            current.next = l;\r\n        }\r\n        count++;\r\n    }\r\n\r\n    /**\r\n     * @pre comp != null\r\n     * @post L'ordinateur comp a été retiré du cluster, s'il s'y trouvait. Si\r\n     *       comp est en tête de liste, la tête de liste passe au noeud suivant,\r\n     *       sinon elle est inchangée. Retourne true si comp a été retiré, false\r\n     *       sinon.\r\n     */\r\n\r\n         QUESTION 6\r\n\r\n    /**\r\n     * @pre filename est un nom de fichier\r\n     * @post Le fichier filename contient l'état du cluster sous forme de texte.\r\n     *       Pour chaque processus de chaque ordinateur du cluster, le fichier\r\n     *       contient une ligne composée du nom et de la capacité demandée,\r\n     *       séparés par un espace. Par exemple :\r\n     *\r\n     *       process1 0\r\n     *       bigprocess 200\r\n     *       smallprocess 20\r\n     *\r\n     *       Le nom des ordinateurs sur lesquels se trouvent les processus n'est\r\n     *       pas sauvegardé. Arrête le programme si une erreur d'I/O se produit.\r\n     */\r\n    public void saveState(String filename)\r\n\r\n         CODE NON FOURNI\r\n\r\n\r\n    /**\r\n     * @pre filename le nom d'un fichier sauvegardé par saveState\r\n     * @post Retire tous les processus présents dans le cluster, puis ajoute au\r\n     *       cluster les processus dont les noms et capacités sont donnés dans\r\n     *       le fichier, selon le format généré par saveState.  Arrête le\r\n     *       programme si une erreur d'I/O se produit ou si la capacité du\r\n     *       cluster est insuffisante.\r\n     */\r\n    public void loadState(String fileName)\r\n\r\n         QUESTION 7\r\n\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -10007,7 +10007,7 @@ }, { "title": "Examen Juin 2011 online : Question 1", - "description": "Prenez connaissance de l'énoncé de l'[examen de juin\r\n2011](https://inginious.info.ucl.ac.be/course/LSINF1101/m12_examj2011enonce_online).\r\n\r\nQuestion 1 : Implémentez la méthode `removeProcess` de la classe\r\n`BasicComputer`, dont la signature est ci-dessous :\r\n\r\n``` java\r\n/**\r\n * @pre p != null\r\n * @post le processus p a été retiré de cet ordinateur, s'il\r\n * s'agit bien du processus présent. Retourne true si\r\n * le processus a été supprimé, false sinon.\r\n */\r\npublic boolean removeProcess(Process p)\r\n{\r\n /*** VOTRE REPONSE ***/\r\n}\r\n```\r\n", + "description": "

Prenez connaissance de l'énoncé de l'examen de juin 2011.

\r\n

Question 1 : Implémentez la méthode removeProcess de la classe BasicComputer, dont la signature est ci-dessous :

\r\n
/**\r\n * @pre p != null\r\n * @post le processus p a été retiré de cet ordinateur, s'il\r\n *         s'agit bien du processus présent. Retourne true si\r\n *         le processus a été supprimé, false sinon.\r\n */\r\npublic boolean removeProcess(Process p)\r\n{\r\n    /*** VOTRE REPONSE ***/\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -10057,7 +10057,7 @@ }, { "title": "Examen Juin 2011 online : Question 2", - "description": "Prenez connaissance de l'énoncé de l'[examen de juin\r\n2011](https://inginious.info.ucl.ac.be/course/LSINF1101/m12_examj2011enonce_online).\r\n\r\nQuestion 2 : Écrivez complètement le constructeur de la classe\r\n`FullComputer`. Ce constructeur prend dans l'ordre les arguments\r\nsuivants : le nom, le nombre de processus à supporter, la capacité de\r\nstockage. Sa spécification est la suivante :\r\n\r\n``` java\r\n/**\r\n * @pre n > 0, name != null, storage >= 0\r\n * @post Construit un FullComputer de nom name, supportant n processus\r\n * et avec une capacité de stockage égale à storage\r\n */\r\n\r\n /*** VOTRE REPONSE ***/\r\n```\r\n", + "description": "

Prenez connaissance de l'énoncé de l'examen de juin 2011.

\r\n

Question 2 : Écrivez complètement le constructeur de la classe FullComputer. Ce constructeur prend dans l'ordre les arguments suivants : le nom, le nombre de processus à supporter, la capacité de stockage. Sa spécification est la suivante :

\r\n
/**\r\n * @pre n > 0, name != null, storage >= 0\r\n * @post Construit un FullComputer de nom name, supportant n processus\r\n * et avec une capacité de stockage égale à storage\r\n */\r\n\r\n /*** VOTRE REPONSE ***/
\r\n", "tags": [ { "text": "INGINIOUS", @@ -10107,7 +10107,7 @@ }, { "title": "Examen Juin 2011 online : Question 3", - "description": "Prenez connaissance de l'énoncé de l'[examen de juin\r\n2011](https://inginious.info.ucl.ac.be/course/LSINF1101/m12_examj2011enonce_online).\r\n\r\nQuestion 3 : Ecrivez complètement (y compris les spécifications) le\r\ncorps de la classe `Process` qui représente un processus. Chaque\r\nprocessus a un nom (`String`), une capacité de stockage requise (`int`)\r\net un identifiant de processus ou PID (`int`). Les PIDs sont attribus\r\nsquentiellement à la cration de chaque nouveau processus (1 pour le\r\npremier, 2 pour le deuxième, etc.) La classe doit définir :\r\n\r\n- Un constructeur avec le nom et la capacité comme paramètres, dans\r\n cet ordre,\r\n- Des méthodes `getName`, `getRequiredStorage` et `getPid` retournant\r\n respectivement le nom, la capacité et le PID,\r\n- Une méthode `toString` retournant une chaîne de caractères\r\n comprenant le nom du processus et la capacité de stockage\r\n nécessaire, séparés par un espace,\r\n- Toutes les variables et méthodes complémentaires nécessaires à votre\r\n implémentation.\r\n\r\nIl n'est pas nécessaire de re-définir la méthode `equals`.\r\n\r\n``` java\r\n/**\r\n * Un processus, avec un nom (String), une capacité de stockage\r\n * requise (int) et un identifiant de processus, ou PID (int).\r\n * Les PIDs sont attribués séquentiellement à la création de chaque\r\n * nouveau processus (1 pour le premier, 2 pour le deuxième, etc.).\r\n * Le premier argument du constructeur doit être le nom du processus.\r\n */\r\n public class Process\r\n {\r\n /*** VOTRE REPONSE ***/\r\n }\r\n```\r\n", + "description": "

Prenez connaissance de l'énoncé de l'examen de juin 2011.

\r\n

Question 3 : Ecrivez complètement (y compris les spécifications) le corps de la classe Process qui représente un processus. Chaque processus a un nom (String), une capacité de stockage requise (int) et un identifiant de processus ou PID (int). Les PIDs sont attribus squentiellement à la cration de chaque nouveau processus (1 pour le premier, 2 pour le deuxième, etc.) La classe doit définir :

\r\n
    \r\n
  • Un constructeur avec le nom et la capacité comme paramètres, dans cet ordre,
  • \r\n
  • Des méthodes getName, getRequiredStorage et getPid retournant respectivement le nom, la capacité et le PID,
  • \r\n
  • Une méthode toString retournant une chaîne de caractères comprenant le nom du processus et la capacité de stockage nécessaire, séparés par un espace,
  • \r\n
  • Toutes les variables et méthodes complémentaires nécessaires à votre implémentation.
  • \r\n
\r\n

Il n'est pas nécessaire de re-définir la méthode equals.

\r\n
/**\r\n  * Un processus, avec un nom (String), une capacité de stockage\r\n  * requise (int) et un identifiant de processus, ou PID (int).\r\n  * Les PIDs sont attribués séquentiellement à la création de chaque\r\n  * nouveau processus (1 pour le premier, 2 pour le deuxième, etc.).\r\n  * Le premier argument du constructeur doit être le nom du processus.\r\n  */\r\n public class Process\r\n {\r\n     /*** VOTRE REPONSE ***/\r\n }
\r\n", "tags": [ { "text": "INGINIOUS", @@ -10157,7 +10157,7 @@ }, { "title": "Examen juin 2011 online : Question 4", - "description": "Prenez connaissance de l'énoncé de l'[examen de juin\r\n2011](https://inginious.info.ucl.ac.be/course/LSINF1101/m12_examj2011enonce_online).\r\n\r\nQuestion 4 : Ecrivez le corps de la méthode `addProcess` de la classe\r\n`FullComputer`. Pensez à utiliser les méthodes de la classe `Process`\r\ndéfinies à la question 3. :\r\n\r\n``` java\r\n/**\r\n * @pre p != null, p ne se trouve pas déjà sur cet ordinateur\r\n * @post le processus p a été ajouté à cet ordinateur, si (1)le\r\n * nombre de processus maximal n'est pas atteint et (2) la capacité de\r\n * stockage nécessaire pour p est disponible. Retourne true si le\r\n * processus a été ajouté, false sinon.\r\n */\r\n public boolean addProcess(Process p)\r\n {\r\n /*** VOTRE REPONSE ***/\r\n }\r\n```\r\n", + "description": "

Prenez connaissance de l'énoncé de l'examen de juin 2011.

\r\n

Question 4 : Ecrivez le corps de la méthode addProcess de la classe FullComputer. Pensez à utiliser les méthodes de la classe Process définies à la question 3. :

\r\n
/**\r\n * @pre p != null, p ne se trouve pas déjà sur cet ordinateur\r\n * @post le processus p a été ajouté à cet ordinateur, si (1)le\r\n *       nombre de processus maximal n'est pas atteint et (2) la capacité de\r\n *       stockage nécessaire pour p est disponible. Retourne true si le\r\n *       processus a été ajouté, false sinon.\r\n */\r\n    public boolean addProcess(Process p)\r\n {\r\n     /*** VOTRE REPONSE ***/\r\n }
\r\n", "tags": [ { "text": "INGINIOUS", @@ -10207,7 +10207,7 @@ }, { "title": "Examen Juin 2011 online : Question 5", - "description": "Prenez connaissance de l'énoncé de l'[examen de juin\r\n2011](https://inginious.info.ucl.ac.be/course/LSINF1101/examj2011q1/jun11.pdf).\r\n\r\nQuestion 5 : Implémentez la méthode `addProcess()` de la classe\r\n`Cluster`, selon la spécification donnée. Aidez-vous de l'exemple\r\nprésenté dans l'énoncé. Indice: vous pouvez utiliser la valeur de\r\n`count`.\r\n\r\n``` java\r\n/**\r\n * @pre p != null, p ne se trouve pas déjà sur un ordinateur du\r\n * cluster.\r\n * @post Le processus p a été ajouté au premier ordinateur, à partir\r\n * de la tête de la liste, disposant des ressources nécessaires.\r\n * La nouvelle tête de liste est le noeud qui suit celui de\r\n * l'ordinateur où p a été ajouté. Si aucun ordinateur ne\r\n * dispose de ressources suffisantes, la tête de liste est\r\n * inchangée et une UnavailableException est lancée.\r\n */\r\npublic void addProcess(Process p) throws UnavailableException {\r\n /*** VOTRE REPONSE ***/\r\n}\r\n```\r\n", + "description": "

Prenez connaissance de l'énoncé de l'examen de juin 2011.

\r\n

Question 5 : Implémentez la méthode addProcess() de la classe Cluster, selon la spécification donnée. Aidez-vous de l'exemple présenté dans l'énoncé. Indice: vous pouvez utiliser la valeur de count.

\r\n
/**\r\n * @pre p != null, p ne se trouve pas déjà sur un ordinateur du\r\n *        cluster.\r\n * @post Le processus p a été ajouté au premier ordinateur, à partir\r\n *         de la tête de la liste, disposant des ressources nécessaires.\r\n *         La nouvelle tête de liste est le noeud qui suit celui de\r\n *         l'ordinateur où p a été ajouté. Si aucun ordinateur ne\r\n *         dispose de ressources suffisantes, la tête de liste est\r\n *         inchangée et une UnavailableException est lancée.\r\n */\r\npublic void addProcess(Process p) throws UnavailableException {\r\n    /*** VOTRE REPONSE ***/\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -10257,7 +10257,7 @@ }, { "title": "Examen juin 2011 online : Question 6", - "description": "Prenez connaissance de l'énoncé de l'[examen de juin\r\n2011](https://inginious.info.ucl.ac.be/course/LSINF1101/examj2011q1/jun11.pdf).\r\n\r\nQuestion 6 : Ecrivez complètement la méthode `removeComputer` de la\r\nclasse `Cluster` selon la spécification donnée. Indice: vous pouvez\r\nutiliser la valeur de `count`.\r\n\r\n``` java\r\n/**\r\n * @pre comp != null\r\n * @post L'ordinateur comp a été retiré du cluster, s'il s'y trouvait.\r\n * Si comp est en tête de liste, la tête de liste passe au noeud suivant,\r\n * sinon elle est inchangée.\r\n * Retourne true si comp a été retiré, false sinon.\r\n */\r\n\r\n /*** VOTRE REPONSE ***/\r\n```\r\n", + "description": "

Prenez connaissance de l'énoncé de l'examen de juin 2011.

\r\n

Question 6 : Ecrivez complètement la méthode removeComputer de la classe Cluster selon la spécification donnée. Indice: vous pouvez utiliser la valeur de count.

\r\n
/**\r\n * @pre comp != null\r\n * @post L'ordinateur comp a été retiré du cluster, s'il s'y trouvait.\r\n *        Si comp est en tête de liste, la tête de liste passe au noeud suivant,\r\n *          sinon elle est inchangée.\r\n *        Retourne true si comp a été retiré, false sinon.\r\n */\r\n\r\n /*** VOTRE REPONSE ***/
\r\n", "tags": [ { "text": "INGINIOUS", @@ -10307,7 +10307,7 @@ }, { "title": "Examen Juin 2011 online : Question 7", - "description": "Prenez connaissance de l'énoncé de l'[examen de juin\r\n2011](https://inginious.info.ucl.ac.be/course/LSINF1101/examj2011q1/jun11.pdf).\r\n\r\nQuestion 7 : Ecrivez le corps de la méthode `loadState` de la classe\r\n`Cluster` selon la spécification donnée. Notez que la pré-condition\r\ngarantit le format du contenu du fichier; pas besoin donc de traiter les\r\nerreurs de format du texte.\r\n\r\n``` java\r\n/**\r\n* @pre filename le nom d'un fichier sauvegardé par saveState\r\n* @post Retire tous les processus présents dans le cluster, puis\r\n* ajoute au cluster les processus dont les noms et capacités\r\n* sont donnés dans le fichier, selon le format généré par\r\n* saveState. Arrête le programme si une erreur d'I/O se\r\n* produit ou si la capacité du cluster est insuffisante.\r\n*/\r\npublic void loadState(String fileName){\r\n /*** VOTRE REPONSE ***/\r\n}\r\n```\r\n", + "description": "

Prenez connaissance de l'énoncé de l'examen de juin 2011.

\r\n

Question 7 : Ecrivez le corps de la méthode loadState de la classe Cluster selon la spécification donnée. Notez que la pré-condition garantit le format du contenu du fichier; pas besoin donc de traiter les erreurs de format du texte.

\r\n
/**\r\n* @pre     filename le nom d'un fichier sauvegardé par saveState\r\n* @post    Retire tous les processus présents dans le cluster, puis\r\n*            ajoute au cluster les processus dont les noms et capacités\r\n*            sont donnés dans le fichier, selon le format généré par\r\n*            saveState.  Arrête le programme si une erreur d'I/O se\r\n*            produit ou si la capacité du cluster est insuffisante.\r\n*/\r\npublic void loadState(String fileName){\r\n  /*** VOTRE REPONSE ***/\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -10357,7 +10357,7 @@ }, { "title": "Phase de réalisation: Soumission", - "description": "Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour\r\nla Mission 1.\r\n\r\nVous attendons une archive **.zip** contenant uniquement les fichiers :\r\n\r\n- MiseEnRoute.java\r\n- README.txt\r\n", + "description": "

Vous pouvez soumettre ici ou via BlueJ votre phase de réalisation pour la Mission 1.

\r\n

Vous attendons une archive .zip contenant uniquement les fichiers :

\r\n
    \r\n
  • MiseEnRoute.java
  • \r\n
  • README.txt
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -10406,7 +10406,7 @@ }, { "title": "Examen Juin 2011: Question 1", - "description": "Prenez connaissance de l'énoncé de l'[examen de juin\r\n2011](https://inginious.info.ucl.ac.be/course/LSINF1101/examj2011q1/jun11.pdf).\r\n\r\nRépondez ici à la Question 1 : Implémentez la méthode `removeProcess` de\r\nla classe `BasicComputer`, dont la signature est ci-dessous :\r\n\r\n``` java\r\n/**\r\n * @pre p != null\r\n * @post le processus p a été retiré de cet ordinateur, s'il\r\n * s'agit bien du processus présent. Retourne true si\r\n * le processus a été supprimé, false sinon.\r\n */\r\npublic boolean removeProcess(Process p)\r\n{\r\n // À implémenter\r\n}\r\n```\r\n\r\n**Vu que l'examen est sur papier, il est préférable que vous rédigiez la\r\nréponse sur une feuille de papier et que vous la recopiiez ici une fois\r\nque vous êtes sûr de vous. INGInious vous permettra de vérifier si votre\r\ncode est correct mais n'oubliez pas qu'à l'examen, vous n'aurez pas\r\nplusieurs essais. Il est donc important de s'entraîner à rédiger du code\r\nsur papier pour se mettre en situation d'examen et évaluer votre temps\r\npour répondre.**\r\n\r\n**Souvenez-vous qu'une réponse correcte sur INGInious ne correspond pas\r\nd'office à un 20 à l'examen (la clarté, la simplicité du code, les\r\nspécifications sont aussi des critères importants non vérifiés par\r\nINGInious).**\r\n", + "description": "

Prenez connaissance de l'énoncé de l'examen de juin 2011.

\r\n

Répondez ici à la Question 1 : Implémentez la méthode removeProcess de la classe BasicComputer, dont la signature est ci-dessous :

\r\n
/**\r\n * @pre p != null\r\n * @post le processus p a été retiré de cet ordinateur, s'il\r\n *         s'agit bien du processus présent. Retourne true si\r\n *         le processus a été supprimé, false sinon.\r\n */\r\npublic boolean removeProcess(Process p)\r\n{\r\n    // À implémenter\r\n}
\r\n

Vu que l'examen est sur papier, il est préférable que vous rédigiez la réponse sur une feuille de papier et que vous la recopiiez ici une fois que vous êtes sûr de vous. INGInious vous permettra de vérifier si votre code est correct mais n'oubliez pas qu'à l'examen, vous n'aurez pas plusieurs essais. Il est donc important de s'entraîner à rédiger du code sur papier pour se mettre en situation d'examen et évaluer votre temps pour répondre.

\r\n

Souvenez-vous qu'une réponse correcte sur INGInious ne correspond pas d'office à un 20 à l'examen (la clarté, la simplicité du code, les spécifications sont aussi des critères importants non vérifiés par INGInious).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -10456,7 +10456,7 @@ }, { "title": "Examen Juin 2011: Question 2", - "description": "Prenez connaissance de l'énoncé de l'[examen de juin\r\n2011](https://inginious.info.ucl.ac.be/course/LSINF1101/examj2011q1/jun11.pdf).\r\n\r\nRépondez ici à la Question 2 : Écrivez complètement le constructeur de\r\nla classe `FullComputer` dont la spécification est la suivante :\r\n\r\n``` java\r\n/**\r\n * @pre n > 0, name != null, storage >= 0\r\n * @post Construit un FullComputer de nom name, supportant n processus\r\n * et avec une capacité de stockage égale à storage\r\n */\r\n\r\n // À implémenter\r\n```\r\n\r\nCe constructeur prend dans l'ordre les arguments suivants : le nom, le\r\nnombre de processus à suporter, la capacité de stockage.\r\n\r\n**Comme l'examen est sur papier, il est préférable que vous rédigiez la\r\nréponse sur une feuille de papier et que vous la recopiiez ici une fois\r\nque vous êtes sûr de vous. INGInious vous permettra de vérifier si votre\r\ncode est correct mais n'oubliez pas qu'à l'examen, vous n'aurez pas\r\nplusieurs essais. Il est donc important de s'entraîner à rédiger du code\r\nsur papier pour se mettre en situation d'examen et évaluer votre temps\r\npour répondre.**\r\n\r\n**Souvenez-vous qu'une réponse correcte sur INGInious ne correspond pas\r\nd'office à un 20 à l'examen (la clarté, la simplicité du code, les\r\nspécifications sont aussi des critères importants non vérifiés par\r\nINGInious).**\r\n", + "description": "

Prenez connaissance de l'énoncé de l'examen de juin 2011.

\r\n

Répondez ici à la Question 2 : Écrivez complètement le constructeur de la classe FullComputer dont la spécification est la suivante :

\r\n
/**\r\n * @pre n > 0, name != null, storage >= 0\r\n * @post Construit un FullComputer de nom name, supportant n processus\r\n * et avec une capacité de stockage égale à storage\r\n */\r\n\r\n // À implémenter
\r\n

Ce constructeur prend dans l'ordre les arguments suivants : le nom, le nombre de processus à suporter, la capacité de stockage.

\r\n

Comme l'examen est sur papier, il est préférable que vous rédigiez la réponse sur une feuille de papier et que vous la recopiiez ici une fois que vous êtes sûr de vous. INGInious vous permettra de vérifier si votre code est correct mais n'oubliez pas qu'à l'examen, vous n'aurez pas plusieurs essais. Il est donc important de s'entraîner à rédiger du code sur papier pour se mettre en situation d'examen et évaluer votre temps pour répondre.

\r\n

Souvenez-vous qu'une réponse correcte sur INGInious ne correspond pas d'office à un 20 à l'examen (la clarté, la simplicité du code, les spécifications sont aussi des critères importants non vérifiés par INGInious).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -10506,7 +10506,7 @@ }, { "title": "Examen Juin 2011: Question 3", - "description": "Prenez connaissance de l'énoncé de l'[examen de juin\r\n2011](https://inginious.info.ucl.ac.be/course/LSINF1101/examj2011q1/jun11.pdf).\r\n\r\nRépondez ici à la Question 3 : Implémentez la classe `Process`\r\nci-dessous :\r\n\r\n``` java\r\n/**\r\n * Un processus, avec un nom (String), une capacité de stockage\r\n * requise (int) et un identifiant de processus, ou PID (int).\r\n * Les PIDs sont attribués séquentiellement à la création de chaque\r\n * nouveau processus (1 pour le premier, 2 pour le deuxième, etc.).\r\n * Le premier argument du constructeur doit être le nom du processus.\r\n */\r\n public class Process\r\n {\r\n // À implémenter\r\n }\r\n```\r\n\r\nN'oubliez pas d'implémenter les méthodes demandées dans la question.\r\n\r\n**Comme l'examen est sur papier, il est préférable que vous rédigiez la\r\nréponse sur une feuille de papier et que vous la recopiiez ici une fois\r\nque vous êtes sûr de vous. INGInious vous permettra de vérifier si votre\r\ncode est correct mais n'oubliez pas qu'à l'examen, vous n'aurez pas\r\nplusieurs essais. Il est donc important de s'entraîner à rédiger du code\r\nsur papier pour se mettre en situation d'examen et évaluer votre temps\r\npour répondre.**\r\n\r\n**Souvenez-vous qu'une réponse correcte sur INGInious ne correspond pas\r\nd'office à un 20 à l'examen (la clarté, la simplicité du code, les\r\nspécifications sont aussi des critères importants non vérifiés par\r\nINGInious).**\r\n", + "description": "

Prenez connaissance de l'énoncé de l'examen de juin 2011.

\r\n

Répondez ici à la Question 3 : Implémentez la classe Process ci-dessous :

\r\n
/**\r\n  * Un processus, avec un nom (String), une capacité de stockage\r\n  * requise (int) et un identifiant de processus, ou PID (int).\r\n  * Les PIDs sont attribués séquentiellement à la création de chaque\r\n  * nouveau processus (1 pour le premier, 2 pour le deuxième, etc.).\r\n  * Le premier argument du constructeur doit être le nom du processus.\r\n  */\r\n public class Process\r\n {\r\n     // À implémenter\r\n }
\r\n

N'oubliez pas d'implémenter les méthodes demandées dans la question.

\r\n

Comme l'examen est sur papier, il est préférable que vous rédigiez la réponse sur une feuille de papier et que vous la recopiiez ici une fois que vous êtes sûr de vous. INGInious vous permettra de vérifier si votre code est correct mais n'oubliez pas qu'à l'examen, vous n'aurez pas plusieurs essais. Il est donc important de s'entraîner à rédiger du code sur papier pour se mettre en situation d'examen et évaluer votre temps pour répondre.

\r\n

Souvenez-vous qu'une réponse correcte sur INGInious ne correspond pas d'office à un 20 à l'examen (la clarté, la simplicité du code, les spécifications sont aussi des critères importants non vérifiés par INGInious).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -10556,7 +10556,7 @@ }, { "title": "Examen juin 2011: Question 4", - "description": "Prenez connaissance de l'énoncé de l'[examen de juin\r\n2011](https://inginious.info.ucl.ac.be/course/LSINF1101/examj2011q1/jun11.pdf).\r\n\r\nRépondez ici à la Question 4 : Ecrivez le corps de la méthode\r\n`addProcess` de la classe `FullComputer`. Pensez à utiliser les méthodes\r\nde la classe `Process` définies à la question 3. :\r\n\r\n``` java\r\n/**\r\n * @pre p != null, p ne se trouve pas déjà sur cet ordinateur\r\n * @post le processus p a été ajouté à cet ordinateur, si (1)le\r\n * nombre de processus maximal n'est pas atteint et (2) la capacité de\r\n * stockage nécessaire pour p est disponible. Retourne true si le\r\n * processus a été ajouté, false sinon.\r\n *\r\n */\r\n public boolean addProcess(Process p)\r\n\r\n // À implémenter\r\n```\r\n\r\n**Comme l'examen est sur papier, il est préférable que vous rédigiez la\r\nréponse sur une feuille de papier et que vous la recopiiez ici une fois\r\nque vous êtes sûr de vous. INGInious vous permettra de vérifier si votre\r\ncode est correct mais n'oubliez pas qu'à l'examen, vous n'aurez pas\r\nplusieurs essais. Il est donc important de s'entraîner à rédiger du code\r\nsur papier pour se mettre en situation d'examen et évaluer votre temps\r\npour répondre.**\r\n\r\n**Souvenez-vous qu'une réponse correcte sur INGInious ne correspond pas\r\nd'office à un 20 à l'examen (la clarté, la simplicité du code, les\r\nspécifications sont aussi des critères importants non vérifiés par\r\nINGInious).**\r\n", + "description": "

Prenez connaissance de l'énoncé de l'examen de juin 2011.

\r\n

Répondez ici à la Question 4 : Ecrivez le corps de la méthode addProcess de la classe FullComputer. Pensez à utiliser les méthodes de la classe Process définies à la question 3. :

\r\n
/**\r\n * @pre p != null, p ne se trouve pas déjà sur cet ordinateur\r\n * @post le processus p a été ajouté à cet ordinateur, si (1)le\r\n * nombre de processus maximal n'est pas atteint et (2) la capacité de\r\n * stockage nécessaire pour p est disponible. Retourne true si le\r\n * processus a été ajouté, false sinon.\r\n *\r\n */\r\n public boolean addProcess(Process p)\r\n\r\n // À implémenter
\r\n

Comme l'examen est sur papier, il est préférable que vous rédigiez la réponse sur une feuille de papier et que vous la recopiiez ici une fois que vous êtes sûr de vous. INGInious vous permettra de vérifier si votre code est correct mais n'oubliez pas qu'à l'examen, vous n'aurez pas plusieurs essais. Il est donc important de s'entraîner à rédiger du code sur papier pour se mettre en situation d'examen et évaluer votre temps pour répondre.

\r\n

Souvenez-vous qu'une réponse correcte sur INGInious ne correspond pas d'office à un 20 à l'examen (la clarté, la simplicité du code, les spécifications sont aussi des critères importants non vérifiés par INGInious).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -10606,7 +10606,7 @@ }, { "title": "Examen Juin 2011: Question 5", - "description": "Prenez connaissance de l'énoncé de l'[examen de juin\r\n2011](https://inginious.info.ucl.ac.be/course/LSINF1101/examj2011q1/jun11.pdf).\r\n\r\nRépondez ici à la Question 5 : Implémentez la méthode `addProcess()` de\r\nla classe `Cluster`.\r\n\r\nVoici sa signature :\r\n\r\n``` java\r\n/**\r\n * @pre p != null, p ne se trouve pas déjà sur un ordinateur du\r\n * cluster.\r\n * @post Le processus p a été ajouté au premier ordinateur, à partir\r\n * de la tête de la liste, disposant des ressources nécessaires.\r\n * La nouvelle tête de liste est le noeud qui suit celui de\r\n * l'ordinateur où p a été ajouté. Si aucun ordinateur ne\r\n * dispose de ressources suffisantes, la tête de liste est\r\n * inchangée et une UnavailableException est lancée.\r\n */\r\npublic void addProcess(Process p) throws UnavailableException{\r\n // À implémenter\r\n}\r\n```\r\n\r\n**Comme l'examen est sur papier, il est préférable que vous rédigiez la\r\nréponse sur une feuille de papier et que vous la recopiiez ici une fois\r\nque vous êtes sûr de vous. INGInious vous permettra de vérifier si votre\r\ncode est correct mais n'oubliez pas qu'à l'examen, vous n'aurez pas\r\nplusieurs essais. Il est donc important de s'entraîner à rédiger du code\r\nsur papier pour se mettre en situation d'examen et évaluer votre temps\r\npour répondre.**\r\n\r\n**Souvenez-vous qu'une réponse correcte sur INGInious ne correspond pas\r\nd'office à un 20 à l'examen (la clarté, la simplicité du code, les\r\nspécifications sont aussi des critères importants non vérifiés par\r\nINGInious).**\r\n", + "description": "

Prenez connaissance de l'énoncé de l'examen de juin 2011.

\r\n

Répondez ici à la Question 5 : Implémentez la méthode addProcess() de la classe Cluster.

\r\n

Voici sa signature :

\r\n
/**\r\n * @pre p != null, p ne se trouve pas déjà sur un ordinateur du\r\n *        cluster.\r\n * @post Le processus p a été ajouté au premier ordinateur, à partir\r\n *         de la tête de la liste, disposant des ressources nécessaires.\r\n *         La nouvelle tête de liste est le noeud qui suit celui de\r\n *         l'ordinateur où p a été ajouté. Si aucun ordinateur ne\r\n *         dispose de ressources suffisantes, la tête de liste est\r\n *         inchangée et une UnavailableException est lancée.\r\n */\r\npublic void addProcess(Process p) throws UnavailableException{\r\n    // À implémenter\r\n}
\r\n

Comme l'examen est sur papier, il est préférable que vous rédigiez la réponse sur une feuille de papier et que vous la recopiiez ici une fois que vous êtes sûr de vous. INGInious vous permettra de vérifier si votre code est correct mais n'oubliez pas qu'à l'examen, vous n'aurez pas plusieurs essais. Il est donc important de s'entraîner à rédiger du code sur papier pour se mettre en situation d'examen et évaluer votre temps pour répondre.

\r\n

Souvenez-vous qu'une réponse correcte sur INGInious ne correspond pas d'office à un 20 à l'examen (la clarté, la simplicité du code, les spécifications sont aussi des critères importants non vérifiés par INGInious).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -10656,7 +10656,7 @@ }, { "title": "Examen juin 2011: Question 6", - "description": "Prenez connaissance de l'énoncé de l'[examen de juin\r\n2011](https://inginious.info.ucl.ac.be/course/LSINF1101/examj2011q1/jun11.pdf).\r\n\r\nRépondez ici à la Question 6 : Ecrivez complètement la méthode\r\n`removeComputer` de la classe `Cluster` dont la spécification et la\r\nsignature sont ci-desosus. Indice: vous pouvez utiliser la valeur de\r\n`count`.\r\n\r\n``` java\r\n/**\r\n * @pr e comp != null\r\n * @po st L'ordinateur comp a été retiré du cluster, s'il s'y\r\n * trouvait. Si comp est en tête de liste, la tête de liste passe au\r\n * noeud suivant, sinon elle est inchangée. Retourne true si comp a\r\n * été retiré, false sinon.\r\n */\r\n\r\n // À implémenter\r\n```\r\n\r\n**Comme l'examen est sur papier, il est préférable que vous rédigiez la\r\nréponse sur une feuille de papier et que vous la recopiiez ici une fois\r\nque vous êtes sûr de vous. INGInious vous permettra de vérifier si votre\r\ncode est correct mais n'oubliez pas qu'à l'examen, vous n'aurez pas\r\nplusieurs essais. Il est donc important de s'entraîner à rédiger du code\r\nsur papier pour se mettre en situation d'examen et évaluer votre temps\r\npour répondre.**\r\n\r\n**Souvenez-vous qu'une réponse correcte sur INGInious ne correspond pas\r\nd'office à un 20 à l'examen (la clarté, la simplicité du code, les\r\nspécifications sont aussi des critères importants non vérifiés par\r\nINGInious).**\r\n", + "description": "

Prenez connaissance de l'énoncé de l'examen de juin 2011.

\r\n

Répondez ici à la Question 6 : Ecrivez complètement la méthode removeComputer de la classe Cluster dont la spécification et la signature sont ci-desosus. Indice: vous pouvez utiliser la valeur de count.

\r\n
/**\r\n * @pr e comp != null\r\n * @po st L'ordinateur comp a été retiré du cluster, s'il s'y\r\n * trouvait. Si comp est en tête de liste, la tête de liste passe au\r\n * noeud suivant, sinon elle est inchangée. Retourne true si comp a\r\n * été retiré, false sinon.\r\n */\r\n\r\n // À implémenter
\r\n

Comme l'examen est sur papier, il est préférable que vous rédigiez la réponse sur une feuille de papier et que vous la recopiiez ici une fois que vous êtes sûr de vous. INGInious vous permettra de vérifier si votre code est correct mais n'oubliez pas qu'à l'examen, vous n'aurez pas plusieurs essais. Il est donc important de s'entraîner à rédiger du code sur papier pour se mettre en situation d'examen et évaluer votre temps pour répondre.

\r\n

Souvenez-vous qu'une réponse correcte sur INGInious ne correspond pas d'office à un 20 à l'examen (la clarté, la simplicité du code, les spécifications sont aussi des critères importants non vérifiés par INGInious).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -10706,7 +10706,7 @@ }, { "title": "Examen Juin 2011: Question 7", - "description": "Prenez connaissance de l'énoncé de l'[examen de juin\r\n2011](https://inginious.info.ucl.ac.be/course/LSINF1101/examj2011q1/jun11.pdf).\r\n\r\nRépondez ici à la Question 7 : Implémentez la méthode `loadState()` de\r\nla classe `Cluster`.\r\n\r\nVoici sa signature :\r\n\r\n``` java\r\n/**\r\n* @pre filename le nom d'un fichier sauvegardé par saveState\r\n* @post Retire tous les processus présents dans le cluster, puis\r\n* ajoute au cluster les processus dont les noms et capacités\r\n* sont donnés dans le fichier, selon le format généré par\r\n* saveState. Arrête le programme si une erreur d'I/O se\r\n* produit ou si la capacité du cluster est insuffisante.\r\n* Les processus sont répartis équitablement entre les\r\n* différents ordinateurs du cluster.\r\n*/\r\npublic void loadState(String fileName){\r\n // À implémenter\r\n}\r\n```\r\n\r\n**Comme l'examen est sur papier, il est préférable que vous rédigiez la\r\nréponse sur une feuille de papier et que vous la recopiiez ici une fois\r\nque vous êtes sûr de vous. INGInious vous permettra de vérifier si votre\r\ncode est correct mais n'oubliez pas qu'à l'examen, vous n'aurez pas\r\nplusieurs essais. Il est donc important de s'entraîner à rédiger du code\r\nsur papier pour se mettre en situation d'examen et évaluer votre temps\r\npour répondre.**\r\n\r\n**Souvenez-vous qu'une réponse correcte sur INGInious ne correspond pas\r\nd'office à un 20 à l'examen (la clarté, la simplicité du code, les\r\nspécifications sont aussi des critères importants non vérifiés par\r\nINGInious).**\r\n", + "description": "

Prenez connaissance de l'énoncé de l'examen de juin 2011.

\r\n

Répondez ici à la Question 7 : Implémentez la méthode loadState() de la classe Cluster.

\r\n

Voici sa signature :

\r\n
/**\r\n* @pre     filename le nom d'un fichier sauvegardé par saveState\r\n* @post    Retire tous les processus présents dans le cluster, puis\r\n*            ajoute au cluster les processus dont les noms et capacités\r\n*            sont donnés dans le fichier, selon le format généré par\r\n*            saveState.  Arrête le programme si une erreur d'I/O se\r\n*            produit ou si la capacité du cluster est insuffisante.\r\n*            Les processus sont répartis équitablement entre les\r\n*            différents ordinateurs du cluster.\r\n*/\r\npublic void loadState(String fileName){\r\n  // À implémenter\r\n}
\r\n

Comme l'examen est sur papier, il est préférable que vous rédigiez la réponse sur une feuille de papier et que vous la recopiiez ici une fois que vous êtes sûr de vous. INGInious vous permettra de vérifier si votre code est correct mais n'oubliez pas qu'à l'examen, vous n'aurez pas plusieurs essais. Il est donc important de s'entraîner à rédiger du code sur papier pour se mettre en situation d'examen et évaluer votre temps pour répondre.

\r\n

Souvenez-vous qu'une réponse correcte sur INGInious ne correspond pas d'office à un 20 à l'examen (la clarté, la simplicité du code, les spécifications sont aussi des critères importants non vérifiés par INGInious).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -10756,7 +10756,7 @@ }, { "title": "Question supplémentaire : Fonctions mathématiques", - "description": "Créer un programme permettant de calculer des fonctions mathématiques.\r\nVous ne pouvez pas utiliser les fonctions mathématiques natives de Java.\r\n", + "description": "

Créer un programme permettant de calculer des fonctions mathématiques. Vous ne pouvez pas utiliser les fonctions mathématiques natives de Java.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -10810,7 +10810,7 @@ }, { "title": "Exercice complémentaire 2 : Equations du second degré", - "description": "Ecrivez un programme qui permet de donner, lorsqu'elles sont réelles,\r\nles solutions de l'[équation du second\r\ndegré](https://fr.wikipedia.org/wiki/Équation_du_second_degré)\r\n\r\nPour cela, écrivez un programme qui demande à l'utilisateur de taper les\r\nvaleurs de *a*, *b* et *c* et ensuite écrit sur sa sortie standard les\r\nracines si celles-ci sont réelles. Pensez aux différents cas possibles\r\nen fonction des différentes valeurs respectives de *a*, *b* et *c*.\r\n\r\nPour rappel, vous pouvez calculer la racine carrée du réel `x` en\r\nutilisant `Math.sqrt(x)`.\r\n\r\nVotre réponse devra compléter le code ci-dessous:\r\n", + "description": "

Ecrivez un programme qui permet de donner, lorsqu'elles sont réelles, les solutions de l'équation du second degré

\r\n

Pour cela, écrivez un programme qui demande à l'utilisateur de taper les valeurs de a, b et c et ensuite écrit sur sa sortie standard les racines si celles-ci sont réelles. Pensez aux différents cas possibles en fonction des différentes valeurs respectives de a, b et c.

\r\n

Pour rappel, vous pouvez calculer la racine carrée du réel x en utilisant Math.sqrt(x).

\r\n

Votre réponse devra compléter le code ci-dessous:

\r\n", "tags": [ { "text": "INGINIOUS", @@ -10864,7 +10864,7 @@ }, { "title": "Question supplémentaire : Division euclidienne", - "description": "Utilisez une boucle pour réaliser une division euclidienne! le diviseur\r\net dividende vous sont donnés, vous devez trouver le quotient et le\r\nreste.\r\n\r\n> ``` java\r\n> int diviseur;\r\n> int dividende;\r\n>\r\n> int reste = 0;\r\n> int quotient = 0;\r\n> ```\r\n", + "description": "

Utilisez une boucle pour réaliser une division euclidienne! le diviseur et dividende vous sont donnés, vous devez trouver le quotient et le reste.

\r\n
\r\n
int diviseur;\r\nint dividende;\r\n\r\nint reste = 0;\r\nint quotient = 0;
\r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -10923,7 +10923,7 @@ }, { "title": "Fonctions équation du second degré", - "description": "Ecrivez la méthode permettant de calculer le nombre de racine d'une\r\néquation du second degré On passe a,b et c en paramètre de votre\r\nméthode. La méthode s'appelle eqsecdeg1 pour la première partie et\r\neqsecdeg2 pour la seconde.\r\n", + "description": "

Ecrivez la méthode permettant de calculer le nombre de racine d'une équation du second degré On passe a,b et c en paramètre de votre méthode. La méthode s'appelle eqsecdeg1 pour la première partie et eqsecdeg2 pour la seconde.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -10977,7 +10977,7 @@ }, { "title": "Fonctions solution d'une équation du second degré", - "description": "Ecrivez la méthode permettant de calculer la valeur d'une équation du\r\nsecond degré On passe a,b et c en paramètre de votre méthode. La méthode\r\ns'appelle eqsecdegsol1 pour la première partie et eqsecdegsol2 pour la\r\nseconde On vous donne accès à eqsecdeg2 permettant de connaître le\r\nnombre de solutions . Pour la deuxième version s'il y a plus qu'une\r\nsolution, vous renvoyez -1\r\n", + "description": "

Ecrivez la méthode permettant de calculer la valeur d'une équation du second degré On passe a,b et c en paramètre de votre méthode. La méthode s'appelle eqsecdegsol1 pour la première partie et eqsecdegsol2 pour la seconde On vous donne accès à eqsecdeg2 permettant de connaître le nombre de solutions . Pour la deuxième version s'il y a plus qu'une solution, vous renvoyez -1

\r\n", "tags": [ { "text": "INGINIOUS", @@ -11031,7 +11031,7 @@ }, { "title": "Révisions : QCM", - "description": "Revision\r\n========\r\n", + "description": "

Revision

\r\n", "tags": [ { "text": "INGINIOUS", @@ -11080,6 +11080,6 @@ "1": "Misconception", "2": "autres" }, - "extraction_date": "2019-12-18T16:15:27.815Z", + "extraction_date": "2020-03-04T17:50:07.705Z", "url": "https://github.com/UCL-INGI/CS1-Java" } \ No newline at end of file diff --git a/results/results4.json b/results/results4.json index 51b7c91..769f5bb 100644 --- a/results/results4.json +++ b/results/results4.json @@ -2,7 +2,7 @@ "exercises": [ { "title": "Bilan Hashing", - "description": "Etant donné une fonction de hachage\r\n$h(\\\\left\\[v\\_0 \\\\cdots v\\_n \\\\right\\]) = \\\\sum\\_{i=0}^{n} v\\_i R^{(n-i-1)} \\\\% M$\r\ndans laquelle \\[*v*0⋯*v**n*\\] dénote un vecteur de\r\nbit et *R* et *M* sont des facteurs constants.\r\n", + "description": "

Etant donné une fonction de hachage $h(\\left[v_0 \\cdots v_n \\right]) = \\sum_{i=0}^{n} v_i R^{(n-i-1)} \\% M$ dans laquelle [v0vn] dénote un vecteur de bit et R et M sont des facteurs constants.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -47,7 +47,7 @@ }, { "title": "Circular LinkedList", - "description": "Context\r\n=======\r\n\r\n[Description](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/bilan_m1/bilan_m1.pdf) of the implementation exercise and\r\ninteresting questions to improve your skills.\r\n\r\nFill-in the body of each method (TODO) below in the corresponding\r\ntextfield. grade: 50% for the correctness of your implementation\r\n(correct or not), 50% for the efficiency (efficient or not).\r\n\r\n``` java\r\npublic class NodeQueue implements Queue {\r\n\r\n // Variables d’instance\r\n\r\n private Node marker;\r\n private int size;\r\n\r\n\r\n @Override\r\n public int size() {\r\n // TODO\r\n return 0;\r\n }\r\n\r\n @Override\r\n public boolean isEmpty() {\r\n // TODO\r\n return true;\r\n }\r\n\r\n @Override\r\n public E front() throws QueueEmptyException {\r\n // TODO\r\n return null;\r\n }\r\n\r\n @Override\r\n public void enqueue(E element) {\r\n // TODO\r\n\r\n }\r\n\r\n @Override\r\n public E dequeue() throws QueueEmptyException {\r\n // TODO\r\n return null;\r\n }\r\n}\r\n```\r\n", + "description": "

Context

\r\n

Description of the implementation exercise and interesting questions to improve your skills.

\r\n

Fill-in the body of each method (TODO) below in the corresponding textfield. grade: 50% for the correctness of your implementation (correct or not), 50% for the efficiency (efficient or not).

\r\n
public class NodeQueue<E> implements Queue<E> {\r\n\r\n    // Variables d’instance\r\n\r\n    private Node<E> marker;\r\n    private int size;\r\n\r\n\r\n    @Override\r\n    public int size() {\r\n        // TODO\r\n        return 0;\r\n    }\r\n\r\n    @Override\r\n    public boolean isEmpty() {\r\n        // TODO\r\n        return true;\r\n    }\r\n\r\n    @Override\r\n    public E front() throws QueueEmptyException {\r\n        // TODO\r\n        return null;\r\n    }\r\n\r\n    @Override\r\n    public void enqueue(E element) {\r\n        // TODO\r\n\r\n    }\r\n\r\n    @Override\r\n    public E dequeue() throws QueueEmptyException {\r\n        // TODO\r\n        return null;\r\n    }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -101,7 +101,7 @@ }, { "title": "Global Warming", - "description": "Context\r\n=======\r\n\r\nAssume the following 5x5 matrix:\r\n\r\n``` java\r\nint [][] tab = new int[][] {{1,3,3,1,3},\r\n {4,2,2,4,5},\r\n {4,4,1,4,2},\r\n {1,4,2,3,6},\r\n {1,1,1,6,3}};\r\n```\r\n\r\nrepresented in the array here under:\r\n\r\n\"matrix\r\n\r\nEach entry of the matrix represents an altitude. The objective is to\r\nimplement a class GlobalWarmingImpl that\r\nthe method described in GlobalWarming\r\ngiven next.\r\n\r\nGiven a global water level, all the positions of the matrix with a value\r\n<= the water level are flooded (under the water) and thus unsafe. So\r\nassuming the water level is 3, all the safe points are green.\r\n\r\nThe methods you must implement is\r\n\r\n- the computations of the number of safe-points given a specified\r\n water level\r\n\r\n\r\n\r\n``` java\r\nimport java.util.List;\r\n\r\nabstract class GlobalWarming {\r\n\r\n\r\n final int[][] altitude;\r\n\r\n /**\r\n * @param altitude is a n x n matrix of int values representing altitudes (positive or negative)\r\n */\r\n public GlobalWarming(int[][] altitude) {\r\n this.altitude = altitude;\r\n }\r\n\r\n /**\r\n *\r\n * @param waterLevel\r\n * @return the number of entries in altitude matrix that would be above\r\n * the specified waterLevel.\r\n * Warning: this is not the waterLevel given in the constructor/\r\n */\r\n public abstract int nbSafePoints(int waterLevel);\r\n\r\n}\r\n```\r\n\r\nPreliminary exercises\r\n=====================\r\n\r\n``` java\r\nint [][] tab = new int[][] {{1,3,3,1,3},\r\n {4,2,2,4,5},\r\n {4,4,1,4,2},\r\n {1,4,2,3,6},\r\n {1,1,1,6,3}};\r\nGlobalWarming gw = new MyGlobalWarming(tab);\r\n```\r\n", + "description": "

Context

\r\n

Assume the following 5x5 matrix:

\r\n
int [][] tab = new int[][] {{1,3,3,1,3},\r\n                          {4,2,2,4,5},\r\n                          {4,4,1,4,2},\r\n                          {1,4,2,3,6},\r\n                          {1,1,1,6,3}};
\r\n

represented in the array here under:

\r\n

\"matrix

\r\n

Each entry of the matrix represents an altitude. The objective is to implement a class GlobalWarmingImpl that the method described in GlobalWarming given next.

\r\n

Given a global water level, all the positions of the matrix with a value <= the water level are flooded (under the water) and thus unsafe. So assuming the water level is 3, all the safe points are green.

\r\n

The methods you must implement is

\r\n
    \r\n
  • the computations of the number of safe-points given a specified water level
  • \r\n
\r\n
import java.util.List;\r\n\r\nabstract class GlobalWarming {\r\n\r\n\r\n    final int[][] altitude;\r\n\r\n    /**\r\n     * @param altitude is a n x n matrix of int values representing altitudes (positive or negative)\r\n     */\r\n    public GlobalWarming(int[][] altitude) {\r\n        this.altitude = altitude;\r\n    }\r\n\r\n    /**\r\n     *\r\n     * @param waterLevel\r\n     * @return the number of entries in altitude matrix that would be above\r\n     *         the specified waterLevel.\r\n     *         Warning: this is not the waterLevel given in the constructor/\r\n     */\r\n    public abstract int nbSafePoints(int waterLevel);\r\n\r\n}
\r\n

Preliminary exercises

\r\n
int [][] tab = new int[][] {{1,3,3,1,3},\r\n                          {4,2,2,4,5},\r\n                          {4,4,1,4,2},\r\n                          {1,4,2,3,6},\r\n                          {1,1,1,6,3}};\r\nGlobalWarming gw = new MyGlobalWarming(tab);
\r\n", "tags": [ { "text": "INGINIOUS", @@ -160,7 +160,7 @@ }, { "title": "Incremental Hash", - "description": "La fonction de Hash calculée sur le sous tableau t\\[from,...,from+M-1\\]\r\nest calculée comme suit:\r\n\r\n$hash(\\[from,...,from+M-1\\])= \\\\left( \\\\sum\\_{i=0}^{M-1} t\\[from+i\\] \\\\cdot R^{(M-1-i)}\\\\right)\\\\%Q$\r\n\r\nLe code pour calculer cette fonction de hash vous est donné. Nous vous\r\ndemandons de calculer\r\n*h**a**s**h*(\\[*f**r**o**m*, ..., *f**r**o**m* + *M* − 1\\]) au départ de\r\n*h**a**s**h*(\\[*f**r**o**m* − 1, ..., *f**r**o**m* + *M* − 2\\]) en O(1).\r\n", + "description": "

La fonction de Hash calculée sur le sous tableau t[from,...,from+M-1] est calculée comme suit:

\r\n

$hash([from,...,from+M-1])= \\left( \\sum_{i=0}^{M-1} t[from+i] \\cdot R^{(M-1-i)}\\right)\\%Q$

\r\n

Le code pour calculer cette fonction de hash vous est donné. Nous vous demandons de calculer hash([from, ..., from + M − 1]) au départ de hash([from − 1, ..., from + M − 2]) en O(1).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -214,7 +214,7 @@ }, { "title": "Huffman", - "description": "Vous devez calculer un arbre de Huffman au départ de la fréquence donnée\r\npour chacune des R lettres (characters).\r\n\r\nPour rappel, dans un arbre de Huffman nous avons que *la somme de la\r\nfréquence associée à chaque feuille multipliée par la profondeur de\r\ncelle-ci est minimale*.\r\n\r\nPar exemple, étant donné les fréquences suivantes:\r\n\r\n\"Input\r\n\r\nun arbre de Huffman pourrait être:\r\n\r\n\"Huffman\r\n", + "description": "

Vous devez calculer un arbre de Huffman au départ de la fréquence donnée pour chacune des R lettres (characters).

\r\n

Pour rappel, dans un arbre de Huffman nous avons que la somme de la fréquence associée à chaque feuille multipliée par la profondeur de celle-ci est minimale.

\r\n

Par exemple, étant donné les fréquences suivantes:

\r\n

\"Input

\r\n

un arbre de Huffman pourrait être:

\r\n

\"Huffman

\r\n", "tags": [ { "text": "INGINIOUS", @@ -263,7 +263,7 @@ }, { "title": "Connected Components", - "description": "L'API de la classe [Graph](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/bilan_m6_cc/javadoc.zip).\r\n\r\nL'API de [Java](https://docs.oracle.com/javase/8/docs/api/).\r\n\r\n``` java\r\npublic class ConnectedComponents {\r\n /**\r\n * @return the number of connected components in g\r\n */\r\n public static int numberOfConnectedComponents(Graph g) {\r\n // TODO\r\n return 0;\r\n }\r\n}\r\n```\r\n", + "description": "

L'API de la classe Graph.

\r\n

L'API de Java.

\r\n
public class ConnectedComponents {\r\n  /**\r\n   * @return the number of connected components in g\r\n   */\r\n  public static int numberOfConnectedComponents(Graph g) {\r\n    // TODO\r\n    return 0;\r\n  }\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -322,7 +322,7 @@ }, { "title": "Quizz: Closest Pair", - "description": "Implémentez un algorithme qui reçoit en entrée un tableau d'entiers et\r\nqui trouve deux valeurs issues de tableau dont la somme se rapproche le\r\nplus d'une valeur entière donnée *x*. Soiet (*a*, *b*) les deux valeurs\r\ntrouvées, celles-ci doivent donc minimiser |*x* − (*a* + *b*)|. Les deux\r\nvaleurs peuvent correspondre à la même entrée du tableau.\r\n\r\nPar exemple pour le tableau suivant\r\n\r\n``` java\r\nint [] input = new int [] {5,10,1,75,150,151,155,18,75,50,30};\r\n```\r\n\r\n- x=20, il faut retourner \\[10,10\\].\r\n- x=153, il faut retrouner \\[1,151\\]\r\n- x=13, il faut retrouner \\[1,10\\]\r\n- x=140 il faut retourner \\[75,75\\]\r\n- x=170 il faut retourner \\[18,151\\]\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/closestpair/project.zip).\r\n", + "description": "

Implémentez un algorithme qui reçoit en entrée un tableau d'entiers et qui trouve deux valeurs issues de tableau dont la somme se rapproche le plus d'une valeur entière donnée x. Soiet (a, b) les deux valeurs trouvées, celles-ci doivent donc minimiser |x − (a + b)|. Les deux valeurs peuvent correspondre à la même entrée du tableau.

\r\n

Par exemple pour le tableau suivant

\r\n
int [] input = new int [] {5,10,1,75,150,151,155,18,75,50,30};
\r\n
    \r\n
  • x=20, il faut retourner [10,10].
  • \r\n
  • x=153, il faut retrouner [1,151]
  • \r\n
  • x=13, il faut retrouner [1,10]
  • \r\n
  • x=140 il faut retourner [75,75]
  • \r\n
  • x=170 il faut retourner [18,151]
  • \r\n
\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -372,7 +372,7 @@ }, { "title": "LinearProbing", - "description": "Dans ce exercice il vous est demandé d'implémenter les fonctions\r\n`resize`, `put` et `get` d'une table de symbole basé sur le hashage par\r\nLinear Probing.\r\n\r\nPour cela la classe suivant vous a été donné. Vous devez completer les\r\n*TODO*.\r\n\r\n``` java\r\nimport java.util.Arrays;\r\n\r\n/**\r\n* Symbol-table implementation with linear-probing hash table.\r\n*/\r\npublic class LinearProbingHashST {\r\n\r\nprivate int n; // number of key-value pairs in the symbol table\r\nprivate int m; // size of linear probing table\r\nprivate Key[] keys; // the keys\r\nprivate Value[] vals; // the values\r\n\r\n\r\n/**\r\n * Initializes an empty symbol table.\r\n */\r\npublic LinearProbingHashST() {this(16);}\r\n\r\n /**\r\n * Initializes an empty symbol table with the specified initial capacity.\r\n */\r\npublic LinearProbingHashST(int capacity) {\r\n m = capacity;\r\n n = 0;\r\n keys = (Key[]) new Object[m];\r\n vals = (Value[]) new Object[m];\r\n}\r\n\r\npublic int size() {return n;}\r\npublic boolean isEmpty() {return size() == 0;}\r\n\r\n// hash function for keys - returns value between 0 and M-1\r\nprivate int hash(Key key) {\r\n return (key.hashCode() & 0x7fffffff) % m;\r\n}\r\n\r\n/**\r\n* resizes the hash table to the given capacity by re-hashing all of the keys\r\n*/\r\nprivate void resize(int capacity) {\r\n //TODO STUDENT\r\n}\r\n\r\n/**\r\n* Inserts the specified key-value pair into the symbol table, overwriting the old\r\n* value with the new value.\r\n*/\r\npublic void put(Key key, Value val) {\r\n //TODO STUDENT\r\n}\r\n\r\n/**\r\n* Returns the value associated with the specified key.\r\n*/\r\npublic Value get(Key key) {\r\n //TODO STUDENT\r\n}\r\n}\r\n```\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/EXAM0119LinearProbing/LSINF1121_EXAM0119_LinearProbing.zip).\r\n", + "description": "

Dans ce exercice il vous est demandé d'implémenter les fonctions resize, put et get d'une table de symbole basé sur le hashage par Linear Probing.

\r\n

Pour cela la classe suivant vous a été donné. Vous devez completer les TODO.

\r\n
import java.util.Arrays;\r\n\r\n/**\r\n* Symbol-table implementation with linear-probing hash table.\r\n*/\r\npublic class LinearProbingHashST<Key, Value> {\r\n\r\nprivate int n;           // number of key-value pairs in the symbol table\r\nprivate int m;           // size of linear probing table\r\nprivate Key[] keys;      // the keys\r\nprivate Value[] vals;    // the values\r\n\r\n\r\n/**\r\n * Initializes an empty symbol table.\r\n */\r\npublic LinearProbingHashST() {this(16);}\r\n\r\n /**\r\n * Initializes an empty symbol table with the specified initial capacity.\r\n */\r\npublic LinearProbingHashST(int capacity) {\r\n    m = capacity;\r\n    n = 0;\r\n    keys = (Key[])   new Object[m];\r\n    vals = (Value[]) new Object[m];\r\n}\r\n\r\npublic int size() {return n;}\r\npublic boolean isEmpty() {return size() == 0;}\r\n\r\n// hash function for keys - returns value between 0 and M-1\r\nprivate int hash(Key key) {\r\n    return (key.hashCode() & 0x7fffffff) % m;\r\n}\r\n\r\n/**\r\n* resizes the hash table to the given capacity by re-hashing all of the keys\r\n*/\r\nprivate void resize(int capacity) {\r\n    //TODO STUDENT\r\n}\r\n\r\n/**\r\n* Inserts the specified key-value pair into the symbol table, overwriting the old\r\n* value with the new value.\r\n*/\r\npublic void put(Key key, Value val) {\r\n    //TODO STUDENT\r\n}\r\n\r\n/**\r\n* Returns the value associated with the specified key.\r\n*/\r\npublic Value get(Key key) {\r\n    //TODO STUDENT\r\n}\r\n}
\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -427,7 +427,7 @@ }, { "title": "Global Warming", - "description": "Context\r\n=======\r\n\r\nAssume the following 5x5 matrix:\r\n\r\n``` java\r\nint [][] tab = new int[][] {{1,3,3,1,3},\r\n {4,2,2,4,5},\r\n {4,4,1,4,2},\r\n {1,4,2,3,6},\r\n {1,1,1,6,3}};\r\n```\r\n\r\nrepresented in the array here under:\r\n\r\n\"matrix\r\n\r\nEach entry of the matrix represents an altitude. The objective is to\r\nimplement a class GlobalWarmingImpl that\r\nimplements all the methods described in GlobalWarming given next.\r\n\r\nA global water level specified in the constructor models the fact that\r\nall the positions of the matrix with a value <= the water level are\r\nflooded (under the water) and thus unsafe. In the above example, the\r\nwater level is 3, all the safe points are green.\r\n\r\nThe method you must implement is the computation of the shortest path\r\nbetween two positions on a same island\r\n\r\nwe assume that points are **only connected vertially or horizontally**.\r\n\r\n``` java\r\nimport java.util.List;\r\n\r\nabstract class GlobalWarming {\r\n\r\n /**\r\n * A class to represent the coordinates on the altitude matrix\r\n */\r\n public static class Point {\r\n\r\n final int x, y;\r\n\r\n Point(int x, int y) {\r\n this.x = x;\r\n this.y = y;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n Point p = (Point) obj;\r\n return p.x == x && p.y == y;\r\n }\r\n }\r\n\r\n final int[][] altitude;\r\n final int waterLevel;\r\n\r\n\r\n /**\r\n * In the following, we assume that the points are connected to\r\n * horizontal or vertical neighbors but not to the diagonal ones\r\n * @param altitude is a n x n matrix of int values representing altitudes (positive or negative)\r\n * @param waterLevel is the water level, every entry <= waterLevel is flooded\r\n */\r\n public GlobalWarming(int[][] altitude, int waterLevel) {\r\n this.altitude = altitude;\r\n this.waterLevel = waterLevel;\r\n }\r\n\r\n\r\n /**\r\n *\r\n * @param p1 a safe point with valid coordinates on altitude matrix\r\n * @param p2 a safe point (different from p1) with valid coordinates on altitude matrix\r\n * @return the shortest simple path (vertical/horizontal moves) if any between from p1 to p2 using only vertical/horizontal moves on safe points.\r\n * an empty list if not path exists (i.e. p1 and p2 are not on the same island).\r\n */\r\n public abstract List shortestPath(Point p1, Point p2);\r\n\r\n}\r\n```\r\n\r\nPreliminary exercises\r\n=====================\r\n\r\n``` java\r\nint [][] tab = new int[][] {{1,3,3,1,3},\r\n {4,2,2,4,5},\r\n {4,4,1,4,2},\r\n {1,4,2,3,6},\r\n {1,1,1,6,3}};\r\nGlobalWarming gw = new MyGlobalWarming(tab,3);\r\n```\r\n\r\n\"matrix\r\n", + "description": "

Context

\r\n

Assume the following 5x5 matrix:

\r\n
int [][] tab = new int[][] {{1,3,3,1,3},\r\n                          {4,2,2,4,5},\r\n                          {4,4,1,4,2},\r\n                          {1,4,2,3,6},\r\n                          {1,1,1,6,3}};
\r\n

represented in the array here under:

\r\n

\"matrix

\r\n

Each entry of the matrix represents an altitude. The objective is to implement a class GlobalWarmingImpl that implements all the methods described in GlobalWarming given next.

\r\n

A global water level specified in the constructor models the fact that all the positions of the matrix with a value <= the water level are flooded (under the water) and thus unsafe. In the above example, the water level is 3, all the safe points are green.

\r\n

The method you must implement is the computation of the shortest path between two positions on a same island

\r\n

we assume that points are only connected vertially or horizontally.

\r\n
import java.util.List;\r\n\r\nabstract class GlobalWarming {\r\n\r\n    /**\r\n     * A class to represent the coordinates on the altitude matrix\r\n     */\r\n    public static class Point {\r\n\r\n        final int x, y;\r\n\r\n        Point(int x, int y) {\r\n            this.x = x;\r\n            this.y = y;\r\n        }\r\n\r\n        @Override\r\n        public boolean equals(Object obj) {\r\n            Point p = (Point) obj;\r\n            return p.x == x && p.y == y;\r\n        }\r\n    }\r\n\r\n    final int[][] altitude;\r\n    final int waterLevel;\r\n\r\n\r\n    /**\r\n     * In the following, we assume that the points are connected to\r\n     * horizontal or vertical neighbors but not to the diagonal ones\r\n     * @param altitude is a n x n matrix of int values representing altitudes (positive or negative)\r\n     * @param waterLevel is the water level, every entry <= waterLevel is flooded\r\n     */\r\n    public GlobalWarming(int[][] altitude, int waterLevel) {\r\n        this.altitude = altitude;\r\n        this.waterLevel = waterLevel;\r\n    }\r\n\r\n\r\n    /**\r\n     *\r\n     * @param p1 a safe point with valid coordinates on altitude matrix\r\n     * @param p2 a safe point (different from p1) with valid coordinates on altitude matrix\r\n     * @return the shortest simple path (vertical/horizontal moves) if any between from p1 to p2 using only vertical/horizontal moves on safe points.\r\n     *         an empty list if not path exists (i.e. p1 and p2 are not on the same island).\r\n     */\r\n    public abstract List<Point> shortestPath(Point p1, Point p2);\r\n\r\n}
\r\n

Preliminary exercises

\r\n
int [][] tab = new int[][] {{1,3,3,1,3},\r\n                          {4,2,2,4,5},\r\n                          {4,4,1,4,2},\r\n                          {1,4,2,3,6},\r\n                          {1,1,1,6,3}};\r\nGlobalWarming gw = new MyGlobalWarming(tab,3);
\r\n

\"matrix

\r\n", "tags": [ { "text": "INGINIOUS", @@ -481,7 +481,7 @@ }, { "title": "Global Warming", - "description": "Context\r\n=======\r\n\r\nAssume the following 5x5 matrix:\r\n\r\n``` java\r\nint [][] tab = new int[][] {{1,3,3,1,3},\r\n {4,2,2,4,5},\r\n {4,4,1,4,2},\r\n {1,4,2,3,6},\r\n {1,1,1,6,3}};\r\n```\r\n\r\nrepresented in the array here under:\r\n\r\n\"matrix\r\n\r\nEach entry of the matrix represents an altitude. The objective is to\r\nimplement a class GlobalWarmingImpl that\r\nimplements all the methods described in GlobalWarming given next.\r\n\r\nA global water level specified in the constructor models the fact that\r\nall the positions of the matrix with a value <= the water level are\r\nflooded (under the water) and thus unsafe. In the above example, the\r\nwater level is 3, all the safe points are green.\r\n\r\nThe methods you must implement are\r\n\r\n- the number of islands\r\n- a test to verify if two positions are on the same island\r\n\r\nwe assume that points are **only connected vertially or horizontally**.\r\n\r\n``` java\r\nimport java.util.List;\r\n\r\nabstract class GlobalWarming {\r\n\r\n /**\r\n * A class to represent the coordinates on the altitude matrix\r\n */\r\n public static class Point {\r\n\r\n final int x, y;\r\n\r\n Point(int x, int y) {\r\n this.x = x;\r\n this.y = y;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n Point p = (Point) obj;\r\n return p.x == x && p.y == y;\r\n }\r\n }\r\n\r\n final int[][] altitude;\r\n final int waterLevel;\r\n\r\n\r\n /**\r\n * In the following, we assume that the points are connected to\r\n * horizontal or vertical neighbors but not to the diagonal ones\r\n * @param altitude is a n x n matrix of int values representing altitudes (positive or negative)\r\n * @param waterLevel is the water level, every entry <= waterLevel is flooded\r\n */\r\n public GlobalWarming(int[][] altitude, int waterLevel) {\r\n this.altitude = altitude;\r\n this.waterLevel = waterLevel;\r\n }\r\n\r\n\r\n /**\r\n * An island is a connected components of safe points wrt to waterLevel\r\n * @return the number of islands\r\n */\r\n public abstract int nbIslands();\r\n\r\n /**\r\n *\r\n * @param p1 a point with valid coordinates on altitude matrix\r\n * @param p2 a point with valid coordinates on altitude matrix\r\n * @return true if p1 and p2 are on the same island, that is both p1 and p2 are safe wrt waterLevel\r\n * and there exists a path (vertical/horizontal moves) from p1 to p2 using only safe positions\r\n */\r\n public abstract boolean onSameIsland(Point p1, Point p2);\r\n\r\n\r\n}\r\n```\r\n\r\nPreliminary exercises\r\n=====================\r\n\r\n``` java\r\nint [][] tab = new int[][] {{1,3,3,1,3},\r\n {4,2,2,4,5},\r\n {4,4,1,4,2},\r\n {1,4,2,3,6},\r\n {1,1,1,6,3}};\r\nGlobalWarming gw = new MyGlobalWarming(tab,3);\r\n```\r\n\r\n\"matrix\r\n", + "description": "

Context

\r\n

Assume the following 5x5 matrix:

\r\n
int [][] tab = new int[][] {{1,3,3,1,3},\r\n                          {4,2,2,4,5},\r\n                          {4,4,1,4,2},\r\n                          {1,4,2,3,6},\r\n                          {1,1,1,6,3}};
\r\n

represented in the array here under:

\r\n

\"matrix

\r\n

Each entry of the matrix represents an altitude. The objective is to implement a class GlobalWarmingImpl that implements all the methods described in GlobalWarming given next.

\r\n

A global water level specified in the constructor models the fact that all the positions of the matrix with a value <= the water level are flooded (under the water) and thus unsafe. In the above example, the water level is 3, all the safe points are green.

\r\n

The methods you must implement are

\r\n
    \r\n
  • the number of islands
  • \r\n
  • a test to verify if two positions are on the same island
  • \r\n
\r\n

we assume that points are only connected vertially or horizontally.

\r\n
import java.util.List;\r\n\r\nabstract class GlobalWarming {\r\n\r\n    /**\r\n     * A class to represent the coordinates on the altitude matrix\r\n     */\r\n    public static class Point {\r\n\r\n        final int x, y;\r\n\r\n        Point(int x, int y) {\r\n            this.x = x;\r\n            this.y = y;\r\n        }\r\n\r\n        @Override\r\n        public boolean equals(Object obj) {\r\n            Point p = (Point) obj;\r\n            return p.x == x && p.y == y;\r\n        }\r\n    }\r\n\r\n    final int[][] altitude;\r\n    final int waterLevel;\r\n\r\n\r\n    /**\r\n     * In the following, we assume that the points are connected to\r\n     * horizontal or vertical neighbors but not to the diagonal ones\r\n     * @param altitude is a n x n matrix of int values representing altitudes (positive or negative)\r\n     * @param waterLevel is the water level, every entry <= waterLevel is flooded\r\n     */\r\n    public GlobalWarming(int[][] altitude, int waterLevel) {\r\n        this.altitude = altitude;\r\n        this.waterLevel = waterLevel;\r\n    }\r\n\r\n\r\n    /**\r\n     * An island is a connected components of safe points wrt to waterLevel\r\n     * @return the number of islands\r\n     */\r\n    public abstract int nbIslands();\r\n\r\n    /**\r\n     *\r\n     * @param p1 a point with valid coordinates on altitude matrix\r\n     * @param p2 a point with valid coordinates on altitude matrix\r\n     * @return true if p1 and p2 are on the same island, that is both p1 and p2 are safe wrt waterLevel\r\n     *        and there exists a path (vertical/horizontal moves) from p1 to p2 using only safe positions\r\n     */\r\n    public abstract boolean onSameIsland(Point p1, Point p2);\r\n\r\n\r\n}
\r\n

Preliminary exercises

\r\n
int [][] tab = new int[][] {{1,3,3,1,3},\r\n                          {4,2,2,4,5},\r\n                          {4,4,1,4,2},\r\n                          {1,4,2,3,6},\r\n                          {1,1,1,6,3}};\r\nGlobalWarming gw = new MyGlobalWarming(tab,3);
\r\n

\"matrix

\r\n", "tags": [ { "text": "INGINIOUS", @@ -535,7 +535,7 @@ }, { "title": "Linked List Stack (Implem)", - "description": "Il vous est demandé d'implémenter l'interface suivante, représentant une\r\npile, en utilisant une liste simplement chainée. Vous devriez avoir au\r\nmoins un constructeur sans argument, créant une pile vide.\r\n\r\nNote: utiliser *java.util.Stack<E>* est interdit!\r\n\r\n``` java\r\nimport java.util.EmptyStackException;\r\n\r\npublic interface Stack {\r\n\r\n public boolean empty();\r\n\r\n public E peek() throws EmptyStackException;\r\n\r\n public E pop() throws EmptyStackException;\r\n\r\n public void push(E item);\r\n\r\n}\r\n```\r\n\r\n``` java\r\nimport java.util.EmptyStackException;\r\n\r\npublic class MyStack implements Stack {\r\n\r\n private Node top; // the node on the top of the stack\r\n private int size; // size of the stack\r\n\r\n // helper linked list class\r\n private class Node {\r\n private E item;\r\n private Node next;\r\n\r\n public Node(E element, Node next) {\r\n this.item = element;\r\n this.next = next;\r\n }\r\n }\r\n\r\n /**\r\n * Tests if this stack is empty\r\n */\r\n @Override\r\n public boolean empty() {\r\n // TODO STUDENT: Implement empty method\r\n }\r\n\r\n /**\r\n * Looks at the object at the top of this stack\r\n * without removing it from the stack\r\n */\r\n @Override\r\n public E peek() throws EmptyStackException {\r\n // TODO STUDENT: Implement peek method\r\n }\r\n\r\n /**\r\n * Removes the object at the top of this stack\r\n * and returns that object as the value of this function\r\n */\r\n @Override\r\n public E pop() throws EmptyStackException {\r\n // TODO STUDENT: Implement pop method\r\n }\r\n\r\n /**\r\n * Pushes an item onto the top of this stack\r\n * @param item the item to append\r\n */\r\n @Override\r\n public void push(E item) {\r\n // TODO STUDENT: Implement push method\r\n\r\n }\r\n}\r\n```\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/m1stack/LSINF1121_PART1_Stack.zip).\r\n", + "description": "

Il vous est demandé d'implémenter l'interface suivante, représentant une pile, en utilisant une liste simplement chainée. Vous devriez avoir au moins un constructeur sans argument, créant une pile vide.

\r\n

Note: utiliser java.util.Stack<E> est interdit!

\r\n
import java.util.EmptyStackException;\r\n\r\npublic interface Stack<E> {\r\n\r\n    public boolean empty();\r\n\r\n    public E peek() throws EmptyStackException;\r\n\r\n    public E pop() throws EmptyStackException;\r\n\r\n    public void push(E item);\r\n\r\n}
\r\n
import java.util.EmptyStackException;\r\n\r\npublic class MyStack<E> implements Stack<E> {\r\n\r\n    private Node<E> top;        // the node on the top of the stack\r\n    private int size;        // size of the stack\r\n\r\n    // helper linked list class\r\n    private class Node<E> {\r\n        private E item;\r\n        private Node<E> next;\r\n\r\n        public Node(E element, Node<E> next) {\r\n            this.item = element;\r\n            this.next = next;\r\n        }\r\n    }\r\n\r\n    /**\r\n    * Tests if this stack is empty\r\n    */\r\n    @Override\r\n    public boolean empty() {\r\n        // TODO STUDENT: Implement empty method\r\n    }\r\n\r\n    /**\r\n    * Looks at the object at the top of this stack\r\n    * without removing it from the stack\r\n    */\r\n    @Override\r\n    public E peek() throws EmptyStackException {\r\n        // TODO STUDENT: Implement peek method\r\n    }\r\n\r\n    /**\r\n    * Removes the object at the top of this stack\r\n    * and returns that object as the value of this function\r\n    */\r\n    @Override\r\n    public E pop() throws EmptyStackException {\r\n        // TODO STUDENT: Implement pop method\r\n    }\r\n\r\n    /**\r\n    * Pushes an item onto the top of this stack\r\n    * @param item the item to append\r\n    */\r\n    @Override\r\n    public void push(E item) {\r\n        // TODO STUDENT: Implement push method\r\n\r\n    }\r\n}
\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -590,7 +590,7 @@ }, { "title": "Write Unit tests Stack (Implem)", - "description": "Rappelez-vous de l'interface Stack :\r\n\r\n``` java\r\nimport java.util.EmptyStackException;\r\n\r\npublic interface Stack {\r\n\r\n public boolean empty();\r\n\r\n public E peek() throws EmptyStackException;\r\n\r\n public E pop() throws EmptyStackException;\r\n\r\n public void push(E item);\r\n\r\n}\r\n```\r\n\r\nIl vous est demandé d'écrire des tests unitaire (en utilisant JUnit)\r\nafin de vérifier si une implémentation particulière de cette interface\r\nest correcte.\r\n\r\nVoici un modèle simple que vous pouvez utiliser pour écrire vos tests\r\n(vous pouvez utiliser d'autres types que des String, bien sûr !) :\r\n\r\n``` java\r\nimport org.junit.Test;\r\nimport static org.junit.Assert.assertEquals;\r\n\r\npublic class StackTests {\r\n\r\n @Test\r\n public void firstTest() {\r\n Stack stack = new MyStack();\r\n stack.push(1);\r\n assertEquals(new Integer(1), stack.pop());\r\n }\r\n\r\n @Test\r\n public void secondTest() {\r\n // ... TODO ...\r\n }\r\n\r\n}\r\n```\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/m1stacktests/LSINF1121_PART1_Stack.zip).\r\n", + "description": "

Rappelez-vous de l'interface Stack :

\r\n
import java.util.EmptyStackException;\r\n\r\npublic interface Stack<E> {\r\n\r\n    public boolean empty();\r\n\r\n    public E peek() throws EmptyStackException;\r\n\r\n    public E pop() throws EmptyStackException;\r\n\r\n    public void push(E item);\r\n\r\n}
\r\n

Il vous est demandé d'écrire des tests unitaire (en utilisant JUnit) afin de vérifier si une implémentation particulière de cette interface est correcte.

\r\n

Voici un modèle simple que vous pouvez utiliser pour écrire vos tests (vous pouvez utiliser d'autres types que des String, bien sûr !) :

\r\n
import org.junit.Test;\r\nimport static org.junit.Assert.assertEquals;\r\n\r\npublic class StackTests {\r\n\r\n    @Test\r\n    public void firstTest() {\r\n        Stack<Integer> stack = new MyStack<Integer>();\r\n        stack.push(1);\r\n        assertEquals(new Integer(1), stack.pop());\r\n    }\r\n\r\n    @Test\r\n    public void secondTest() {\r\n        // ... TODO ...\r\n    }\r\n\r\n}
\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -689,7 +689,7 @@ }, { "title": "Median", - "description": "Nous vous donnons l'API d'une classe Vector permettant d'accéder,\r\nmodifier et interchanger deux élements en temps constant. Votre tâche\r\nest d'implémenter une méthode permettant de calculer la médiane d'un\r\nVecteur.\r\n\r\n``` java\r\npublic interface Vector {\r\n // taille du vecteur\r\n public int size();\r\n // mets la valeur v à l'indice i du vecteur\r\n public void set(int i, int v);\r\n // renvoie la valeur à l'indice i du vecteur\r\n public int get(int i);\r\n // échange les valeurs aux positions i et j\r\n public void swap(int i, int j);\r\n\r\n}\r\n```\r\n\r\n[Un projet Eclipse contenant des tests basiques vous est fourni en\r\ncliquant sur ce\r\nlien.](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/median/project.zip)\r\n", + "description": "

Nous vous donnons l'API d'une classe Vector permettant d'accéder, modifier et interchanger deux élements en temps constant. Votre tâche est d'implémenter une méthode permettant de calculer la médiane d'un Vecteur.

\r\n
public interface Vector {\r\n    // taille du vecteur\r\n    public int size();\r\n    // mets la valeur v à l'indice i du vecteur\r\n    public void set(int i, int v);\r\n    // renvoie la valeur à l'indice i du vecteur\r\n    public int get(int i);\r\n    // échange les valeurs aux positions i et j\r\n    public void swap(int i, int j);\r\n\r\n}
\r\n

Un projet Eclipse contenant des tests basiques vous est fourni en cliquant sur ce lien.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -743,7 +743,7 @@ }, { "title": "Circular linkedlist (Implem)", - "description": "On s’intéresse à l'implémentation d'une\r\n`liste simplement chaînée circulaire`, c’est-à-dire une liste pour\r\nlaquelle la dernière position de la liste fait référence, comme position\r\nsuivante, à la première position de la liste.\r\n\r\n![image](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/p1circularlinkedlist/CircularLinkedList.png)\r\n\r\nL’ajout d’un nouvel élément dans la file (méthode `enqueue`) se fait en\r\nfin de liste et le retrait (méthode `remove`) se fait a un index particulier de la liste. Une (seule)\r\nréférence sur la fin de la liste (`last`) est nécessaire pour effectuer\r\ntoutes les opérations sur cette file.\r\n\r\nIl vous est donc demander d'implémenter cette liste simplement chaînée\r\ncirculaire à partir de la classe `CircularLinkedList.java` où vous devez\r\ncompleter (*TODO STUDENT*) les méthodes d'ajout (`enqueue`) et de\r\nretrait (`remove`) ainsi qu'un itérateur (`ListIterator`) qui permet de\r\nparcourir la liste en FIFO. *Attention:* un itérateur ne peut être\r\nmodifié au cours de son utilisation.\r\n\r\n``` java\r\npackage student;\r\n\r\nimport java.util.ConcurrentModificationException;\r\nimport java.util.Iterator;\r\nimport java.util.NoSuchElementException;\r\n\r\npublic class CircularLinkedList implements Iterable {\r\n private long nOp = 0; // count the number of operations\r\n private int n; // size of the stack\r\n private Node last; // trailer of the list\r\n\r\n // helper linked list class\r\n private class Node {\r\n private Item item;\r\n private Node next;\r\n }\r\n\r\n public CircularLinkedList() {\r\n last = null;\r\n n = 0;\r\n }\r\n\r\n public boolean isEmpty() { return n == 0; }\r\n\r\n public int size() { return n; }\r\n\r\n private long nOp() { return nOp; }\r\n\r\n /**\r\n * Append an item at the end of the list\r\n * @param item the item to append\r\n */\r\n public void enqueue(Item item) {\r\n // TODO STUDENT: Implement add method\r\n }\r\n\r\n /**\r\n * Removes the element at the specified position in this list.\r\n * Shifts any subsequent elements to the left (subtracts one from their indices).\r\n * Returns the element that was removed from the list.\r\n */\r\n public Item remove(int index) {\r\n // TODO STUDENT: Implement remove method\r\n }\r\n\r\n /**\r\n * Returns an iterator that iterates through the items in FIFO order.\r\n * @return an iterator that iterates through the items in FIFO order.\r\n */\r\n public Iterator iterator() {\r\n return new ListIterator();\r\n }\r\n\r\n /**\r\n * Implementation of an iterator that iterates through the items in FIFO order.\r\n *\r\n */\r\n private class ListIterator implements Iterator {\r\n // TODO STUDDENT: Implement the ListIterator\r\n }\r\n\r\n}\r\n```\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/p1circularlinkedlist/LSINF1121CircularLinkedList.zip).\r\n", + "description": "

On s’intéresse à l'implémentation d'une liste simplement chaînée circulaire, c’est-à-dire une liste pour laquelle la dernière position de la liste fait référence, comme position suivante, à la première position de la liste.

\r\n

\"image\"

\r\n

L’ajout d’un nouvel élément dans la file (méthode enqueue) se fait en fin de liste et le retrait (méthode remove) se fait a un index particulier de la liste. Une (seule) référence sur la fin de la liste (last) est nécessaire pour effectuer toutes les opérations sur cette file.

\r\n

Il vous est donc demander d'implémenter cette liste simplement chaînée circulaire à partir de la classe CircularLinkedList.java où vous devez completer (TODO STUDENT) les méthodes d'ajout (enqueue) et de retrait (remove) ainsi qu'un itérateur (ListIterator) qui permet de parcourir la liste en FIFO. Attention: un itérateur ne peut être modifié au cours de son utilisation.

\r\n
package student;\r\n\r\nimport java.util.ConcurrentModificationException;\r\nimport java.util.Iterator;\r\nimport java.util.NoSuchElementException;\r\n\r\npublic class CircularLinkedList<Item> implements Iterable<Item> {\r\n private long nOp = 0; // count the number of operations\r\n private int n;          // size of the stack\r\n private Node  last;   // trailer of the list\r\n\r\n // helper linked list class\r\n private class Node {\r\n     private Item item;\r\n     private Node next;\r\n }\r\n\r\n public CircularLinkedList() {\r\n     last = null;\r\n     n = 0;\r\n }\r\n\r\n public boolean isEmpty() { return n == 0; }\r\n\r\n public int size() { return n; }\r\n\r\n private long nOp() { return nOp; }\r\n\r\n /**\r\n  * Append an item at the end of the list\r\n  * @param item the item to append\r\n  */\r\n public void enqueue(Item item) {\r\n     // TODO STUDENT: Implement add method\r\n }\r\n\r\n /**\r\n  * Removes the element at the specified position in this list.\r\n  * Shifts any subsequent elements to the left (subtracts one from their indices).\r\n  * Returns the element that was removed from the list.\r\n  */\r\n public Item remove(int index) {\r\n     // TODO STUDENT: Implement remove method\r\n }\r\n\r\n /**\r\n  * Returns an iterator that iterates through the items in FIFO order.\r\n  * @return an iterator that iterates through the items in FIFO order.\r\n  */\r\n public Iterator<Item> iterator() {\r\n     return new ListIterator();\r\n }\r\n\r\n /**\r\n  * Implementation of an iterator that iterates through the items in FIFO order.\r\n  *\r\n  */\r\n private class ListIterator implements Iterator<Item> {\r\n     // TODO STUDDENT: Implement the ListIterator\r\n }\r\n\r\n}
\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -793,7 +793,7 @@ }, { "title": "Circular linkedlist (Implem)", - "description": "On s’intéresse à l'implémentation d'une\r\n`liste simplement chaînée circulaire`, c’est-à-dire une liste pour\r\nlaquelle la dernière position de la liste fait référence, comme position\r\nsuivante, à la première position de la liste.\r\n\r\n
\r\n\"\"\r\n
\r\n\r\nL’ajout d’un nouvel élément dans la file (méthode `enqueue`) se fait en\r\nfin de liste et le retrait (méthode `remove`) se fait a un index particulier de la liste. Une (seule)\r\nréférence sur la fin de la liste (`last`) est nécessaire pour effectuer\r\ntoutes les opérations sur cette file.\r\n\r\nIl vous est donc demander d'implémenter cette liste simplement chaînée\r\ncirculaire à partir de la classe `CircularLinkedList.java` où vous devez\r\ncompleter (*TODO STUDENT*):\r\n\r\n- la méthode d'ajout (`enqueue`);\r\n- la méthode de retrait (`remove`) \\[L'exception\r\n `IndexOutOfBoundsException` est lancée quand la valeur de l'index\r\n n'est pas comprise en 0 et size()-1\\];\r\n- l'itérateur (`ListIterator`) qui permet de parcourir la liste en\r\n FIFO.\r\n\r\n*Attention:* L'itérateur devra lancer des exceptions dans les cas\r\nsuivants:\r\n\r\n- étant donnée que le `remove` est optionnel dans\r\n l'[API](https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html)\r\n , l'iterateur devra juste lancer un `UnsupportedOperationException`\r\n en cas d'appel du `remove`;\r\n- étant donnée qu'on ne peut modifier l'itérateur alors qu'on est en\r\n train d'itérer, l'iterateur devra lancer un\r\n `ConcurrentModificationException` dans ce cas dans le `next` et le\r\n `hasNest`;\r\n- si le `next` est appelé alors qu'il n'y a plus de prochain élément,\r\n l'iterateur devra lancer un `NoSuchElementException`.\r\n\r\n\r\n\r\n``` java\r\nimport java.util.ConcurrentModificationException;\r\nimport java.util.Iterator;\r\nimport java.util.NoSuchElementException;\r\n\r\npublic class CircularLinkedList implements Iterable {\r\n private long nOp = 0; // count the number of operations\r\n private int n; // size of the stack\r\n private Node last; // trailer of the list\r\n\r\n // helper linked list class\r\n private class Node {\r\n private Item item;\r\n private Node next;\r\n }\r\n\r\n public CircularLinkedList() {\r\n last = null;\r\n n = 0;\r\n }\r\n\r\n public boolean isEmpty() { return n == 0; }\r\n\r\n public int size() { return n; }\r\n\r\n private long nOp() { return nOp; }\r\n\r\n /**\r\n * Append an item at the end of the list\r\n * @param item the item to append\r\n */\r\n public void enqueue(Item item) {\r\n // TODO STUDENT: Implement add method\r\n }\r\n\r\n /**\r\n * Removes the element at the specified position in this list.\r\n * Shifts any subsequent elements to the left (subtracts one from their indices).\r\n * Returns the element that was removed from the list.\r\n */\r\n public Item remove(int index) {\r\n // TODO STUDENT: Implement remove method\r\n }\r\n\r\n /**\r\n * Returns an iterator that iterates through the items in FIFO order.\r\n * @return an iterator that iterates through the items in FIFO order.\r\n */\r\n public Iterator iterator() {\r\n return new ListIterator();\r\n }\r\n\r\n /**\r\n * Implementation of an iterator that iterates through the items in FIFO order.\r\n *\r\n */\r\n private class ListIterator implements Iterator {\r\n // TODO STUDENT: Implement the ListIterator\r\n }\r\n\r\n}\r\n```\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part1CircularLinkedList/LSINF1121_PART1_CircularLinkedList.zip).\r\n", + "description": "

On s’intéresse à l'implémentation d'une liste simplement chaînée circulaire, c’est-à-dire une liste pour laquelle la dernière position de la liste fait référence, comme position suivante, à la première position de la liste.

\r\n
\r\n\"\"\r\n
\r\n

L’ajout d’un nouvel élément dans la file (méthode enqueue) se fait en fin de liste et le retrait (méthode remove) se fait a un index particulier de la liste. Une (seule) référence sur la fin de la liste (last) est nécessaire pour effectuer toutes les opérations sur cette file.

\r\n

Il vous est donc demander d'implémenter cette liste simplement chaînée circulaire à partir de la classe CircularLinkedList.java où vous devez completer (TODO STUDENT):

\r\n
    \r\n
  • la méthode d'ajout (enqueue);
  • \r\n
  • la méthode de retrait (remove) [L'exception IndexOutOfBoundsException est lancée quand la valeur de l'index n'est pas comprise en 0 et size()-1];
  • \r\n
  • l'itérateur (ListIterator) qui permet de parcourir la liste en FIFO.
  • \r\n
\r\n

Attention: L'itérateur devra lancer des exceptions dans les cas suivants:

\r\n
    \r\n
  • étant donnée que le remove est optionnel dans l'API , l'iterateur devra juste lancer un UnsupportedOperationException en cas d'appel du remove;
  • \r\n
  • étant donnée qu'on ne peut modifier l'itérateur alors qu'on est en train d'itérer, l'iterateur devra lancer un ConcurrentModificationException dans ce cas dans le next et le hasNest;
  • \r\n
  • si le next est appelé alors qu'il n'y a plus de prochain élément, l'iterateur devra lancer un NoSuchElementException.
  • \r\n
\r\n
import java.util.ConcurrentModificationException;\r\nimport java.util.Iterator;\r\nimport java.util.NoSuchElementException;\r\n\r\npublic class CircularLinkedList<Item> implements Iterable<Item> {\r\n private long nOp = 0; // count the number of operations\r\n private int n;          // size of the stack\r\n private Node  last;   // trailer of the list\r\n\r\n // helper linked list class\r\n private class Node {\r\n     private Item item;\r\n     private Node next;\r\n }\r\n\r\n public CircularLinkedList() {\r\n     last = null;\r\n     n = 0;\r\n }\r\n\r\n public boolean isEmpty() { return n == 0; }\r\n\r\n public int size() { return n; }\r\n\r\n private long nOp() { return nOp; }\r\n\r\n /**\r\n  * Append an item at the end of the list\r\n  * @param item the item to append\r\n  */\r\n public void enqueue(Item item) {\r\n     // TODO STUDENT: Implement add method\r\n }\r\n\r\n /**\r\n  * Removes the element at the specified position in this list.\r\n  * Shifts any subsequent elements to the left (subtracts one from their indices).\r\n  * Returns the element that was removed from the list.\r\n  */\r\n public Item remove(int index) {\r\n     // TODO STUDENT: Implement remove method\r\n }\r\n\r\n /**\r\n  * Returns an iterator that iterates through the items in FIFO order.\r\n  * @return an iterator that iterates through the items in FIFO order.\r\n  */\r\n public Iterator<Item> iterator() {\r\n     return new ListIterator();\r\n }\r\n\r\n /**\r\n  * Implementation of an iterator that iterates through the items in FIFO order.\r\n  *\r\n  */\r\n private class ListIterator implements Iterator<Item> {\r\n     // TODO STUDENT: Implement the ListIterator\r\n }\r\n\r\n}
\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -848,7 +848,7 @@ }, { "title": "Global Warming (implem)", - "description": "Context\r\n=======\r\n\r\nSupposons la matrice 5x5 suivante :\r\n\r\n``` java\r\nint [][] tab = new int[][] {{1,3,3,1,3},\r\n {4,2,2,4,5},\r\n {4,4,1,4,2},\r\n {1,4,2,3,6},\r\n {1,1,1,6,3}};\r\n```\r\n\r\nreprésentée dans le tableau ci-dessous :\r\n\r\n\"matrix\r\n\r\nChaque entrée de la matrice représente une altitude. L'objectif est\r\nd'implémenter une classe `GlobalWarmingImpl` qui étend la méthode GlobalWarming décrite ci-dessous.\r\n\r\nCompte tenu d'un niveau d'eau global, toutes les positions de la matrice\r\nayant une valeur *<=* au niveau d'eau sont inondées et donc peu\r\nsûres. Donc, en supposant que le niveau d'eau est de *3*, tous les\r\npoints sûrs sont en vert (dans la représentation ci-dessus).\r\n\r\nLa méthode que vous devez implémentez est `nbSafePoints`\r\n\r\n- le calcul du nombre de points de sécurité pour un niveau d'eau donné\r\n\r\n\r\n\r\n``` java\r\nimport java.util.List;\r\n\r\nabstract class GlobalWarming {\r\n\r\n\r\n final int[][] altitude;\r\n\r\n /**\r\n * @param altitude is a n x n matrix of int values representing altitudes (positive or negative)\r\n */\r\n public GlobalWarming(int[][] altitude) {\r\n this.altitude = altitude;\r\n }\r\n\r\n /**\r\n *\r\n * @param waterLevel\r\n * @return the number of entries in altitude matrix that would be above\r\n * the specified waterLevel.\r\n * Warning: this is not the waterLevel given in the constructor/\r\n */\r\n public abstract int nbSafePoints(int waterLevel);\r\n\r\n}\r\n```\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part2GlobalWarming/LSINF1121_PART2_GlobalWarming.zip).\r\n\r\nExercices préliminaires\r\n=======================\r\n\r\n``` java\r\nint [][] tab = new int[][] {{1,3,3,1,3},\r\n {4,2,2,4,5},\r\n {4,4,1,4,2},\r\n {1,4,2,3,6},\r\n {1,1,1,6,3}};\r\nGlobalWarming gw = new MyGlobalWarming(tab);\r\n```\r\n", + "description": "

Context

\r\n

Supposons la matrice 5x5 suivante :

\r\n
int [][] tab = new int[][] {{1,3,3,1,3},\r\n                          {4,2,2,4,5},\r\n                          {4,4,1,4,2},\r\n                          {1,4,2,3,6},\r\n                          {1,1,1,6,3}};
\r\n

représentée dans le tableau ci-dessous :

\r\n

\"matrix

\r\n

Chaque entrée de la matrice représente une altitude. L'objectif est d'implémenter une classe GlobalWarmingImpl qui étend la méthode GlobalWarming décrite ci-dessous.

\r\n

Compte tenu d'un niveau d'eau global, toutes les positions de la matrice ayant une valeur <= au niveau d'eau sont inondées et donc peu sûres. Donc, en supposant que le niveau d'eau est de 3, tous les points sûrs sont en vert (dans la représentation ci-dessus).

\r\n

La méthode que vous devez implémentez est nbSafePoints

\r\n
    \r\n
  • le calcul du nombre de points de sécurité pour un niveau d'eau donné
  • \r\n
\r\n
import java.util.List;\r\n\r\nabstract class GlobalWarming {\r\n\r\n\r\n    final int[][] altitude;\r\n\r\n    /**\r\n     * @param altitude is a n x n matrix of int values representing altitudes (positive or negative)\r\n     */\r\n    public GlobalWarming(int[][] altitude) {\r\n        this.altitude = altitude;\r\n    }\r\n\r\n    /**\r\n     *\r\n     * @param waterLevel\r\n     * @return the number of entries in altitude matrix that would be above\r\n     *         the specified waterLevel.\r\n     *         Warning: this is not the waterLevel given in the constructor/\r\n     */\r\n    public abstract int nbSafePoints(int waterLevel);\r\n\r\n}
\r\n

Le projet IntelliJ est disponible ici.

\r\n

Exercices préliminaires

\r\n
int [][] tab = new int[][] {{1,3,3,1,3},\r\n                          {4,2,2,4,5},\r\n                          {4,4,1,4,2},\r\n                          {1,4,2,3,6},\r\n                          {1,1,1,6,3}};\r\nGlobalWarming gw = new MyGlobalWarming(tab);
\r\n", "tags": [ { "text": "INGINIOUS", @@ -908,7 +908,7 @@ }, { "title": "Median (implem)", - "description": "Nous vous donnons l'API d'une classe Vector permettant d'accéder,\r\nmodifier et interchanger deux élements en temps constant. Votre tâche\r\nest d'implémenter une méthode permettant de calculer la médiane d'un\r\nVecteur.\r\n\r\n``` java\r\npublic interface Vector {\r\n // taille du vecteur\r\n public int size();\r\n // mets la valeur v à l'indice i du vecteur\r\n public void set(int i, int v);\r\n // renvoie la valeur à l'indice i du vecteur\r\n public int get(int i);\r\n // échange les valeurs aux positions i et j\r\n public void swap(int i, int j);\r\n\r\n}\r\n```\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part2Median/LSINF1121_PART2_Median.zip).\r\n", + "description": "

Nous vous donnons l'API d'une classe Vector permettant d'accéder, modifier et interchanger deux élements en temps constant. Votre tâche est d'implémenter une méthode permettant de calculer la médiane d'un Vecteur.

\r\n
public interface Vector {\r\n    // taille du vecteur\r\n    public int size();\r\n    // mets la valeur v à l'indice i du vecteur\r\n    public void set(int i, int v);\r\n    // renvoie la valeur à l'indice i du vecteur\r\n    public int get(int i);\r\n    // échange les valeurs aux positions i et j\r\n    public void swap(int i, int j);\r\n\r\n}
\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -958,7 +958,7 @@ }, { "title": "Merge Sort (implem)", - "description": "Considérons l'algorithme de tri (descendant) `Merge Sort`.\r\n\r\n``` java\r\npublic class MergeSort {\r\n /**\r\n * Pre-conditions: a[lo..mid] and a[mid+1..hi] are sorted\r\n * Post-conditions: a[lo..hi] is sorted\r\n */\r\n private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {\r\n for (int k = lo; k <= hi; k++) {\r\n aux[k] = a[k];\r\n }\r\n\r\n int i = lo;\r\n int j = mid + 1;\r\n for (int k = lo; k <= hi; k++) {\r\n if (i > mid) {\r\n a[k] = aux[j++];\r\n } else if (j > hi) {\r\n a[k] = aux[i++];\r\n } else if (aux[j].compareTo(aux[i]) < 0) {\r\n a[k] = aux[j++];\r\n } else {\r\n a[k] = aux[i++];\r\n }\r\n }\r\n }\r\n\r\n // Mergesort a[lo..hi] using auxiliary array aux[lo..hi]\r\n private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {\r\n // TODO\r\n }\r\n\r\n /**\r\n * Rearranges the array in ascending order, using the natural order\r\n */\r\n public static void sort(Comparable[] a) {\r\n // TODO\r\n }\r\n}\r\n```\r\n\r\n**Note:** Les questions suivantes vous demanderont d'implémenter la\r\nfonction left out. Vous n'avez pas besoin de mettre les accolades\r\n(`{ }`) entourant le corps de la fonction dans votre réponse.\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part2MergeSort/LSINF1121_PART2_MergeSort.zip).\r\n", + "description": "

Considérons l'algorithme de tri (descendant) Merge Sort.

\r\n
public class MergeSort {\r\n    /**\r\n     * Pre-conditions: a[lo..mid] and a[mid+1..hi] are sorted\r\n     * Post-conditions: a[lo..hi] is sorted\r\n     */\r\n    private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {\r\n        for (int k = lo; k <= hi; k++) {\r\n            aux[k] = a[k];\r\n        }\r\n\r\n        int i = lo;\r\n        int j = mid + 1;\r\n        for (int k = lo; k <= hi; k++) {\r\n            if (i > mid) {\r\n                a[k] = aux[j++];\r\n            } else if (j > hi) {\r\n                a[k] = aux[i++];\r\n            } else if (aux[j].compareTo(aux[i]) < 0) {\r\n                a[k] = aux[j++];\r\n            } else {\r\n                a[k] = aux[i++];\r\n            }\r\n        }\r\n    }\r\n\r\n    // Mergesort a[lo..hi] using auxiliary array aux[lo..hi]\r\n    private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {\r\n        // TODO\r\n    }\r\n\r\n    /**\r\n     * Rearranges the array in ascending order, using the natural order\r\n     */\r\n    public static void sort(Comparable[] a) {\r\n        // TODO\r\n    }\r\n}
\r\n

Note: Les questions suivantes vous demanderont d'implémenter la fonction left out. Vous n'avez pas besoin de mettre les accolades ({ }) entourant le corps de la fonction dans votre réponse.

\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1053,7 +1053,7 @@ }, { "title": "Union Intervals (implem)", - "description": "Etant donné un tableau d'intervalles (fermés), Il vous est demandé\r\nd'implémenter l'opération `union`. Cette opération retournera le tableau\r\nminimal d'intervalles triés couvrant exactement l'union des points\r\ncouverts par les intervalles d'entrée.\r\n\r\nPar exemple, l'union des intervalles *\\[7,9\\],\\[5,8\\],\\[2,4\\]* est\r\n*\\[2,4\\],\\[5,9\\]*.\r\n\r\nLa classe `Interval` permetant de stocker les intervalles vous est\r\nfourni et se présente comme suit (vous pouvez l'utiliser directement\r\ndans votre code):\r\n\r\n``` java\r\npublic class Interval implements Comparable {\r\n\r\n final int min, max;\r\n public Interval(int min, int max) {\r\n assert(min <= max);\r\n this.min = min;\r\n this.max = max;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n return ((Interval) obj).min == min && ((Interval) obj).max == max;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return \"[\"+min+\",\"+max+\"]\";\r\n }\r\n\r\n @Override\r\n public int compareTo(Interval o) {\r\n if (min < o.min) return -1;\r\n else if (min == o.min) return max - o.max;\r\n else return 1;\r\n }\r\n}\r\n```\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part2UnionIntervals/LSINF1121_PART2_UnionIntervals.zip).\r\n\r\nNous vous conseillons de le télécharger d'implémenter/tester avant de\r\nsoumettre ce qui vous est demandé.\r\n", + "description": "

Etant donné un tableau d'intervalles (fermés), Il vous est demandé d'implémenter l'opération union. Cette opération retournera le tableau minimal d'intervalles triés couvrant exactement l'union des points couverts par les intervalles d'entrée.

\r\n

Par exemple, l'union des intervalles [7,9],[5,8],[2,4] est [2,4],[5,9].

\r\n

La classe Interval permetant de stocker les intervalles vous est fourni et se présente comme suit (vous pouvez l'utiliser directement dans votre code):

\r\n
public class Interval implements Comparable<Interval> {\r\n\r\n    final int min, max;\r\n    public Interval(int min, int max) {\r\n        assert(min <= max);\r\n        this.min = min;\r\n        this.max = max;\r\n    }\r\n\r\n    @Override\r\n    public boolean equals(Object obj) {\r\n        return ((Interval) obj).min == min && ((Interval) obj).max == max;\r\n    }\r\n\r\n    @Override\r\n    public String toString() {\r\n        return "["+min+","+max+"]";\r\n    }\r\n\r\n    @Override\r\n    public int compareTo(Interval o) {\r\n        if (min < o.min) return -1;\r\n        else if (min == o.min) return max - o.max;\r\n        else return 1;\r\n    }\r\n}
\r\n

Le projet IntelliJ est disponible ici.

\r\n

Nous vous conseillons de le télécharger d'implémenter/tester avant de soumettre ce qui vous est demandé.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1103,7 +1103,7 @@ }, { "title": "Binary Search Tree (implem)", - "description": "Etant donné un arbre de recherche binaire, dont les noeuds implémentent\r\nl'interface Node:\r\n\r\n``` java\r\ninterface Node {\r\n /**\r\n * @return the value contained in this node\r\n */\r\n int getValue();\r\n\r\n /**\r\n * @return the node on the left (whose value is < than the current value)\r\n * if it exists, null if not\r\n */\r\n Node getLeft();\r\n\r\n /**\r\n * @return the node on the right (whose value is > than the current value)\r\n * if it exists, null if not\r\n */\r\n Node getRight();\r\n}\r\n```\r\n\r\nL'on vous demande de fournir le **corps** de la fonction *ceil*, qui\r\ntrouve dans l'arbre le plus petit élément plus grand ou égal à value (donc soit l'élément lui-même soit\r\nl'élément situé directement après par ordre de grandeur). Si un tel\r\nélément n'existe pas, elle doit retourner null.\r\n\r\nPar exemple si on a ce BST,\r\n\r\n
\r\n\"\"\r\n
\r\n\r\n- ceil(11) nous renverra 11,\r\n- ceil(4) nous renverra 8,\r\n- et ceil(21) nous renverra null.\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/PART3Bst/LSINF1121_PART3_BinarySearchTree.zip).\r\n", + "description": "

Etant donné un arbre de recherche binaire, dont les noeuds implémentent l'interface Node:

\r\n
interface Node {\r\n    /**\r\n      * @return the value contained in this node\r\n      */\r\n    int getValue();\r\n\r\n    /**\r\n     * @return the node on the left (whose value is < than the current value)\r\n     * if it exists, null if not\r\n     */\r\n    Node getLeft();\r\n\r\n    /**\r\n      * @return the node on the right (whose value is > than the current value)\r\n      * if it exists, null if not\r\n      */\r\n    Node getRight();\r\n}
\r\n

L'on vous demande de fournir le corps de la fonction ceil, qui trouve dans l'arbre le plus petit élément plus grand ou égal à value (donc soit l'élément lui-même soit l'élément situé directement après par ordre de grandeur). Si un tel élément n'existe pas, elle doit retourner null.

\r\n

Par exemple si on a ce BST,

\r\n
\r\n\"\"\r\n
\r\n
    \r\n
  • ceil(11) nous renverra 11,
  • \r\n
  • ceil(4) nous renverra 8,
  • \r\n
  • et ceil(21) nous renverra null.
  • \r\n
\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1163,7 +1163,7 @@ }, { "title": "Binary Search Tree Iterator (implem)", - "description": "On s’intéresse à l'implémentation d'un itérateur (`BSTIterator`) qui\r\npermet de traverser un `Binary Search Tree` dans l'ordre croissant\r\n(*In-order transversal*).\r\n\r\nPar exemple si on a ce BST,\r\n\r\n
\r\n\"\"\r\n
\r\n\r\non veut le parcourir comme suit *\\[3,8,9,11,12,14,15,18,20\\]*\r\n\r\n*Attention:* L'itérateur devra lancer des exceptions dans les cas\r\nsuivants:\r\n\r\n- étant donnée qu'on ne peut modifier l'itérateur alors qu'on est en\r\n train d'itérer, l'iterateur devra lancer un\r\n `ConcurrentModificationException` dans ce cas dans le `next` et le\r\n `hasNest`;\r\n- si le `next` est appelé alors qu'il n'y a plus de prochain élément,\r\n l'iterateur devra lancer un `NoSuchElementException`.\r\n\r\n\r\n\r\n``` java\r\nimport java.util.ConcurrentModificationException;\r\nimport java.util.Iterator;\r\nimport java.util.NoSuchElementException;\r\nimport java.util.Stack;\r\n\r\n public class BST, Value> implements Iterable {\r\n private Node root; // root of BST\r\n\r\n private class Node {\r\n private final Key key; // sorted by key\r\n private Value val; // associated data\r\n private Node left, right; // left and right subtrees\r\n private int size; // number of nodes in subtree\r\n\r\n public Node(Key key, Value val, int size) {\r\n this.key = key;\r\n this.val = val;\r\n this.size = size;\r\n }\r\n\r\n public int getSize() {\r\n return size;\r\n }\r\n }\r\n\r\n /**\r\n * Initializes an empty symbol table.\r\n */\r\n public BST() {}\r\n\r\n /**\r\n * Returns true if this symbol table is empty.\r\n * @return {@code true} if this symbol table is empty; {@code false} otherwise\r\n */\r\n public boolean isEmpty() {\r\n return size() == 0;\r\n }\r\n\r\n /**\r\n * Returns the number of key-value pairs in this symbol table.\r\n * @return the number of key-value pairs in this symbol table\r\n */\r\n public int size() {\r\n return size(root);\r\n }\r\n\r\n // return number of key-value pairs in BST rooted at x\r\n private int size(Node x) {\r\n if (x == null) return 0;\r\n else return x.size;\r\n }\r\n\r\n public void inOrder(){\r\n inOrder(root);\r\n }\r\n private void inOrder(Node x) {\r\n if (x == null) return;\r\n\r\n inOrder(x.left);\r\n System.out.println(x.key+\"=>\"+x.val);\r\n inOrder(x.right);\r\n }\r\n\r\n /**\r\n * Returns the value associated with the given key.\r\n *\r\n * @param key the key\r\n * @return the value associated with the given key if the key is in the symbol table\r\n * and {@code null} if the key is not in the symbol table\r\n */\r\n public Value get(Key key) {\r\n return get(root, key);\r\n }\r\n\r\n private Value get(Node x, Key key) {\r\n if (x == null) return null;\r\n int cmp = key.compareTo(x.key);\r\n if (cmp < 0) return get(x.left, key);\r\n else if (cmp > 0) return get(x.right, key);\r\n else return x.val;\r\n }\r\n\r\n /**\r\n * Search for key, update value if key is found. Grow table if key is new.\r\n *\r\n * @param key the key\r\n * @param val the value\r\n */\r\n public void put(Key key, Value val) {\r\n root = put(root, key, val);\r\n }\r\n private Node put(Node x, Key key, Value val) {\r\n if (x == null) return new Node(key, val, 1);\r\n int cmp = key.compareTo(x.key);\r\n if (cmp < 0) x.left = put(x.left, key, val);\r\n else if (cmp > 0) x.right = put(x.right, key, val);\r\n else x.val = val;\r\n x.size = 1 + size(x.left) + size(x.right);\r\n return x;\r\n }\r\n\r\n /**\r\n * Returns an iterator that iterates through the keys in Incresing order\r\n * (In-Order transversal).\r\n * @return an iterator that iterates through the items in FIFO order.\r\n */\r\n @Override\r\n public Iterator iterator() {\r\n return new BSTIterator();\r\n }\r\n\r\n /**\r\n * Implementation of an iterator that iterates through the keys of BST in incresing order (In-order transversal).\r\n *\r\n */\r\n private class BSTIterator implements Iterator {\r\n\r\n // TODO STUDDENT: Implement the BSTIterator\r\n\r\n }\r\n}\r\n```\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/PART3OrderedBstIterator/LSINF1121_PART3_OrderedBstIterator.zip).\r\n", + "description": "

On s’intéresse à l'implémentation d'un itérateur (BSTIterator) qui permet de traverser un Binary Search Tree dans l'ordre croissant (In-order transversal).

\r\n

Par exemple si on a ce BST,

\r\n
\r\n\"\"\r\n
\r\n

on veut le parcourir comme suit [3,8,9,11,12,14,15,18,20]

\r\n

Attention: L'itérateur devra lancer des exceptions dans les cas suivants:

\r\n
    \r\n
  • étant donnée qu'on ne peut modifier l'itérateur alors qu'on est en train d'itérer, l'iterateur devra lancer un ConcurrentModificationException dans ce cas dans le next et le hasNest;
  • \r\n
  • si le next est appelé alors qu'il n'y a plus de prochain élément, l'iterateur devra lancer un NoSuchElementException.
  • \r\n
\r\n
import java.util.ConcurrentModificationException;\r\nimport java.util.Iterator;\r\nimport java.util.NoSuchElementException;\r\nimport java.util.Stack;\r\n\r\n   public class BST<Key extends Comparable<Key>, Value> implements Iterable<Key> {\r\n    private Node root;             // root of BST\r\n\r\n    private class Node {\r\n        private final Key key;       // sorted by key\r\n        private Value val;           // associated data\r\n        private Node left, right;    // left and right subtrees\r\n        private int size;            // number of nodes in subtree\r\n\r\n        public Node(Key key, Value val, int size) {\r\n            this.key = key;\r\n            this.val = val;\r\n            this.size = size;\r\n        }\r\n\r\n        public int getSize() {\r\n            return size;\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Initializes an empty symbol table.\r\n     */\r\n    public BST() {}\r\n\r\n    /**\r\n     * Returns true if this symbol table is empty.\r\n     * @return {@code true} if this symbol table is empty; {@code false} otherwise\r\n     */\r\n    public boolean isEmpty() {\r\n        return size() == 0;\r\n    }\r\n\r\n    /**\r\n     * Returns the number of key-value pairs in this symbol table.\r\n     * @return the number of key-value pairs in this symbol table\r\n     */\r\n    public int size() {\r\n        return size(root);\r\n    }\r\n\r\n    // return number of key-value pairs in BST rooted at x\r\n    private int size(Node x) {\r\n        if (x == null) return 0;\r\n        else return x.size;\r\n    }\r\n\r\n    public void inOrder(){\r\n        inOrder(root);\r\n    }\r\n    private void inOrder(Node x) {\r\n        if (x == null) return;\r\n\r\n        inOrder(x.left);\r\n        System.out.println(x.key+"=>"+x.val);\r\n        inOrder(x.right);\r\n    }\r\n\r\n    /**\r\n     * Returns the value associated with the given key.\r\n     *\r\n     * @param  key the key\r\n     * @return the value associated with the given key if the key is in the symbol table\r\n     *         and {@code null} if the key is not in the symbol table\r\n     */\r\n    public Value get(Key key) {\r\n        return get(root, key);\r\n    }\r\n\r\n    private Value get(Node x, Key key) {\r\n        if (x == null) return null;\r\n        int cmp = key.compareTo(x.key);\r\n        if      (cmp < 0) return get(x.left, key);\r\n        else if (cmp > 0) return get(x.right, key);\r\n        else              return x.val;\r\n    }\r\n\r\n    /**\r\n     * Search for key, update value if key is found. Grow table if key is new.\r\n     *\r\n     * @param  key the key\r\n     * @param  val the value\r\n     */\r\n    public void put(Key key, Value val) {\r\n        root = put(root, key, val);\r\n    }\r\n    private Node put(Node x, Key key, Value val) {\r\n        if (x == null) return new Node(key, val, 1);\r\n        int cmp = key.compareTo(x.key);\r\n        if      (cmp < 0) x.left  = put(x.left,  key, val);\r\n        else if (cmp > 0) x.right = put(x.right, key, val);\r\n        else              x.val   = val;\r\n        x.size = 1 + size(x.left) + size(x.right);\r\n        return x;\r\n    }\r\n\r\n    /**\r\n     * Returns an iterator that iterates through the keys in Incresing order\r\n     * (In-Order transversal).\r\n     * @return an iterator that iterates through the items in FIFO order.\r\n     */\r\n    @Override\r\n    public Iterator<Key> iterator() {\r\n        return new BSTIterator();\r\n    }\r\n\r\n        /**\r\n  * Implementation of an iterator that iterates through the keys of BST in incresing order (In-order transversal).\r\n  *\r\n  */\r\n    private class BSTIterator implements Iterator<Key> {\r\n\r\n        // TODO STUDDENT: Implement the BSTIterator\r\n\r\n    }\r\n}
\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1258,7 +1258,7 @@ }, { "title": "QCM Binary Trees", - "description": "Consider this ordered binary tree:\r\n\r\n
\r\n\"\"\r\n
\r\n\r\nWe traverse this tree and we print the value of each node we visit it.\r\n", + "description": "

Consider this ordered binary tree:

\r\n
\r\n\"\"\r\n
\r\n

We traverse this tree and we print the value of each node we visit it.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1308,7 +1308,7 @@ }, { "title": "Red Black Tree", - "description": "Prenons l'exemple d'un `Red-Black Tree` vide dans lequel on ajoute\r\nprogressivement des chiffres.\r\n\r\nLes questions suivantes vous demanderont d'écrire une représentation du\r\n`Red-Black Tree` au fur et à mesure que nous y ajouterons des objets.\r\n\r\nÉcrivez la réponse comme si vous lisiez le `Red-Black Tree` de gauche à\r\ndroite et de haut en bas (en ignorant les blancs possibles). Par\r\nexemple, si votre réponse est :\r\n\r\n
\r\n\"\"\r\n
\r\n\r\nVous écririez:\r\n\r\n 6 24 7 1 3 5 9\r\n\r\nRemarquez comment le nœud 2-3 composé de `2`et `4` est écrit d'une\r\nmanière fusionnée (`24`).\r\n", + "description": "

Prenons l'exemple d'un Red-Black Tree vide dans lequel on ajoute progressivement des chiffres.

\r\n

Les questions suivantes vous demanderont d'écrire une représentation du Red-Black Tree au fur et à mesure que nous y ajouterons des objets.

\r\n

Écrivez la réponse comme si vous lisiez le Red-Black Tree de gauche à droite et de haut en bas (en ignorant les blancs possibles). Par exemple, si votre réponse est :

\r\n
\r\n\"\"\r\n
\r\n

Vous écririez:

\r\n
6 24 7 1 3 5 9
\r\n

Remarquez comment le nœud 2-3 composé de 2et 4 est écrit d'une manière fusionnée (24).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1358,7 +1358,7 @@ }, { "title": "Write Unit tests Red Black Tree", - "description": "Il vous est demandé d'écrire des tests unitaire (en utilisant JUnit)\r\nafin de vérifier si une implémentation particulière d'un\r\n`Red-Black Tree` est correcte.\r\n\r\nVoici un modèle simple que vous pouvez utiliser pour écrire vos tests :\r\n\r\n> ``` java\r\n> import org.junit.Test;\r\n> import static org.junit.Assert.assertEquals;\r\n>\r\n> public class RedBlackTests {\r\n>\r\n> @Test\r\n> public void firstTest() {\r\n> // ... TODO ...\r\n> }\r\n>\r\n> @Test\r\n> public void secondTest() {\r\n> // ... TODO ...\r\n> }\r\n>\r\n> }\r\n> ```\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/PART3WriteUnittestsRedBlackTree/LSINF1121_PART3_UnitTestsRedBlackTree.zip).\r\n", + "description": "

Il vous est demandé d'écrire des tests unitaire (en utilisant JUnit) afin de vérifier si une implémentation particulière d'un Red-Black Tree est correcte.

\r\n

Voici un modèle simple que vous pouvez utiliser pour écrire vos tests :

\r\n
\r\n
import org.junit.Test;\r\nimport static org.junit.Assert.assertEquals;\r\n\r\npublic class RedBlackTests {\r\n\r\n    @Test\r\n    public void firstTest() {\r\n        // ... TODO ...\r\n    }\r\n\r\n    @Test\r\n    public void secondTest() {\r\n        // ... TODO ...\r\n    }\r\n\r\n}
\r\n
\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1403,7 +1403,7 @@ }, { "title": "Incremental Hash (implem)", - "description": "La fonction de Hash calculée sur le sous tableau\r\n*t*\\[*f**r**o**m*, ..., *f**r**o**m* + *M* − 1\\] est calculée comme\r\nsuit:\r\n\r\n$hash(\\[from,...,from+M-1\\])= \\\\left( \\\\sum\\_{i=0}^{M-1} t\\[from+i\\] \\\\cdot R^{(M-1-i)}\\\\right)\\\\%Q$\r\n\r\nLe code pour calculer cette fonction de hash vous est donné. Nous vous\r\ndemandons de calculer\r\n*h**a**s**h*(\\[*f**r**o**m*, ..., *f**r**o**m* + *M* − 1\\]) au départ de\r\n*h**a**s**h*(\\[*f**r**o**m* − 1, ..., *f**r**o**m* + *M* − 2\\]) en O(1).\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part4IncrementalHash/LSINF1121_PART4_IncrementalHash.zip).\r\n", + "description": "

La fonction de Hash calculée sur le sous tableau t[from, ..., from + M − 1] est calculée comme suit:

\r\n

$hash([from,...,from+M-1])= \\left( \\sum_{i=0}^{M-1} t[from+i] \\cdot R^{(M-1-i)}\\right)\\%Q$

\r\n

Le code pour calculer cette fonction de hash vous est donné. Nous vous demandons de calculer hash([from, ..., from + M − 1]) au départ de hash([from − 1, ..., from + M − 2]) en O(1).

\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1453,7 +1453,7 @@ }, { "title": "QCM Hashing", - "description": "Etant donné une fonction de hachage:\r\n\r\n$h(\\\\left\\[v\\_0 \\\\cdots v\\_{n-1} \\\\right\\]) = \\\\sum\\\\limits\\_{i=0}^{n-1} v\\_i R^{(n-i-1)} \\\\% M$\r\n\r\ndans laquelle \\[*v*0⋯*v**n* − 1\\] dénote un\r\nvecteur de bit et *R* et *M* sont des facteurs constants.\r\n", + "description": "

Etant donné une fonction de hachage:

\r\n

$h(\\left[v_0 \\cdots v_{n-1} \\right]) = \\sum\\limits_{i=0}^{n-1} v_i R^{(n-i-1)} \\% M$

\r\n

dans laquelle [v0vn − 1] dénote un vecteur de bit et R et M sont des facteurs constants.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1503,7 +1503,7 @@ }, { "title": "QCM Rabin Karp", - "description": "A la page 777 du livre \"Algorithms\" 4th edition, on vous propose\r\nl'implémentation suivante de l'algorithme de Rabin Karp.\r\n\r\n``` java\r\npublic class RabinKarp {\r\n private String pat; // the pattern // needed only for Las Vegas\r\n private long patHash; // pattern hash value\r\n private int m; // pattern length\r\n private long q; // a large prime, small enough to avoid long overflow\r\n private int R; // radix\r\n private long RM; // R^(M-1) % Q\r\n\r\n public RabinKarp(String pat) {\r\n this.pat = pat; // save pattern (needed only for Las Vegas)\r\n R = 256;\r\n m = pat.length();\r\n q = longRandomPrime();\r\n\r\n // precompute R^(m-1) % q for use in removing leading digit\r\n RM = 1;\r\n for (int i = 1; i <= m-1; i++)\r\n RM = (R * RM) % q;\r\n patHash = hash(pat, m);\r\n }\r\n\r\n // Compute hash for key[0..m-1].\r\n private long hash(String key, int m) {\r\n long h = 0;\r\n for (int j = 0; j < m; j++)\r\n h = (R * h + key.charAt(j)) % q;\r\n return h;\r\n }\r\n\r\n // Monte Carlo\r\n private boolean check(int i) {\r\n return true;\r\n }\r\n\r\n // Returns the index of the first occurrrence of the pattern string in the text string.\r\n public int search(String txt) {\r\n int n = txt.length();\r\n if (n < m) return n;\r\n long txtHash = hash(txt, m);\r\n\r\n // check for match at offset 0\r\n if ((patHash == txtHash) && check(txt, 0))\r\n return 0;\r\n\r\n // check for hash match; if hash match, check for exact match\r\n for (int i = m; i < n; i++) {\r\n // Remove leading digit, add trailing digit, check for match.\r\n txtHash = (txtHash + q - RM*txt.charAt(i-m) % q) % q;\r\n txtHash = (txtHash*R + txt.charAt(i)) % q;\r\n\r\n // match\r\n int offset = i - m + 1;\r\n if ((patHash == txtHash) && check(txt, offset))\r\n return offset;\r\n }\r\n\r\n // no match\r\n return n;\r\n }\r\n\r\n\r\n // a random 31-bit prime\r\n private static long longRandomPrime() {\r\n BigInteger prime = BigInteger.probablePrime(31, new Random());\r\n return prime.longValue();\r\n }\r\n\r\n}\r\n```\r\n", + "description": "

A la page 777 du livre \"Algorithms\" 4th edition, on vous propose l'implémentation suivante de l'algorithme de Rabin Karp.

\r\n
public class RabinKarp {\r\n  private String pat;      // the pattern  // needed only for Las Vegas\r\n  private long patHash;    // pattern hash value\r\n  private int m;           // pattern length\r\n  private long q;          // a large prime, small enough to avoid long overflow\r\n  private int R;           // radix\r\n  private long RM;         // R^(M-1) % Q\r\n\r\n  public RabinKarp(String pat) {\r\n      this.pat = pat;      // save pattern (needed only for Las Vegas)\r\n      R = 256;\r\n      m = pat.length();\r\n      q = longRandomPrime();\r\n\r\n      // precompute R^(m-1) % q for use in removing leading digit\r\n      RM = 1;\r\n      for (int i = 1; i <= m-1; i++)\r\n          RM = (R * RM) % q;\r\n      patHash = hash(pat, m);\r\n  }\r\n\r\n  // Compute hash for key[0..m-1].\r\n  private long hash(String key, int m) {\r\n      long h = 0;\r\n      for (int j = 0; j < m; j++)\r\n          h = (R * h + key.charAt(j)) % q;\r\n      return h;\r\n  }\r\n\r\n  // Monte Carlo\r\n  private boolean check(int i) {\r\n      return true;\r\n  }\r\n\r\n  // Returns the index of the first occurrrence of the pattern string in the text string.\r\n  public int search(String txt) {\r\n      int n = txt.length();\r\n      if (n < m) return n;\r\n      long txtHash = hash(txt, m);\r\n\r\n      // check for match at offset 0\r\n      if ((patHash == txtHash) && check(txt, 0))\r\n          return 0;\r\n\r\n      // check for hash match; if hash match, check for exact match\r\n      for (int i = m; i < n; i++) {\r\n          // Remove leading digit, add trailing digit, check for match.\r\n          txtHash = (txtHash + q - RM*txt.charAt(i-m) % q) % q;\r\n          txtHash = (txtHash*R + txt.charAt(i)) % q;\r\n\r\n          // match\r\n          int offset = i - m + 1;\r\n          if ((patHash == txtHash) && check(txt, offset))\r\n              return offset;\r\n      }\r\n\r\n      // no match\r\n      return n;\r\n  }\r\n\r\n\r\n  // a random 31-bit prime\r\n  private static long longRandomPrime() {\r\n      BigInteger prime = BigInteger.probablePrime(31, new Random());\r\n      return prime.longValue();\r\n  }\r\n\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1553,7 +1553,7 @@ }, { "title": "Rabin Karp of k patterns (implem)", - "description": "On s'intéresse à l'algorithme de Rabin-Karp. On voudrait le modifier\r\nquelque peu pour déterminer si un mot parmi une liste (tous les mots\r\nsont de même longueur) est présent dans le texte.\r\n\r\nPour cela, vous devez modifier l'algorithme de Rabin-Karp qui se trouve\r\nci-dessous (Page 777 du livre).\r\n\r\nPlus précisément, on vous demande de modifier cette classe de manière à\r\navoir un constructeur de la forme:\r\n\r\n``` java\r\npublic RabinKarp(String[] pat)\r\n```\r\n\r\nDe plus la fonction `search` doit retourner l'indice du début du premier\r\nmot (parmi le tableau `pat`) trouvé dans le texte ou la taille du texte\r\nsi aucun mot n'aparait dans le texte.\r\n\r\nExemple: Si txt = “Here find interresting exercise for Rabin Karp” et\r\npat={“have”, “find”, “Karp”} la fonction `search` doit renvoyer 5 car le\r\nmot \"find\" présent dans le texte et dans la liste commence à l'indice 5.\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part4RabinKarp/LSINF1121_PART4_RabinKarp.zip).\r\n", + "description": "

On s'intéresse à l'algorithme de Rabin-Karp. On voudrait le modifier quelque peu pour déterminer si un mot parmi une liste (tous les mots sont de même longueur) est présent dans le texte.

\r\n

Pour cela, vous devez modifier l'algorithme de Rabin-Karp qui se trouve ci-dessous (Page 777 du livre).

\r\n

Plus précisément, on vous demande de modifier cette classe de manière à avoir un constructeur de la forme:

\r\n
public RabinKarp(String[] pat)
\r\n

De plus la fonction search doit retourner l'indice du début du premier mot (parmi le tableau pat) trouvé dans le texte ou la taille du texte si aucun mot n'aparait dans le texte.

\r\n

Exemple: Si txt = “Here find interresting exercise for Rabin Karp” et pat={“have”, “find”, “Karp”} la fonction search doit renvoyer 5 car le mot \"find\" présent dans le texte et dans la liste commence à l'indice 5.

\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1598,7 +1598,7 @@ }, { "title": "Binary Heap Push (implem)", - "description": "Dans cette tâche on vous propose d'implémenter la fonction d'insertion\r\n`push()` d'un heap binaire.\r\n\r\n> La fonction push agit sur un tableau, nommé `contenu`, qui représente\r\n> un arbre, selon la méthode vue au cours: le noeud n°i de l'arbre a\r\n> pour enfant les indices 2\\*i et 2\\*i+1.\r\n\r\nil faut noter que dans le livre à la page 318 a été proposée le `MaxPQ`\r\nmais ici nous vous proposons de plutot réfléchir aux changements à\r\napporter à ce code pour implémenter un `MinPQ` notamment à la fonction\r\nd'insertion.\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/PART5BinaryHeapPush/LSINF1121_PART5_BinaryHeapPush.zip).\r\n", + "description": "

Dans cette tâche on vous propose d'implémenter la fonction d'insertion push() d'un heap binaire.

\r\n
\r\n

La fonction push agit sur un tableau, nommé contenu, qui représente un arbre, selon la méthode vue au cours: le noeud n°i de l'arbre a pour enfant les indices 2*i et 2*i+1.

\r\n
\r\n

il faut noter que dans le livre à la page 318 a été proposée le MaxPQ mais ici nous vous proposons de plutot réfléchir aux changements à apporter à ce code pour implémenter un MinPQ notamment à la fonction d'insertion.

\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1648,7 +1648,7 @@ }, { "title": "Global Warming (implem)", - "description": "Context\r\n=======\r\n\r\nSupposons la matrice 5x5 suivante:\r\n\r\n``` java\r\nint [][] tab = new int[][] {{1,3,3,1,3},\r\n {4,2,2,4,5},\r\n {4,4,1,4,2},\r\n {1,4,2,3,6},\r\n {1,1,1,6,3}};\r\n```\r\n\r\nreprésentée dans le tableau ci-dessous :\r\n\r\n\"matrix\r\n\r\nChaque entrée de la matrice représente une altitude. L'objectif est\r\nd'implémenter une classe GlobalWarmingImpl qui implémente toutes les\r\nméthodes décrites dans GlobalWarming\r\ndonnées ci-dessous.\r\n\r\nUn niveau d'eau global spécifié dans le constructeur modélise le fait\r\nque toutes les positions de la matrice avec une valeur <= le niveau\r\nd'eau sont inondées (sous l'eau) et donc dangereuses. Dans l'exemple\r\nci-dessus, le niveau d'eau est de 3, tous les points sûrs sont en vert.\r\n\r\nLes méthodes que vous devez implémenter sont les suivantes\r\n\r\n- le nombre d'îles\r\n- un test pour vérifier si deux positions sont sur la même île\r\n\r\nnous supposons que les points sont **uniquement connectés verticalement\r\nou horizontalement**.\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part5GlobalWarming/LSINF1121_PART5_GlobalWarming.zip).\r\n\r\n``` java\r\nimport java.util.List;\r\n\r\nabstract class GlobalWarming {\r\n\r\n /**\r\n * A class to represent the coordinates on the altitude matrix\r\n */\r\n public static class Point {\r\n\r\n final int x, y;\r\n\r\n Point(int x, int y) {\r\n this.x = x;\r\n this.y = y;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n Point p = (Point) obj;\r\n return p.x == x && p.y == y;\r\n }\r\n }\r\n\r\n final int[][] altitude;\r\n final int waterLevel;\r\n\r\n\r\n /**\r\n * In the following, we assume that the points are connected to\r\n * horizontal or vertical neighbors but not to the diagonal ones\r\n * @param altitude is a n x n matrix of int values representing altitudes (positive or negative)\r\n * @param waterLevel is the water level, every entry <= waterLevel is flooded\r\n */\r\n public GlobalWarming(int[][] altitude, int waterLevel) {\r\n this.altitude = altitude;\r\n this.waterLevel = waterLevel;\r\n }\r\n\r\n\r\n /**\r\n * An island is a connected components of safe points wrt to waterLevel\r\n * @return the number of islands\r\n */\r\n public abstract int nbIslands();\r\n\r\n /**\r\n *\r\n * @param p1 a point with valid coordinates on altitude matrix\r\n * @param p2 a point with valid coordinates on altitude matrix\r\n * @return true if p1 and p2 are on the same island, that is both p1 and p2 are safe wrt waterLevel\r\n * and there exists a path (vertical/horizontal moves) from p1 to p2 using only safe positions\r\n */\r\n public abstract boolean onSameIsland(Point p1, Point p2);\r\n\r\n\r\n}\r\n```\r\n\r\nPreliminary exercises\r\n=====================\r\n\r\n``` java\r\nint [][] tab = new int[][] {{1,3,3,1,3},\r\n {4,2,2,4,5},\r\n {4,4,1,4,2},\r\n {1,4,2,3,6},\r\n {1,1,1,6,3}};\r\nGlobalWarming gw = new MyGlobalWarming(tab,3);\r\n```\r\n\r\n\"matrix\r\n", + "description": "

Context

\r\n

Supposons la matrice 5x5 suivante:

\r\n
int [][] tab = new int[][] {{1,3,3,1,3},\r\n                          {4,2,2,4,5},\r\n                          {4,4,1,4,2},\r\n                          {1,4,2,3,6},\r\n                          {1,1,1,6,3}};
\r\n

représentée dans le tableau ci-dessous :

\r\n

\"matrix

\r\n

Chaque entrée de la matrice représente une altitude. L'objectif est d'implémenter une classe GlobalWarmingImpl qui implémente toutes les méthodes décrites dans GlobalWarming données ci-dessous.

\r\n

Un niveau d'eau global spécifié dans le constructeur modélise le fait que toutes les positions de la matrice avec une valeur <= le niveau d'eau sont inondées (sous l'eau) et donc dangereuses. Dans l'exemple ci-dessus, le niveau d'eau est de 3, tous les points sûrs sont en vert.

\r\n

Les méthodes que vous devez implémenter sont les suivantes

\r\n
    \r\n
  • le nombre d'îles
  • \r\n
  • un test pour vérifier si deux positions sont sur la même île
  • \r\n
\r\n

nous supposons que les points sont uniquement connectés verticalement ou horizontalement.

\r\n

Le projet IntelliJ est disponible ici.

\r\n
import java.util.List;\r\n\r\nabstract class GlobalWarming {\r\n\r\n    /**\r\n     * A class to represent the coordinates on the altitude matrix\r\n     */\r\n    public static class Point {\r\n\r\n        final int x, y;\r\n\r\n        Point(int x, int y) {\r\n            this.x = x;\r\n            this.y = y;\r\n        }\r\n\r\n        @Override\r\n        public boolean equals(Object obj) {\r\n            Point p = (Point) obj;\r\n            return p.x == x && p.y == y;\r\n        }\r\n    }\r\n\r\n    final int[][] altitude;\r\n    final int waterLevel;\r\n\r\n\r\n    /**\r\n     * In the following, we assume that the points are connected to\r\n     * horizontal or vertical neighbors but not to the diagonal ones\r\n     * @param altitude is a n x n matrix of int values representing altitudes (positive or negative)\r\n     * @param waterLevel is the water level, every entry <= waterLevel is flooded\r\n     */\r\n    public GlobalWarming(int[][] altitude, int waterLevel) {\r\n        this.altitude = altitude;\r\n        this.waterLevel = waterLevel;\r\n    }\r\n\r\n\r\n    /**\r\n     * An island is a connected components of safe points wrt to waterLevel\r\n     * @return the number of islands\r\n     */\r\n    public abstract int nbIslands();\r\n\r\n    /**\r\n     *\r\n     * @param p1 a point with valid coordinates on altitude matrix\r\n     * @param p2 a point with valid coordinates on altitude matrix\r\n     * @return true if p1 and p2 are on the same island, that is both p1 and p2 are safe wrt waterLevel\r\n     *        and there exists a path (vertical/horizontal moves) from p1 to p2 using only safe positions\r\n     */\r\n    public abstract boolean onSameIsland(Point p1, Point p2);\r\n\r\n\r\n}
\r\n

Preliminary exercises

\r\n
int [][] tab = new int[][] {{1,3,3,1,3},\r\n                          {4,2,2,4,5},\r\n                          {4,4,1,4,2},\r\n                          {1,4,2,3,6},\r\n                          {1,1,1,6,3}};\r\nGlobalWarming gw = new MyGlobalWarming(tab,3);
\r\n

\"matrix

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1698,7 +1698,7 @@ }, { "title": "Heap", - "description": "Considérons la structure de données `Heap` dans laquelle on ajoute\r\nprogressivement des nombres.\r\n\r\nLes questions suivantes vous demanderont d'écrire une représentation du\r\n`Heap` au fur et à mesure que nous y ajoutons des objets. Vous devez\r\nécrire le `Heap` comme s'il était stocké dans un tableau. Par exemple,\r\nsi votre réponse est :\r\n\r\n 9\r\n / \\\r\n 5 8\r\n / \\\r\n 4 3\r\n\r\nVous devriez écrire:\r\n\r\n 9 5 8 4 3\r\n", + "description": "

Considérons la structure de données Heap dans laquelle on ajoute progressivement des nombres.

\r\n

Les questions suivantes vous demanderont d'écrire une représentation du Heap au fur et à mesure que nous y ajoutons des objets. Vous devez écrire le Heap comme s'il était stocké dans un tableau. Par exemple, si votre réponse est :

\r\n
9\r\n/ \\\r\n5   8\r\n/ \\\r\n4   3
\r\n

Vous devriez écrire:

\r\n
9 5 8 4 3
\r\n", "tags": [ { "text": "INGINIOUS", @@ -1743,7 +1743,7 @@ }, { "title": "Huffman (implem)", - "description": "Vous devez calculer un arbre de Huffman au départ de la fréquence donnée\r\npour chacune des R lettres (characters).\r\n\r\nPour rappel, dans un arbre de Huffman nous avons que *la somme de la\r\nfréquence associée à chaque feuille multipliée par la profondeur de\r\ncelle-ci est minimale*.\r\n\r\nPar exemple, étant donné les fréquences suivantes:\r\n\r\n\"Input\r\n\r\nun arbre de Huffman pourrait être:\r\n\r\n\"Huffman\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part5Huffman/LSINF1121_PART5_Huffman.zip).\r\n", + "description": "

Vous devez calculer un arbre de Huffman au départ de la fréquence donnée pour chacune des R lettres (characters).

\r\n

Pour rappel, dans un arbre de Huffman nous avons que la somme de la fréquence associée à chaque feuille multipliée par la profondeur de celle-ci est minimale.

\r\n

Par exemple, étant donné les fréquences suivantes:

\r\n

\"Input

\r\n

un arbre de Huffman pourrait être:

\r\n

\"Huffman

\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1788,7 +1788,7 @@ }, { "title": "Union find", - "description": "Considérons un graphe composé de 10 nœuds disjoints (numérotés de 0 à\r\n9). Nous utilisons une structure de données union-find pour représenter\r\nce graphe. Dans un premier temps, chaque nœud est contenu dans une\r\npartition qui porte son nom. Ainsi, la représentation du graphique dans\r\nle tableau `id[]` est :\r\n\r\n 0 1 2 3 4 5 6 7 8 9\r\n\r\nLes questions suivantes vous demanderont de donner la représentation du\r\ngraphe après avoir utilisé l'algorithme **quick-find** pour ajouter une\r\narête entre 2 noeuds. Vous devez donner cette représentation de la même\r\nmanière qu'elle a été donnée ci-dessus.\r\n\r\n**Note:** Lorsque nous joignons `p-q` avec l'algorithme quick-find, la\r\nconvention est de changer `id[p]` (et éventuellement d'autres entrées)\r\nmais pas `id[q]`.\r\n", + "description": "

Considérons un graphe composé de 10 nœuds disjoints (numérotés de 0 à 9). Nous utilisons une structure de données union-find pour représenter ce graphe. Dans un premier temps, chaque nœud est contenu dans une partition qui porte son nom. Ainsi, la représentation du graphique dans le tableau id[] est :

\r\n
0 1 2 3 4 5 6 7 8 9
\r\n

Les questions suivantes vous demanderont de donner la représentation du graphe après avoir utilisé l'algorithme quick-find pour ajouter une arête entre 2 noeuds. Vous devez donner cette représentation de la même manière qu'elle a été donnée ci-dessus.

\r\n

Note: Lorsque nous joignons p-q avec l'algorithme quick-find, la convention est de changer id[p] (et éventuellement d'autres entrées) mais pas id[q].

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1833,7 +1833,7 @@ }, { "title": "PART 6 - Breadth First Paths (implem)", - "description": "Considérez cette classe, `BreadthFirstShortestPaths`, qui calcule le\r\nchemin le plus court entre plusieurs sources de nœuds et n'importe quel\r\nnœud dans un graphe non dirigé en utilisant un parcours BFS.\r\n\r\n``` java\r\n// TODO\r\n\r\npublic class BreadthFirstShortestPaths {\r\n\r\n private static final int INFINITY = Integer.MAX_VALUE;\r\n private boolean[] marked; // marked[v] = is there an s-v path\r\n private int[] distTo; // distTo[v] = number of edges shortest s-v path\r\n\r\n /**\r\n * Computes the shortest path between any\r\n * one of the sources and very other vertex\r\n * @param G the graph\r\n * @param sources the source vertices\r\n */\r\n public BreadthFirstShortestPaths(Graph G, Iterable sources) {\r\n marked = new boolean[G.V()];\r\n distTo = new int[G.V()];\r\n for (int v = 0;v < G.V();v++) {\r\n distTo[v] = INFINITY;\r\n }\r\n bfs(G, sources);\r\n }\r\n\r\n // Breadth-first search from multiple sources\r\n private void bfs(Graph G, Iterable sources) {\r\n // TODO\r\n }\r\n\r\n /**\r\n * Is there a path between (at least one of) the sources and vertex v?\r\n * @param v the vertex\r\n * @return true if there is a path, and false otherwise\r\n */\r\n public boolean hasPathTo(int v) {\r\n // TODO\r\n }\r\n\r\n /**\r\n * Returns the number of edges in a shortest path\r\n * between one of the sources and vertex v?\r\n * @param v the vertex\r\n * @return the number of edges in a shortest path\r\n */\r\n public int distTo(int v) {\r\n // TODO\r\n }\r\n}\r\n```\r\n\r\nLa classe `Graph` est déjà implémentée et la voici :\r\n\r\n``` java\r\npublic class Graph {\r\n // @return the number of vertices\r\n public int V() { }\r\n\r\n // @return the number of edges\r\n public int E() { }\r\n\r\n // Add edge v-w to this graph\r\n public void addEdge(int v, int w) { }\r\n\r\n // @return the vertices adjacent to v\r\n public Iterable adj(int v) { }\r\n\r\n // @return a string representation\r\n public String toString() { }\r\n}\r\n```\r\n\r\n**Note:** Les questions suivantes vous demanderont d'implémenter tous\r\nles `TODO` de la classe `BreadthFirstShortestPaths`. Vous n'avez pas\r\nbesoin de mettre les accolades (`{ }`) entourant le corps de la fonction\r\ndans votre réponse.\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part6BreadthFirstPaths/LSINF1121_PART6_BreadthFirstShortestPaths.zip).\r\n", + "description": "

Considérez cette classe, BreadthFirstShortestPaths, qui calcule le chemin le plus court entre plusieurs sources de nœuds et n'importe quel nœud dans un graphe non dirigé en utilisant un parcours BFS.

\r\n
// TODO\r\n\r\npublic class BreadthFirstShortestPaths {\r\n\r\n    private static final int INFINITY = Integer.MAX_VALUE;\r\n    private boolean[] marked; // marked[v] = is there an s-v path\r\n    private int[] distTo;     // distTo[v] = number of edges shortest s-v path\r\n\r\n    /**\r\n     * Computes the shortest path between any\r\n     * one of the sources and very other vertex\r\n     * @param G the graph\r\n     * @param sources the source vertices\r\n     */\r\n     public BreadthFirstShortestPaths(Graph G, Iterable<Integer> sources) {\r\n         marked = new boolean[G.V()];\r\n         distTo = new int[G.V()];\r\n         for (int v = 0;v < G.V();v++) {\r\n             distTo[v] = INFINITY;\r\n         }\r\n         bfs(G, sources);\r\n     }\r\n\r\n     // Breadth-first search from multiple sources\r\n     private void bfs(Graph G, Iterable<Integer> sources) {\r\n         // TODO\r\n     }\r\n\r\n     /**\r\n      * Is there a path between (at least one of) the sources and vertex v?\r\n      * @param v the vertex\r\n      * @return true if there is a path, and false otherwise\r\n      */\r\n     public boolean hasPathTo(int v) {\r\n         // TODO\r\n     }\r\n\r\n     /**\r\n      * Returns the number of edges in a shortest path\r\n      * between one of the sources and vertex v?\r\n      * @param v the vertex\r\n      * @return the number of edges in a shortest path\r\n      */\r\n     public int distTo(int v) {\r\n         // TODO\r\n     }\r\n}
\r\n

La classe Graph est déjà implémentée et la voici :

\r\n
public class Graph {\r\n    // @return the number of vertices\r\n    public int V() { }\r\n\r\n    // @return the number of edges\r\n    public int E() { }\r\n\r\n    // Add edge v-w to this graph\r\n    public void addEdge(int v, int w) { }\r\n\r\n    // @return the vertices adjacent to v\r\n    public Iterable<Integer> adj(int v) { }\r\n\r\n    // @return a string representation\r\n    public String toString() { }\r\n}
\r\n

Note: Les questions suivantes vous demanderont d'implémenter tous les TODO de la classe BreadthFirstShortestPaths. Vous n'avez pas besoin de mettre les accolades ({ }) entourant le corps de la fonction dans votre réponse.

\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1888,7 +1888,7 @@ }, { "title": "Connected Components (implem)", - "description": "Il vous ait demandé d'implémenter la classe des composants connexes\r\n`ConnectedComponent` étant donnée un graphe. La classe\r\n[Graph](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part6ConnectedComponents/javadoc.zip) disponible dans le code\r\nest celle de l'API de la classe\r\n[Java](https://docs.oracle.com/javase/8/docs/api/).\r\n\r\n``` java\r\npublic class ConnectedComponents {\r\n /**\r\n * @return the number of connected components in g\r\n */\r\n public static int numberOfConnectedComponents(Graph g) {\r\n // TODO\r\n return 0;\r\n }\r\n}\r\n```\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part6ConnectedComponents/LSINF1121_PART6_ConnectedComponents.zip).\r\n", + "description": "

Il vous ait demandé d'implémenter la classe des composants connexes ConnectedComponent étant donnée un graphe. La classe Graph disponible dans le code est celle de l'API de la classe Java.

\r\n
public class ConnectedComponents {\r\n  /**\r\n   * @return the number of connected components in g\r\n   */\r\n  public static int numberOfConnectedComponents(Graph g) {\r\n    // TODO\r\n    return 0;\r\n  }\r\n}
\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1948,7 +1948,7 @@ }, { "title": "Depth First Paths (implem)", - "description": "Considérez cette classe, `DepthFirstPaths`, qui calcule les chemins vers\r\nn'importe quel noeud connecté à partir d'un noeud source `s` dans un\r\ngraphe non dirigé en utilisant un parcours DFS.\r\n\r\n``` java\r\n// TODO\r\n\r\npublic class DepthFirstPaths {\r\n private boolean[] marked; // marked[v] = is there an s-v path?\r\n private int[] edgeTo; // edgeTo[v] = last edge on s-v path\r\n private final int s;\r\n\r\n /**\r\n * Computes a path between s and every other vertex in graph G\r\n * @param G the graph\r\n * @param s the source vertex\r\n */\r\n public DepthFirstPaths(Graph G, int s) {\r\n this.s = s;\r\n edgeTo = new int[G.V()];\r\n marked = new boolean[G.V()];\r\n dfs(G, s);\r\n }\r\n\r\n // Depth first search from v\r\n private void dfs(Graph G, int v) {\r\n // TODO\r\n }\r\n\r\n /**\r\n * Is there a path between the source s and vertex v?\r\n * @param v the vertex\r\n * @return true if there is a path, false otherwise\r\n */\r\n public boolean hasPathTo(int v) {\r\n // TODO\r\n }\r\n\r\n /**\r\n * Returns a path between the source vertex s and vertex v, or\r\n * null if no such path\r\n * @param v the vertex\r\n * @return the sequence of vertices on a path between the source vertex\r\n * s and vertex v, as an Iterable\r\n */\r\n public Iterable pathTo(int v) {\r\n // TODO\r\n }\r\n}\r\n```\r\n\r\nLa classe `Graph` est déjà implémentée. En voici la spécification :\r\n\r\n``` java\r\npublic class Graph {\r\n // @return the number of vertices\r\n public int V() { }\r\n\r\n // @return the number of edges\r\n public int E() { }\r\n\r\n // Add edge v-w to this graph\r\n public void addEdge(int v, int w) { }\r\n\r\n // @return the vertices adjacent to v\r\n public Iterable adj(int v) { }\r\n\r\n // @return a string representation\r\n public String toString() { }\r\n}\r\n```\r\n\r\n**Note:** Les questions suivantes vous demanderont d'implémenter tous\r\nles `TODO` de la classe `DepthFirstPaths`. Vous n'avez pas besoin de\r\nmettre les accolades (`{ }`) entourant le corps de la fonction dans\r\nvotre réponse.\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part6DepthFirstPaths/LSINF1121_PART6_DepthFirstPaths.zip).\r\n", + "description": "

Considérez cette classe, DepthFirstPaths, qui calcule les chemins vers n'importe quel noeud connecté à partir d'un noeud source s dans un graphe non dirigé en utilisant un parcours DFS.

\r\n
// TODO\r\n\r\npublic class DepthFirstPaths {\r\n    private boolean[] marked; // marked[v] = is there an s-v path?\r\n    private int[] edgeTo;     // edgeTo[v] = last edge on s-v path\r\n    private final int s;\r\n\r\n    /**\r\n     * Computes a path between s and every other vertex in graph G\r\n     * @param G the graph\r\n     * @param s the source vertex\r\n     */\r\n     public DepthFirstPaths(Graph G, int s) {\r\n         this.s = s;\r\n         edgeTo = new int[G.V()];\r\n         marked = new boolean[G.V()];\r\n         dfs(G, s);\r\n     }\r\n\r\n     // Depth first search from v\r\n     private void dfs(Graph G, int v) {\r\n         // TODO\r\n     }\r\n\r\n     /**\r\n      * Is there a path between the source s and vertex v?\r\n      * @param v the vertex\r\n      * @return true if there is a path, false otherwise\r\n      */\r\n     public boolean hasPathTo(int v) {\r\n         // TODO\r\n     }\r\n\r\n     /**\r\n      * Returns a path between the source vertex s and vertex v, or\r\n      * null if no such path\r\n      * @param v the vertex\r\n      * @return the sequence of vertices on a path between the source vertex\r\n      *         s and vertex v, as an Iterable\r\n      */\r\n     public Iterable<Integer> pathTo(int v) {\r\n         // TODO\r\n     }\r\n}
\r\n

La classe Graph est déjà implémentée. En voici la spécification :

\r\n
public class Graph {\r\n    // @return the number of vertices\r\n    public int V() { }\r\n\r\n    // @return the number of edges\r\n    public int E() { }\r\n\r\n    // Add edge v-w to this graph\r\n    public void addEdge(int v, int w) { }\r\n\r\n    // @return the vertices adjacent to v\r\n    public Iterable<Integer> adj(int v) { }\r\n\r\n    // @return a string representation\r\n    public String toString() { }\r\n}
\r\n

Note: Les questions suivantes vous demanderont d'implémenter tous les TODO de la classe DepthFirstPaths. Vous n'avez pas besoin de mettre les accolades ({ }) entourant le corps de la fonction dans votre réponse.

\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1998,7 +1998,7 @@ }, { "title": "Digraph (implem)", - "description": "Implémentez l'interface `Digraph.java` dans la classe\r\n`DigraphImplem.java` à l'aide d'une structure de donnée de type\r\n`liste d'adjacence` pour représenter les graphes dirigés.\r\n\r\n``` java\r\npackage student;\r\n\r\npublic interface Digraph {\r\n\r\n /**\r\n * The number of vertices\r\n */\r\n public int V();\r\n\r\n /**\r\n * The number of edges\r\n */\r\n public int E();\r\n\r\n /**\r\n * Add the edge v->w\r\n */\r\n public void addEdge(int v, int w);\r\n\r\n /**\r\n * The nodes adjacent to edge v\r\n */\r\n public Iterable adj(int v);\r\n\r\n /**\r\n * A copy of the digraph with all edges reversed\r\n */\r\n public Digraph reverse();\r\n\r\n}\r\n```\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part6Digraph/LSINF1121_PART6_Digraph.zip).\r\n", + "description": "

Implémentez l'interface Digraph.java dans la classe DigraphImplem.java à l'aide d'une structure de donnée de type liste d'adjacence pour représenter les graphes dirigés.

\r\n
package student;\r\n\r\npublic interface Digraph {\r\n\r\n    /**\r\n     * The number of vertices\r\n     */\r\n    public int V();\r\n\r\n    /**\r\n     * The number of edges\r\n     */\r\n    public int E();\r\n\r\n    /**\r\n     * Add the edge v->w\r\n     */\r\n    public void addEdge(int v, int w);\r\n\r\n    /**\r\n     * The nodes adjacent to edge v\r\n     */\r\n    public Iterable<Integer> adj(int v);\r\n\r\n    /**\r\n     * A copy of the digraph with all edges reversed\r\n     */\r\n    public Digraph reverse();\r\n\r\n}
\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2048,7 +2048,7 @@ }, { "title": "Word Transformation Shortest Path (implem)", - "description": "On vous demande d'implémenter la classe `WordTransformationSP` qui\r\npermet de trouver le plus court chemin permettant de passer d'un string\r\n*A* à un autre string *B* (avec la certitude qu'il y a bien un chemin\r\npermettant de transformer *A* en *B*).\r\n\r\nPour cela on definit une opération `rotation(x, y)` qui inverse l’ordre\r\ndes lettres entre la position x et y (non-inclus). Par exemple, avec\r\nA=`HAMBURGER`, si l'on fait `rotation(A, 4, 8)`, cela nous donne\r\n`HAMBEGRUR`. Vous pouvez donc constater que la sous-string `URGE` a été\r\ninversé en `EGRU` et le reste de la chaine est resté inchangé: `HAMB` +\r\n`ECRU` + `R` = `HAMBEGRUR`.\r\n\r\nDisons qu’une `rotation(x, y)` a un cout de y-x. Par exemple passer de\r\n`HAMBURGER` à `HAMBEGRUR` coût *8-4 = 4*.\r\n\r\nLa question est de savoir quel est le coût minimum pour atteindre une\r\nstring B à partir A?\r\n\r\nVous devez donc inmplémenter la méthode une fonction\r\n`public static int minimalCost(String A, String B)` qui retourne le cout\r\nminimal pour atteindre le String B depuis A en utilisant l'opération\r\nrotation.\r\n\r\n``` java\r\nimport java.util.*;\r\n\r\npublic class WordTransformationSP {\r\n /**\r\n *\r\n * Rotate the substring between start and end of a given string s\r\n * eg. s = HAMBURGER, rotation(s,4,8) = HAMBEGRUR i.e. HAMB + EGRU + R\r\n * @param s\r\n * @param start\r\n * @param end\r\n * @return rotated string\r\n */\r\n public static String rotation(String s, int start, int end) {\r\n return s.substring(0,start)+new StringBuilder(s.substring(start,end)).reverse().toString()+s.substring(end);\r\n }\r\n\r\n /**\r\n * Compute the minimal cost from string \"from\" to string \"to\" representing the shortest path\r\n * @param from\r\n * @param to\r\n * @return\r\n */\r\n public static int minimalCost(String from, String to) {\r\n //TODO\r\n return 0;\r\n }\r\n}\r\n```\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part6DijkstraForWordTransformation/LSINF1121_PART6_WordTransformation.zip).\r\n\r\n**Note:** vous pouvez ajouter d'autres fonctions et des private classes\r\nsi vous le désirez.\r\n", + "description": "

On vous demande d'implémenter la classe WordTransformationSP qui permet de trouver le plus court chemin permettant de passer d'un string A à un autre string B (avec la certitude qu'il y a bien un chemin permettant de transformer A en B).

\r\n

Pour cela on definit une opération rotation(x, y) qui inverse l’ordre des lettres entre la position x et y (non-inclus). Par exemple, avec A=HAMBURGER, si l'on fait rotation(A, 4, 8), cela nous donne HAMBEGRUR. Vous pouvez donc constater que la sous-string URGE a été inversé en EGRU et le reste de la chaine est resté inchangé: HAMB + ECRU + R = HAMBEGRUR.

\r\n

Disons qu’une rotation(x, y) a un cout de y-x. Par exemple passer de HAMBURGER à HAMBEGRUR coût 8-4 = 4.

\r\n

La question est de savoir quel est le coût minimum pour atteindre une string B à partir A?

\r\n

Vous devez donc inmplémenter la méthode une fonction public static int minimalCost(String A, String B) qui retourne le cout minimal pour atteindre le String B depuis A en utilisant l'opération rotation.

\r\n
import java.util.*;\r\n\r\npublic  class WordTransformationSP {\r\n    /**\r\n     *\r\n     * Rotate the substring between start and end of a given string s\r\n     * eg. s = HAMBURGER, rotation(s,4,8) = HAMBEGRUR i.e. HAMB + EGRU + R\r\n     * @param s\r\n     * @param start\r\n     * @param end\r\n     * @return rotated string\r\n     */\r\n    public static String rotation(String s, int start, int end) {\r\n        return s.substring(0,start)+new StringBuilder(s.substring(start,end)).reverse().toString()+s.substring(end);\r\n    }\r\n\r\n    /**\r\n     * Compute the minimal cost from string "from" to string "to" representing the shortest path\r\n     * @param from\r\n     * @param to\r\n     * @return\r\n     */\r\n    public static int minimalCost(String from, String to) {\r\n        //TODO\r\n        return 0;\r\n    }\r\n}
\r\n

Le projet IntelliJ est disponible ici.

\r\n

Note: vous pouvez ajouter d'autres fonctions et des private classes si vous le désirez.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2098,7 +2098,7 @@ }, { "title": "Global Warming (implem)", - "description": "Context\r\n=======\r\n\r\nSupposons la matrice 5x5 suivante:\r\n\r\n``` java\r\nint [][] tab = new int[][] {{1,3,3,1,3},\r\n {4,2,2,4,5},\r\n {4,4,1,4,2},\r\n {1,4,2,3,6},\r\n {1,1,1,6,3}};\r\n```\r\n\r\nreprésentée dans le tableau ci-dessous :\r\n\r\n\"matrix\r\n\r\nChaque entrée de la matrice représente une altitude. L'objectif est\r\nd'implémenter une classe GlobalWarmingImpl qui implémente toutes les\r\nméthodes décrites dans GlobalWarming\r\ndonnées ci-dessous.\r\n\r\nUn niveau d'eau global spécifié dans le constructeur modélise le fait\r\nque toutes les positions de la matrice avec une valeur <= le niveau\r\nd'eau sont inondées (sous l'eau) et donc dangereuses. Dans l'exemple\r\nci-dessus, le niveau d'eau est de 3, tous les points sûrs sont en vert.\r\n\r\nLa méthode que vous devez implémenter doit permettre de calculer le\r\nchemin le plus court entre deux positions sont sur la même île\r\n\r\nnous supposons que les points sont **uniquement connectés verticalement\r\nou horizontalement**.\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part6GlobalWarming/LSINF1121_PART6_GlobalWarming.zip).\r\n\r\n``` java\r\nimport java.util.List;\r\n\r\nabstract class GlobalWarming {\r\n\r\n /**\r\n * A class to represent the coordinates on the altitude matrix\r\n */\r\n public static class Point {\r\n\r\n final int x, y;\r\n\r\n Point(int x, int y) {\r\n this.x = x;\r\n this.y = y;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n Point p = (Point) obj;\r\n return p.x == x && p.y == y;\r\n }\r\n }\r\n\r\n final int[][] altitude;\r\n final int waterLevel;\r\n\r\n\r\n /**\r\n * In the following, we assume that the points are connected to\r\n * horizontal or vertical neighbors but not to the diagonal ones\r\n * @param altitude is a n x n matrix of int values representing altitudes (positive or negative)\r\n * @param waterLevel is the water level, every entry <= waterLevel is flooded\r\n */\r\n public GlobalWarming(int[][] altitude, int waterLevel) {\r\n this.altitude = altitude;\r\n this.waterLevel = waterLevel;\r\n }\r\n\r\n\r\n /**\r\n *\r\n * @param p1 a safe point with valid coordinates on altitude matrix\r\n * @param p2 a safe point (different from p1) with valid coordinates on altitude matrix\r\n * @return the shortest simple path (vertical/horizontal moves) if any between from p1 to p2 using only vertical/horizontal moves on safe points.\r\n * an empty list if not path exists (i.e. p1 and p2 are not on the same island).\r\n */\r\n public abstract List shortestPath(Point p1, Point p2);\r\n\r\n}\r\n```\r\n\r\nExercices Preliminaires\r\n=======================\r\n\r\n``` java\r\nint [][] tab = new int[][] {{1,3,3,1,3},\r\n {4,2,2,4,5},\r\n {4,4,1,4,2},\r\n {1,4,2,3,6},\r\n {1,1,1,6,3}};\r\nGlobalWarming gw = new MyGlobalWarming(tab,3);\r\n```\r\n\r\n\"matrix\r\n", + "description": "

Context

\r\n

Supposons la matrice 5x5 suivante:

\r\n
int [][] tab = new int[][] {{1,3,3,1,3},\r\n                          {4,2,2,4,5},\r\n                          {4,4,1,4,2},\r\n                          {1,4,2,3,6},\r\n                          {1,1,1,6,3}};
\r\n

représentée dans le tableau ci-dessous :

\r\n

\"matrix

\r\n

Chaque entrée de la matrice représente une altitude. L'objectif est d'implémenter une classe GlobalWarmingImpl qui implémente toutes les méthodes décrites dans GlobalWarming données ci-dessous.

\r\n

Un niveau d'eau global spécifié dans le constructeur modélise le fait que toutes les positions de la matrice avec une valeur <= le niveau d'eau sont inondées (sous l'eau) et donc dangereuses. Dans l'exemple ci-dessus, le niveau d'eau est de 3, tous les points sûrs sont en vert.

\r\n

La méthode que vous devez implémenter doit permettre de calculer le chemin le plus court entre deux positions sont sur la même île

\r\n

nous supposons que les points sont uniquement connectés verticalement ou horizontalement.

\r\n

Le projet IntelliJ est disponible ici.

\r\n
import java.util.List;\r\n\r\nabstract class GlobalWarming {\r\n\r\n    /**\r\n     * A class to represent the coordinates on the altitude matrix\r\n     */\r\n    public static class Point {\r\n\r\n        final int x, y;\r\n\r\n        Point(int x, int y) {\r\n            this.x = x;\r\n            this.y = y;\r\n        }\r\n\r\n        @Override\r\n        public boolean equals(Object obj) {\r\n            Point p = (Point) obj;\r\n            return p.x == x && p.y == y;\r\n        }\r\n    }\r\n\r\n    final int[][] altitude;\r\n    final int waterLevel;\r\n\r\n\r\n    /**\r\n     * In the following, we assume that the points are connected to\r\n     * horizontal or vertical neighbors but not to the diagonal ones\r\n     * @param altitude is a n x n matrix of int values representing altitudes (positive or negative)\r\n     * @param waterLevel is the water level, every entry <= waterLevel is flooded\r\n     */\r\n    public GlobalWarming(int[][] altitude, int waterLevel) {\r\n        this.altitude = altitude;\r\n        this.waterLevel = waterLevel;\r\n    }\r\n\r\n\r\n    /**\r\n     *\r\n     * @param p1 a safe point with valid coordinates on altitude matrix\r\n     * @param p2 a safe point (different from p1) with valid coordinates on altitude matrix\r\n     * @return the shortest simple path (vertical/horizontal moves) if any between from p1 to p2 using only vertical/horizontal moves on safe points.\r\n     *         an empty list if not path exists (i.e. p1 and p2 are not on the same island).\r\n     */\r\n    public abstract List<Point> shortestPath(Point p1, Point p2);\r\n\r\n}
\r\n

Exercices Preliminaires

\r\n
int [][] tab = new int[][] {{1,3,3,1,3},\r\n                          {4,2,2,4,5},\r\n                          {4,4,1,4,2},\r\n                          {1,4,2,3,6},\r\n                          {1,1,1,6,3}};\r\nGlobalWarming gw = new MyGlobalWarming(tab,3);
\r\n

\"matrix

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2153,7 +2153,7 @@ }, { "title": "PART 6 : Maze (implem)", - "description": "Nous sommes intéressés par la résolution de labyrinthe (labyrinthe)\r\nreprésenté par une matrice d'entiers 0-1 de taille nxm. Cette matrice est un tableau à deux\r\ndimensions. Une entrée égale à '1' signifie qu'il y a un mur et que\r\ncette position n'est donc pas accessible, tandis que '0' signifie que la\r\nposition est libre.\r\n\r\nNous vous demandons d'écrire un code Java pour découvrir le chemin le\r\nplus court entre deux coordonnées sur cette matrice de (x1, y1) à (x2,\r\ny2).\r\n\r\nLes déplacements ne peuvent être que verticaux ou horizontaux (pas en\r\ndiagonale), un pas à la fois.\r\n\r\nLe résultat du chemin est un `Iterable` de coordonnées de l'origine à la\r\ndestination. Ces coordonnées sont représentées par des entiers compris\r\nentre 0 et n \\* m-1, où un entier 'a'\r\nreprésente la position x =a/m et y=a%m.\r\n\r\nSi la position de début ou de fin est un mur ou s’il n’ya pas de chemin,\r\nil faut renvoyer un `Iterable` vide. Il en va de même s'il n'y a pas de\r\nchemin entre l'origine et la destination.\r\n\r\n``` java\r\nimport java.util.LinkedList;\r\n\r\npublic class Maze {\r\n public static Iterable shortestPath(int [][] maze, int x1, int y1, int x2, int y2) {\r\n //TODO\r\n return new LinkedList<>();\r\n }\r\n\r\n public static int ind(int x,int y, int lg) {return x*lg + y;}\r\n\r\n public static int row(int pos, int mCols) { return pos / mCols; }\r\n\r\n public static int col(int pos, int mCols) { return pos % mCols; }\r\n}\r\n```\r\n\r\n[Le projet IntelliJ est disponible\r\nici](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/Part6Maze/LSINF1121_PART6_Maze.zip).\r\n", + "description": "

Nous sommes intéressés par la résolution de labyrinthe (labyrinthe) représenté par une matrice d'entiers 0-1 de taille nxm. Cette matrice est un tableau à deux dimensions. Une entrée égale à '1' signifie qu'il y a un mur et que cette position n'est donc pas accessible, tandis que '0' signifie que la position est libre.

\r\n

Nous vous demandons d'écrire un code Java pour découvrir le chemin le plus court entre deux coordonnées sur cette matrice de (x1, y1) à (x2, y2).

\r\n

Les déplacements ne peuvent être que verticaux ou horizontaux (pas en diagonale), un pas à la fois.

\r\n

Le résultat du chemin est un Iterable de coordonnées de l'origine à la destination. Ces coordonnées sont représentées par des entiers compris entre 0 et n * m-1, où un entier 'a' représente la position x =a/m et y=a%m.

\r\n

Si la position de début ou de fin est un mur ou s’il n’ya pas de chemin, il faut renvoyer un Iterable vide. Il en va de même s'il n'y a pas de chemin entre l'origine et la destination.

\r\n
import java.util.LinkedList;\r\n\r\npublic class Maze {\r\n    public static Iterable<Integer> shortestPath(int [][] maze,  int x1, int y1, int x2, int y2) {\r\n        //TODO\r\n        return new LinkedList<>();\r\n    }\r\n\r\n    public static int ind(int x,int y, int lg) {return x*lg + y;}\r\n\r\n    public static int row(int pos, int mCols) { return pos / mCols; }\r\n\r\n    public static int col(int pos, int mCols) { return pos % mCols; }\r\n}
\r\n

Le projet IntelliJ est disponible ici.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2203,7 +2203,7 @@ }, { "title": "Règles de participation aux cours", - "description": "Ce qui est interdit\r\n===================\r\n\r\nIl est interdit de partager son code avec un autre groupe et même avec\r\nson propre groupe pour les parties individuelles des missions.\r\n\r\nIl est interdit de publier son code de manière publique (`GitHub`,\r\n`Bitbucket`, `Dropbox` ou `Drive` partagé, etc) pendant et après le\r\nquadrimestre. Nous vous fournirons un repository `Git` pour vos travaux\r\nde groupes, qui sera seulement visible par les membres de votre groupe.\r\n\r\nIl est interdit de prendre le code de quelqu’un d’autre (même\r\npartiellement), y compris du code disponible sur le web. Seul le code\r\nfourni dans le livre de référence peut être utilisé.\r\n\r\nCe qui est autorisé\r\n===================\r\n\r\nÉchanger et discuter des idées avec des collègues (y compris d’un autre\r\ngroupe) est autorisé (oralement autour d’un tableau, sur un forum, etc).\r\nMais il est interdit de demander et/ou fournir une réponse toute faite\r\nou du code source.\r\n\r\nExemple de ce qui est interdit :\r\n\r\n- Tu as mis quoi à la réponse à la question 1 ?\r\n\r\nExemple de ce qui est autorisé :\r\n\r\n- J’hésite entre la méthode 1 et la méthode 2 pour réaliser l’objectif\r\n 1, je pense que la méthode 1 est meilleure pour la raison x, que\r\n penses-tu de cet argument ?\r\n\r\nPourquoi ?\r\n==========\r\n\r\nCar le matériel pédagogique mis en place s’améliore chaque année et\r\nprend beaucoup de temps à développer. Le copyright de celui-ci\r\nappartient d’ailleurs à l’UCL et non aux étudiants.\r\n\r\nContourner les outils pédagogiques mis en place (par exemple en\r\nempruntant du code déjà écrit) ne vous rend pas service. C’est même le\r\nmeilleur moyen d’échouer à l’examen qui visera précisément à évaluer les\r\ncompétences acquises: programmation, réponses aux questions, etc.\r\n\r\nEn partageant du code ou des réponses (dans le meilleur des cas\r\napproximativement correctes...) vous inciteriez certains étudiants à ne\r\npas réfléchir par eux-mêmes, voir pire, à apprendre des réponses\r\npotentiellement erronées.\r\n\r\nLa note de participation ne vise pas l’exactitude des productions\r\n(réponses, codes) mais l’attitude et la motivation de l’étudiant à\r\ns’améliorer et acquérir les compétences visées.\r\n\r\nRisque\r\n======\r\n\r\nTout manquement à un de ces points sera sanctionné comme un acte de\r\ntricherie et sera dès lors reporté au président des jurys. Pour rappel,\r\nen cas de tricherie, l'étudiant peut se voir attribuer un zéro pour le\r\ncours, voire se voir attribuer zéro pour l'ensemble des cours de la\r\nsession.\r\n\r\nVos codes sont analysés par des outils de détection de plagiat. Un\r\nétudiant averti en vaut deux.\r\n", + "description": "

Ce qui est interdit

\r\n

Il est interdit de partager son code avec un autre groupe et même avec son propre groupe pour les parties individuelles des missions.

\r\n

Il est interdit de publier son code de manière publique (GitHub, Bitbucket, Dropbox ou Drive partagé, etc) pendant et après le quadrimestre. Nous vous fournirons un repository Git pour vos travaux de groupes, qui sera seulement visible par les membres de votre groupe.

\r\n

Il est interdit de prendre le code de quelqu’un d’autre (même partiellement), y compris du code disponible sur le web. Seul le code fourni dans le livre de référence peut être utilisé.

\r\n

Ce qui est autorisé

\r\n

Échanger et discuter des idées avec des collègues (y compris d’un autre groupe) est autorisé (oralement autour d’un tableau, sur un forum, etc). Mais il est interdit de demander et/ou fournir une réponse toute faite ou du code source.

\r\n

Exemple de ce qui est interdit :

\r\n
    \r\n
  • Tu as mis quoi à la réponse à la question 1 ?
  • \r\n
\r\n

Exemple de ce qui est autorisé :

\r\n
    \r\n
  • J’hésite entre la méthode 1 et la méthode 2 pour réaliser l’objectif 1, je pense que la méthode 1 est meilleure pour la raison x, que penses-tu de cet argument ?
  • \r\n
\r\n

Pourquoi ?

\r\n

Car le matériel pédagogique mis en place s’améliore chaque année et prend beaucoup de temps à développer. Le copyright de celui-ci appartient d’ailleurs à l’UCL et non aux étudiants.

\r\n

Contourner les outils pédagogiques mis en place (par exemple en empruntant du code déjà écrit) ne vous rend pas service. C’est même le meilleur moyen d’échouer à l’examen qui visera précisément à évaluer les compétences acquises: programmation, réponses aux questions, etc.

\r\n

En partageant du code ou des réponses (dans le meilleur des cas approximativement correctes...) vous inciteriez certains étudiants à ne pas réfléchir par eux-mêmes, voir pire, à apprendre des réponses potentiellement erronées.

\r\n

La note de participation ne vise pas l’exactitude des productions (réponses, codes) mais l’attitude et la motivation de l’étudiant à s’améliorer et acquérir les compétences visées.

\r\n

Risque

\r\n

Tout manquement à un de ces points sera sanctionné comme un acte de tricherie et sera dès lors reporté au président des jurys. Pour rappel, en cas de tricherie, l'étudiant peut se voir attribuer un zéro pour le cours, voire se voir attribuer zéro pour l'ensemble des cours de la session.

\r\n

Vos codes sont analysés par des outils de détection de plagiat. Un étudiant averti en vaut deux.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2248,7 +2248,7 @@ }, { "title": "Rabin Karp", - "description": "A la page 777 du livre \"Algorithms\" 4th edition, on vous propose\r\nl'implémentation suivante de l'algorithme de Rabin Karp.\r\n\r\n``` java\r\npublic class RabinKarp {\r\n private String pat; // the pattern // needed only for Las Vegas\r\n private long patHash; // pattern hash value\r\n private int m; // pattern length\r\n private long q; // a large prime, small enough to avoid long overflow\r\n private int R; // radix\r\n private long RM; // R^(M-1) % Q\r\n\r\n public RabinKarp(String pat) {\r\n this.pat = pat; // save pattern (needed only for Las Vegas)\r\n R = 256;\r\n m = pat.length();\r\n q = longRandomPrime();\r\n\r\n // precompute R^(m-1) % q for use in removing leading digit\r\n RM = 1;\r\n for (int i = 1; i <= m-1; i++)\r\n RM = (R * RM) % q;\r\n patHash = hash(pat, m);\r\n }\r\n\r\n // Compute hash for key[0..m-1].\r\n private long hash(String key, int m) {\r\n long h = 0;\r\n for (int j = 0; j < m; j++)\r\n h = (R * h + key.charAt(j)) % q;\r\n return h;\r\n }\r\n\r\n // Monte Carlo\r\n private boolean check(int i) {\r\n return true;\r\n }\r\n\r\n // Returns the index of the first occurrrence of the pattern string in the text string.\r\n public int search(String txt) {\r\n int n = txt.length();\r\n if (n < m) return n;\r\n long txtHash = hash(txt, m);\r\n\r\n // check for match at offset 0\r\n if ((patHash == txtHash) && check(txt, 0))\r\n return 0;\r\n\r\n // check for hash match; if hash match, check for exact match\r\n for (int i = m; i < n; i++) {\r\n // Remove leading digit, add trailing digit, check for match.\r\n txtHash = (txtHash + q - RM*txt.charAt(i-m) % q) % q;\r\n txtHash = (txtHash*R + txt.charAt(i)) % q;\r\n\r\n // match\r\n int offset = i - m + 1;\r\n if ((patHash == txtHash) && check(txt, offset))\r\n return offset;\r\n }\r\n\r\n // no match\r\n return n;\r\n }\r\n\r\n\r\n // a random 31-bit prime\r\n private static long longRandomPrime() {\r\n BigInteger prime = BigInteger.probablePrime(31, new Random());\r\n return prime.longValue();\r\n }\r\n\r\n}\r\n```\r\n", + "description": "

A la page 777 du livre \"Algorithms\" 4th edition, on vous propose l'implémentation suivante de l'algorithme de Rabin Karp.

\r\n
public class RabinKarp {\r\n  private String pat;      // the pattern  // needed only for Las Vegas\r\n  private long patHash;    // pattern hash value\r\n  private int m;           // pattern length\r\n  private long q;          // a large prime, small enough to avoid long overflow\r\n  private int R;           // radix\r\n  private long RM;         // R^(M-1) % Q\r\n\r\n  public RabinKarp(String pat) {\r\n      this.pat = pat;      // save pattern (needed only for Las Vegas)\r\n      R = 256;\r\n      m = pat.length();\r\n      q = longRandomPrime();\r\n\r\n      // precompute R^(m-1) % q for use in removing leading digit\r\n      RM = 1;\r\n      for (int i = 1; i <= m-1; i++)\r\n          RM = (R * RM) % q;\r\n      patHash = hash(pat, m);\r\n  }\r\n\r\n  // Compute hash for key[0..m-1].\r\n  private long hash(String key, int m) {\r\n      long h = 0;\r\n      for (int j = 0; j < m; j++)\r\n          h = (R * h + key.charAt(j)) % q;\r\n      return h;\r\n  }\r\n\r\n  // Monte Carlo\r\n  private boolean check(int i) {\r\n      return true;\r\n  }\r\n\r\n  // Returns the index of the first occurrrence of the pattern string in the text string.\r\n  public int search(String txt) {\r\n      int n = txt.length();\r\n      if (n < m) return n;\r\n      long txtHash = hash(txt, m);\r\n\r\n      // check for match at offset 0\r\n      if ((patHash == txtHash) && check(txt, 0))\r\n          return 0;\r\n\r\n      // check for hash match; if hash match, check for exact match\r\n      for (int i = m; i < n; i++) {\r\n          // Remove leading digit, add trailing digit, check for match.\r\n          txtHash = (txtHash + q - RM*txt.charAt(i-m) % q) % q;\r\n          txtHash = (txtHash*R + txt.charAt(i)) % q;\r\n\r\n          // match\r\n          int offset = i - m + 1;\r\n          if ((patHash == txtHash) && check(txt, offset))\r\n              return offset;\r\n      }\r\n\r\n      // no match\r\n      return n;\r\n  }\r\n\r\n\r\n  // a random 31-bit prime\r\n  private static long longRandomPrime() {\r\n      BigInteger prime = BigInteger.probablePrime(31, new Random());\r\n      return prime.longValue();\r\n  }\r\n\r\n}
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2297,7 +2297,7 @@ }, { "title": "Breadth First Paths", - "description": "Consider this class, `BreadthFirstShortestPaths`, that computes the\r\nshortest path between multiple node sources and any node in an\r\nundirected graph.\r\n\r\n``` java\r\n// TODO\r\n\r\npublic class BreadthFirstShortestPaths {\r\n\r\n private static final int INFINITY = Integer.MAX_VALUE;\r\n private boolean[] marked; // marked[v] = is there an s-v path\r\n private int[] distTo; // distTo[v] = number of edges shortest s-v path\r\n\r\n /**\r\n * Computes the shortest path between any\r\n * one of the sources and very other vertex\r\n * @param G the graph\r\n * @param sources the source vertices\r\n */\r\n public BreadthFirstShortestPaths(Graph G, Iterable sources) {\r\n marked = new boolean[G.V()];\r\n distTo = new int[G.V()];\r\n for (int v = 0;v < G.V();v++) {\r\n distTo[v] = INFINITY;\r\n }\r\n bfs(G, sources);\r\n }\r\n\r\n // Breadth-first search from multiple sources\r\n private void bfs(Graph G, Iterable sources) {\r\n // TODO\r\n }\r\n\r\n /**\r\n * Is there a path between (at least one of) the sources and vertex v?\r\n * @param v the vertex\r\n * @return true if there is a path, and false otherwise\r\n */\r\n public boolean hasPathTo(int v) {\r\n // TODO\r\n }\r\n\r\n /**\r\n * Returns the number of edges in a shortest path\r\n * between one of the sources and vertex v?\r\n * @param v the vertex\r\n * @return the number of edges in a shortest path\r\n */\r\n public int distTo(int v) {\r\n // TODO\r\n }\r\n}\r\n```\r\n\r\nThe class `Graph` is already implemented. Here is its specification:\r\n\r\n``` java\r\npublic class Graph {\r\n // @return the number of vertices\r\n public int V() { }\r\n\r\n // @return the number of edges\r\n public int E() { }\r\n\r\n // Add edge v-w to this graph\r\n public void addEdge(int v, int w) { }\r\n\r\n // @return the vertices adjacent to v\r\n public Iterable adj(int v) { }\r\n\r\n // @return a string representation\r\n public String toString() { }\r\n}\r\n```\r\n\r\n**Note:** The following questions will ask you to implement the function\r\nleft out. You don't need to put the brackets (`{ }`) surrounding the\r\nfunction body in your answer.\r\n", + "description": "

Consider this class, BreadthFirstShortestPaths, that computes the shortest path between multiple node sources and any node in an undirected graph.

\r\n
// TODO\r\n\r\npublic class BreadthFirstShortestPaths {\r\n\r\n    private static final int INFINITY = Integer.MAX_VALUE;\r\n    private boolean[] marked; // marked[v] = is there an s-v path\r\n    private int[] distTo;     // distTo[v] = number of edges shortest s-v path\r\n\r\n    /**\r\n     * Computes the shortest path between any\r\n     * one of the sources and very other vertex\r\n     * @param G the graph\r\n     * @param sources the source vertices\r\n     */\r\n     public BreadthFirstShortestPaths(Graph G, Iterable<Integer> sources) {\r\n         marked = new boolean[G.V()];\r\n         distTo = new int[G.V()];\r\n         for (int v = 0;v < G.V();v++) {\r\n             distTo[v] = INFINITY;\r\n         }\r\n         bfs(G, sources);\r\n     }\r\n\r\n     // Breadth-first search from multiple sources\r\n     private void bfs(Graph G, Iterable<Integer> sources) {\r\n         // TODO\r\n     }\r\n\r\n     /**\r\n      * Is there a path between (at least one of) the sources and vertex v?\r\n      * @param v the vertex\r\n      * @return true if there is a path, and false otherwise\r\n      */\r\n     public boolean hasPathTo(int v) {\r\n         // TODO\r\n     }\r\n\r\n     /**\r\n      * Returns the number of edges in a shortest path\r\n      * between one of the sources and vertex v?\r\n      * @param v the vertex\r\n      * @return the number of edges in a shortest path\r\n      */\r\n     public int distTo(int v) {\r\n         // TODO\r\n     }\r\n}
\r\n

The class Graph is already implemented. Here is its specification:

\r\n
public class Graph {\r\n    // @return the number of vertices\r\n    public int V() { }\r\n\r\n    // @return the number of edges\r\n    public int E() { }\r\n\r\n    // Add edge v-w to this graph\r\n    public void addEdge(int v, int w) { }\r\n\r\n    // @return the vertices adjacent to v\r\n    public Iterable<Integer> adj(int v) { }\r\n\r\n    // @return a string representation\r\n    public String toString() { }\r\n}
\r\n

Note: The following questions will ask you to implement the function left out. You don't need to put the brackets ({ }) surrounding the function body in your answer.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2351,7 +2351,7 @@ }, { "title": "Bloom Filters", - "description": "Les filtres de Bloom\r\n====================\r\n\r\nUn filtre de Bloom, est une structure de donnée très compacte et\r\nefficace qui permet d'implémenter un test d'appartenance rapide\r\n(`.contains()`) à un très grand *ensemble*. Cependant, contrairement au\r\ntest d'appartenance à un ensemble tel qu'implémenté à l'aide d'une\r\nHashMap, le test d'appartenance implémenté via un filtre de bloom peut\r\nrenvoyer un résultat erroné (faux positifs possibles mais pas de faux\r\nnégatifs) dans certains cas et cela, avec une faible probabilité.\r\n\r\nL'efficacité de cette structure, et le fait qu'elle ne requière qu'une\r\nquantité très faible (et constante !) de mémoire quel que soit le nombre\r\nd'éléments contenus dans l'ensemble en ont fait une structure de choix\r\npour un très grand nombre d'applications. A titre d'exemple, on\r\nmentionnera le fait que les filtres de Bloom sont utilisés par certains\r\ndevices réseaux pour faire du *Deep Packet Inspection*, ou encore que\r\nles bases de données *Google Big Table*, *Apache Cassandra* ou encore\r\n*Postgresql* utilisent cette structure de donnée afin de tester si une\r\ndonnée se trouve en cache ou non.\r\n\r\nEn effet la recherche de la donnée étant généralement coûteuse, un\r\nfiltre de Bloom est utilisé pour éviter de faire une recherche si la\r\ndonnée n'est pas présente. Par contre, comme les erreurs de type\r\nfaux-positifs sont possibles, le filtre de Bloom peut dire que la donnée\r\ns'y trouve alors que ça n'est pas vrai. Dans ce cas, il faudra effectuer\r\nla recherche pour vérifier et payer le coût de cette recherche (par\r\nexemple une recherche linéaire avec des accès sur le disque).\r\n\r\nConcrètement\r\n============\r\n\r\nConcrètement, un filtre de bloom consiste en un vecteur\r\n*V* = *v*1..*v**n* de bit et d'un ensemble\r\n*F* = *f*1..*f**k* de fonctions de hachage\r\n\r\nPour ajouter un élément *X* dans le set, on applique successivement\r\nchacune des fonctions *f**i* ∈ *F* de hachage. L'application\r\nde chacune de ces fonctions à l'élément *X* renvoie un nombre\r\n*h**i* ∈ \\[0..*n*−1\\]. Pour marquer l'ajout de *X* au filtre\r\nde bloom, on met à 1 simplement chacun des\r\n*v**h**i* bits dans *V*.\r\n\r\nDe façon similaire, pour tester l'appartenance d'un élément *X* au set,\r\non vérifie que le *h**i* ème bit  ∈ *V* correspondant à\r\n*f**i*(*X*) est égal à 1. Le test d'appartenance ne renverra\r\ntrue que ssi, cette condition est\r\nvérifiée pour chacune des *f**i* ∈ *F*.\r\n\r\nExemples\r\n--------\r\n\r\nEn supposant qu'on ait un filtre de Bloom représenté par 1 byte et 3\r\nfonctions de hachage telles que:\r\n\r\n``` \r\nf1(\"Salut\") = 0\r\nf2(\"Salut\") = 1\r\nf3(\"Salut\") = 2\r\n\r\net\r\n\r\nf1(\"1121\") = 0\r\nf2(\"1121\") = 1\r\nf3(\"1121\") = 4\r\n```\r\n\r\nL'ajout de \"Salut\" au filtre 00000000 transforme celui-ci en 11100000.\r\nSi par la suite on veut tester que \"Salut\" est bien présent dans le\r\nfiltre, on s'assure que les bits v1, v2 et v3 sont bien égaux à 1.\r\n\r\nEn continuant sur le même exemple, on voit que la chaine \"1121\" n'est\r\npas présente dans la structure puisque le 4eme bit est égal à 0.\r\n", + "description": "

Les filtres de Bloom

\r\n

Un filtre de Bloom, est une structure de donnée très compacte et efficace qui permet d'implémenter un test d'appartenance rapide (.contains()) à un très grand ensemble. Cependant, contrairement au test d'appartenance à un ensemble tel qu'implémenté à l'aide d'une HashMap, le test d'appartenance implémenté via un filtre de bloom peut renvoyer un résultat erroné (faux positifs possibles mais pas de faux négatifs) dans certains cas et cela, avec une faible probabilité.

\r\n

L'efficacité de cette structure, et le fait qu'elle ne requière qu'une quantité très faible (et constante !) de mémoire quel que soit le nombre d'éléments contenus dans l'ensemble en ont fait une structure de choix pour un très grand nombre d'applications. A titre d'exemple, on mentionnera le fait que les filtres de Bloom sont utilisés par certains devices réseaux pour faire du Deep Packet Inspection, ou encore que les bases de données Google Big Table, Apache Cassandra ou encore Postgresql utilisent cette structure de donnée afin de tester si une donnée se trouve en cache ou non.

\r\n

En effet la recherche de la donnée étant généralement coûteuse, un filtre de Bloom est utilisé pour éviter de faire une recherche si la donnée n'est pas présente. Par contre, comme les erreurs de type faux-positifs sont possibles, le filtre de Bloom peut dire que la donnée s'y trouve alors que ça n'est pas vrai. Dans ce cas, il faudra effectuer la recherche pour vérifier et payer le coût de cette recherche (par exemple une recherche linéaire avec des accès sur le disque).

\r\n

Concrètement

\r\n

Concrètement, un filtre de bloom consiste en un vecteur V = v1..vn de bit et d'un ensemble F = f1..fk de fonctions de hachage

\r\n

Pour ajouter un élément X dans le set, on applique successivement chacune des fonctions fi ∈ F de hachage. L'application de chacune de ces fonctions à l'élément X renvoie un nombre hi ∈ [0..n−1]. Pour marquer l'ajout de X au filtre de bloom, on met à 1 simplement chacun des vhi bits dans V.

\r\n

De façon similaire, pour tester l'appartenance d'un élément X au set, on vérifie que le hi ème bit  ∈ V correspondant à fi(X) est égal à 1. Le test d'appartenance ne renverra true que ssi, cette condition est vérifiée pour chacune des fi ∈ F.

\r\n

Exemples

\r\n

En supposant qu'on ait un filtre de Bloom représenté par 1 byte et 3 fonctions de hachage telles que:

\r\n
f1("Salut") = 0\r\nf2("Salut") = 1\r\nf3("Salut") = 2\r\n\r\net\r\n\r\nf1("1121") = 0\r\nf2("1121") = 1\r\nf3("1121") = 4
\r\n

L'ajout de \"Salut\" au filtre 00000000 transforme celui-ci en 11100000. Si par la suite on veut tester que \"Salut\" est bien présent dans le filtre, on s'assure que les bits v1, v2 et v3 sont bien égaux à 1.

\r\n

En continuant sur le même exemple, on voit que la chaine \"1121\" n'est pas présente dans la structure puisque le 4eme bit est égal à 0.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2406,7 +2406,7 @@ }, { "title": "Depth First Paths", - "description": "Consider this class, `DepthFirstPaths`, that computes paths to any\r\nconnected node from a source node `s` in an undirected graph.\r\n\r\n``` java\r\n// TODO\r\n\r\npublic class DepthFirstPaths {\r\n private boolean[] marked; // marked[v] = is there an s-v path?\r\n private int[] edgeTo; // edgeTo[v] = last edge on s-v path\r\n private final int s;\r\n\r\n /**\r\n * Computes a path between s and every other vertex in graph G\r\n * @param G the graph\r\n * @param s the source vertex\r\n */\r\n public DepthFirstPaths(Graph G, int s) {\r\n this.s = s;\r\n edgeTo = new int[G.V()];\r\n marked = new boolean[G.V()];\r\n dfs(G, s);\r\n }\r\n\r\n // Depth first search from v\r\n private void dfs(Graph G, int v) {\r\n // TODO\r\n }\r\n\r\n /**\r\n * Is there a path between the source s and vertex v?\r\n * @param v the vertex\r\n * @return true if there is a path, false otherwise\r\n */\r\n public boolean hasPathTo(int v) {\r\n // TODO\r\n }\r\n\r\n /**\r\n * Returns a path between the source vertex s and vertex v, or\r\n * null if no such path\r\n * @param v the vertex\r\n * @return the sequence of vertices on a path between the source vertex\r\n * s and vertex v, as an Iterable\r\n */\r\n public Iterable pathTo(int v) {\r\n // TODO\r\n }\r\n}\r\n```\r\n\r\nThe class `Graph` is already implemented. Here is its specification:\r\n\r\n``` java\r\npublic class Graph {\r\n // @return the number of vertices\r\n public int V() { }\r\n\r\n // @return the number of edges\r\n public int E() { }\r\n\r\n // Add edge v-w to this graph\r\n public void addEdge(int v, int w) { }\r\n\r\n // @return the vertices adjacent to v\r\n public Iterable adj(int v) { }\r\n\r\n // @return a string representation\r\n public String toString() { }\r\n}\r\n```\r\n\r\n**Note:** The following questions will ask you to implement the function\r\nleft out. You don't need to put the brackets (`{ }`) surrounding the\r\nfunction body in your answer.\r\n", + "description": "

Consider this class, DepthFirstPaths, that computes paths to any connected node from a source node s in an undirected graph.

\r\n
// TODO\r\n\r\npublic class DepthFirstPaths {\r\n    private boolean[] marked; // marked[v] = is there an s-v path?\r\n    private int[] edgeTo;     // edgeTo[v] = last edge on s-v path\r\n    private final int s;\r\n\r\n    /**\r\n     * Computes a path between s and every other vertex in graph G\r\n     * @param G the graph\r\n     * @param s the source vertex\r\n     */\r\n     public DepthFirstPaths(Graph G, int s) {\r\n         this.s = s;\r\n         edgeTo = new int[G.V()];\r\n         marked = new boolean[G.V()];\r\n         dfs(G, s);\r\n     }\r\n\r\n     // Depth first search from v\r\n     private void dfs(Graph G, int v) {\r\n         // TODO\r\n     }\r\n\r\n     /**\r\n      * Is there a path between the source s and vertex v?\r\n      * @param v the vertex\r\n      * @return true if there is a path, false otherwise\r\n      */\r\n     public boolean hasPathTo(int v) {\r\n         // TODO\r\n     }\r\n\r\n     /**\r\n      * Returns a path between the source vertex s and vertex v, or\r\n      * null if no such path\r\n      * @param v the vertex\r\n      * @return the sequence of vertices on a path between the source vertex\r\n      *         s and vertex v, as an Iterable\r\n      */\r\n     public Iterable<Integer> pathTo(int v) {\r\n         // TODO\r\n     }\r\n}
\r\n

The class Graph is already implemented. Here is its specification:

\r\n
public class Graph {\r\n    // @return the number of vertices\r\n    public int V() { }\r\n\r\n    // @return the number of edges\r\n    public int E() { }\r\n\r\n    // Add edge v-w to this graph\r\n    public void addEdge(int v, int w) { }\r\n\r\n    // @return the vertices adjacent to v\r\n    public Iterable<Integer> adj(int v) { }\r\n\r\n    // @return a string representation\r\n    public String toString() { }\r\n}
\r\n

Note: The following questions will ask you to implement the function left out. You don't need to put the brackets ({ }) surrounding the function body in your answer.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2455,7 +2455,7 @@ }, { "title": "Heap", - "description": "Consider the `Heap` data structure in which we progressively add\r\nnumbers.\r\n\r\nThe following questions will ask you to write a representation of the\r\n`Heap` as we add objects in it. You must write the `Heap` as if it was\r\nstored in an array. For example, if your answer is:\r\n\r\n 9\r\n / \\\r\n 5 8\r\n / \\\r\n 4 3\r\n\r\nYou would write:\r\n\r\n 9 5 8 4 3\r\n", + "description": "

Consider the Heap data structure in which we progressively add numbers.

\r\n

The following questions will ask you to write a representation of the Heap as we add objects in it. You must write the Heap as if it was stored in an array. For example, if your answer is:

\r\n
9\r\n/ \\\r\n5   8\r\n/ \\\r\n4   3
\r\n

You would write:

\r\n
9 5 8 4 3
\r\n", "tags": [ { "text": "INGINIOUS", @@ -2504,7 +2504,7 @@ }, { "title": "Merge Sort", - "description": "Consider the (top-down) sorting algorithm `Merge Sort`\r\n\r\n``` java\r\npublic class MergeSort {\r\n /**\r\n * Pre-conditions: a[lo..mid] and a[mid+1..hi] are sorted\r\n * Post-conditions: a[lo..hi] is sorted\r\n */\r\n private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {\r\n for (int k = lo; k <= hi; k++) {\r\n aux[k] = a[k];\r\n }\r\n\r\n int i = lo;\r\n int j = mid + 1;\r\n for (int k = lo; k <= hi; k++) {\r\n if (i > mid) {\r\n a[k] = aux[j++];\r\n } else if (j > hi) {\r\n a[k] = aux[i++];\r\n } else if (aux[j].compareTo(aux[i]) < 0) {\r\n a[k] = aux[j++];\r\n } else {\r\n a[k] = aux[i++];\r\n }\r\n }\r\n }\r\n\r\n // Mergesort a[lo..hi] using auxiliary array aux[lo..hi]\r\n private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {\r\n // TODO\r\n }\r\n\r\n /**\r\n * Rearranges the array in ascending order, using the natural order\r\n */\r\n public static void sort(Comparable[] a) {\r\n // TODO\r\n }\r\n}\r\n```\r\n\r\n**Note:** The following questions will ask you to implement the function\r\nleft out. You don't need to put the brackets (`{ }`) surrounding the\r\nfunction body in your answer.\r\n", + "description": "

Consider the (top-down) sorting algorithm Merge Sort

\r\n
public class MergeSort {\r\n    /**\r\n     * Pre-conditions: a[lo..mid] and a[mid+1..hi] are sorted\r\n     * Post-conditions: a[lo..hi] is sorted\r\n     */\r\n    private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {\r\n        for (int k = lo; k <= hi; k++) {\r\n            aux[k] = a[k];\r\n        }\r\n\r\n        int i = lo;\r\n        int j = mid + 1;\r\n        for (int k = lo; k <= hi; k++) {\r\n            if (i > mid) {\r\n                a[k] = aux[j++];\r\n            } else if (j > hi) {\r\n                a[k] = aux[i++];\r\n            } else if (aux[j].compareTo(aux[i]) < 0) {\r\n                a[k] = aux[j++];\r\n            } else {\r\n                a[k] = aux[i++];\r\n            }\r\n        }\r\n    }\r\n\r\n    // Mergesort a[lo..hi] using auxiliary array aux[lo..hi]\r\n    private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {\r\n        // TODO\r\n    }\r\n\r\n    /**\r\n     * Rearranges the array in ascending order, using the natural order\r\n     */\r\n    public static void sort(Comparable[] a) {\r\n        // TODO\r\n    }\r\n}
\r\n

Note: The following questions will ask you to implement the function left out. You don't need to put the brackets ({ }) surrounding the function body in your answer.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2558,7 +2558,7 @@ }, { "title": "Red Black Tree", - "description": "Consider an empty `Red-Black Tree` in which we progressively add\r\nnumbers.\r\n\r\nThe following questions will ask you to write a representation of the\r\n`Red-Black Tree` as we add objects in it. Write it as if you were\r\nreading from left to right and from top to bottom (ignoring the possible\r\nblanks). For example, if your answer is:\r\n\r\n 6\r\n / \\\r\n (2 4) 7\r\n / | \\ \\\r\n 1 3 5 9\r\n\r\nYou would write:\r\n\r\n 6 24 7 1 3 5 9\r\n\r\nNotice how the 2-3 node composed of `2` and `4` is written in a merged\r\nway (`24`).\r\n", + "description": "

Consider an empty Red-Black Tree in which we progressively add numbers.

\r\n

The following questions will ask you to write a representation of the Red-Black Tree as we add objects in it. Write it as if you were reading from left to right and from top to bottom (ignoring the possible blanks). For example, if your answer is:

\r\n
6\r\n/   \\\r\n(2 4)   7\r\n/ | \\    \\\r\n1  3  5    9
\r\n

You would write:

\r\n
6 24 7 1 3 5 9
\r\n

Notice how the 2-3 node composed of 2 and 4 is written in a merged way (24).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2607,7 +2607,7 @@ }, { "title": "QCM Binary Trees", - "description": "Consider this ordered binary tree:\r\n\r\n 4\r\n / \\\r\n 2 5\r\n / \\ / \\\r\n 1 3 6 7\r\n\r\nWe traverse this tree and we print the value of each node we visit it.\r\n", + "description": "

Consider this ordered binary tree:

\r\n
4\r\n/   \\\r\n2       5\r\n/ \\     / \\\r\n1   3   6   7
\r\n

We traverse this tree and we print the value of each node we visit it.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2656,7 +2656,7 @@ }, { "title": "Union find", - "description": "Consider a graph made of 10 disjoint nodes (numbered from 0 to 9). We\r\nuse a union-find data structure to represent this graph. At first, each\r\nnode is contained in a partition named after the node. Thus, the\r\nrepresentation of the graph in the array `id[]` is:\r\n\r\n 0 1 2 3 4 5 6 7 8 9\r\n\r\nThe following questions will ask you to type the representation of the\r\ngraph after we use the **quick-find** algorithm to add an edge between 2\r\nnodes. You must type this representation in the same way it was typed\r\nabove.\r\n\r\n**Note:** When we join `p-q` with the quick-find algorithm, the\r\nconvention is to change `id[p]` (and potentially other entries) but not\r\n`id[q]`.\r\n", + "description": "

Consider a graph made of 10 disjoint nodes (numbered from 0 to 9). We use a union-find data structure to represent this graph. At first, each node is contained in a partition named after the node. Thus, the representation of the graph in the array id[] is:

\r\n
0 1 2 3 4 5 6 7 8 9
\r\n

The following questions will ask you to type the representation of the graph after we use the quick-find algorithm to add an edge between 2 nodes. You must type this representation in the same way it was typed above.

\r\n

Note: When we join p-q with the quick-find algorithm, the convention is to change id[p] (and potentially other entries) but not id[q].

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2705,7 +2705,7 @@ }, { "title": "Binary Search Tree", - "description": "Etant donné un arbre de recherche binaire, dont les noeuds implémentent\r\nl'interface Node:\r\n\r\n``` java\r\ninterface Node {\r\n /**\r\n * @return la valeur contenue dans ce noeud\r\n */\r\n int getValue();\r\n\r\n /**\r\n * @return Le noeud situe a gauche (dont la valeur est < que la valeur actuelle) s'il existe, null sinon\r\n */\r\n Node getLeft();\r\n\r\n /**\r\n * @return Le noeud situe a droite (dont la valeur est > que la valeur actuelle) s'il existe, null sinon\r\n */\r\n Node getRight();\r\n}\r\n```\r\n\r\nL'on vous demande de fournir le **corps** de la fonction *ceil*, qui\r\ntrouve dans l'arbre le plus petit élément plus grand ou égal à value (donc soit l'élément lui-même soit\r\nl'élément situé directement après par ordre de grandeur). Si un tel\r\nélément n'existe pas, elle doit retourner null.\r\n\r\n[Un projet Eclipse contenant des tests basiques vous est fourni en\r\ncliquant sur ce\r\nlien.](https://inginious.info.ucl.ac.be/course/LSINF1121-2016/whiteexam2016bst/project.zip)\r\n", + "description": "

Etant donné un arbre de recherche binaire, dont les noeuds implémentent l'interface Node:

\r\n
interface Node {\r\n    /**\r\n      * @return la valeur contenue dans ce noeud\r\n      */\r\n    int getValue();\r\n\r\n    /**\r\n     * @return Le noeud situe a gauche (dont la valeur est < que la valeur actuelle) s'il existe, null sinon\r\n     */\r\n    Node getLeft();\r\n\r\n    /**\r\n      * @return Le noeud situe a droite (dont la valeur est > que la valeur actuelle) s'il existe, null sinon\r\n      */\r\n    Node getRight();\r\n}
\r\n

L'on vous demande de fournir le corps de la fonction ceil, qui trouve dans l'arbre le plus petit élément plus grand ou égal à value (donc soit l'élément lui-même soit l'élément situé directement après par ordre de grandeur). Si un tel élément n'existe pas, elle doit retourner null.

\r\n

Un projet Eclipse contenant des tests basiques vous est fourni en cliquant sur ce lien.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2812,6 +2812,6 @@ "1": "Misconception", "2": "autres" }, - "extraction_date": "2019-12-18T16:15:13.840Z", + "extraction_date": "2020-03-04T17:50:17.245Z", "url": "https://github.com/UCL-INGI/LSINF1121-Data-Structures-And-Algorithms" } \ No newline at end of file diff --git a/results/results5.json b/results/results5.json index 28309bc..18beb93 100644 --- a/results/results5.json +++ b/results/results5.json @@ -838,7 +838,7 @@ }, { "title": "Exercice 1", - "description": "Utilise le bloc\r\n\r\n> \"image\"\r\n\r\npour faire avancer le zombie d'un pas.\r\n", + "description": "
\r\n
\r\n

Utilise le bloc

\r\n
\r\n

\"image\"

\r\n
\r\n

pour faire avancer le zombie d'un pas.

\r\n
\r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -894,7 +894,7 @@ }, { "title": "Exercice 2", - "description": "\"image\"\r\n\r\n**Amène le zombie vers le tournesol, mais évite la plante carnivore !**\r\n", + "description": "

\"image\"

\r\n

Amène le zombie vers le tournesol, mais évite la plante carnivore !

\r\n", "tags": [ { "text": "INGINIOUS", @@ -950,7 +950,7 @@ }, { "title": "Exercice 3", - "description": "\"image\"\r\n\r\n**Devoir... atteindre... tournesol.**\r\n", + "description": "

\"image\"

\r\n

Devoir... atteindre... tournesol.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1002,7 +1002,7 @@ }, { "title": "Exercice 4", - "description": "Essaie le bloc « Répéter » pour utiliser moins de blocs...\r\n", + "description": "

Essaie le bloc « Répéter » pour utiliser moins de blocs...

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1058,7 +1058,7 @@ }, { "title": "Exercice 5", - "description": "\"image\"\r\n\r\n**Peux-tu résoudre cette énigme en utilisant le moins de blocs possible\r\n?**\r\n", + "description": "

\"image\"

\r\n

Peux-tu résoudre cette énigme en utilisant le moins de blocs possible ?

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1114,7 +1114,7 @@ }, { "title": "Exercice 6", - "description": "\"image\"\r\n\r\n**Chère personne. Moi zombie. Devoir... atteindre... tournesol.**\r\n", + "description": "

\"image\"

\r\n

Chère personne. Moi zombie. Devoir... atteindre... tournesol.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1170,7 +1170,7 @@ }, { "title": "Exercice 7", - "description": "\"image\"\r\n\r\n**Utilise le bloc « Répéter » pour amener le zombie au tournesol. (Évite\r\nles plantes carnivores!)**\r\n", + "description": "

\"image\"

\r\n

Utilise le bloc « Répéter » pour amener le zombie au tournesol. (Évite les plantes carnivores!)

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1226,7 +1226,7 @@ }, { "title": "Exercice 8", - "description": "Cette fois, utilise la boucle \"répéter jusqu'à\".\r\n\r\nAttention, ton code doit être capable de traverser autant de cases que\r\nnécéssaire jusqu'à la plante !\r\n", + "description": "

Cette fois, utilise la boucle \"répéter jusqu'à\".

\r\n

Attention, ton code doit être capable de traverser autant de cases que nécéssaire jusqu'à la plante !

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1286,7 +1286,7 @@ }, { "title": "Exercice 9", - "description": "\"image\"\r\n\r\n**Peux-tu rejoindre le tournesol en utilisant uniquement quatre blocs\r\n?**\r\n", + "description": "

\"image\"

\r\n

Peux-tu rejoindre le tournesol en utilisant uniquement quatre blocs ?

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1342,7 +1342,7 @@ }, { "title": "Exercice 10", - "description": "\"image\"\r\n\r\n**Peux-tu aller au tournesol en utilisant uniquement six blocs?**\r\n", + "description": "

\"image\"

\r\n

Peux-tu aller au tournesol en utilisant uniquement six blocs?

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1398,7 +1398,7 @@ }, { "title": "Exercice 11", - "description": "\"image\"\r\n\r\n**OK, c'est légèrement différent. Peux-tu le faire en seulement six\r\nblocs ?**\r\n", + "description": "

\"image\"

\r\n

OK, c'est légèrement différent. Peux-tu le faire en seulement six blocs ?

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1454,7 +1454,7 @@ }, { "title": "Exercice 1", - "description": "Termine le code pour dessiner ces triangles. Le code pour dessiner un\r\ntriangle est déjà fait pour toi. Indice : les 3 triangles sont dans une\r\nrotation de 360 degrés.\r\n", + "description": "

Termine le code pour dessiner ces triangles. Le code pour dessiner un triangle est déjà fait pour toi. Indice : les 3 triangles sont dans une rotation de 360 degrés.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1506,7 +1506,7 @@ }, { "title": "Exercice 2", - "description": "Maintenant imbrique cette boucle à l'intérieur d'une autre boucle pour\r\ndessiner 10 triangles. C'est ce qu'on appelle une boucle imbriquée.\r\nIndice : les 10 triangles sont toujours dans une rotation de 360 degrés.\r\n", + "description": "

Maintenant imbrique cette boucle à l'intérieur d'une autre boucle pour dessiner 10 triangles. C'est ce qu'on appelle une boucle imbriquée. Indice : les 10 triangles sont toujours dans une rotation de 360 degrés.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1558,7 +1558,7 @@ }, { "title": "Exercice 3", - "description": "Maintenant, crée un soleil avec le code d'un petit triangle, en\r\nutilisant une boucle imbriquée.\r\n", + "description": "

Maintenant, crée un soleil avec le code d'un petit triangle, en utilisant une boucle imbriquée.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1610,7 +1610,7 @@ }, { "title": "Exercice 4", - "description": "Boucle ce dessin 6 fois. De combien as-tu besoin de tourner à chaque\r\nfois ?\r\n\r\nIndice : Combien font 360 divisé par 6 ?\r\n", + "description": "

Boucle ce dessin 6 fois. De combien as-tu besoin de tourner à chaque fois ?

\r\n

Indice : Combien font 360 divisé par 6 ?

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1662,7 +1662,7 @@ }, { "title": "Exercice 5", - "description": "Dessine ces 36 triangles avec une boucle imbriquée\r\n", + "description": "

Dessine ces 36 triangles avec une boucle imbriquée

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1714,7 +1714,7 @@ }, { "title": "Exercice 1", - "description": "Utilise une boucle pour recueillir tout le nectar.\r\n", + "description": "

Utilise une boucle pour recueillir tout le nectar.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1766,7 +1766,7 @@ }, { "title": "Exercice 2", - "description": "Recueille tout le nectar de chaque fleur. Utilise une boucle imbriquée.\r\n", + "description": "

Recueille tout le nectar de chaque fleur. Utilise une boucle imbriquée.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1822,7 +1822,7 @@ }, { "title": "Exercice 3", - "description": "Recueille tout le nectar à l’aide d’une boucle imbriquée.\r\n", + "description": "

Recueille tout le nectar à l’aide d’une boucle imbriquée.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1878,7 +1878,7 @@ }, { "title": "Exercice 4", - "description": "Ces fleurs pourpres ont une quantité inconnue de nectar. Utilise une\r\nboucle «Tant que nectar» pour recueillir tout le nectar. Cette boucle\r\ns'exécutera tant que la condition est vraie, dans ce cas «Nectar >\r\n0».\r\n", + "description": "

Ces fleurs pourpres ont une quantité inconnue de nectar. Utilise une boucle «Tant que nectar» pour recueillir tout le nectar. Cette boucle s'exécutera tant que la condition est vraie, dans ce cas «Nectar > 0».

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1938,7 +1938,7 @@ }, { "title": "Exercice 5", - "description": "Mets cette boucle dans une autre boucle pour créer une boucle imbriquée\r\net recueillir tout le nectar des fleurs.\r\n", + "description": "

Mets cette boucle dans une autre boucle pour créer une boucle imbriquée et recueillir tout le nectar des fleurs.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -1998,7 +1998,7 @@ }, { "title": "Exercice 6", - "description": "Recueille tout le nectar de ces fleurs en imbriquant une boucle « Tant\r\nque » à l'intérieur d’un bloc « Répéter ».\r\n", + "description": "

Recueille tout le nectar de ces fleurs en imbriquant une boucle « Tant que » à l'intérieur d’un bloc « Répéter ».

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2058,7 +2058,7 @@ }, { "title": "Exercice 7", - "description": "Recueille tout le nectar et fabrique tout le miel en utilisant des\r\nboucles.\r\n", + "description": "

Recueille tout le nectar et fabrique tout le miel en utilisant des boucles.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2118,7 +2118,7 @@ }, { "title": "Exercice 1", - "description": "Termine de dessiner la boîte. (Chaque ligne a une longueur de 250\r\npixels)\r\n", + "description": "

Termine de dessiner la boîte. (Chaque ligne a une longueur de 250 pixels)

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2174,7 +2174,7 @@ }, { "title": "Exercice 2", - "description": "Ce parterre de fleurs rectangulaire a un périmètre de 600 pixels. Le\r\ncôté le plus long a une longueur de 200 pixels. Dessine le rectangle.\r\nRemarque : Tu ne dois pas repasser sur les lignes des fleurs, uniquement\r\ndessiner le rectangle\r\n", + "description": "

Ce parterre de fleurs rectangulaire a un périmètre de 600 pixels. Le côté le plus long a une longueur de 200 pixels. Dessine le rectangle. Remarque : Tu ne dois pas repasser sur les lignes des fleurs, uniquement dessiner le rectangle

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2230,7 +2230,7 @@ }, { "title": "Exercice 3", - "description": "Essaie le code qui est déjà présent pour comprendre ce qu'il fait.\r\nEnsuite, complète-le pour résoudre l'exercice.\r\n", + "description": "

Essaie le code qui est déjà présent pour comprendre ce qu'il fait. Ensuite, complète-le pour résoudre l'exercice.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2286,7 +2286,7 @@ }, { "title": "Exercice 4", - "description": "Combien y a-t-il de degrés dans un cercle ? Utilise un boucle pour\r\ncompléter le dessin\r\n", + "description": "

Combien y a-t-il de degrés dans un cercle ? Utilise un boucle pour compléter le dessin

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2342,7 +2342,7 @@ }, { "title": "Exercice 5", - "description": "Quel angle doit-tu utiliser ?\r\n", + "description": "

Quel angle doit-tu utiliser ?

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2398,7 +2398,7 @@ }, { "title": "Exercice 6", - "description": "La ligne médiane d’un terrain de football est perpendiculaire à ses\r\nlignes de touche. Ce terrain a un périmètre de 800 pixels et il est long\r\nde 240 pixels. Quelle est sa largeur ? Trace les limites et la ligne\r\nmédiane.\r\n", + "description": "

La ligne médiane d’un terrain de football est perpendiculaire à ses lignes de touche. Ce terrain a un périmètre de 800 pixels et il est long de 240 pixels. Quelle est sa largeur ? Trace les limites et la ligne médiane.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2454,7 +2454,7 @@ }, { "title": "Exercice 7", - "description": "Dessine l'autre moitié pour que le dessin soit symétrique. Les triangles\r\nsont équilatéraux et mesurent 50 pixels de long.\r\n", + "description": "

Dessine l'autre moitié pour que le dessin soit symétrique. Les triangles sont équilatéraux et mesurent 50 pixels de long.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2514,7 +2514,7 @@ }, { "title": "Exercice 8", - "description": "Complète les lignes vertes. Les lignes ont 250 pixels de long et sont à\r\n15 pixels l’une de l’autre.\r\n", + "description": "

Complète les lignes vertes. Les lignes ont 250 pixels de long et sont à 15 pixels l’une de l’autre.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2570,7 +2570,7 @@ }, { "title": "Exercice 9", - "description": "Dessin libre ! Tu peux appuyer sur le bouton vert pour regarder le\r\nrésultat et soumettre la tâche pour sauvegarder tes dessins.\r\n", + "description": "

Dessin libre ! Tu peux appuyer sur le bouton vert pour regarder le résultat et soumettre la tâche pour sauvegarder tes dessins.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2618,7 +2618,7 @@ }, { "title": "Exercice 1", - "description": "Dessine les verres carrés. Astuce : le pont entre les verres fait 25\r\npixels de moins que la longueur du carré.\r\n", + "description": "

Dessine les verres carrés. Astuce : le pont entre les verres fait 25 pixels de moins que la longueur du carré.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2674,7 +2674,7 @@ }, { "title": "Exercice 2", - "description": "Les fonctions te permettent de définir de nouveaux blocs ! Nous avons\r\ndéplacé les blocs pour dessiner un carré dans une fonction appelée\r\n«Dessiner un carré». Peut-tu utiliser la fonction «Dessiner un carré»\r\npour créer les lunettes ? Les carrés sont toujours à 50 pixels l'un de\r\nl'autre.\r\n", + "description": "

Les fonctions te permettent de définir de nouveaux blocs ! Nous avons déplacé les blocs pour dessiner un carré dans une fonction appelée «Dessiner un carré». Peut-tu utiliser la fonction «Dessiner un carré» pour créer les lunettes ? Les carrés sont toujours à 50 pixels l'un de l'autre.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2734,7 +2734,7 @@ }, { "title": "Exercice 3", - "description": "Utilise le bloc \"répéter\" pour dessiner trois carrés\r\n", + "description": "

Utilise le bloc \"répéter\" pour dessiner trois carrés

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2794,7 +2794,7 @@ }, { "title": "Exercice 4", - "description": "Nous avons renommé la fonction «Dessiner un carré» en «Dessiner un\r\nhexagone», mais elle ne dessine encore que des carrés ! Peux-tu modifier\r\nla fonction «Dessine un hexagone» pour dessiner un hexagone avec des\r\ncôtés de 50 pixels et dessiner l'image en utilisant la fonction ?\r\n", + "description": "

Nous avons renommé la fonction «Dessiner un carré» en «Dessiner un hexagone», mais elle ne dessine encore que des carrés ! Peux-tu modifier la fonction «Dessine un hexagone» pour dessiner un hexagone avec des côtés de 50 pixels et dessiner l'image en utilisant la fonction ?

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2858,7 +2858,7 @@ }, { "title": "Exercice 5", - "description": "Les fonctions sont vraiment très biens pour dessiner des choses\r\ncomplexes plusieurs fois. Peux-tu utiliser la fonction «Dessiner une\r\nfleur» pour remplir le reste du parterre ? (Indice : les plantes sont\r\nséparées les unes des autres d’une longueur de 100 pixels)\r\n", + "description": "

Les fonctions sont vraiment très biens pour dessiner des choses complexes plusieurs fois. Peux-tu utiliser la fonction «Dessiner une fleur» pour remplir le reste du parterre ? (Indice : les plantes sont séparées les unes des autres d’une longueur de 100 pixels)

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2918,7 +2918,7 @@ }, { "title": "Exercice 1", - "description": "Récolte tout le nectar de chaque fleur.\r\n", + "description": "

Récolte tout le nectar de chaque fleur.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -2970,7 +2970,7 @@ }, { "title": "Exercice 2", - "description": "Les fonctions sont des blocs de code qui effectuent une tâche. Utilise\r\nla fonction « Obtenir 5 » pour obtenir 5 nectars à la fois. Veille\r\négalement à utiliser une boucle pour obtenir un compte de bloc idéal.\r\n", + "description": "

Les fonctions sont des blocs de code qui effectuent une tâche. Utilise la fonction « Obtenir 5 » pour obtenir 5 nectars à la fois. Veille également à utiliser une boucle pour obtenir un compte de bloc idéal.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3026,7 +3026,7 @@ }, { "title": "Exercice 3", - "description": "La fonction «Déplacer et obtenir le nectar» déplace l'abeille, recueille\r\nle nectar et renvoie l'abeille là où elle a commencé. Utilise-la pour\r\nrécolter tout le nectar.\r\n", + "description": "

La fonction «Déplacer et obtenir le nectar» déplace l'abeille, recueille le nectar et renvoie l'abeille là où elle a commencé. Utilise-la pour récolter tout le nectar.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3082,7 +3082,7 @@ }, { "title": "Exercice 4", - "description": "Il y a maintenant davantage de nectar dans les fleurs. Modifie la\r\nfonction donnée afin qu'elle recueille 4 nectars et utilise-la pour\r\nrecueillir l'ensemble du nectar de la fleur.\r\n", + "description": "

Il y a maintenant davantage de nectar dans les fleurs. Modifie la fonction donnée afin qu'elle recueille 4 nectars et utilise-la pour recueillir l'ensemble du nectar de la fleur.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3138,7 +3138,7 @@ }, { "title": "Exercice 5", - "description": "Crée ta propre fonction qui obtiendra 7 nectars, se déplacera vers\r\nl'avant et fera 7 unités de miel. Utilise la fonction pour recueillir le\r\nnectar de chaque fleur et fabriquer du miel dans chaque gâteau de miel.\r\n", + "description": "

Crée ta propre fonction qui obtiendra 7 nectars, se déplacera vers l'avant et fera 7 unités de miel. Utilise la fonction pour recueillir le nectar de chaque fleur et fabriquer du miel dans chaque gâteau de miel.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3198,7 +3198,7 @@ }, { "title": "Exercice 6", - "description": "Les fleurs pourpres peuvent avoir 1 ou 0 nectar. Crée une fonction qui\r\nrécolte du nectar seulement sur les fleurs pourpres qui en ont.\r\n", + "description": "

Les fleurs pourpres peuvent avoir 1 ou 0 nectar. Crée une fonction qui récolte du nectar seulement sur les fleurs pourpres qui en ont.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3262,7 +3262,7 @@ }, { "title": "Exercice 1", - "description": "L'abeille ne peut pas savoir ce qui se trouve sous le nuage. Recueille\r\nle nectar seulement sur les fleurs, mais vérifie d'abord si c'est une\r\nfleur ou un gâteau de miel.\r\n", + "description": "

L'abeille ne peut pas savoir ce qui se trouve sous le nuage. Recueille le nectar seulement sur les fleurs, mais vérifie d'abord si c'est une fleur ou un gâteau de miel.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3318,7 +3318,7 @@ }, { "title": "Exercice 2", - "description": "L'abeille veut seulement du nectar. Tous les objets ne sont pas des\r\nfleurs, alors vérifie sous CHAQUE NUAGE pour voir s’il s’y cache une\r\nfleur. Si c'est le cas, alors tu peux recueillir du nectar.\r\n", + "description": "

L'abeille veut seulement du nectar. Tous les objets ne sont pas des fleurs, alors vérifie sous CHAQUE NUAGE pour voir s’il s’y cache une fleur. Si c'est le cas, alors tu peux recueillir du nectar.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3374,7 +3374,7 @@ }, { "title": "Exercice 3", - "description": "L'objet inconnu est soit une fleur, soit un gâteau de miel. Utilise le\r\nbloc «Si/Sinon» pour récupérer le nectar si c'est une fleur, ou pour\r\nfabriquer du miel (parce que c'est un gâteau de miel).\r\n", + "description": "

L'objet inconnu est soit une fleur, soit un gâteau de miel. Utilise le bloc «Si/Sinon» pour récupérer le nectar si c'est une fleur, ou pour fabriquer du miel (parce que c'est un gâteau de miel).

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3434,7 +3434,7 @@ }, { "title": "Exercice 4", - "description": "Cette fleur pourpre peut avoir 3, 2 ou 1 nectar(s). Tu vas de nouveau\r\navoir besoin du bloc \"si\" et d'une boucle. Tous les éléments sont sur le\r\nplan de travail, mais pas emboîtés !\r\n", + "description": "

Cette fleur pourpre peut avoir 3, 2 ou 1 nectar(s). Tu vas de nouveau avoir besoin du bloc \"si\" et d'une boucle. Tous les éléments sont sur le plan de travail, mais pas emboîtés !

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3494,7 +3494,7 @@ }, { "title": "Exercice 5", - "description": "Écris à l'intérieur de la fonction «Vérifier la fleur et fabriquer du\r\nmiel». Ta fonction doit vérifier si la fleur pourpre a 1, 2 ou 3 nectars\r\net recueillir l'ensemble du nectar. Ensuite, avance et fabrique du miel.\r\n", + "description": "

Écris à l'intérieur de la fonction «Vérifier la fleur et fabriquer du miel». Ta fonction doit vérifier si la fleur pourpre a 1, 2 ou 3 nectars et recueillir l'ensemble du nectar. Ensuite, avance et fabrique du miel.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3554,7 +3554,7 @@ }, { "title": "Exercice 1", - "description": "Utilise le bloc « Répéter jusqu'à » pour amener le zombie au tournesol.\r\n", + "description": "

Utilise le bloc « Répéter jusqu'à » pour amener le zombie au tournesol.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3606,7 +3606,7 @@ }, { "title": "Exercice 2", - "description": "Utilise le bloc « Si » pour me laisser décider quand tourner. Indice:\r\nici, tu n’as besoin que d'un bloc supplémentaire, mais regarde bien\r\ncomment nous avons fait afin de pouvoir le faire toi-même la prochaine\r\nfois.\r\n", + "description": "

Utilise le bloc « Si » pour me laisser décider quand tourner. Indice: ici, tu n’as besoin que d'un bloc supplémentaire, mais regarde bien comment nous avons fait afin de pouvoir le faire toi-même la prochaine fois.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3662,7 +3662,7 @@ }, { "title": "Exercice 3", - "description": "Même chose que le puzzle précédent, mais tu dois te rappeler comment tu\r\nas utilisé le bloc «Si» et le bloc « Répéter » ensemble.\r\n", + "description": "

Même chose que le puzzle précédent, mais tu dois te rappeler comment tu as utilisé le bloc «Si» et le bloc « Répéter » ensemble.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3718,7 +3718,7 @@ }, { "title": "Exercice 4", - "description": "Utilise le bloc \"si chemin\" encore une fois pour t'entraîner - ce n'est\r\npas très différent, mais attention aux plantes carnivores!\r\n", + "description": "

Utilise le bloc \"si chemin\" encore une fois pour t'entraîner - ce n'est pas très différent, mais attention aux plantes carnivores!

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3774,7 +3774,7 @@ }, { "title": "Exercice 5", - "description": "Le blocs « Si/Sinon » vérifie une condition et puis fait une chose OU\r\nune autre. Pour amener le personnage au tournesol, essaie d'utiliser ce\r\nnouveau bloc.\r\n", + "description": "

Le blocs « Si/Sinon » vérifie une condition et puis fait une chose OU une autre. Pour amener le personnage au tournesol, essaie d'utiliser ce nouveau bloc.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3830,7 +3830,7 @@ }, { "title": "Exercice 6", - "description": "Voici un autre exercice avec le bloc « Si/Sinon », sans aide cette fois\r\n!\r\n", + "description": "

Voici un autre exercice avec le bloc « Si/Sinon », sans aide cette fois !

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3886,7 +3886,7 @@ }, { "title": "Exercice 7", - "description": "Peux tu rajouter juste 3 blocs pour aider le zombie à résoudre un\r\nlabyrinthe plus complexe ?\r\n\r\nSi tu le fais bien, il peut parcourir n'importe quel chemin sinueux peu\r\nimporte la longueur!\r\n", + "description": "

Peux tu rajouter juste 3 blocs pour aider le zombie à résoudre un labyrinthe plus complexe ?

\r\n

Si tu le fais bien, il peut parcourir n'importe quel chemin sinueux peu importe la longueur!

\r\n", "tags": [ { "text": "INGINIOUS", @@ -3986,7 +3986,7 @@ }, { "title": "1. Le plus léger (blocs normaux)", - "description": "Avant de trier toute une liste, attaquons-nous à un problème plus simple\r\n: trouver le plus petit élément.\r\n\r\nPeux-tu créer un algorithme qui retourne le plus petit élément de la\r\nliste avec ces blocs ?\r\n\r\nAttention, souviens-toi bien que la liste ne sera pas dans l'ordre !\r\n", + "description": "

Avant de trier toute une liste, attaquons-nous à un problème plus simple : trouver le plus petit élément.

\r\n

Peux-tu créer un algorithme qui retourne le plus petit élément de la liste avec ces blocs ?

\r\n

Attention, souviens-toi bien que la liste ne sera pas dans l'ordre !

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4025,7 +4025,7 @@ }, { "title": "1. Le plus léger (blocs custom)", - "description": "Avant de trier toute une liste, attaquons-nous à un problème plus simple\r\n: trouver le plus petit élément.\r\n\r\nPeux-tu créer un algorithme qui retourne le plus petit élément de la\r\nliste avec ces blocs ?\r\n\r\nAttention, souviens-toi bien que la liste ne sera pas dans l'ordre ! Tu\r\npeux appuyer sur le bouton vert en haut à gauche pour voir ce que tu\r\ncode fait : la bouteille A est en rouge et la B en bleu. Est-ce que la\r\nplus petite valeur est bien en rouge à la fin de l'animation ?\r\n", + "description": "

Avant de trier toute une liste, attaquons-nous à un problème plus simple : trouver le plus petit élément.

\r\n

Peux-tu créer un algorithme qui retourne le plus petit élément de la liste avec ces blocs ?

\r\n

Attention, souviens-toi bien que la liste ne sera pas dans l'ordre ! Tu peux appuyer sur le bouton vert en haut à gauche pour voir ce que tu code fait : la bouteille A est en rouge et la B en bleu. Est-ce que la plus petite valeur est bien en rouge à la fin de l'animation ?

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4069,7 +4069,7 @@ }, { "title": "2. Questions - le plus léger", - "description": "Peux-tu compter les comparaisons nécéssaires pour trouver les éléments\r\nles plus légers des listes suivantes ?\r\n\r\nAttention, souviens-toi que l'ordinateur ne peut pas se rendre compte\r\nqu'il a l'élément le plus léger avant de les avoir tous examinés !\r\n", + "description": "

Peux-tu compter les comparaisons nécéssaires pour trouver les éléments les plus légers des listes suivantes ?

\r\n

Attention, souviens-toi que l'ordinateur ne peut pas se rendre compte qu'il a l'élément le plus léger avant de les avoir tous examinés !

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4108,7 +4108,7 @@ }, { "title": "3. Tri par sélection", - "description": "Maintenant, utilise l'algorithme *le\\_plus\\_léger* (il est déjà fait\r\npour toi) pour trier la liste par sélection.\r\n\r\nTu peux cliquer sur le bouton vers à gauche pour voir une animation qui\r\ncorrespond à ce que fait le code : l'élément \"le plus léger jusqu'ici\"\r\nest en rouge, et celui qu'on compare, en bleu.\r\n\r\nUne fois que tu as l'élement le plus léger, place-le dans une nouvelle\r\nliste et recommence.\r\n", + "description": "

Maintenant, utilise l'algorithme le_plus_léger (il est déjà fait pour toi) pour trier la liste par sélection.

\r\n

Tu peux cliquer sur le bouton vers à gauche pour voir une animation qui correspond à ce que fait le code : l'élément \"le plus léger jusqu'ici\" est en rouge, et celui qu'on compare, en bleu.

\r\n

Une fois que tu as l'élement le plus léger, place-le dans une nouvelle liste et recommence.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4152,7 +4152,7 @@ }, { "title": "4. Questions - tri par sélection", - "description": "Maintenant, peux-tu compter les comparaisons nécéssaires pour trier en\r\nentier les listes suivantes ?\r\n", + "description": "

Maintenant, peux-tu compter les comparaisons nécéssaires pour trier en entier les listes suivantes ?

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4191,7 +4191,7 @@ }, { "title": "7. Tri par insertion", - "description": "Le tri par insertion est celui que tu fais naturellement si tu trie un\r\npaquet de carte : tu prends les cartes une à une et les mets à leur\r\nplace.\r\n\r\nRegarde l'animation et compte les comparaisons. Est-ce mieux ou moins\r\nbien que le tri par sélection ? Est-ce que le nombre de comparaison est\r\ntoujours le même ?\r\n", + "description": "

Le tri par insertion est celui que tu fais naturellement si tu trie un paquet de carte : tu prends les cartes une à une et les mets à leur place.

\r\n

Regarde l'animation et compte les comparaisons. Est-ce mieux ou moins bien que le tri par sélection ? Est-ce que le nombre de comparaison est toujours le même ?

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4235,7 +4235,7 @@ }, { "title": "7.5 Tri par insertion - pire cas", - "description": "Ici, tu peux voir le pire cas du tri par insertion. Combien fait-il de\r\ncomparaisons ? Est-ce similaire au tri par sélection ?\r\n", + "description": "

Ici, tu peux voir le pire cas du tri par insertion. Combien fait-il de comparaisons ? Est-ce similaire au tri par sélection ?

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4279,7 +4279,7 @@ }, { "title": "Tri rapide", - "description": "Le tri rapide est un peu plus compliqué à comprendre, mais utilise un\r\nprincipe très courant en informatique : diviser pour mieux régner.\r\nPlutôt que d'essayer de trier toute la liste d'un coup, on prend un\r\nélément au hasard (le pivot), et on met les autres éléments avant s'ils\r\nsont plus petits, et après s'ils sont plus grands, sans ce soucier de\r\nleur ordre. Ensuite, on recommence avec un autre pivot, jusqu'à-ce que\r\nla liste soit triée.\r\n\r\nCette fois-ci, l'animation est un peu plus compliquée. Peut-tu compter\r\nles comparaisons ?\r\n", + "description": "

Le tri rapide est un peu plus compliqué à comprendre, mais utilise un principe très courant en informatique : diviser pour mieux régner. Plutôt que d'essayer de trier toute la liste d'un coup, on prend un élément au hasard (le pivot), et on met les autres éléments avant s'ils sont plus petits, et après s'ils sont plus grands, sans ce soucier de leur ordre. Ensuite, on recommence avec un autre pivot, jusqu'à-ce que la liste soit triée.

\r\n

Cette fois-ci, l'animation est un peu plus compliquée. Peut-tu compter les comparaisons ?

\r\n", "tags": [ { "text": "INGINIOUS", @@ -4327,6 +4327,6 @@ "1": "Misconception", "2": "autres" }, - "extraction_date": "2019-12-18T16:14:29.127Z", + "extraction_date": "2020-03-04T17:50:43.060Z", "url": "https://github.com/CelineDknp/JobBlockly" } \ No newline at end of file diff --git a/results/results6.json b/results/results6.json index d3cbeb6..7587920 100644 --- a/results/results6.json +++ b/results/results6.json @@ -2,7 +2,7 @@ "exercises": [ { "title": "Les conditions", - "description": "C'est fatiguant de devoir regarder l'arbre de décision pour chaque\r\ngâteau. Et si on faisait un programme qui peut déterminer si un gâteau a\r\nbien été fait selon l'arbre de décision ou pas? T'es partant ? Allons-y\r\n!\r\n\r\nPour rappel, l'arbre de décision ressemblait à ceci :\r\n\r\n> \"image\"\r\n\r\nUtilise les blocs pour programmer l'arbre de décision. Pour t'aider, on\r\na déjà mis les premiers blocs. Tu dois simplement déterminer les cas où\r\nle gâteau est valide.\r\n", + "description": "

C'est fatiguant de devoir regarder l'arbre de décision pour chaque gâteau. Et si on faisait un programme qui peut déterminer si un gâteau a bien été fait selon l'arbre de décision ou pas? T'es partant ? Allons-y !

\r\n

Pour rappel, l'arbre de décision ressemblait à ceci :

\r\n
\r\n

\"image\"

\r\n
\r\n

Utilise les blocs pour programmer l'arbre de décision. Pour t'aider, on a déjà mis les premiers blocs. Tu dois simplement déterminer les cas où le gâteau est valide.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -42,7 +42,7 @@ }, { "title": "Les brochettes de fruits", - "description": "C'est le moment d'être créatif ! Tu vas pouvoir créer tes propres\r\nbrochettes de fruits pour te régaler ! Fais attention, les pics à\r\nbrochette doivent contenir 7 morceaux de fruits, pas plus, pas moins.\r\nMais tu peux choisir ce que tu mets dessus.\r\n\r\nTu as beaucoup de blocs à ta disposition mais tu ne dois pas tous les\r\nutiliser. A toi de réfléchir aux blocs qui sont utiles ou non, mais\r\nn'oublie pas que le thème de la séance, c'est les boucles ;)\r\n\r\n**Attention** Chaque fois que tu veux créer une nouvelle brochette, tu\r\ndois recommencer un programme. Tu ne peux pas faire plusieurs brochettes\r\nen même temps.\r\n", + "description": "

C'est le moment d'être créatif ! Tu vas pouvoir créer tes propres brochettes de fruits pour te régaler ! Fais attention, les pics à brochette doivent contenir 7 morceaux de fruits, pas plus, pas moins. Mais tu peux choisir ce que tu mets dessus.

\r\n

Tu as beaucoup de blocs à ta disposition mais tu ne dois pas tous les utiliser. A toi de réfléchir aux blocs qui sont utiles ou non, mais n'oublie pas que le thème de la séance, c'est les boucles ;)

\r\n

Attention Chaque fois que tu veux créer une nouvelle brochette, tu dois recommencer un programme. Tu ne peux pas faire plusieurs brochettes en même temps.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -82,7 +82,7 @@ }, { "title": "La règle de trois", - "description": "Maintenant qu'on se rappelle du fonctionnement d'une règle de trois, il\r\nest temps de calculer les quantités nécessaires pour faire le gâteau\r\npour plus de 2 personnes. A toi de voir pour combien de personnes tu\r\nveux faire la recette.\r\n\r\n**Recette pour deux personnes**\r\n\r\n- 45gr de farine\r\n- 45gr de sucre\r\n- 45gr de beurre\r\n- 1 oeuf\r\n- 3gr de levure chimique\r\n", + "description": "

Maintenant qu'on se rappelle du fonctionnement d'une règle de trois, il est temps de calculer les quantités nécessaires pour faire le gâteau pour plus de 2 personnes. A toi de voir pour combien de personnes tu veux faire la recette.

\r\n

Recette pour deux personnes

\r\n
    \r\n
  • 45gr de farine
  • \r\n
  • 45gr de sucre
  • \r\n
  • 45gr de beurre
  • \r\n
  • 1 oeuf
  • \r\n
  • 3gr de levure chimique
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -122,7 +122,7 @@ }, { "title": "Initiation à INGInious", - "description": "Cet exercice est simple, mais il te permettra de comprendre comment\r\nfonctionne INGInious. Réorganise les différents blocs pour reformer la\r\nrecette de la tartine au chocolat. La recette est la suivante :\r\n\r\n- Ouvrir le sachet de pain\r\n- Prendre une tartine\r\n- Poser la tartine sur l'assiette\r\n- Ouvrir le pot de chocolat\r\n- Prendre le couteau\r\n- Tremper le couteau dans le chocolat\r\n- Tartiner le chocolat sur la tartine\r\n- Poser le couteau\r\n- Plier la tartine\r\n- La manger !\r\n\r\nN'hésite pas à faire des erreurs pour voir ce que fait INGInious dans ce\r\ncas-là.\r\n", + "description": "

Cet exercice est simple, mais il te permettra de comprendre comment fonctionne INGInious. Réorganise les différents blocs pour reformer la recette de la tartine au chocolat. La recette est la suivante :

\r\n
    \r\n
  • Ouvrir le sachet de pain
  • \r\n
  • Prendre une tartine
  • \r\n
  • Poser la tartine sur l'assiette
  • \r\n
  • Ouvrir le pot de chocolat
  • \r\n
  • Prendre le couteau
  • \r\n
  • Tremper le couteau dans le chocolat
  • \r\n
  • Tartiner le chocolat sur la tartine
  • \r\n
  • Poser le couteau
  • \r\n
  • Plier la tartine
  • \r\n
  • La manger !
  • \r\n
\r\n

N'hésite pas à faire des erreurs pour voir ce que fait INGInious dans ce cas-là.

\r\n", "tags": [ { "text": "INGINIOUS", @@ -162,7 +162,7 @@ }, { "title": "Tri des élèves", - "description": "A la séance dernière, vous vous êtes triés selon la première lettre de\r\nvos noms de famille. On va maintenant programmer ce tri ensemble !\r\n\r\n**Petit rappel de la méthode utilisée**\r\n\r\n- Il y a une file d'attente avec tous les enfants et une rangée qui\r\n est vide au départ.\r\n- Le premier de la file d'attente va comparer la première lettre de\r\n son nom de famille avec la personne de la rangée en face de lui, si\r\n il y en a une.\r\n- Si la lettre du premier de la file d'attente est plus petite (donc\r\n se trouve avant dans l'alphabet), alors le reste de la rangée se\r\n décale et le premier de la file d'attente prend la place de celui\r\n avec qui il a fait la comparaison\r\n- Sinon, le premier de la file d'attente se décale pour faire face à\r\n l'enfant suivant (si il y en a un) et lui pose la même question.\r\n", + "description": "

A la séance dernière, vous vous êtes triés selon la première lettre de vos noms de famille. On va maintenant programmer ce tri ensemble !

\r\n

Petit rappel de la méthode utilisée

\r\n
    \r\n
  • Il y a une file d'attente avec tous les enfants et une rangée qui est vide au départ.
  • \r\n
  • Le premier de la file d'attente va comparer la première lettre de son nom de famille avec la personne de la rangée en face de lui, si il y en a une.
  • \r\n
  • Si la lettre du premier de la file d'attente est plus petite (donc se trouve avant dans l'alphabet), alors le reste de la rangée se décale et le premier de la file d'attente prend la place de celui avec qui il a fait la comparaison
  • \r\n
  • Sinon, le premier de la file d'attente se décale pour faire face à l'enfant suivant (si il y en a un) et lui pose la même question.
  • \r\n
\r\n", "tags": [ { "text": "INGINIOUS", @@ -206,6 +206,6 @@ "1": "Misconception", "2": "autres" }, - "extraction_date": "2019-12-18T16:15:00.616Z", + "extraction_date": "2020-03-04T17:50:45.487Z", "url": "https://github.com/lin3out/cuisine-algorithmique" } \ No newline at end of file diff --git a/strategies/inginious-git.js b/strategies/inginious-git.js index 934a259..9d598f4 100644 --- a/strategies/inginious-git.js +++ b/strategies/inginious-git.js @@ -24,7 +24,7 @@ const rst2md = (str) => { try { const result = child_process.spawnSync( "pandoc", - ["--from=rst", "--to=markdown_strict-fenced_code_attributes+backtick_code_blocks"], + ["--from=rst", "--to=html5", "--no-highlight"], {input: str, encoding: "utf-8"} ); return result.stdout; @@ -543,7 +543,7 @@ function handle_exercise_title(exercise) { // regex useful to clean inginious links const img_html_regex = /]+src="([^">]+)"/gm; // as pandoc links always start by src, it should work as expected -const markdown_links_regex = /\[([^\[]+)\]\((.*)\)/gm; // only takes link part : [](thisOne) - result : thisOne +const links_regex = /]+)"/gm; // only takes link part : [](thisOne) - result : thisOne // To handle links inside markdown since Inginious links are a real mess function clean_inginious_links(description, inginious_link) { @@ -580,6 +580,6 @@ function clean_inginious_links(description, inginious_link) { // purge description of nasty broken inginious links return description - .replace(markdown_links_regex, (_match, p1, p2) => `[${p1}](${url_solver(p2)})`) + .replace(links_regex, (_match, p1, p2) => ` `