Skip to content

Commit

Permalink
Implemented Splay Tree Data Structure. Fix for array_rand for non-arr…
Browse files Browse the repository at this point in the history
…ay result. Rewriting.
  • Loading branch information
Ramy-Badr-Ahmed committed Oct 11, 2024
1 parent e2d9d80 commit 0a046c2
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions tests/DataStructures/SplayTreeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -457,24 +457,34 @@ public function testDeleteMultipleKeys()
{
$arrayData = [200 => "Value 200", 150 => "Value 150", 170 => "Value 170",
250 => "Value 250", 300 => "Value 300", 360 => "Value 360", 230 => "Value 230",
240 => "Value 240", 220 => "Value 220", 50 => "Value 50", 28 => "Value 28", 164 => "Value 164",
240 => "Value 240", 220 => "Value 220", 50 => "Value 50", 28 => "Value 28",
164 => "Value 164", 321 => "Value 321", 40 => "Value 40"
];

$splayTree = new SplayTree($arrayData);
$treeSize = $splayTree->size();

$numberOfNodesToDelete = rand(1, count($arrayData));
// pick randomly some nodes to delete
$randomNodesToDelete = array_rand($arrayData, rand(1, count($arrayData)));

$randomNodesToDelete = array_rand($arrayData, $numberOfNodesToDelete);
$randomNodesToDelete = is_array($randomNodesToDelete)
? $randomNodesToDelete
: [$randomNodesToDelete];

for ($i = 0; $i < count($randomNodesToDelete); $i++) {
$splayTree->delete($randomNodesToDelete[$i]);
$isFound = $splayTree->isFound($randomNodesToDelete[$i]);
$this->assertFalse($isFound, "Node with key $randomNodesToDelete[$i] was not deleted.");
$expectedSize = $treeSize - count($randomNodesToDelete);

foreach ($randomNodesToDelete as $key) {
$isFound = $splayTree->isFound($key); // splay the key to the root before deletion
$this->assertTrue($isFound, "Node with key $key is not present for deletion.");

$rootKey = $splayTree->getRoot()->key;
$this->assertEquals($rootKey, $key, "Target key was not splayed to root correctly.");

$splayTree->delete($splayTree->getRoot()->key);
}

$this->assertEquals(
$treeSize - $numberOfNodesToDelete,
$expectedSize,
$splayTree->size(),
"After deletion, total nodes count was not updated correctly."
);
Expand Down

0 comments on commit 0a046c2

Please sign in to comment.