Last active
April 25, 2023 15:05
-
-
Save Muqsit/0db0cd93094d006bf0f71162731ef22f to your computer and use it in GitHub Desktop.
A memory-efficient adjacency matrix that can store values in the range 0-15 (4 bits) per cell. Takes roughly 8 * v bytes of memory space (where v = number of vertices). Suitable for Minecraft redstone wires which have a strength of up to 15.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
final class AdjacencyMatrix{ | |
public static function read(string $data) : self{ | |
return new self(array_values(unpack("J*", $data))); | |
} | |
public static function of(int $size) : self{ | |
return new self(array_fill(0, ($size >> 4) | $size, 0)); | |
} | |
/** | |
* @param list<int> $values | |
*/ | |
private function __construct( | |
private array $values | |
){} | |
public function set(int $x, int $y, int $value) : void{ | |
$this->values[($x >> 4) | $y] |= ($value << ($x * 4)); | |
} | |
public function get(int $x, int $y) : int{ | |
return ($this->values[($x >> 4) | $y] >> ($x * 4)) & 15; | |
} | |
public function write() : string{ | |
return pack("J*", ...$this->values); | |
} | |
} | |
$m = AdjacencyMatrix::of(8); | |
for($i = 0; $i < 4; $i++){ | |
$m->set(4, $i, ($i + 1) * 2); | |
} | |
for($i = 0; $i < 4; $i++){ | |
$m->set(6, 6-$i, 15); | |
} | |
for($i = 0; $i < 4; $i++){ | |
var_dump($m->get(4, $i)); | |
} | |
for($i = 0; $i < 4; $i++){ | |
var_dump($m->get(6, 6-$i)); | |
} | |
var_dump($m); | |
var_dump(AdjacencyMatrix::read($m->write())); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment