Voici une liste d’exercices pour expérimenter la construction d’algorithmes en se concentrant sur la construction de boucles.
Le sujet porte sur la manipulation des chaînes de caractères.
À l’instar des listes/tableaux, les chaînes peuvent être parcourues, et peuvent être vues comme une collection de caractères.
Une fois vos algorithmes conçus, il est recommandé de les coder en Python afin de pouvoir les tester.
Cependant, si vous ne vous sentez pas encore à l’aise avec Python, vous pouvez simplement les écrire sur une feuille et les tester à la main.
Lors du test de vos algorithmes, essayez de penser à des cas couvrant tous les résultats possibles.
Par exemple, si votre algorithme doit retourner true ou false, testez-le avec des entrées qui conduisent aux deux cas.
Contrainte – Il existe de nombreuses façons d’écrire un algorithme pour résoudre un problème, et de nombreuses façons de programmer un algorithme.
Dans cette activité pratique, vous n’avez pas le droit d’utiliser le mot-clé break.
Réfléchissez également soigneusement à savoir si vous avez besoin d’une boucle bornée (for) ou non bornée (while).
Important
Le but de cette séance est de vous aider à maîtriser des notions importantes en informatique.
Un assistant de programmation intelligent tel que GitHub Copilot, que vous avez peut-être déjà installé, sera capable de vous fournir une solution à ces exercices uniquement à partir d’un nom de fichier judicieusement choisi.
Pour l’entraînement, nous vous conseillons de désactiver ces outils dans un premier temps.
À la fin de l’activité pratique, nous vous suggérons de retravailler les exercices avec ces outils activés.
Suivre ces deux étapes améliorera vos compétences à la fois de manière fondamentale et pratique.
Nous vous fournissons également les solutions aux exercices.
Veillez à ne les consulter qu’après avoir trouvé une solution, afin de comparer !
Même si vous êtes sûr que votre solution est correcte, jetez-y un œil, car elles fournissent parfois des éléments supplémentaires que vous auriez pu manquer.
Contenu de l’activité
1 — Dernière occurrence
Commencez avec le programme suivant :
# The string to manipulates ="IMT Atlantique"print(s)
# Write your codes here# ...
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// The string to manipulate String s ="IMT Atlantique";
System.out.println(s);
// Write your codes here// ... }
}
Concevez un algorithme qui détermine la position (entre 0 et la longueur de s moins 1) de la dernière occurrence d’un symbole dans la chaîne s.
Le symbole recherché est stocké dans une variable nommée v.
L’algorithme affiche la position trouvée ou indique si le symbole n’est pas présent dans s.
L’algorithme peut être évalué avec les valeurs suivantes :
s = "IMT Atlantique" et v = 'l'
s = "IMT Atlantique" et v = 'z'
s = "I love Computer Science and Algorithms" et v = 'o'
Correction
# The string to manipulates ="IMT Atlantique"print(s)
# The thing to searchv ='t'# Last occurrence of v in sindex = len(s) -1while index >=0and s[index] != v:
index -=1# Print resultif index >=0:
print("Found at index", index)
else:
print("Not found")
# The string to manipulates ="IMT Atlantique"print(s)
# The thing to searchv ='l'# Use string method to find last occurrenceresult = s.rfind(v)
# Print resultif result !=-1:
print("Found at index", result)
else:
print("Not found")
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// The string to manipulate String s ="IMT Atlantique";
System.out.println(s);
// The thing to searchchar v ='t';
// Last occurrence of v in sint index = s.length() - 1;
while (index >= 0 && s.charAt(index) != v) {
index--;
}
// Print resultif (index >= 0) {
System.out.println("Found at index "+ index);
} else {
System.out.println("Not found");
}
}
}
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// The string to manipulate String s ="IMT Atlantique";
System.out.println(s);
// The thing to searchchar v ='l';
// Use string method to find last occurrenceint result = s.lastIndexOf(v);
// Print resultif (result !=-1) {
System.out.println("Found at index "+ result);
} else {
System.out.println("Not found");
}
}
}
2 — Première occurrence
Reprenez le même code de base que dans l’exercice 1.
Concevez un algorithme qui détermine la position (entre 0 et la longueur de s moins 1) de la première occurrence d’un symbole dans la chaîne s.
Le symbole recherché est stocké dans une variable nommée v.
L’algorithme affiche la position trouvée ou indique si le symbole n’est pas présent dans s.
L’algorithme peut être évalué avec les valeurs suivantes :
s = "IMT Atlantique" et v = 'l'
s = "IMT Atlantique" et v = 'z'
s = "I love Computer Science and Algorithms" et v = 'o'
Correction
# The string to manipulates ="IMT Atlantique"print(s)
# The thing to searchv ='t'# Initialize variable for the while loopindex =0# Iterate from the start to the endwhile index < len(s) and s[index] != v:
index +=1# Print the resultif index < len(s):
print("Found at index", index)
else:
print("Not found")
# The string to manipulates ="IMT Atlantique"print(s)
# The thing to searchv ='l'# Use string method to find first occurrenceresult = s.find(v)
# Print resultif result !=-1:
print("Found at index", result)
else:
print("Not found")
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// The string to manipulate String s ="IMT Atlantique";
System.out.println(s);
// The thing to searchchar v ='l';
// Initialize variable for the while loopint index = 0;
// Iterate from the start to the endwhile (index < s.length() && s.charAt(index) != v) {
index++;
}
// Print the resultif (index < s.length()) {
System.out.println("Found at index "+ index);
} else {
System.out.println("Not found");
}
}
}
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// The string to manipulate String s ="IMT Atlantique";
System.out.println(s);
// The thing to searchchar v ='l';
// Use string method to find first occurrenceint result = s.indexOf(v);
// Print resultif (result !=-1) {
System.out.println("Found at index "+ result);
} else {
System.out.println("Not found");
}
}
}
3 — Préfixe
Reprenez le même code de base que dans l’exercice 1.
Considérant un second tableau de caractères, nommé pref par exemple, déterminez si pref est un préfixe de s.
Réfléchissez bien aux différents scénarios possibles liés aux longueurs de s et pref.
L’algorithme affiche si pref est un préfixe de s.
L’algorithme peut être évalué avec les valeurs suivantes :
s = "IMT Atlantique" et pref = "IMT"
s = "IMT Atlantique" et pref = "IMT Atlantique is a great school"
s = "I love Computer Science and Algorithms" et pref = "I love"
Correction
# The string to manipulates ="IMT Atlantique"print(s)
# The thing to searchpref ="IMT"# Iterate over the string util a different character is foundi =0while i < len(s) and i < len(pref) and s[i] == pref[i]:
i +=1# Print resultif i == len(pref):
print(pref, "is a prefix of", s)
else:
print(pref, "is not a prefix of", s)
# The string to manipulates ="IMT Atlantique"print(s)
# The thing to searchpref ="IMT"# Use string method for thatif s.startswith(pref):
print(pref, "is a prefix of", s)
else:
print(pref, "is not a prefix of", s)
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// The string to manipulate String s ="IMT Atlantique";
System.out.println(s);
// The prefix to search String pref ="IMT";
// Iterate over the string until a different character is foundint i = 0;
while (i < s.length() && i < pref.length() && s.charAt(i) == pref.charAt(i)) {
i++;
}
// Print resultif (i == pref.length()) {
System.out.println(pref +" is a prefix of "+ s);
} else {
System.out.println(pref +" is not a prefix of "+ s);
}
}
}
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// The string to manipulate String s ="IMT Atlantique";
System.out.println(s);
// The thing to search String pref ="IMT";
// Use string method for thatif (s.startsWith(pref)) {
System.out.println(pref +" is a prefix of "+ s);
} else {
System.out.println(pref +" is not a prefix of "+ s);
}
}
}
4 — Contient
Reprenez le même code de base que dans l’exercice 1.
Considérant un second tableau de caractères, nommé substr par exemple, déterminez si substr est présent dans s.
L’algorithme indique la position de la première occurrence de substr dans s ou s’il n’est pas présent.
L’algorithme peut être évalué avec les valeurs suivantes :
s = "IMT Atlantique" et substr = "Atlan"
s = "IMT Atlantique" et substr = "Pyhton"
s = "I love Computer Science and Algorithms" et substr = "and"
Correction
# The string to manipulates ="IMT Atlantique"print(s)
# The thing to searchsubstr ="Atlan"# Initialize variablesindex_start =0index_sub =0found =False# Outer loop: iterate through each position in the string where the substring could startwhile index_start <= len(s) - len(substr) and index_sub < len(substr):
# Inner loop: check if the substring matches at this position index_sub =0while index_sub < len(substr) and s[index_start + index_sub] == substr[index_sub]:
index_sub +=1 index_start +=1# Print a message if not foundif index_sub >= len(substr):
print("Substring found at position", index_start -1)
else:
print("Substring not found")
# The string to manipulates ="IMT Atlantique"print(s)
# The thing to searchsubstr ="Atlan"# You can directly check with 'in' keywordif substr in s:
print("Substring found at index", s.index(substr))
else:
print("Substring not found")
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// The string to manipulate String s ="IMT Atlantique";
System.out.println(s);
// The thing to search String substr ="Atlan";
// Initialize variablesint indexStart = 0;
int indexSub = 0;
boolean found =false;
// Outer loop: iterate through each position in the string where the substring could startwhile (indexStart <= s.length() - substr.length() && indexSub < substr.length()) {
// Inner loop: check if the substring matches at this position indexSub = 0;
while (indexSub < substr.length() && s.charAt(indexStart + indexSub) == substr.charAt(indexSub)) {
indexSub++;
}
indexStart++;
}
// Print a message if not foundif (indexSub >= substr.length()) {
System.out.println("Substring found at position "+ (indexStart - 1));
} else {
System.out.println("Substring not found");
}
}
}
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// The string to manipulate String s ="IMT Atlantique";
System.out.println(s);
// The thing to search String substr ="Atlan";
// Use string method for thatif (s.contains(substr)) {
System.out.println("Substring found at index "+ s.indexOf(substr));
} else {
System.out.println("Substring not found");
}
}
}
5 — Inverser
Reprenez le même code de base que dans l’exercice 1.
Déterminez un algorithme qui inverse le contenu de la chaîne s.
L’algorithme peut être évalué avec les valeurs suivantes :
s = "IMT Atlantique"
s = "euqitnaltA TMI"
s = "I love Computer Science and Algorithms"
Correction
# The string to manipulates ="IMT Atlantique"print(s)
# Loop to append to a new stringresult =""for character in s:
result = character + result
# Print the resultprint("Reversed string:", result)
# The string to manipulates ="IMT Atlantique"print(s)
# Using operator []result = s[::-1]
# Print the resultprint("Reversed string:", result)
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// The string to manipulate String s ="IMT Atlantique";
System.out.println(s);
// Loop to append to a new string String result ="";
for (int i = 0; i < s.length(); i++) {
result = s.charAt(i) + result;
}
// Print the result System.out.println("Reversed string: "+ result);
}
}
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// The string to manipulate String s ="IMT Atlantique";
System.out.println(s);
// Using StringBuilder for reversing a string String result =new StringBuilder(s).reverse().toString();
// Print the result System.out.println("Reversed string: "+ result);
}
}
6 — Palindrome
Un palindrome est un mot qui peut se lire dans les deux sens, comme par exemple “radar” ou “laval”.
Déterminez une première stratégie naïve pour vérifier si une chaîne est un palindrome basée sur l’algorithme d’inversion conçu précédemment.
L’algorithme peut être évalué avec les valeurs suivantes :
s = "laval"
s = "rennes"
s = "detartrated"
Correction
# Initialize variabless ="LAVAL"i =0# Iterate over the stringwhile i < len(s) /2and s[i] == s[len(s) -1- i]:
i +=1# Show result# Show resultif i >= len(s) /2:
print(s, "is a palindrome")
else:
print(s, "is not a palindrome")
# The string to manipulates ="laval"print(s)
# Check if s is a palindromeif s == s[::-1]:
print(s, "is a palindrome")
else:
print(s, "is not a palindrome")
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// The string to manipulate String s ="laval";
System.out.println(s);
// Initialize variablesint i = 0;
// Loop to check characters from start and endwhile (i < s.length() / 2 && s.charAt(i) == s.charAt(s.length() - i - 1)) {
i++;
}
// Print a message based on the resultif (i >= s.length() / 2) {
System.out.println(s +" is a palindrome");
} else {
System.out.println(s +" is not a palindrome");
}
}
}
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// The string to manipulate String s ="laval";
System.out.println(s);
// Check if s is a palindrome using StringBuilderif (s.equals(new StringBuilder(s).reverse().toString())) {
System.out.println(s +" is a palindrome");
} else {
System.out.println(s +" is not a palindrome");
}
}
}
6.1 — Défi supplémentaire (optionnel)
Un palindrome peut aussi être une phrase, telle que "A man, a plan, a canal: Panama".
Adaptez votre algorithme pour ignorer les espaces, les signes de ponctuation et convertir en minuscules avant de vérifier si la chaîne est un palindrome.
Python fournit des méthodes intégrées pour ces opérations : isalnum(), lower().
Correction
# The string to manipulates ="A man, a plan, a canal: Panama"print(s)
# Remove spaces, punctuation marks and convert to lowercasesimplified_s =""for character in s:
if character.isalnum():
simplified_s += character.lower()
# Iterate over the stringi =0while i < len(simplified_s) /2and simplified_s[i] == simplified_s[len(simplified_s) -1- i]:
i +=1# Show resultif i >= len(simplified_s) /2:
print(s, "is a palindrome")
else:
print(s, "is not a palindrome")
# The string to manipulates ="A man, a plan, a canal: Panama"print(s)
# Remove spaces, punctuation marks and convert to lowercasesimplified_s =''.join(character for character in s if character.isalnum()).lower()
# Check if s is a palindromeif simplified_s == simplified_s[::-1]:
print(s, "is a palindrome")
else:
print(s, "is not a palindrome")
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// The string to manipulate String s ="A man, a plan, a canal: Panama";
System.out.println(s);
// Remove spaces, punctuation marks and convert to lowercase StringBuilder builder =new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char character = s.charAt(i);
if (Character.isLetterOrDigit(character)) {
builder.append(Character.toLowerCase(character));
}
}
String simplifiedS = builder.toString();
// Iterate over the stringint i = 0;
while (i < simplifiedS.length() / 2 && simplifiedS.charAt(i) == simplifiedS.charAt(simplifiedS.length() - 1 - i)) {
i++;
}
// Show resultif (i >= simplifiedS.length() / 2) {
System.out.println(s +" is a palindrome");
} else {
System.out.println(s +" is not a palindrome");
}
}
}
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// The string to manipulate String s ="A man, a plan, a canal: Panama";
System.out.println(s);
// Remove spaces, punctuation marks and convert to lowercase String simplifiedS = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
// Check if s is a palindrome using StringBuilderif (simplifiedS.contentEquals(new StringBuilder(simplifiedS).reverse())) {
System.out.println(s +" is a palindrome");
} else {
System.out.println(s +" is not a palindrome");
}
}
}
7 — Optimisez vos solutions
Ce que vous pouvez faire maintenant est d’utiliser des outils d’IA tels que GitHub Copilot ou ChatGPT, soit pour générer la solution, soit pour améliorer la première solution que vous avez proposée !
Essayez cela pour tous les exercices ci-dessus, afin de voir les différences avec vos solutions.
Pour aller plus loin
8 — Hexadécimal
Considérez une chaîne représentant un nombre en format hexadécimal.
Calculez sa valeur décimale.
Pour rappel, un nombre hexadécimal peut contenir les chiffres suivants : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
‘A’ vaut 10, et ainsi de suite.
Par exemple :
Une solution intégrée existe en Python (et dans d’autres langages) pour résoudre ce problème, mais essayez de travailler avec des boucles pour vous familiariser avec leur utilisation.
On suppose que chaque symbole dans la chaîne à convertir est un chiffre acceptable en format hexadécimal.
Correction
# Initialize variablesto_convert ="8EA4"result =0# Iterate over the stringfor index in range(len(to_convert)):
# Convert to decimal value =Nonematch to_convert[index]:
case'A': value =10case'B': value =11case'C': value =12case'D': value =13case'E': value =14case'F': value =15case _ : value = int(to_convert[index])
# Aggregate to solution power = len(to_convert) - index -1 result +=16** power * value
# Print resultprint("Decimal version of", to_convert, "is", result)
# Value to convertto_convert ="8EA4"# Convert into decimalresult = int(to_convert, 16)
print("Decimal version of", to_convert, "is", result)
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// Initialize variables String toConvert ="8EA4";
int result = 0;
// Iterate over the stringfor (int index = 0; index < toConvert.length(); index++) {
// Convert to decimalint value;
char currentChar = toConvert.charAt(index);
switch (currentChar) {
case'A': value = 10; break;
case'B': value = 11; break;
case'C': value = 12; break;
case'D': value = 13; break;
case'E': value = 14; break;
case'F': value = 15; break;
default: value = Character.getNumericValue(currentChar); break;
}
// Aggregate to solutionint power = toConvert.length() - index - 1;
result += Math.pow(16, power) * value;
}
// Print result System.out.println("Decimal version of "+ toConvert +" is "+ result);
}
}
/**
* To run this code, you need to have Java installed on your computer, then:
* - Create a file named `Main.java` in a directory of your choice.
* - Copy this code in the file.
* - Open a terminal in the directory where the file is located.
* - Run the command `javac Main.java` to compile the code.
* - Run the command `java -ea Main` to execute the compiled code.
* Note: '-ea' is an option to enable assertions in Java.
*/publicclassMain {
/**
* This is the entry point of your program.
* It contains the first codes that are going to be executed.
*
* @param args Command line arguments received.
*/publicstaticvoidmain(String[] args) {
// Value to convert String toConvert ="8EA4";
// Convert into decimal using Java's built-in methodint result = Integer.parseInt(toConvert, 16);
System.out.println("Decimal version of "+ toConvert +" is "+ result);
}
}
Pour aller plus loin
9 — Vérification des invariants
Coder et tester des boucles avec quelques cas, même judicieusement sélectionnés, ne suffit pas à garantir que votre algorithme renverra toujours le résultat attendu.
En utilisant l’induction mathématique, vérifiez la correction des itérations que vous avez conçues durant cette activité.