[PHP] Spiral Words Algorithm - Muhammad Faruq Nuruddinsyah
[PHP] Spiral Words Algorithm

Algorithm to create a spiral structure from the input text.

Sample input text:
muhammad faruq nuruddinsyah

Output:
d i n s y a
d a d _ f h
u m m u a _
r m a h r _
u n _ q u _


Source Code:
<?php
 
// Algoritma kata spiral (converted from Dafturn Dinfio source code)
// Faruq @ 2012
 
 
echo("Masukkan kata: "); $text = trim(fgets(STDIN)); echo "\n";
if($text == "") $text = "abcdefghijklmnopqrstuvwxyz";
 
$len = strlen($text);
$n = round(sqrt($len), 0);
$m = ceil(sqrt($len));
 
$cx = ceil($m / 2); $cy = ceil($n / 2);
$len = $n * $m;
 
$data = array_fill(1, $len, ""); $enc = array_fill(1, $n, array_fill(1, $m, ""));
 
for($i = 1; $i <= $len; $i++){
	$data[$i] = substr($text, $i - 1, 1);
	if($data[$i] == " " || $i > strlen($text)) $data[$i] = "_";
}
 
$i = 2; $a = 1;
$dir_x = "r"; $dir_y = "d";
$posi = $cy; $posj = $cx;
$enc[$posi][$posj] = $data[1];
 
while($i <= $len){
	for($j = 1; $j <= $a; $j++){
		if($j >= $len) break;
 
		if($dir_x == "r") $posj++; else $posj--;
		if($i <= $len) $enc[$posi][$posj] = $data[$i];
		$i++;
	}
	for($j = 1; $j <= $a; $j++){
		if($j >= $len) break;
 
		if($dir_y == "d") $posi++; else $posi--;
		if($i <= $len) $enc[$posi][$posj] = $data[$i];
		$i++;
	}
 
	if($dir_x == "r") $dir_x = "l"; else $dir_x = "r";
	if($dir_y == "d") $dir_y = "u"; else $dir_y = "d";
 
	$a++;
}
 
 
// print out the result
 
for($i = 1; $i <= $n; $i++){
	for($j = 1; $j <= $m; $j++){
		echo($enc[$i][$j] . " ");
	}
	echo("\n");
}
 
?>

Informasi:
Lihat semua daftar ACS - Download: spiral-words.php - Tanggal: 3 Mei 2013 - Kategori: PHP