You are currently viewing Tutorial PHP: Skrip Anagram dan Kata Acak

Tutorial PHP: Skrip Anagram dan Kata Acak

Anagram sendiri seperti yang kita kenal adalah permainan mengacak kata-kata dalam suatu bahasa. Dengan PHP kita dapat membuat anagram dan kata-kata acak dengan bantuan sebuah Class, Word Solver karya om Arturs Sosins aka ar2rsawseen. Silakan unduh kode sumbernya disini.

Untuk menggunakannya, sesuai contoh berikut:
1. Buat interfacenya

[sourcecode language=”php”]
//it can take some time
set_time_limit(0);
$time = microtime();
$time = explode(‘ ‘, $time);
$start = $time[1] + $time[0];
?>
<form method=’post’ action=”>
<p>Rules: <input type=’text’ name=’rules’ value=’a(cl)s[s]*e’/></p>
<p>Use all letters: <select name=’use_all’>
<option value=’true’>Yes</option>
<option value=’false’>No</option>
</select></p>
<p>Return: <select name=’type’>
<option value=’words’>Valid words</option>
<option value=’anagrams’>Anagrams</option>
</select></p>
<p><input type=’submit’ value=’Generate’/></p>
</form>
<?php
if(isset($_POST["rules"]) && trim($_POST["rules"]) != "")
{
//declaring class instance
include("./word_solver.php");
$ws = new word_solver();

if(isset($_POST["use_all"]) && $_POST["use_all"] == "false")
{
//use all provided letters
$ws->not_all();
}

//setting rules for words
$ws->set_rules($_POST["rules"]);

//getting results
if(isset($_POST["type"]) && $_POST["type"] == "anagrams")
{
$arr = $ws->get_anagrams();
}
else
{
$arr = $ws->get_words();
}
$errors = $ws->get_errors();
if(!empty($errors))
{
echo "<p>Errors:</p>";
echo "<pre>";
print_r($errors);
echo "</pre>";
}
echo "<pre>";
print_r($arr);
echo "</pre>";
}
$time = microtime();
$time = explode(‘ ‘, $time);
$end = $time[1] + $time[0];
$total_time = round(($end – $start), 4);
echo ‘<p>PHP execution: ‘.$total_time.’ seconds.</p>’;
[/sourcecode]

2. Buat file processornya:

[sourcecode language=”php”]
set_time_limit(0);
$time = microtime();
$time = explode(‘ ‘, $time);
$start = $time[1] + $time[0];

//declaring class instance
include("./word_solver.php");
$ws = new word_solver();

//use all provided letters
$ws->use_all();

//setting rules for words
$ws->set_rules("a(cl)s[s]*e");

//getting results
$arr = $ws->get_words();
echo "<pre>";
print_r($arr);
echo "</pre>";

$time = microtime();
$time = explode(‘ ‘, $time);
$end = $time[1] + $time[0];
$total_time = round(($end – $start), 4);
echo ‘<p>PHP execution: ‘.$total_time.’ seconds.</p>’;
[/sourcecode]

Screenshoot

Berikut tangkapan layar hasil dari anagram yang kita lakukan dengan script tersebut dari rule: e(cl)m[k]*a.