Skip to content
Snippets Groups Projects
Commit 9dda7b2f authored by Guyslain's avatar Guyslain
Browse files

"TD1 + initialisation"

parents
No related branches found
No related tags found
No related merge requests found
Showing
with 1112 additions and 0 deletions
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
\ No newline at end of file
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
plugins {
id("application")
}
application {
mainClass = "fr.univamu.progav.Main"
}
group = "fr.univamu"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
testImplementation(platform("org.junit:junit-bom:5.10.0"))
testImplementation("org.junit.jupiter:junit-jupiter")
}
tasks.test {
useJUnitPlatform()
}
\ No newline at end of file
File added
#Mon Sep 09 10:51:55 CEST 2024
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
gradlew 0 → 100755
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
rootProject.name = "ProgAv"
package fr.univamu;
public class Main {
}
\ No newline at end of file
package fr.univamu.progav;
public class Main {
public static void main(String[] args) {
}
}
package fr.univamu.progav.td1;
import java.util.ArrayList;
import java.util.List;
public class BreadthFirstSearch {
public interface Tree {
int getValue();
List<Tree> getChildren();
}
private List<Integer> orderedValue = new ArrayList<>();
public BreadthFirstSearch(Tree root) {
List<Tree> currentLevel = new ArrayList<>();
currentLevel.add(root);
while (!currentLevel.isEmpty()) {
List<Tree> nextLevel = new ArrayList<>();
for (Tree tree : currentLevel) {
orderedValue.add(tree.getValue());
for (Tree child : tree.getChildren()) {
nextLevel.add(child);
}
}
currentLevel = nextLevel;
}
}
public List<Integer> getOrderedValue() {
return orderedValue;
}
}
package fr.univamu.progav.td1;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class ExercicesBoucles {
public interface Person {
int age();
String name();
boolean isFemale();
Person mother();
Person father();
List<Person> children();
}
// Exercice : compléter toutes les méthodes suivantes
public static boolean hasFemale(List<Person> persons) {
return false;
}
// retourne vrai si la liste contient un individu homme et mineur (moins de 18 ans)
public static boolean containsMinorMale(List<Person> persons) {
return false;
}
// retourne un individu de la liste, femme et ayant au moins un enfant,
// null si aucun individu ne convient
public static Person findMother(List<Person> persons) {
return null;
}
// retourne vrai si tous les individus de la liste sont majeurs (âge >= 18)
public static boolean areAllMajor(List<Person> persons) {
return false;
}
// trouve un individu de la liste ayant un enfant, et retourne l'âge
// de cet enfant, ou -1 si aucun individu n'a d'enfant.
public static int ageOfSomeChild(List<Person> persons) {
return 0;
}
// retourne la liste de tous les hommes de la liste
public static List<Person> males(List<Person> persons) {
return List.of();
}
// retourne le nombre de femmes de la liste
public static int nbFemales(List<Person> persons) {
return 0;
}
// retourne la personne la plus agée de la liste,
// null si la liste est vide
public static Person eldest(List<Person> persons) {
return null;
}
// retourne une chaîne de caractères, comprenant les noms de toutes les
// personnes de la liste, dans l'ordre, séparés par une espace.
public static String names(List<Person> persons) {
StringBuilder builder = new StringBuilder();
builder.append("Ceci est ajouté");
builder.append(" en fin de chaîne.");
return builder.toString(); // -> "Ceci est ajouté en fin de chaîne."
}
// retourne vrai si les nombres d'hommes et de femmes sont égaux.
public static boolean hasAsManyMalesAsFemales(List<Person> persons) {
return false;
}
// retourne l'âge moyen des individus de la liste (0 si la liste est vide)
public static double averageAge(List<Person> persons) {
return 0;
}
}
package fr.univamu.progav.td1;
import java.util.List;
public class ExercicesConditionnelle {
// Exercice 1 : selon la couleur du feu et la présence d'autres véhicules,
// décider si la voiture avance ou s'arrête.
public interface Car {
void go();
void stop();
}
public interface TrafficLight {
boolean isGreen();
boolean isRed();
boolean isYellow();
}
public interface CrossRoad {
boolean isFree(); // le carrefour est libre de toute autre voiture
}
// La méthode decideStopOrGo doit appeler soit car.stop(), soit car.go(), correctement.
public static void decideStopOrGo(Car car, TrafficLight light, CrossRoad crossRoad) {
return;
}
// Exercice 2 : On souhaite calculer le tarif d’un billet de train pour une
// personne. Le tarif normal est de 10 euros, les mineurs et les sans-emplois
// bénéficient d’un tarif réduit à 5 euros. Enfin, les personnes ayant un
// abonnement annuel ne paient rien.
public interface Costumer {
int age();
boolean isUnemployed();
boolean hasAnnualSubscription();
}
public static double getPrice(Costumer costumer) {
return 0;
}
// Exercice 3 : Décider si une année est bissextile.
// Les années bissextiles ont lieu tous les 4 ans.
// Sauf les dernières années de chaque siècle (1900, 2100 ne sont pas bissextiles)
// Sauf tous les 4 siècles (1600, 2000, 2400 sont bissextiles)
public static boolean isLeapYear(int year) {
// n % p == 0 teste la divisibilité de n par p
// (car n % p est le reste de la division de n par p)
return false;
}
// Exercice 4 : calculer le jour suivant.
// On reçoit une date,
// par exemple day=11, month=09, year=2024 pour le 11 septembre 2024.
// On doit retourner la date du lendemain, sous forme d'une chaîne
// de caractère, dans l'exemple "12/09/2024".
public final static List<Integer> MONTHS =
List.of( 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
public static String nextDayString(int day, int month, int year) {
int nextDay = day;
int nextMonth = month;
int nextYear = year;
// Mise au format de la date (ne pas modifier) :
return String.format("%02d/%02d/%02d", nextDay, nextMonth, nextYear);
}
}
package fr.univamu.progav.td1;
import java.util.ArrayList;
import java.util.List;
public class Primes {
public static List<Integer> primes(int max) {
List<Integer> primes = new ArrayList<>();
primes.add(2);
for (int n = 3; n <= max; n = n + 2) {
boolean isPossiblyPrime = true;
for (int p : primes) {
if (n % p == 0) {
isPossiblyPrime = false;
break;
}
}
if (isPossiblyPrime) {
primes.add(n);
}
}
return primes;
}
}
Exercice 1
==========
Ouvrir la classe `ExercicesConditionnelle`, qui comprend 4 questions. Pour
chaque question compléter la méthode correspondante. Tester que votre
solution est correcte en utilisant les tests unitaires fournis.
Exercice 2
==========
Ouvrir la classe `ExercicesBoucles`, qui comprend 11 questions. Pour chaque
question, compléter la méthode correspondante. tester que votre solution est
correcte en utilisant les tests unitaires fournis.
Exercice 3
==========
Refactoriser la méthode `search` de la classe `BreadthFirstSearch`, d'abord en
extrayant les boucles internes en méthode *à la main*, puis en utilisant les
outils d'IntelliJ.
Pour extraire une méthode avec IntelliJ, sélectionner la boucle à extraire
(ou en tout cas les instructions que vous souhaitez déplacer vers une
méthode), puis utiliser le raccourci clavier 'Ctrl+Alt+M'. Donner un
nom à la méthode. Renseignez les
champs correctement et assurez-vous bien que l'extraction est correcte, au
besoin corriger. (N'oubliez pas, en cas d'échec, vous pouvez simplement
revenir en arrière avec 'Ctrl-Z').
Les tests doivent toujours passés après vos modifications.
Exercice 4
==========
Refactoriser la méthode `primes` de la classe `Primes`, en extrayant la
boucle interne et en simplifiant autant que possible.
package fr.univamu.progav.td1;
import fr.univamu.progav.td1.mock.MockTree;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class BreadthFirstSearchTest {
@Test
void searchTree0() {
List<Integer> bfsOrder =
new BreadthFirstSearch(MockTree.tree0).getOrderedValue();
assertEquals(List.of(0,1,2,3,4), bfsOrder);
}
@Test
void searchTree1() {
List<Integer> bfsOrder =
new BreadthFirstSearch(MockTree.tree1).getOrderedValue();
assertEquals(List.of(1,2,7,3,5,8,9,4,6), bfsOrder);
}
@Test
void searchLeaf() {
List<Integer> bfsOrder = new BreadthFirstSearch(MockTree.of(2)).getOrderedValue();
assertEquals(List.of(2), bfsOrder);
}
}
\ No newline at end of file
package fr.univamu.progav.td1;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
import static fr.univamu.progav.td1.ExercicesBoucles.Person;
class ExercicesBouclesTest {
private record MockPerson(
int age,
String name,
boolean isFemale,
Person mother,
Person father,
List<Person> children
) implements Person {}
private static final Person alfa =
new MockPerson(78,"Alfa",true,null,null, new ArrayList<>());
private static final Person bravo =
new MockPerson(82,"Bravo",false,null,null, new ArrayList<>());
private static final Person charlie =
new MockPerson(42,"Charlie",false, alfa,bravo,List.of());
private static final Person delta =
new MockPerson(38,"Delta",false, alfa,bravo, new ArrayList<>());
private static final Person echo =
new MockPerson(41,"Echo",true,null,null, new ArrayList<>());
private static final Person foxtrot =
new MockPerson(7,"Foxtrot",true,echo,delta, List.of());
private static final Person golf =
new MockPerson(25,"Golf",true,null,null, new ArrayList<>());
private static final Person hotel =
new MockPerson(2,"Hotel",false,golf,null, List.of());
private static final Person india =
new MockPerson(8,"India",true,null,null, List.of());
private static final Person juliett =
new MockPerson(18,"Juliett",false,null,null,List.of());
static {
alfa.children().addAll(List.of(charlie, delta));
bravo.children().addAll(List.of(charlie, delta));
delta.children().add(foxtrot);
echo.children().add(foxtrot);
golf.children().add(hotel);
}
private static final List<Person> ALL =
List.of(alfa,bravo,charlie,delta,echo,foxtrot,golf,hotel,india,juliett);
@Test
void hasFemale() {
assertTrue(ExercicesBoucles.hasFemale(ALL));
assertFalse(ExercicesBoucles.hasFemale(ALL.stream().filter(p -> !p.isFemale()).toList()));
assertTrue(ExercicesBoucles.hasFemale(List.of(alfa)));
assertFalse(ExercicesBoucles.hasFemale(List.of()), "Cas de la liste vide");
}
@Test
void containsMinorMale() {
assertTrue(ExercicesBoucles.containsMinorMale(ALL));
assertFalse(ExercicesBoucles.containsMinorMale(ALL.stream().filter(p -> p.age() >= 18).toList()), "Pas de mineurs");
assertFalse(ExercicesBoucles.containsMinorMale(ALL.stream().filter(Person::isFemale).toList()), "Pas d'hommes");
assertFalse(ExercicesBoucles.containsMinorMale(List.of()), "Cas de la liste vide");
}
@Test
void findMother() {
Person found = ExercicesBoucles.findMother(ALL);
assertNotNull(found);
assertTrue(found.isFemale() && !found.children().isEmpty());
assertEquals(golf,ExercicesBoucles.findMother(List.of(bravo,charlie,delta,golf,hotel,india)));
assertNull(ExercicesBoucles.findMother(List.of(bravo,charlie,delta,foxtrot,hotel,india)));
assertNull(ExercicesBoucles.findMother(List.of()), "Cas de la liste vide");
}
@Test
void areAllMajor() {
assertFalse(ExercicesBoucles.areAllMajor(ALL));
assertTrue(ExercicesBoucles.areAllMajor(ALL.stream().filter(p -> p.age() > 18).toList()));
assertTrue(ExercicesBoucles.areAllMajor(ALL.stream().filter(p -> p.age() >= 18).toList()), "Cas d'un individu ayant 18 ans");
assertFalse(ExercicesBoucles.areAllMajor(ALL.stream().filter(p -> p.age() < 18).toList()));
assertTrue(ExercicesBoucles.areAllMajor(List.of()), "Cas de la liste vide");
}
@Test
void ageOfSomeChild() {
assertTrue(List.of(charlie.age(),delta.age()).contains(ExercicesBoucles.ageOfSomeChild(List.of(hotel,india,juliett,alfa,foxtrot,charlie))));
assertEquals(-1,ExercicesBoucles.ageOfSomeChild(List.of(charlie,foxtrot,hotel,india,juliett)));
assertEquals(-1,ExercicesBoucles.ageOfSomeChild(List.of()),"Cas de la liste vide");
}
@Test
void males() {
List<Person> allMales = ExercicesBoucles.males(ALL);
List<Person> expected = ALL.stream().filter(p -> !p.isFemale()).toList();
assertNotNull(allMales);
assertEquals(expected.size(), allMales.size(), "Nombre d'hommes incorrect");
for (Person p : expected ) {
assertTrue(allMales.contains(p), p.name() + " est un homme qui n'est pas dans la liste");
}
List<Person> neitherMaleNorFemale = ExercicesBoucles.males(ALL.stream().filter(Person::isFemale).toList());
assertNotNull(neitherMaleNorFemale);
assertTrue(neitherMaleNorFemale.isEmpty());
List<Person> empty = ExercicesBoucles.males(List.of());
assertNotNull(empty, "Cas de la liste vide");
assertTrue(empty.isEmpty(), "Cas de la liste vide");
}
@Test
void nbFemales() {
assertEquals(0,ExercicesBoucles.nbFemales(List.of()), "Cas de la liste vide");
assertEquals(5,ExercicesBoucles.nbFemales(ALL));
assertEquals(0,ExercicesBoucles.nbFemales(ALL.stream().filter(p -> !p.isFemale()).collect(Collectors.toList())));
}
@Test
void eldest() {
assertNull(ExercicesBoucles.eldest(List.of()), "Cas de la liste vide");
assertEquals(bravo,ExercicesBoucles.eldest(ALL));
}
@Test
void names() {
String allNames = ExercicesBoucles.names(ALL).trim();
assertEquals("Alfa Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliett",allNames);
assertEquals("",ExercicesBoucles.names(List.of()), "Cas de la liste vide");
}
@Test
void hasAsManyMalesAsFemales() {
assertTrue(ExercicesBoucles.hasAsManyMalesAsFemales(List.of()), "Cas de la liste vide");
assertFalse(ExercicesBoucles.hasAsManyMalesAsFemales(List.of(alfa)));
assertFalse(ExercicesBoucles.hasAsManyMalesAsFemales(List.of(bravo)));
assertFalse(ExercicesBoucles.hasAsManyMalesAsFemales(ALL.stream().filter(Person::isFemale).toList()));
assertFalse(ExercicesBoucles.hasAsManyMalesAsFemales(ALL.stream().filter(p -> !p.isFemale()).toList()));
assertTrue(ExercicesBoucles.hasAsManyMalesAsFemales(ALL));
}
@Test
void averageAge() {
assertEquals(0,ExercicesBoucles.averageAge(List.of()), "Cas de la liste vide");
double average = ExercicesBoucles.averageAge(ALL);
double expected = 34.1;
assertTrue(Math.abs(average - expected) < 0.1, "La moyenne correcte est " + expected);
}
}
\ No newline at end of file
package fr.univamu.progav.td1;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ExercicesConditionnelleTest {
static final class MockCar implements ExercicesConditionnelle.Car {
int nbGo = 0;
int nbStop = 0;
public void go() { nbGo++; }
public void stop() { nbStop++; }
}
enum Light implements ExercicesConditionnelle.TrafficLight {
RED("rouge"), GREEN("vert"), YELLOW("orange");
private final String name;
Light(String name) { this.name = name; }
public boolean isGreen() { return this == GREEN; }
public boolean isRed() { return this == RED; }
public boolean isYellow() { return this == YELLOW; }
}
@Test
void testDecideGo() {
MockCar car = new MockCar();
ExercicesConditionnelle.decideStopOrGo(car, Light.GREEN,()->true);
String situation = "(" + Light.GREEN.name + ", carrefour libre)";
assertTrue(1 == car.nbGo + car.nbStop,
() -> "la voiture doit prendre exactement une décision " + situation);
assertTrue(0 == car.nbStop,() -> "La voiture ne doit pas s'arrêter au vert " + situation);
assertTrue(1 == car.nbGo,() -> "La voiture doit s'avancer au vert " + situation);
}
@Test
void testDecideStop() {
for (Light light : Light.values()) {
MockCar car = new MockCar();
ExercicesConditionnelle.decideStopOrGo(car, light,()-> false);
String situation = "(" + light.name + ", carrefour occupé)";
assertTrue(1 == car.nbGo + car.nbStop,
() -> "la voiture doit prendre exactement une décision " + situation);
assertTrue(0 == car.nbGo,()-> "La voiture ne doit pas avancer " + situation);
assertTrue(1 == car.nbStop, () -> "La voiture doit s'arrêter " + situation);
}
for (Light light : List.of(Light.YELLOW,Light.RED)) {
MockCar car = new MockCar();
ExercicesConditionnelle.decideStopOrGo(car, light,()-> true);
String situation = "(" + light.name + ", carrefour libre)";
assertTrue(car.nbGo + car.nbStop == 1, () -> "la voiture doit prendre exactement une " +
"décision" +
"situation");
assertTrue(car.nbGo == 0,()-> "La voiture ne doit pas avancer " + situation);
assertTrue(car.nbStop == 1, () -> "La voiture doit s'arrêter " + situation);
}
}
record MockCostumer(
int age,
boolean isUnemployed,
boolean hasAnnualSubscription,
double price
) implements ExercicesConditionnelle.Costumer {
@Override
public String toString() {
return "Âge " + age + " "
+ (isUnemployed? "sans emploi ": "")
+ (hasAnnualSubscription? "avec abonnement annuel": "");
}
}
private List<MockCostumer> costumers =
List.of(
new MockCostumer(28,false,false,10),
new MockCostumer(19,false,false,10),
new MockCostumer(18,false,false,5),
new MockCostumer(28,true,false,5),
new MockCostumer(28,false,true,0),
new MockCostumer(28,true,true,0),
new MockCostumer(18,true,false,5),
new MockCostumer(18,false,true,0),
new MockCostumer(18,true,true,0),
new MockCostumer(15,false,false,5),
new MockCostumer(15,true,false,5),
new MockCostumer(15,false,true,0),
new MockCostumer(15,true,true,0)
);
@Test
void getPriceTest() {
for (MockCostumer costumer : costumers) {
double price = ExercicesConditionnelle.getPrice(costumer);
assertEquals(costumer.price, price,
"prix incorrect dans le cas : " + costumer);
}
}
@Test
void leapYearTest() {
for (int year : List.of(1984,1988,2004,2024,4080,1600,2000,2400,5200)) {
assertTrue(ExercicesConditionnelle.isLeapYear(year), () -> year + " est bissextile");
}
for (int year : List.of(2025,1979,1999,1900,2100,5100,2023)) {
assertTrue(!ExercicesConditionnelle.isLeapYear(year), () -> year + " n'est pas bissextile");
}
}
public record Date(int day, int month, int year) {
@Override
public String toString() {
return String.format("%02d/%02d/%02d", day, month, year);
}
}
private List<Date> dates = List.of(
new Date(11,9,2024),
new Date(30,9,2024),
new Date(28,2,2024),
new Date(28,2,2023),
new Date(28,2,2000),
new Date(31,12,2024),
new Date(31,12,2000),
new Date(31,1,2024),
new Date(30,4,2024),
new Date(30,5,2024)
);
private List<String> datesOutputs = List.of(
"12/09/2024",
"01/10/2024",
"29/02/2024",
"01/03/2023",
"29/02/2000",
"01/01/2025",
"01/01/2001",
"01/02/2024",
"01/05/2024",
"31/05/2024"
);
@Test
void nextDayTest() {
for (int i = 0;i < dates.size();i++) {
Date date = dates.get(i);
assertEquals(datesOutputs.get(i),
ExercicesConditionnelle.nextDayString(date.day,date.month,date.year));
}
}
}
package fr.univamu.progav.td1;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class PrimesTest {
public static final List<Integer> PRIMES = List.of(2,
3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61, 67, 71, 73, 79, 83, 89, 97
);
@Test
void primes() {
List<Integer> primesTo100 = Primes.primes(100);
assertEquals(PRIMES, primesTo100);
}
void includesBound() {
List<Integer> primesTo83 = Primes.primes(83);
assertTrue(primesTo83.contains(83));
}
}
\ No newline at end of file
package fr.univamu.progav.td1.mock;
import fr.univamu.progav.td1.BreadthFirstSearch;
import java.util.ArrayList;
import java.util.List;
public class MockTree implements BreadthFirstSearch.Tree {
public static final BreadthFirstSearch.Tree tree0 =
of(0,of(1),of(2),of(3),of(4));
public static final BreadthFirstSearch.Tree tree1 =
of(1,
of(2,
of(3,
of(4)),
of(5,
of(6))),
of(7,
of(8),
of(9)));
public List<BreadthFirstSearch.Tree> getChildren() {
return children;
}
public int getValue() {
return value;
}
public static MockTree of(int value, BreadthFirstSearch.Tree... children) {
MockTree tree = new MockTree(value);
for (BreadthFirstSearch.Tree child : children) {
tree.addChild(child);
}
return tree;
}
private List<BreadthFirstSearch.Tree> children = new ArrayList<>();
private int value;
private MockTree(int value) {
this.value = value;
}
public void addChild(BreadthFirstSearch.Tree child) {
children.add(child);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment