From 91db11cc2d01395db57f04ef54083050503de013 Mon Sep 17 00:00:00 2001 From: adrien <adrien@malingrey.fr> Date: Sat, 3 May 2025 14:14:56 +0200 Subject: [PATCH] permutations --- Grille.php | 2 +- dico.php | 30 ++++++++++++++++++++++-------- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/Grille.php b/Grille.php index daa62b3..5a6fb4d 100644 --- a/Grille.php +++ b/Grille.php @@ -25,7 +25,7 @@ class Grille implements Iterator, ArrayAccess { $this->lettres_suivantes = []; foreach ($hauteur == $largeur ? [$hauteur] : [$hauteur, $largeur] as $longueur) { $this->lettres_suivantes[$longueur] = []; - foreach (mots_espaces($longueur, $hauteur == $largeur ? MAX_MOTS : MAX_MOTS/2) as $mots) { + foreach (mots_permutes($longueur) as $mots) { $mot = implode(" ", $mots); $ref = &$this->lettres_suivantes[$longueur]; for ($i = 0; $i < $longueur; $i++) { diff --git a/dico.php b/dico.php index 0c0a05d..6722b9c 100644 --- a/dico.php +++ b/dico.php @@ -3,9 +3,8 @@ const MIN_LETTRES_MOT_1 = 2; const MIN_LETTRES_MOT_2 = 1; -const MAX_MOTS = 1000000; -$dico = [[]]; +$dico = [[""]]; if (($lecteur = fopen("dico.csv", "r")) !== FALSE) { $header = fgetcsv($lecteur, 0, "\t"); while (($ligne = fgetcsv($lecteur, 0, "\t")) !== FALSE) { @@ -32,24 +31,39 @@ if (($lecteur = fopen("dico.csv", "r")) !== FALSE) { fclose($lecteur); } -function mots_espaces($longueur, $nb_mots_restants=MAX_MOTS) +function mots_espaces($longueur) { global $dico; foreach ($dico[$longueur] as $mot => $definition) { yield [$mot]; - if (--$nb_mots_restants <= 0) return; } for ($i = MIN_LETTRES_MOT_1; ($j = $longueur - $i - 1) >= MIN_LETTRES_MOT_2; $i++) { foreach ($dico[$i] as $mot => $definition) { - foreach (mots_espaces($j, $nb_mots_restants) as $mots) { + foreach (mots_espaces($j) as $mots) { if (!in_array($mot, $mots)) { yield [$mot, ...$mots]; - if (--$nb_mots_restants <= 0) return; - yield [...$mots, $mot]; - if (--$nb_mots_restants <= 0) return; } } } } } + +function permutations(array $elements) +{ + if (count($elements) <= 1) { + yield $elements; + } else { + foreach (permutations(array_slice($elements, 1)) as $permutation) { + foreach (range(0, count($elements) - 1) as $i) { + yield [...array_slice($permutation, 0, $i), $elements[0], ...array_slice($permutation, $i)]; + } + } + } +} + +function mots_permutes($longueur) { + foreach (mots_espaces($longueur) as $mots) { + yield from permutations($mots); + } +} \ No newline at end of file