Nantes Université

Skip to content
Extraits de code Groupes Projets
Valider 1e97a14c rédigé par Arnaud LANOIX's avatar Arnaud LANOIX
Parcourir les fichiers

init TP1

parent
Aucune branche associée trouvée
Aucune étiquette associée trouvée
Aucune requête de fusion associée trouvée
Affichage de
avec 963 ajouts et 0 suppression
# qalgo.tp1.recursivite
> **ATTENTION :** Si vous utilisez un PC de l'IUT, décommentez
> les 4 lignes `systemProp.http.proxyXXX`
> dans le fichier `gradle.properties` pour activer la configuration du proxy.
## Compte à rebours
Implémentez la méthode `CountDown.count(n : Int)`.
Des cas de test sont donnés dans `TestCountDown`.
Notez la classe `InstrumentedCountDown` ; à quoi sert cette classe ?
## Factorielle
Implémentez la méthode `RecursiveFactorial.facto(n)`.
Des cas de test sont donnés dans `TestRecursiveFactorial`.
Quand tous les autres cas de test sont **OK**,
`facto19()` et `facto20()` échouent encore ; pourquoi ?
Quelle correction apportée ? Faites le.
Implémentez maintenant la méthode `IterativeFactorial.facto(n)`.
Des cas de test sont donnés dans `TestIterativeFactorial`.
## Palindrôme
Un palindrome est une chaîne qui se lit indifféremment dans les deux sens de lecture.
Exemples :
+ "Laval"
+ "Tu l'as trop écrasé César ce Port-Salut"
+ "Élu par cette crapule"
1. Implémentez la méthode `RecursivePalindrome.isormalizedPalindrome(s : String)`
qui vérifie qu'une chaîne normalisée est un palindrome
2. Implémentez la méthode `RecursivePalindrome.normalize(s : String)`
qui normalise une chaîne en ignorant les espaces, les accents et la casse.
Des cas de test sont donnés dans `TestPalindrome`.
## Permutations
Implémentez dans `RecursiveHeapPermutations` la version récursive de l'algorithme de Heap :
https://fr.wikipedia.org/wiki/Algorithme_de_Heap
Des cas de test sont donnés dans `TestRecursivePermutations`.
Vous devriez arriver au point où tous les cas de tests sont OK sauf `PermutTrop()` ;
pourquoi ?
Implémentez dans `IterativeHeapPermutations` la version itérative de l'algorithme de Heap.
Des cas de test sont donnés dans `TestIterativePermutations`.
\ No newline at end of file
plugins {
kotlin("jvm") version "1.9.21"
//kotlin("plugin.serialization") version "1.9.21"
}
group = "org.example"
version = "1.0-SNAPSHOT"
repositories {
maven {
url = uri("http://nexus.dep-info.iut-nantes.univ-nantes.prive/repository/maven-central/")
isAllowInsecureProtocol = true
}
//mavenCentral()
}
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter:5.11.2")
testImplementation("org.junit.jupiter:junit-jupiter-params:5.11.2")
//implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.3")
}
tasks.test {
useJUnitPlatform()
}
kotlin {
jvmToolchain(11)
}
\ No newline at end of file
kotlin.code.style=official
#systemProp.http.proxyHost=srv-proxy-etu-2.iut-nantes.univ-nantes.prive
#systemProp.http.proxyPort=3128
#systemProp.https.proxyHost=srv-proxy-etu-2.iut-nantes.univ-nantes.prive
#systemProp.https.proxyPort=3128
\ No newline at end of file
Fichier ajouté
#Wed Sep 25 15:57:43 CEST 2024
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#!/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
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.5.0"
}
rootProject.name = "qalgo.tp1.recursivite"
\ No newline at end of file
package countdown
open class CountDown {
/**
* implémentation RECURSIVE d'un affichage de type "compte à rebours"
*/
open fun count(number: Int): String {
TODO()
}
}
package factorial
interface FactorialStrategy {
/**
* retourne n!
*/
fun facto(n: Int): Int
}
package factorial
open class IterativeFactorial : FactorialStrategy {
/**
* Implémentation ITERATIVE du calcul de n!
*/
override fun facto(n: Int): Int {
TODO()
}
}
package factorial
open class RecursiveFactorial : FactorialStrategy {
/**
* implémentation RECURSIVE du calcul de n!
*/
override fun facto(n: Int): Int {
TODO()
}
}
package palindrome
open class RecursivePalindrome {
fun isPalindrome(s: String): Boolean {
return isNormalizedPalindrome(normalize(s))
}
/**
* normalise la chaîne de caractères, cad
* suppression des caractères non alphabétiques,
* suppression des accents,
* mise en minuscules,
*/
private fun normalize(s: String): String {
// TODO
return s
}
/**
* implémentation RECURSIVE de la verification d'un palindrome
*/
protected open fun isNormalizedPalindrome(s: String): Boolean {
TODO()
}
}
\ No newline at end of file
package permutations
open class IterativeHeapPermutations<K> : RecursiveHeapPermutations<K>() {
/**
* implémentation de la version ITERATIVE de l'algorithme de Heap :
* https://fr.wikipedia.org/wiki/Algorithme_de_Heap
*/
override fun heap(
data: MutableList<K>,
k: Int,
): List<List<K>> {
TODO()
}
}
package permutations
interface PermutationsStrategy<K> {
/**
* donne la liste de toutes les permutations de la liste passée en paramètre
* @param data la liste de valeurs à permuter
*/
fun permutations(data: List<K>): List<List<K>>
/**
* méthode utilitaire qui réalise l'échange entre deux positions dans une liste
* @param data une liste de valeurs
* @param a la position n°1 dans l'échange
* @param b la position n°2 dans l'échange
*/
fun swap(
data: MutableList<K>,
a: Int,
b: Int,
) {
val temp = data[a]
data[a] = data[b]
data[b] = temp
}
}
package permutations
open class RecursiveHeapPermutations<K> : PermutationsStrategy<K> {
/**
* donne les permutations en utilisant la version RECURSIVE de l"algorithme de Heap :
* https://fr.wikipedia.org/wiki/Algorithme_de_Heap
*/
override fun permutations(data: List<K>) = heap(data.toMutableList(), data.size)
/**
* implémentation de la version RECURSIVE de l'algorithme de Heap :
* https://fr.wikipedia.org/wiki/Algorithme_de_Heap
*/
open fun heap(
data: MutableList<K>,
k: Int,
): List<List<K>> {
TODO()
}
}
import countdown.CountDown
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
class TestCountDown {
lateinit var countDown: CountDown
inner class InstrumentedCountDown : CountDown() {
var countCalls = 0
override fun count(number: Int): String {
countCalls++
return super.count(number)
}
}
@BeforeEach
fun init() {
countDown = InstrumentedCountDown()
}
@Test
fun printCountDown0() {
assertEquals(
"GO",
countDown.count(0),
)
assertEquals(1, (countDown as InstrumentedCountDown).countCalls)
}
@Test
fun printCountDown4() {
assertEquals(
"4... 3... 2... 1... GO",
countDown.count(4),
)
assertEquals(5, (countDown as InstrumentedCountDown).countCalls)
}
@Test
fun printCountDown10() {
assertEquals(
"10... 9... 8... 7... 6... 5... 4... 3... 2... 1... GO",
countDown.count(10),
)
assertEquals(11, (countDown as InstrumentedCountDown).countCalls)
}
@Test
fun printCountDown100() {
var strExcepted = ""
for (i in 100 downTo 1) {
strExcepted += "$i... "
}
strExcepted += "GO"
assertEquals(
strExcepted,
countDown.count(100),
)
assertEquals(101, (countDown as InstrumentedCountDown).countCalls)
}
@ParameterizedTest(name = "countDown({0}) : impossible")
@CsvSource("-1", "-42", "-2", "-4", "-100")
fun countDownError(n: Int) {
assertThrows<IllegalArgumentException> { countDown.count(n) }
}
}
import factorial.FactorialStrategy
import factorial.IterativeFactorial
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
class TestIterativeFactorial {
lateinit var facto: FactorialStrategy
/**
* NB cette sous-classe seet à tester le nombre d'appels récursifs
*/
inner class InstrumentedFactorial : IterativeFactorial() {
var nbCalls = 0
override fun facto(n: Int): Int {
nbCalls++
return super.facto(n)
}
}
@BeforeEach
fun init() {
facto = InstrumentedFactorial()
}
@Test
fun facto0() {
assertEquals(1, facto.facto(0))
assertEquals(1, (facto as InstrumentedFactorial).nbCalls)
}
@Test
fun facto1() {
assertEquals(1, facto.facto(1))
assertEquals(1, (facto as InstrumentedFactorial).nbCalls)
}
@Test
fun facto2() {
assertEquals(2, facto.facto(2))
assertEquals(1, (facto as InstrumentedFactorial).nbCalls)
}
@ParameterizedTest(name = "factorielle({0}) = {1}")
@CsvSource(
"0,1", "1,1", "2,2", "3,6", "4,24", "7,5040",
"8,40320", "9,362880", "10,3628800", "11,39916800",
"12,479001600",
)
fun factoData(
n: Int,
result: Int
) {
assertEquals(result, facto.facto(n))
assertEquals(1, (facto as InstrumentedFactorial).nbCalls)
}
@Test
fun facto19() {
assertEquals(121645100408832000, facto.facto(19))
assertEquals(1, (facto as InstrumentedFactorial).nbCalls)
}
@Test
fun facto20() {
assertEquals(2432902008176640000, facto.facto(20))
assertEquals(1, (facto as InstrumentedFactorial).nbCalls)
}
@ParameterizedTest(name = "factorielle({0}) : impossible")
@CsvSource("-1", "-42", "-2", "-4", "-100")
fun factoBadData(n: Int) {
assertThrows<IllegalArgumentException> { facto.facto(n) }
}
}
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
import permutations.IterativeHeapPermutations
import permutations.PermutationsStrategy
class TestIterativePermutations {
lateinit var permuteInt: PermutationsStrategy<Int>
lateinit var permuteString: PermutationsStrategy<String>
inner class InstrumentedHeapPermutations<K> : IterativeHeapPermutations<K>() {
var calls = 0
override fun heap(data: MutableList<K>, k: Int): List<List<K>> {
calls++
return super.heap(data, k)
}
}
@BeforeEach
fun initializePermutationStrategies() {
permuteInt = InstrumentedHeapPermutations()
permuteString = InstrumentedHeapPermutations()
}
@Test
fun permutcompare0() {
val expected = listOf(emptyList<String>())
val result = permuteString.permutations(emptyList())
assertEquals(1, result.size.toLong())
assertEquals(expected.size, result.size)
expected.forEach { assertTrue(result.contains(it)) }
assertEquals(1, (permuteString as InstrumentedHeapPermutations).calls)
}
@Test
fun permutcompare1() {
val expected = listOf(listOf("1"))
val result = permuteString.permutations(listOf("1"))
assertEquals(expected.size, result.size)
assertEquals(1, result.size.toLong())
expected.forEach { assertTrue(result.contains(it)) }
assertEquals(1, (permuteString as InstrumentedHeapPermutations).calls)
}
@Test
fun permutcompare2() {
val expected = listOf(listOf(1, 2), listOf(2, 1))
val result = permuteInt.permutations(listOf(1, 2))
assertEquals(2, result.size.toLong())
assertEquals(expected.size, result.size)
expected.forEach { assertTrue(result.contains(it)) }
assertEquals(1, (permuteInt as InstrumentedHeapPermutations).calls)
}
@ParameterizedTest(name = "elements permuted : {0},{1},{2}")
@CsvSource("A,B,C", "A,C,B", "B,A,C", "B,C,A", "C,A,B", "C,B,A")
fun permutcompare3(
data1: String,
data2: String,
data3: String,
) {
val expected =
listOf(
listOf("A", "B", "C"),
listOf("A", "C", "B"),
listOf("B", "A", "C"),
listOf("B", "C", "A"),
listOf("C", "A", "B"),
listOf("C", "B", "A"),
)
val result = permuteString.permutations(listOf(data1, data2, data3))
assertEquals(6, result.size.toLong())
assertEquals(expected.size, result.size)
expected.forEach { assertTrue(result.contains(it)) }
assertEquals(1, (permuteString as InstrumentedHeapPermutations).calls)
}
@ParameterizedTest(name = "elements permuted : {0},{1},{2}")
@CsvSource("Riri, Fifi, Loulou", "Riri, Loulou, Fifi", "Fifi, Riri, Loulou")
fun permutcompare32(
data1: String,
data2: String,
data3: String,
) {
val expected =
listOf(
listOf("Riri", "Fifi", "Loulou"),
listOf("Riri", "Loulou", "Fifi"),
listOf("Fifi", "Riri", "Loulou"),
listOf("Fifi", "Loulou", "Riri"),
listOf("Loulou", "Riri", "Fifi"),
listOf("Loulou", "Fifi", "Riri"),
)
val result = permuteString.permutations(listOf(data1, data2, data3))
assertEquals(6, result.size.toLong())
assertEquals(expected.size, result.size)
println(result)
expected.forEach { assertTrue(result.contains(it)) }
assertEquals(1, (permuteString as InstrumentedHeapPermutations).calls)
}
@Test
fun permutcompare4() {
val expected =
listOf(
listOf("Belle Marquise", "vos beaux yeux", "me font mourir", "d'amour"),
listOf("Belle Marquise", "vos beaux yeux", "d'amour", "me font mourir"),
listOf("Belle Marquise", "me font mourir", "vos beaux yeux", "d'amour"),
listOf("Belle Marquise", "me font mourir", "d'amour", "vos beaux yeux"),
listOf("Belle Marquise", "d'amour", "me font mourir", "vos beaux yeux"),
listOf("Belle Marquise", "d'amour", "vos beaux yeux", "me font mourir"),
listOf("vos beaux yeux", "Belle Marquise", "me font mourir", "d'amour"),
listOf("vos beaux yeux", "Belle Marquise", "d'amour", "me font mourir"),
listOf("vos beaux yeux", "me font mourir", "Belle Marquise", "d'amour"),
listOf("vos beaux yeux", "me font mourir", "d'amour", "Belle Marquise"),
listOf("vos beaux yeux", "d'amour", "me font mourir", "Belle Marquise"),
listOf("vos beaux yeux", "d'amour", "Belle Marquise", "me font mourir"),
listOf("me font mourir", "vos beaux yeux", "Belle Marquise", "d'amour"),
listOf("me font mourir", "vos beaux yeux", "d'amour", "Belle Marquise"),
listOf("me font mourir", "Belle Marquise", "vos beaux yeux", "d'amour"),
listOf("me font mourir", "Belle Marquise", "d'amour", "vos beaux yeux"),
listOf("me font mourir", "d'amour", "Belle Marquise", "vos beaux yeux"),
listOf("me font mourir", "d'amour", "vos beaux yeux", "Belle Marquise"),
listOf("d'amour", "vos beaux yeux", "me font mourir", "Belle Marquise"),
listOf("d'amour", "vos beaux yeux", "Belle Marquise", "me font mourir"),
listOf("d'amour", "me font mourir", "vos beaux yeux", "Belle Marquise"),
listOf("d'amour", "me font mourir", "Belle Marquise", "vos beaux yeux"),
listOf("d'amour", "Belle Marquise", "me font mourir", "vos beaux yeux"),
listOf("d'amour", "Belle Marquise", "vos beaux yeux", "me font mourir"),
)
val result = permuteString.permutations(listOf("Belle Marquise", "vos beaux yeux", "me font mourir", "d'amour"))
assertEquals(24, result.size.toLong())
assertEquals(expected.size, result.size)
expected.forEach { assertTrue(result.contains(it)) }
assertEquals(1, (permuteString as InstrumentedHeapPermutations).calls)
}
@ParameterizedTest(name = "nb elements permuted : {0} gives {1} permutations")
@CsvSource(
"0,1",
"1,1",
"2,2",
"3,6",
"4,24",
"5,120",
"6,720",
"7,5040",
"8,40320",
"9,362880",
"10,3628800"
)
fun permut(limit: Int, nbPermutations: Long) {
val data = mutableListOf<Int>()
for (i in 0 until limit)
data.add(i)
val result = permuteInt.permutations(data)
assertEquals(nbPermutations, result.size.toLong())
assertEquals(1, (permuteString as InstrumentedHeapPermutations).calls)
}
@ParameterizedTest(name = "nb elements permuted : {0} gives {1} permutations")
@CsvSource(
"11,39916800",
"12,479001600",
)
fun permutTrop(limit: Int, nbPermutations: Long) {
val data = mutableListOf<Int>()
for (i in 0 until limit)
data.add(i)
val result = permuteInt.permutations(data)
assertEquals(nbPermutations, result.size.toLong())
}
}
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
import org.junit.jupiter.params.provider.ValueSource
import palindrome.RecursivePalindrome
class TestPalindrome {
lateinit var palindrome: RecursivePalindrome
@BeforeEach
fun setUp() {
palindrome = InstrumentedPalindrome()
}
inner class InstrumentedPalindrome : RecursivePalindrome() {
var calls = 0
override fun isNormalizedPalindrome(s: String): Boolean {
calls++
return super.isNormalizedPalindrome(s)
}
}
@ParameterizedTest(name = "isPalindrome({0}) ok")
@CsvSource(
"\"\", 1",
"\"A\", 1",
"\"xx\", 2",
"\"xxx\", 2",
"\"xXx\", 2",
"\"laval\", 3",
"\"kayak\", 3",
"\"radar\", 3",
"\"ressasser\", 5",
"\"été\", 2",
"\"Xx\", 2",
"\"xX\", 2",
"\"Kayak\", 3",
"\"Radar\", 3",
"\"Laval\", 3",
"\"Eté\", 2",
"\"Élu par cette crapule\", 10",
"\"Engage le jeu que je le gagne\", 12",
"\"Tu l'as trop écrasé César ce Port-Salut\", 16",
"\"À révéler mon nom : mon nom relèvera\", 15",
"\"Eva ! can I stab bats in a cave ?\", 12",
"\"God ! A red nugget! A fat egg under a dog\", 15",
"\"Mr. Owl ate my metal worm\", 10",
"\"Was it a car or a cat I saw\", 10"
)
fun palindromeOk(str: String, nbCalls: Int) {
assertTrue(palindrome.isPalindrome(str))
assertEquals(nbCalls, (palindrome as InstrumentedPalindrome).calls)
}
@ParameterizedTest(name = "isPalindrome({0}) ko")
@ValueSource(
strings = arrayOf(
"lavable",
"ressasse",
"kayaks",
"Eva ! puis-je poignarder des chauves-souris dans une grotte ?"
)
)
fun palindromeKo(str: String) {
assertFalse(palindrome.isPalindrome(str))
}
}
\ No newline at end of file
0% Chargement en cours ou .
You are about to add 0 people to the discussion. Proceed with caution.
Terminez d'abord l'édition de ce message.
Veuillez vous inscrire ou vous pour commenter