Skip to content

Instantly share code, notes, and snippets.

@muhajirinlpu
Created April 15, 2017 14:39
Show Gist options
  • Save muhajirinlpu/d0394d4ce64c770ac3440de9bd8b00c7 to your computer and use it in GitHub Desktop.
Save muhajirinlpu/d0394d4ce64c770ac3440de9bd8b00c7 to your computer and use it in GitHub Desktop.
This is a confused version of door challenge :v
<?php
class Doors
{
protected $doors = [];
protected $round = 0;
const CLOSE = "close";
const HALF_CLOSE = "half_close";
const OPEN = "open";
protected $attributes = [
"open" => 0,
"half_close" => 0,
"close" => 0,
"most_half_close_door" => 0,
"round_most_half_close_door" => 0,
];
public function __construct($doors, $round = null)
{
$this->setupDoors($doors);
$this->round = ($round) ? $round : $doors;
$this->run();
}
public function __get($property)
{
if (!array_key_exists($property, $this->attributes))
throw new Exception("Attribute not found");
return $this->attributes[$property];
}
protected function setupDoors($doors)
{
for ($i=1; $i <= $doors; $i++) {
$this->doors[$i] = Doors::CLOSE;
}
}
protected function setDoor($key, $defaultValue, $roundNow)
{
if ($key % $roundNow == 0) {
return false;
}
if ($defaultValue === Doors::CLOSE){
$value = Doors::OPEN;
$this->attributes['open']++;
} elseif ($defaultValue === Doors::OPEN){
$value = Doors::HALF_CLOSE;
$this->attributes['half_close']++;
} elseif ($defaultValue === Doors::HALF_CLOSE){
$value = $value = Doors::CLOSE;
$this->attributes['close']++;
}
$this->doors[$key] = $value;
}
protected function resetAttributes()
{
$this->attributes['open'] = 0;
$this->attributes['close'] = 0;
$this->attributes['half_close'] = 0;
}
protected function indexAttributes($round)
{
if ($this->attributes['half_close'] > $this->attributes['most_half_close_door']) {
$this->attributes['most_half_close_door'] = $this->attributes['half_close'];
$this->attributes['round_most_half_close_door'] = $round;
}
}
protected function run()
{
for ($round = 1; $round <= $this->round; $round++) {
$this->resetAttributes();
foreach ($this->doors as $key => $value) {
$this->setDoor($key, $value, $round);
}
$this->indexAttributes($round);
}
}
}
echo "Enter your doors : ";
$handle = fopen("php://stdin", 'r');
$doors = (int) trim(fgets($handle));
fclose($handle);
echo "Enter your round (let blank for same as doors): ";
$handle = fopen("php://stdin", 'r');
$round = (int) trim(fgets($handle));
fclose($handle);
$door = new Doors($doors, $round);
print_r($door);
echo "> Half close door in the end is " . $door->half_close . PHP_EOL .
"> Most half close door is in round " . $door->round_most_half_close_door . PHP_EOL;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment