La présentation est en train de télécharger. S'il vous plaît, attendez

La présentation est en train de télécharger. S'il vous plaît, attendez

Algorithme et structure de données

Présentations similaires


Présentation au sujet: "Algorithme et structure de données"— Transcription de la présentation:

1 Algorithme et structure de données
IUP1 Miage

2 Objectifs Acquérir les notions de base de programmation impérative
structures de contrôles appels à des procédures récursivité Connaître les bases de la programmation objet Savoir réutiliser du code

3 Combien ? Quand ? Cours/TD TP sur machine
3h par semaine pendant 13 semaines le lundi de 9h à 12h TP sur machine 3h de TP par semaine pendant 13 semaines le lundi de 13h30 à 16h30

4 Objectifs Connaître les structures de données élémentaires, tableaux, piles, files, listes chaînées, arbres Être sensibilisé aux problèmes algorithmiques et leur complexité Connaître quelques algorithmes de base (tris, techniques "diviser pour régner", ...)

5 Le langage ! JAVA, mais son aspect orienté objet sera réduit au minimum Il ne s'agit pas d'un cours de programmation Java ! Cours/TD Alternance cours et exercices d'application sur papier TP sur machine approfondir les structures de données et algorithmes du cours faire "tourner" les exercices de TD

6 Pointeurs … Ce cours est largement inspiré par :
Algorithmique et Programmation en tronc commun du DEUG cours ASD en IUP1 de Jean-Marc Fédou Tutorial en ligne de Sun Documentation API

7 Premiers pas en Java Type de base Variable Méthode
Structure de contrôle Chaîne de caractères

8 Type de base Tous les langages de programmation manipulent des variables auxquelles sont affectées des valeurs La notion de type permet de définir les valeurs possibles définir les opérations licites

9 Type de base

10 Type de base byte : entier relatif (Z) short : entier relatif (Z)
Arithmétique complément à deux sur un octet (8 bits) [-128 , +127] short : entier relatif (Z) Arithmétique complément à deux sur deux octets (16 bits) [ , ]

11 Type de base int : entier relatif (Z) [ , ]

12 float : nombre réel en virgule Flottante IEEE-754
Soit à coder le nombre +3,25 (+11,01 en base 2) Normaliser l'écriture en base 2 sous la forme (1,…).2n +11,01 = +(1,101).21 La représentation IEEE code séparément sur 32 bits signe (ici +) exposant n (ici 1) mantisse (suite de bits après la virgule, ici 101)

13 float : nombre réel (norme IEEE-754)
Normalisation en base 2 sous la forme : (1,…).2n signe sur le bit de poids fort (0 pour +) exposant codé sur 8 bits. En fait, on code sur un octet la valeur n+127 mantisse codée sur les 23 bits de poids faibles

14 float : nombre réel (norme IEEE-754)
exposant : coder sur un octet n+127  n+127  0  n+127  255 Exposants interdits signifie que le nombre est dénormalisé indique que l'on n'a pas affaire à un nombre Not a Number (NaN) signale des erreurs de calculs, par exemple une division par 0 1  n+127  254 Le plus petit exposant ­126 le plus grand exposant +127

15 Norme IEEE-754 http://babbage.cs.qc.edu/courses/cs341/IEEE-754.html
Programme en langage C qui affiche le code d'un nombre flottant /* Affichage hexadécimal des 4 octets d'un nombre flottant IEEE */ #include <stdio.h> main(){ float x; unsigned char *p = (unsigned char *)&x ; printf("Entrer un nombre flottant : \n"); scanf("%f", &x); printf("%x %x %x %x\n",*p,*(p+1),*(p+2),*(p+3)); }

16 Type de base double : nombre décimaux [4.9*10-324, 1.8*10308]

17 char : le type caractère
Pas de méthode pour stocker directement les caractères Chaque caractère possède donc son équivalent en code numérique

18 Le code Unicode (1991) code des caractères sur 16 bits
Indépendant du système d'exploitation ou du langage Quasi-totalité des alphabets existants (arabe, arménien, cyrillique, grec, hébreu, latin, ...) Compatible avec le code ASCII

19 Le code ASCII (1960) code ASCII
American Standard Code for Information Interchange Le code ASCII de base représente les caractères sur 7 bits (c'est-à-dire 128 caractères possibles, de 0 à 127)

20 Le code ASCII Les codes 0 à 31 ne des caractères de contrôle
retour à la ligne (CR) Bip sonore (BEL) Les codes 65 à 90 représentent les majuscules Les codes 97 à 122 représentent les minuscules modifier le 6ème bit pour passer de majuscules à minuscules ajouter 32 au code ASCII en base décimale

21 Type de base boolean : deux valeurs possibles
true (VRAI) false (FAUX) S’il y a du soleil ALORS je vais a la plage SI (soleil==VRAI) ALORS aller_a_la_plage SI soleil ALORS aller_a_la_plage

22 Type de base Keyword Description Size/Format (integers)
byte Byte-length integer 8-bit two's complement short Short integer 16-bit two's complement int Integer 32-bit two's complement long Long integer 64-bit two's complement (real numbers) float Single-precision floating point 32-bit IEEE 754 double Double-precision floating point 64-bit IEEE 754 (other types) char A single character 16-bit Unicode character boolean A boolean value true or false

23 Types de base Primitive Data Types Integer Floating
byte 8bits to 127 float 32bits 1.4E E38 short 16bits to 32767 double 64bits 4.9E E308 int bits -2^31 to 2^31-1 long bits -2^63 to 2^63-1 Textual Logical char 16bits 0 to 65535 one bit : true or false

24 Concept de Variable Définition : un élément d’information identifié par un nom On doit explicitement indiquer le nom et le type d’une variable On utilise le nom pour faire référence à l’information que la variable contient Le type détermine les valeurs licites pour la variable et les opérations autorisées

25 Concept de Variable Pour donner un nom et un type à une variable il faut la déclarer type name Une variable a une portée la section de code ou le nom de la variable peut être utilisé

26 Variable : déclaration
int compteur ; float prixHt ; char aChar ; boolean fin ;

27 Variable : valeur par défaut

28 Variable : affectation d’une valeur
Une affectation permet de donner une nouvelle valeur à une variable La valeur précédente est PERDUE int compteur ; compteur = 3 ;

29 Variable : affectation d’un valeur
int r = 2 ; double pi ; pi = 3.14 ; double perimetre = 2*pi*r ; //déclarer ET affecter char c = ’c’ ; boolean pair = true; int compteur ; compteur = compteur +1 ;

30 int maxInteger = Integer.MAX_VALUE; float maxFloat = Float.MAX_VALUE;
char aChar = 'S'; boolean fin = true; S.o.p("Le plus grand integer est :" + maxInteger); S.o.p("Le plus grand float est :" + maxFloat); S.o.p("Le caractère est :" + aChar); S.o.p("fin est :" + fin); Le plus grand integer est : Le plus grand float est : e+38 Le caractère est : S fin est : true

31 Affectation et Conversion de type
Attention, contrairement à C, Java n'autorise pas conversions de types, sauf s'il n'y a aucune perte de précision un entier peut être promu en double un double ne peut pas être promu en entier

32 Affectation et Conversion de type
Un entier peut être promu en double int i = 2 ; double d = 3.1 ; d = i ; Un double ne peut pas être promu en entier i = d ; // !!

33 Affectation et Cast Un double ne peut pas être promu en entier
int i = 2 ; double d = 3.1 ; i = d ; // !! Un double peut être forcé en entier i = (int) d ;

34 final int A_FINAL_VAR = 10;
Variable final La valeur d’une variable déclarée final ne peut pas être modifiée après avoir été initialisée Une telle variable est similaire à une constante dans les autres langages de programmation Pour déclarer une variable final : final int A_FINAL_VAR = 10;

35 Opérateur Arithmétique
Operator Use Description + op1 + op2 Adds op1 and op2 - op1 - op2 Subtracts op2 from op1 * op1 * op2 Multiplies op1 by op2 / op1 / op2 Divides op1 by op2 % op1%op2 Computes the remainder of dividing op1 by op2

36 Opérateur Arithmétique
Le résultat peut dépendre du contexte 25 / > 8 //pour la division entière de 25 par 8 25.0 / > 25 / > 25 % > 1 //pour le reste de la division de 25 par 8 25 % > // 25=3.1*

37 Opérateur Relationnel
Operateur Use Returns true if > op1 > op2 op1 is greater than op2 >= op1 >= op2 op1 is greater than or equal to op2 < op1 < op2 op1 is less than op2 <= op1 <= op2 op1 is less than or equal to op2 == op1 == op2 op1 and op2 are equal != op1 != op2 op1 and op2 are not equal

38 Opérateur Conditionnel
Operator Use Returns true if && op1 && op2 op1 and op2 are both true conditionally evaluates op2 || op1 || op2 either op1 or op2 is true ! ! op op is false & op1 & op2 always evaluates op1 and op2 | op1 | op2 ^ op1 ^ op2 if op1 and op2 are different that is if one or the other of the operands is true but not both

39 Créer votre première application

40 Le premier programme, Hello, affiche simplement le texte "Hello !"
Créer un fichier source Hello.java Un fichier source contient du texte, écrit en Java Compiler le source en fichier bytecode Hello.class Le compilateur javac, traduit le texte source en instructions compréhensibles par la Machine Virtuelle Java (JVM) Exécuter le programme contenu dans le fichier bytecode L'interprète java implémente la JVM L'interprète traduit le bytecode en instructions exécutables par votre machine

41 Write once, run anywhere
La compilation d'un programme, ne génère pas d'instructions spécifiques à votre plate-forme Mais du bytecode Java, qui sont des instructions de la Machine Virtuelle Java (JVM) Si votre plate-forme (Windows, UNIX, MacOS, un browser Internet) dispose d’une JVM, elle peut comprendre le bytecode

42 Créer le fichier source Java Hello.java
class Hello { public static void main(String[] args) { System.out.println("Hello !"); }

43 Compiler le fichier source
> javac Hello.java Si la compilation réussit le fichier Hello.class est créer Ce fichier contient le bytecode

44 Interpréter et Exécuter l'application
> java Hello L'argument de l'interprète est le nom de la classe à exécuter ce n’est pas le nom du fichier Faire la distinction M/m

45 Disséquons l'application "Hello"
Définir une classe Définir la méthode main Utiliser des méthodes

46 Définir la classe Hello
public class Hello { public static void main(String[] args) { System.out.println("Hello !"); }

47 Définir la méthode main
public class Hello { public static void main(String[] args) { System.out.println("Hello !"); } Une application Java doit contenir une méthode main Appelée en premier par l'interprète main appelle les autres méthodes nécessaires pour exécuter l'application

48 Utiliser d’autres méthodes …
public class Hello { public static void main(String[] args) { System.out.println("Hello !"); }

49 > Java Hello toto titi
public class Hello { public static void main(String [] args) { S.o.p("Salut: "); S.o.p(args[0]+" "+ args[1]); }

50 int année = Integer.parseInt("2004")
Conversion String2int Méthode int parseInt(String) de la classe Integer public static int parseInt(String s) throws NumberFormatException Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002d') to indicate a negative value. The resulting integer value is returned Parameters: s - a string. Returns: the integer represented by the argument in decimal. int année = Integer.parseInt("2004")

51 > java Somme 10 11 public class Somme {
public static void main(String args[]) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); S.o.p(a+"+"+b+"="+(a+b)); }

52 Console.readDouble(str)
Entrées au clavier Problème : les entrées au clavier ne sont pas aisées en Java Nous allons utilisé (Travaux Dirigés) la classe Console pour simplifier la tâche Console.readInt(str) retourne un nombre entier de type int entré au clavier Console.readDouble(str) retourne un nombre de type double entré au clavier

53 Entrées au clavier retourne un caractère de type char
Console.readInt(str) retourne un nombre de type int Console.readLong(str) retourne un nombre de type long Console.readDouble(str) retourne un nombre de type double Console.readChar(str) retourne un caractère de type char Console.readLine(str) retourne une chaîne de type String

54 Utiliser la classe Console
Pour chaque classe qui fait appel à la classe Console ajoutez (entre votre commentaire de début et le mot class) import unsa.Console; ajouter comme dernière instruction de la méthode main() System.exit(0);

55 Classe Console Exemple
import unsa.Console; public class TestConsole{ public static void main (String args[]){ char c = Console.readChar("Entrez un char"); S.o.p("echo: " + c ); int i = Console.readInt("Entrez un int"); S.o.p("echo: " + i ); System.exit(0); }

56 Générer un nombre aléatoire
Utiliser la méthode random() de la classe Math public static double random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range

57 Math.random() Comment obtenir un entier dans [0,n] ?
int tirage = Math.random(); Types incompatibles int tirage = (int) Math.random(); retourne 0 int tirage = (int) Math.random()*100; int tirage = (int) (Math.random()*100);

58 Générer un nombre aléatoire
Utiliser la méthode nextInt(int) de la classe Random int nextInt(int n) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence

59 Générer une suite aléatoire …
Random suiteAlea = new Random(); System.out.println(suiteAlea.nextInt(5)); System.out.println(suiteAlea.nextInt()); System.out.println(suiteAlea.nextFloat()); System.out.println(suiteAlea.nextBoolean());

60 Conventions d’écriture du code
class CompteEnBanque methode crediterCompte(25) getSolde() setSolde(10) variable empruntCourant Constante TAUX_INTERET Java les respecte donc respectez-les !!

61 Contrôle du Flux d’instructions
Sans contrôle du flux les instructions sont exécutées dans l’ordre où elles apparaissent dans le fichier source Contrôler le flux pour Exécuter conditionnellement des instructions Exécuter de façon répétitive un bloc de code

62 Instructions de Contrôle
Les Instructions de Contrôle if return switch continue while do-while for break

63 while (expression) { instructions }
Instruction while On utilise l'instruction while pour exécuter répétitivement un bloc de code tant qu'une condition reste vraie while (expression) { instructions } On commence par évaluer l'expression, qui doit retourner une valeur booléenne Si expression retourne true, alors on exécute les instructions associées L'instruction while continue en testant expression et en exécutant les instructions jusqu'à ce que expression retourne false

64 Instruction while Ce programme utilise une instruction while pour parcourir une String, copiant les caractères dans un buffer jusqu'à rencontrer la lettre 'g' String copyFromMe = "Copy this string until you encounter the letter 'g'."; StringBuffer copyToMe = new StringBuffer(); int i=0; char c=copyFromMe.charAt(i); while (c != 'g') { copyToMe.append(c); i=i+1; c = copyFromMe.charAt(i); } S.o.p(copyToMe); Valeur affichée par S.o.p ? The value printed by the last line is: Copy this strin

65 Instruction do-while Java fournit une autre structure similaire do-while do {instructions} while(expression); expression est évaluée à la base de la boucle les instructions associées sont donc exécutées au moins une fois

66 Instruction do-while String copyFromMe = "Copy this string until you encounter the letter 'g'."; StringBuffer copyToMe = new StringBuffer(); int i=0; char c ; do { c = copyFromMe.charAt(i); copyToMe.append(c); i=i+1 ; } while (c != 'g'); S.o.p(copyToMe); Valeur affichée par S.o.p ? The value printed by the last line is: Copy this strin

67 Instruction for for(initialisation;terminaison;incrément){instructions} initialisation initialise la boucle ; exécuté une seule fois au début de la boucle terminaison détermine quand terminer la boucle évaluée au début de chaque itération Quand l'expression retourne false, la boucle se termine incrément exécutée à la fin de chaque itération Souvent utilisé pour parcourir les éléments d'un tableau (Array), ou les caractères d'une chaîne (String)

68 Instruction for int[] arrayOfInts = {32, 87, 3, 589};
for(int i=0; i<arrayOfInts.length; i++) { S.o.p(arrayOfInts[i] + " "); } Valeurs affichées par S.o.p ?

69 for vs. while for(int i=0 ; i<arrayOfInts.length ; i++) {
S.o.p(arrayOfInts[i] + " "); } int i=0 ; while(i<arrayOfInts.length) i++;

70 Garantir la fin des itérations
do { afficher(a) } while (a != 10) do { afficher(a) a = a+1; } while (a != 10) a = 1; do { afficher(a) a = a+1 ; } while (a != 10) a = 10; do { afficher(a) a = a+1; } while (a != 10)

71 Question 1

72 Question 1 a==12

73 Question 2

74 Question 2 a=0

75 Question 3

76 Question 3 a=0

77 Question 4

78 Question 4 j=0

79 Instructions if/else if (reponse == OK) { // code to perform OK action
} if (reponse == OK) { // code to perform OK action } else { // code to perform Cancel action

80 Cascade de structure if …
int score = 76; char grade; if (score >= 90) { grade = 'A'; } else // score < 90 if (score >= 80) { grade = 'B'; } else // score < 80 if (score >= 70) { grade = 'C'; } else // score < 70 if (score >= 60) { grade = 'D'; } else // score < 60 { grade = 'F'; } S.o.p("Grade = " + grade); Valeur affichée par S.o.p ? C

81 Instruction switch Permet d'exécuter, conditionnellement à la valeur d'un entier, certaines instructions int mois = 10; switch (mois) { case 1: S.o.p("Janvier") ; break; case 2: S.o.p("Février") ; break; case 3: S.o.p("Mars") ; break; case 10: S.o.p("Octobre") ; break; case 11: S.o.p("Novembre") ; break; case 12: S.o.p("Décembre") ; break; default: S.o.p("non valide!"); } Valeur affichée par S.o.p ?

82 Un exemple … Un programme qui permette de :
Saisir deux nombres réels au clavier Afficher un menu à l'écran S)omme des deux nombres P)roduit des deux nombres M)oyenne des deux nombres Saisir le choix de l'utilisateur, ‘S', 'P' ou 'M‘ Afficher le résultat correspondant

83 import unsa.Console; public class Exo { public static void main(String [] args) { float nb1= Console.readFloat("Entrer un nombre réel : "); float nb2= Console.readFloat("Entrer un nombre réel : "); S.o.p("*****************************"); S.o.p("* S)omme des deux nombres *"); S.o.p("* P)roduit des deux nombres *"); S.o.p("* M)oyenne des deux nombres *"); switch (Console.readChar("Faites votre choix")) { case 'S' : S.o.p(nb1+nb2);break; case ‘P' : S.o.p(nb1*nb2);break; case ‘M' : S.o.p((nb1+nb2)/2);break; default : S.o.p("erreur de saisie"); } System.exit(0);}

84 import unsa.Console; public class Exo { public static void main(String [] args) { float nb1= Console.readFloat("Entrer un nombre réel : "); float nb2= Console.readFloat("Entrer un nombre réel : "); S.o.p("*****************************"); S.o.p("* S)omme des deux nombres *"); S.o.p("* P)roduit des deux nombres *"); S.o.p("* M)oyenne des deux nombres *"); switch (Console.readChar("Faites votre choix")) { case 'S' : case 's' : S.o.p(nb1+nb2);break; case ‘P' : case ‘p' : S.o.p(nb1*nb2);break; case 'm' : case 'M' : S.o.p((nb1+nb2)/2);break; default : S.o.p("erreur de saisie"); } System.exit(0);}

85 public static void main(String [] args) {
float nb1= Console.readFloat("Entrer un nombre réel : "); float nb2= Console.readFloat("Entrer un nombre réel : "); S.o.p("*****************************"); S.o.p("* S)omme des deux nombres *"); S.o.p("* P)roduit des deux nombres *"); S.o.p("* M)oyenne des deux nombres *"); switch (Character.toLowerCase(Console.readChar("choix ?"))) { case ‘s': S.o.p("somme : "+(nb1+nb2)) ;break; case ‘p': S.o.p("produit: "+(nb1*nb2)) ;break; case ‘m': S.o.p("moyenne: "+(nb1+nb2)/2);break; default : S.o.p("erreur de saisie"); }

86 public static void main(String [] args) {
float nb1= Console.readFloat("Entrer un nombre réel : "); float nb2= Console.readFloat("Entrer un nombre réel : "); S.o.p("*****************************"); S.o.p("* S)omme des deux nombres *"); S.o.p("* P)roduit des deux nombres *"); S.o.p("* M)oyenne des deux nombres *"); char rep ; do { rep= Character.toLowerCase(Console.readChar("choix ?")); switch (rep) { case ‘s': S.o.p("somme : "+(nb1+nb2)) ;break; case ‘p': S.o.p("produit: "+(nb1*nb2)) ;break; case ‘m': S.o.p("moyenne: "+(nb1+nb2)/2);break; default : S.o.p("erreur de saisie"); } } while ((rep != 's') && (rep != 'p') && (rep != 'm')) ;

87 Conversion d'un caractère en minuscule
Il faut distinguer le type primitif char et la classe Character char rep ; rep=Character.toLowerCase(Console.readChar("votre choix ?")); S.o.p(rep); Console.readChar("votre choix ?") readChar est une méthode de la classe Console qui retourne le char lu au clavier static char toLowerCase(char ch) Méthode static de la classe Character : le caractère donnée char ch est converti en minuscule avant d'être retourné en résultat char

88 Capitaliser un texte Public static void main(String[] args) {
String str=Console.readLine("Tapez un texte"); char ch; // un caractère de str char prevCh='.'; // le caractère précédent ch for (int i = 0; i < str.length(); i++ ) { ch = str.charAt(i); if ( Character.isLetter(ch) && ! Character.isLetter(prevCh) ) S.o.p( Character.toUpperCase(ch) ); else S.o.p(ch); prevCh = ch; }

89 Notion d'algorithme une procédure de calcul bien définie qui prend en entrée une ou plusieurs valeurs et qui délivre en sortie un résultat Exemples d'algorithmes PGCD (Plus Grand Commun Diviseur) Algorithmes de tri Algorithmes de recherche Recherche d'une chaîne de caractère dans un texte (Logiciels de traitement de texte). Recherche dans un dictionnaire Attention, certains problèmes n'admettent pas de solution algorithmique exacte et utilisable. On utilise dans ce cas des algorithmes heuristiques qui fournissent des solutions convenables.

90 Algorithme d’Euclide PGCD (Plus Grand Commun Diviseur) de deux nombres u et v Algorithme naïf on teste successivement si chaque nombre entier est diviseur commun Algorithme d'Euclide (IIIème siécle) pour calculer le pgcd de deux nombre entiers

91 Calculer le PGCD de deux entiers A et B
Algorithme d'Euclide Calculer le PGCD de deux entiers A et B PGCD(A,B) = PGCD(B,R) A = (B x Q) + R 0 <= R < B 294 = (231 x 1) + 63 231 = (63 x 3) + 42 63 = (42 x 1) + 21 42 = (21 x 2) + 0 PGCD(294,231) = 21

92 Algorithme d'Euclide int a=21, b=14 ; int r ;
S.o.p("PGCD "+a+" et "+b+"  = "); r=a%b; /* division euclidienne de a par b a=b*q+r et 0 <= r < b */ while (r!=0){ a=b ; b=r; // pgcd(a,b)=pgcd(b,r) } S.o.p(b);

93 Algorithme d'Euclide (version récursive)
int pgcd(int a , int b) { int r = a%b; if (r!=0) return pgcd(b,r) ; else return b ; }

94 Algorithme d'Euclide (version récursive)
public class Exo { static int pgcd(int a, int b){ int r = a%b; if(r != 0) return pgcd(b,r); else return b ; } public static void main (String args []){ int x = 21 , y = 14 ; S.o.p("PGCD "+x+" et "+y+" est "+pgcd(x,y));

95 Fonction Factoriel (version récursive)
public class Exo { static int factoriel(int n){ if (n != 0) return n*factoriel(n-1); else return 1 ; } public static void main (String args []){ int a = 4 ; S.o.p(a+"! = "+factoriel(a));

96 Fonction Factoriel (version itérative)
public class Exo { public static void main (String args []){ int n = 3 ; int fact = 1 ; for(int i=2 ; i <= n ; i++) fact=fact*i ; S.o.p(n+"! = "+fact) ; }

97 Fonction Factoriel (version itérative)
public class Exo { public static void main (String args []){ int n = 3 ; int fact = 1 ; for(int i=2 ; i <= n ; i++) fact=fact*i ; S.o.p(n+"! = "+fact) ; }

98 Le plus grand Factoriel ?
public class Exo { public static void main (String args []){ byte n = ? ; S.o.p(n+"! = "+fact(n)) ; short n = ? ; int n = ? ; long n = ? ; }

99 Le plus grand Factoriel ?
Byte n = 5 ; // 2^7-1 = 127 S.o.p(n+"!="+fact) ; // 5! = 120 short n = 7 ; // 2^15-1 = S.o.p(n+"!="+fact) ; // 7! = 5 040

100 Le plus grand Factoriel ?
int n = 12 ; // 2^31-1 = S.o.p(n+"!="+fact); // 12! = // 13! =

101 Quand doit-on écrire les tests ?
eXtreme Programming Pratique la plus en vogue aujourd'hui Ecrire les tests avant même de commencer à coder Pair programming (programmation en binôme) discussion du binôme autour de développement à effectuer (on ne parle pas des 5 jours à venir mais des 30 minutes à venir) l'un des développeurs écrit les tests, tandis que l'autre implémente

102 Le framework de tests unitaires JUnit
Développé en Java par Kent Beck (initiateur de XP) et Erich Gamma (initiateurs des Design Patterns). Objectifs de JUnit Tester des applications Java Faciliter la création de ces tests Tests de non régression Exécuter automatiquement des tests Obtenir un feedback rapidement Ecrire du code de qualité plus rapidement

103 Comment tester la fonction factoriel !
public class Exo { static int factoriel(int n){ if (n != 0) return n*factoriel(n-1); else return 1 ; } public static void main (String args []){ int a = 4 ; S.o.p(a+"! = "+factoriel(a));

104 Junit : un framework de tests unitaires
import junit.framework.TestCase; public class FactorielTest extends TestCase { public void test0() { Exo t = new Exo(); int attendu = 1; // 0! int actuel = t.factoriel(0); assertEquals("factoriel 0", attendu, actuel);} public void test1() { int attendu = 120; // 5! int actuel = t.factoriel(5); assertEquals("factoriel 5", attendu, actuel);} }

105 Un TestRunner permet de lancer l'exécution des Tests
public static void main(String[] args) { junit.textui.TestRunner.run(FactorielTest.class); } junit.awtui.TestRunner.run(FactorielTest.class); } junit.swingui.TestRunner.run(FactorielTest.class); }

106 Tests unitaires avec Junit
import junit.framework.TestCase; public class FactorielTest extends TestCase { public void test2() { Exo t = new Exo(); int n=5 ; int actuel = t.factoriel(n)/t.factoriel(n-1); int attendu = n; assertEquals("5!/4!", attendu, actuel); }

107 Tests unitaires avec Junit
import junit.framework.TestCase; public class FactorielTest extends TestCase { public void test3() { Exo t = new Exo(); int actuel = t.factoriel(17); assertTrue(actuel>0); }

108 Le nombre Mystérieux public static void main (String args[]){
int inconnu = (int) (Math.random()*100); int score=0; int prop=Console.readInt("proposition :"); score++; while (prop != inconnu){ if (prop < inconnu) S.o.p("TROP PETIT"); else S.o.p("TROP GRAND"); prop=Console.readInt("proposition :"); score++; } S.o.p("Vous avez trouvé en "+score+" coups"); System.exit(0);

109 La classe String String str = "abc"; char str[] = {'a', 'b', 'c'};
String str = new String("abc"); int length() Returns the length of this string S.o.p(str.length());

110 char charAt(int index)
Parameters: index - the index of the character Returns: the character at the specified index of this string. The first character is at index 0 Throws: IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string String str = "abc"; S.o.p(str.charAt(2));

111 int compareTo(String anotherString)
Parameters: anotherString - the String to be compared Returns: the value 0 if the argument string is equal to this string a value less than 0 if this string is lexicographically less than the string argument a value greater than 0 if this string is lexicographically greater than the string argument Throws: NullPointerException - if anotherString is null

112 int indexOf(int ch) Parameters: Returns: ch - a character
the index of the first occurrence of the character in the character sequence represented by this object or -1 if the character does not occur String str = "abcb"; S.o.p(str.indexOf(’b’));

113 int indexOf(String str)
Parameters: str - any string. Returns: if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned if it does not occur as a substring, -1 is returned Throws: NullPointerException - if str is null String str = "abcabc"; S.o.p(str.indexOf("bc"));

114 String substring(int beginIndex)
Parameters: beginIndex - the beginning index, inclusive Returns: the specified substring Throws: IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object

115 String substring(int beginIndex)
"unhappy".substring(2) returns ? "Harbison".substring(3) "emptiness".substring(9)

116 String substring(int beginIndex)
"unhappy".substring(2) returns "happy" "Harbison".substring(3) returns "bison" "emptiness".substring(9) returns "" (an empty string)

117 String substring(int beginIndex, int endIndex)
"hamburger".substring(4, 8) returns ? "smiles".substring(1, 5)

118 String substring(int beginIndex, int endIndex)
"hamburger".substring(4, 8) returns "urge" "smiles".substring(1, 5) returns "mile"

119 public String concat(String str)
Parameters: str - the String that is concatenated to the end of this String Returns: a string that represents the concatenation of this object's characters followed by the string argument's characters Throws: NullPointerException - if str is null

120 public String concat(String str)
"cares".concat("s") returns ?  "to".concat("get").concat("her") returns ?

121 public String concat(String str)
"cares".concat("s") returns "caress"   "to".concat("get").concat("her") returns "together"

122 La classe StringBuffer
A string buffer is like a String, but can be modified At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls

123 StringBuffer append(String str)
Parameters: str - a string Returns: a reference to this StringBuffer StringBuffer str= "toto"; str.append("titi"); S.o.p(str);

124 StringBuffer replace(int start, int end, String str)
Parameters: start - The beginning index, inclusive end - The ending index, exclusive str - String that will replace previous contents Returns: This string buffer Throws: StringIndexOutOfBoundsException - if start is negative, greater than length(), or greater than end

125 StringBuffer reverse()
The character sequence contained in this string buffer is replaced by the reverse of the sequence StringBuffer str = "esope"; S.o.p(str.reverse());

126 É s o p e r e s t e i c i e t s e r e p o s e
public static void main(String [] args) { String phrase=Console.readLine("Entrez une string"); final int taille = phrase.length(); int i = 0, j = taille - 1; while(i<taille/2 && phrase.charAt(i) == phrase.charAt(j)) {i++ ; j-- ;} if (i >= taille/2) S.o.p(phrase+" est un palindrome"); else S.o.p (phrase+" n’est pas un palindrome"); System.exit(0); }

127 É s o p e r e s t e i c i e t s e r e p o s e
public static void main(String [] args) { String phrase=Console.readLine("votre texte").toUpperCase(); StringBuffer sb1 = new StringBuffer(phrase); StringBuffer sb2 = new StringBuffer(phrase); sb1.reverse(); if (sb1.toString().equals(sb2.toString())) S.o.p(phrase+" est un palindrome"); else S.o.p(phrase+" n'est pas un palindrome"); System.exit(0); }

128 Algorithme du drapeau tricolore
On aligne n boules, réparties en un nombre quelconque de boules bleues, blanches ou rouges, disposées dans un ordre quelconque Écrire un algorithme qui trie le tableau de telle façon que toutes les boules bleues apparaissent au début, suivies des boules blanches puis des boules rouges Le tri doit être réalisé en unique parcours

129

130 b r i b i r i r b i r

131 Algorithme du drapeau tricolore
int d[]={3,1,3,1,2,3,2,3,2,1}; // 1=bleu 2=blanc 3=rouge for(int k=0 ; k<d.length ; k++) { S.o.p(d[k]+" ");} int i=0 , b=0 , r=d.length-1 ; while ( i <= r ) { switch (d[i]) { case 1 : echanger(b,i); b++;i++;break; case 2 : i++; break; case 3 : echanger(r,i); r--; break; } S.o.p("le drapeau ..."); B = prochaine case vide pour un bleu R= prochaine case vide pour un rouge I indice courant de la boule examinée

132 Comment les arguments sont-ils passés aux méthodes ?
public class Demo { static void f(int b) { b = 10; } public static void main(String [] args) { int a = 5; f(a); S.o.p("a = " + a); // Quelle est la valeur affichée, 5 ou 10 ? In the main method, the variable arg1 is given the value 5, and then passed as an argument to the method f. This method declares a parameter of the same name, arg1, used to access the argument. What happens when you run this simple program? The method f modifies the value of arg1, so what value gets printed, 5 or 10? It turns out that 5 is the right answer. This implies that setting arg1 to 10 in method f has no effect outside of the method. Why does it work this way? The answer has to do with the distinction between the pass-by-value and pass-by-reference approaches to passing arguments to a method. The Java language uses pass-by-value exclusively.

133 Comment les arguments sont-ils passés aux méthodes ?
public class Demo { static void f(int a) { a = 10; } public static void main(String [] args) { int a = 5; f(a); S.o.p("a = " + a); // Quelle est la valeur affichée, 5 ou 10 ? In the main method, the variable arg1 is given the value 5, and then passed as an argument to the method f. This method declares a parameter of the same name, arg1, used to access the argument. What happens when you run this simple program? The method f modifies the value of arg1, so what value gets printed, 5 or 10? It turns out that 5 is the right answer. This implies that setting arg1 to 10 in method f has no effect outside of the method. Why does it work this way? The answer has to do with the distinction between the pass-by-value and pass-by-reference approaches to passing arguments to a method. The Java language uses pass-by-value exclusively.

134 Passage des arguments par valeur
public class Demo { static void f(int a) { a = 10; S.o.p("a de f= " + a); } public static void main(String args[]) { int a = 5; f(a); S.o.p("a du main = " + a); In the main method, the variable arg1 is given the value 5, and then passed as an argument to the method f. This method declares a parameter of the same name, arg1, used to access the argument. What happens when you run this simple program? The method f modifies the value of arg1, so what value gets printed, 5 or 10? It turns out that 5 is the right answer. This implies that setting arg1 to 10 in method f has no effect outside of the method. Why does it work this way? The answer has to do with the distinction between the pass-by-value and pass-by-reference approaches to passing arguments to a method. The Java language uses pass-by-value exclusively.

135 Passage des arguments par valeur
public class Demo { static void echanger(int i, int j) { int aux=i ; i=j; j=aux ; } public static void main(String args[]) { int a = 5 , b=10 ; S.o.p("a = " + a+" b = " + b); echanger(a,b); In the main method, the variable arg1 is given the value 5, and then passed as an argument to the method f. This method declares a parameter of the same name, arg1, used to access the argument. What happens when you run this simple program? The method f modifies the value of arg1, so what value gets printed, 5 or 10? It turns out that 5 is the right answer. This implies that setting arg1 to 10 in method f has no effect outside of the method. Why does it work this way? The answer has to do with the distinction between the pass-by-value and pass-by-reference approaches to passing arguments to a method. The Java language uses pass-by-value exclusively.

136 Passage d'un objet en argument
public class Demo { static void echanger(StringBuffer i, StringBuffer j) { StringBuffer aux=new StringBuffer(j.toString()); j.replace(0, j.length(), i.toString()) ; i.replace(0, i.length(), aux.toString()) ;} public static void main(String args[]) { StringBuffer a = new StringBuffer("totoToto") ; StringBuffer b = new StringBuffer("titi") ; S.o.p("a = " + a+" et b = " + b); echanger(a,b); }

137 Passage d'un objet en argument
static void lireTableau(int tLu[]){ for (int i=0 ; i<tLu.length ; i++) tLu[i] = Console.readInt("Taper un entier : "); } static void afficherTableau(int tAf[]){ for (int i=0;i<tAf.length;i++) S.o.p(tAf[i] + " "); public static void main(String [] args){ final int TAILLE=5; int tableau [] = new int[TAILLE]; lireTableau(tableau); afficherTableau(tableau); System.exit(0);


Télécharger ppt "Algorithme et structure de données"

Présentations similaires


Annonces Google