Created
May 6, 2013 14:55
-
-
Save toopay/5525668 to your computer and use it in GitHub Desktop.
Simple Spies Program
This file contains hidden or 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 | |
/** | |
* Program interogasi sederhana | |
* | |
* @author Taufan Aditya <[email protected]> | |
*/ | |
class Node { | |
public $question; | |
public $yes; | |
public $no; | |
/** | |
* Node factory | |
* | |
* @param string Pertanyaan | |
* @return Node | |
*/ | |
public static function create($question = '') | |
{ | |
$node = new static(); | |
$node->question = $question; | |
$node->yes = NULL; | |
$node->no = NULL; | |
return $node; | |
} | |
} | |
class Interogation { | |
/** | |
* Ambil argument dari standard input | |
* | |
* @param int Limit karakter | |
*/ | |
public function get_stream($limit = 0) | |
{ | |
$stdin = fopen('php://stdin','r'); | |
$stream = trim(fgets($stdin, $limit), "\n"); | |
fclose($stdin); | |
return $stream; | |
} | |
/** | |
* Ajukan pertanyaan | |
* | |
* @param string Pertanyaan | |
* @return bool Jawaban (TRUE = Yes, FALSE = No) | |
*/ | |
public function yes_no($question = '') | |
{ | |
if (empty($question)) { | |
return FALSE; | |
} | |
printf("%s? (y/n)", $question); | |
$answer = $this->get_stream(3); | |
return strtolower(substr($answer,0,1)) == 'y'; | |
} | |
/** | |
* Main function | |
*/ | |
public function start() | |
{ | |
$start = Node::create('Apakah dia laki-laki'); | |
$start->yes = Node::create('Arliansah'); | |
$start->no = Node::create('Youppie'); | |
do { | |
$current = $start; | |
while(true) { | |
if ($this->yes_no($current->question)) { | |
if ($current->yes) { | |
$current = $current->yes; | |
} else { | |
printf("Tersangka ditemukan! %s!\n", $current->question); | |
break; | |
} | |
} elseif ($current->no) { | |
$current = $current->no; | |
} else { | |
/* Buat target baru */ | |
printf("Kalau begitu siapa namanya?"); | |
$suspect = $this->get_stream(20); | |
/* Buat kopi target */ | |
$current->yes = Node::create($suspect); | |
$current->no = Node::create($current->question); | |
/* Dan ganti pertanyaan ini dengan pertanyaan baru */ | |
printf("Berikan pertanyaan yang YES untuk %s tapi NO untuk %s?\n", | |
$suspect, | |
$current->question); | |
$question = $this->get_stream(40); | |
$current->question = $question; | |
break; | |
} | |
} | |
} while ($this->yes_no('Ulang kembali')); | |
} | |
} | |
$app = new Interogation(); | |
$app->start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment