interface trie avec des strings

This commit is contained in:
2025-05-07 21:21:48 +02:00
parent d5a120cd9a
commit ddebd453df
4 changed files with 40 additions and 21 deletions

View File

@ -5,8 +5,7 @@ class Trie implements ArrayAccess, IteratorAggregate, Countable {
public array $branches = [];
private $nb_branches = 0;
// ArrayAccess
public function offsetSet($cles, $valeur): void {
public function arraySet($cles, $valeur) {
$this->nb_branches++;
$cle = $cles[0];
$cles = array_slice($cles, 1);
@ -14,38 +13,38 @@ class Trie implements ArrayAccess, IteratorAggregate, Countable {
$this->branches[$cle] = $valeur;
} else {
if (!isset($this->branches[$cle])) $this->branches[$cle] = new Trie();
$this->branches[$cle]->offsetSet($cles, $valeur);
$this->branches[$cle]->arraySet($cles, $valeur);
}
}
public function offsetExists($cles): bool {
public function arrayExists($cles) {
$cle = $cles[0];
$cles = array_slice($cles, 1);
if ($cles == []) {
return isset($this->branches[$cle]);
} else {
return isset($this->branches[$cle]) && $this->branches[$cle]->offsetExists($cles);
return isset($this->branches[$cle]) && $this->branches[$cle]->arrayExists($cles);
}
}
public function &offsetGet($cles): mixed {
public function &arrayGet($cles) {
$cle = $cles[0];
$cles = array_slice($cles, 1);
if ($cles == []) {
return $this->branches[$cle];
} else {
return $this->branches[$cle]->offsetGet($cles);
return $this->branches[$cle]->arrayGet($cles);
}
}
public function offsetUnset($cles): void {
public function arrayUnset($cles) {
$cle = $cles[0];
$cles = array_slice($cles, 1);
if ($cles == []) {
unset($this->branches[$cle]);
$this->nb_branches--;
} else {
$this->branches[$cle]->offsetUnset($cles);
$this->branches[$cle]->arrayUnset($cles);
$this->nb_branches--;
if (count($this->branches[$cle]) == 0) {
unset($this->branches[$cle]);
@ -53,11 +52,10 @@ class Trie implements ArrayAccess, IteratorAggregate, Countable {
}
}
// IteratorAggregate
public function getIterator(): Traversable {
public function arrayIterator() {
foreach ($this->branches as $cle => $branche) {
if ($branche instanceof Trie) {
foreach($branche as $sous_cles => $feuille) {
foreach($branche->arrayIterator() as $sous_cles => $feuille) {
yield array_merge([$cle], $sous_cles) => $feuille;
}
} else {
@ -66,6 +64,30 @@ class Trie implements ArrayAccess, IteratorAggregate, Countable {
}
}
// ArrayAccess
public function offsetSet($string, $valeur): void {
$this->arraySet(str_split($string), $valeur);
}
public function offsetExists($string): bool {
return $this->arrayExists(str_split($string));
}
public function &offsetGet($string): mixed {
return $this->arrayGet(str_split($string));
}
public function offsetUnset($string): void {
$this->arrayUnset(str_split($string));
}
// IteratorAggregate
public function getIterator(): Traversable {
foreach($this->arrayIterator() as $array => $valeur) {
yield implode("", $array) => $valeur;
}
}
// Countable
public function count(): int {
return $this->nb_branches;