How do I get this PHP code to output HTML in order to enter the player's number and generate the tournament?
<?php
class RoundRobin
{
var $MaxTeams;
var $MaxCombinations;
var $tourn;
var $mList;
var $cList;
var $cUsed;
function RoundRobin($max)
{
$this->MaxTeams=$max;
$this->MaxCombinations=($this->MaxTeams/2)*($this->MaxTeams-1);
}
function ShowSchedule($players,$totalChecks)
{
echo $players.' players'."\n";
for ($r=1; $r <= $players/2; $r++) echo 'Game'.$r;
echo "\n";
echo" +-";
for ($r=1; $r <= ($players/2)*6-2; $r++) echo '-';
echo "\n";
$index = 1;
for ($r=1; $r <= $players-1; $r++)
{
echo 'Week '.$r. '|';
for ($m=1; $m <= $players/2; $m++)
{
echo $this->tourn[$index]['one'].'&'. $this->tourn[$index]['two'];
$index++;
}
echo "\n";
}
echo "\n".$totalChecks,' combinations tried'. "\n\n";
}
function array_copy(&$dest,$source)
{
if(count($source)>count($dest)) {echo 'fatal'; exit;}
//for($a=0;$a<count($source);$a++)
$dest['one']=$source['one'];
$dest['two']=$source['two'];
}
function ClearArrays()
{
for ($i=0; $i <= $this->MaxCombinations; $i++)
{
$this->tourn[$i]['one']=0;
$this->tourn[$i]['two']=0;
$this->cList[$i]['one']=0;
$this->cList[$i]['two']=0;
$this->cUsed[$i]=0;
if($i<=$this->MaxTeams/2)$this->mList[$i] = 0;
}
}
function Scheldule($players)
{
while ($players <= $this->MaxTeams)
{
$combinations = $players/2 * ($players-1);
$totalChecks = 0;
$this->ClearArrays();
/* set up list of all combinations */
$m=1;
for ($a=1; $a<$players; $a++)
for ($b=$a+1; $b<=$players; $b++)
{
$this->cList[$m]['one'] = $a;
$this->cList[$m]['two'] = $b;
$m++;
}
$roundCount=1;
$index=1;
while ($roundCount <= $players-1)
{
$matchCount = 1;
$round_set = 0;
for ($i=0; $i<=$this->MaxTeams/2; $i++) $this->mList[$i] = 0;
$startC = $roundCount;
while ($matchCount <= $players/2)
{
$c = $combinations + 1;
while ($c > $combinations)
{
$c = $startC;
/* find an unused pair that would be legitimate */
while (
($c <= $combinations)
&&
( //
($round_set & (1 << $this->cList[$c]['one'])) ||
($round_set & (1 << $this->cList[$c]['two'])) ||
(!empty($this->cUsed[$c]))
)
) $c++;
if ($c > $combinations)
{
do {
$this->mList[$matchCount] = 0;
$matchCount--;
$index--;
$round_set &= ~(1 << $this->cList[$this->mList[$matchCount]]['one']);
$round_set &= ~(1 << $this->cList[$this->mList[$matchCount]]['two']);
$this->cUsed[$this->mList[$matchCount]] = false;
$this->tourn[$index]['one'] = 0;
$this->tourn[$index]['two'] = 0;
}
while ($this->cList[$this->mList[$matchCount]]['one'] != $this->cList[$this->mList[$matchCount]+1]['one']);
$startC = $this->mList[$matchCount]+1;
}
}
$this->array_copy(&$this->tourn[$index],$this->cList[$c]);
$totalChecks++;
if (($totalChecks % 1000) == 0) printf("%d\033A\n", $totalChecks );
$this->cUsed[$c] = true;
$this->mList[$matchCount] = $c;
$startC = 1;
$round_set |= (1 << $this->cList[$c]['one']);
$round_set |= (1 << $this->cList[$c]['two']);
$index++;
$matchCount++;
}
$roundCount++;
}
/* yahoo!, scheduled all the rounds */
printf(" " );
$this->ShowSchedule($players,$totalChecks);
/* try and make a schedule using two more teams */
$players += 2;
}
}
}
?>
It's a PHP class. Reading the manual might help you.
Something along the lines of this might work:
$rr = new RoundRobin( 5 );
$rr->Scheldule( $_POST['PlayerCount'] );
But I can't be bothered deciphering the code to work out if it really will.
Also, if you haven't yet learnt HTML forms, read a tutorial like w3schools.
Related
I don't want to create a big if list for all the story chapters of my website.
if $commentformname[$a] is equal to the number of the current chapter, then I make an array $commentonchapter1[$a] saying that a comment was inserted in the chapter 1, and chapter 2, and so on.
So if a comment was posted in the chapter 2, a array called commentonchapter2 will be created.
if ($sitecomments == true) {
$c = 0;
$i = 0;
$z = 0;
#defines the comment form name, name of who commented, the comment text and time (to be converted, example: 2020-04-09T15:53:07.580Za > 12:53 09/04/2020)
while ($c <= $commentsnumb) {
$commentformname[$z] = $comments[$i];
$i++;
$commenttername[$z] = $comments[$i];
$i++;
$commenttext[$z] = $comments[$i];
$i++;
$commenttime[$z] = $comments[$i];
$i++;
$c++;
$z++;
}
#shows the text of the comments tab
echo '<hr class="'.$sitehr2.'" />'."\n";
echo $divzoomanim.'<'.$n.'><p></p><br /><b>'.$tabnames[7].': '.$orangespan.$commentsnormalnumb.$spanc.' '.$icons[12].'</b><br /><br /><p></p></'.$n.'>'.$divc.'<hr class="'.$sitehr.'" />'."\n";
$i = 0;
$z = 0;
#converts the comment date and time
#example
#from 2020-04-09T15:53:07.580Za
#to 12:53 09/04/2020
while ($z <= $commentsnumb) {
$commenttime[$z] = substr($commenttime[$z], 0, -1);
$commenttime[$z] = date("H:i d/m/Y", strtotime($commenttime[$z]));
$z++;
}
$a = 0;
$z = 0;
$i = 0;
#styles the form name
#example
#from "pequenata-comment-7"
#to '<b>Commented on form "Pequenata-comment-7"</b>'
while ($a <= $commentsnumb) {
if ($lang == $langs[0] or $lang == $langs[1]) {
$commentformname[$i] = '<b>'.$commenttxt3.' '.$commenttxt5.' '.strtolower($formtxt).':</b> "'.ucwords($commentformname[$i]).'"';
}
if ($lang == $langs[2]) {
$commentformname[$i] = '<b>'.$commenttxt3.' '.$commenttxt4.' '.strtolower($formtxt).':</b> "'.ucwords($commentformname[$i]).'"';
}
$a++;
$z++;
$i++;
}
$a = 0;
$a2 = 1;
$i = 0;
$z = 0;
$c = 0;
$v = 0;
$b = 0;
$commentschapternumb = 0;
#Generates the array of the website comments
while ($c <= $commentsnumb) {
#Generates the comments of the website if the strlen of $commentformname[$a] is equal to 45, String: <b>Commented on form "Pequenata-comment-7"</b>
if (strlen($commentformname[$a]) == 45) {
$cmntsgeral[$b] = '<'.$m.' class="'.$textstyle2.'" style="text-align:left;border-width:3px;border-color:'.$bordercolor.';border-style:solid;"><div style="margin-left:5%;margin-right:5%;">'.'<br /><b>'.$a2.' - '.$commenttername[$i].'</b> - '.$commenttime[$i].'<br />'.$commentformname[$i].' '.'<hr class="'.$sitehr3.'" />'.$commenttext[$i].'<br /><br /><br /><br /><br />'.$divc.'</'.$m.'>'."<br />"."\n";
#Dispalyer disabled because of showing the wrong array (using $z, so it was tring to print a number on the array that didn't existed ($cmntschapter was incrementing on $z)
#echo $cmntsgeral[$z];
$a2++;
$b++;
}
#Generates the array of the chapter comments
if (strlen($commentformname[$a]) == 47) {
$cmntschapter[$v] = '<'.$m.' class="'.$textstyle2.'" style="text-align:left;border-width:3px;border-color:'.$bordercolor.';border-style:solid;"><div style="margin-left:5%;margin-right:5%;">'.'<br /><b>'.$a2.' - '.$commenttername[$i].'</b> - '.$commenttime[$i].'<br />'.$commentformname[$i].' '.'<hr class="'.$sitehr3.'" />'.$commenttext[$i].'<br /><br /><br /><br /><br />'.$divc.'</'.$m.'>'."<br />"."\n";
#Doesn't show the chapter comments because they shouldn't be showed in the website comments tab
#echo $cmntschapter[$z];
$v++;
$commentschapternumb++;
}
$a++;
$i++;
$z++;
$c++;
}
#Shows the website comments on the comments tab of the site
$z = 0;
while ($z <= $commentsnormalnumbtowrite) {
echo $cmntsgeral[$z];
$z++;
}
}
$data = array(5,0,15,20,22,14,13,15,12,22,40,25);
Hi , i want to traverse the data points above and find the turning points based on a range.
The way i'm tackling it so far is simply taking the $array[$i] - $array[$i-1] , and if the absolute difference is greater than the range - i'm taking it as a turning point . however - the logic is flawed as if it moved slightly up and then back down - it breaks the cycle.
The 3 down values should have been enough to make X , a turning point downwards , but because they individually do not meet the range - they are discarded .
Any solutions ?
if($diff >= 0)
{
$diff_up = $diff_up + $diff;
}
else
{
$diff_down = $diff_down + abs($diff);
}
if((($diff_up-$diff_down) >=$range) && ($pivot_type != "UP"))
{
echo "Pivot UP at : ".$current;
break;
}
else if((($diff_down-$diff_up) >$range) && ($pivot_type != "DOWN"))
{
echo "Pivot DOWN at : ".$current;
break;
}
What you are looking for is all local minima and maxima, This is a good article.
I made this (with inspiration from:
get extremes from list of numbers):
<?php
$data = array(5,0,15,20,22,14,13,15,12,22,40,25);
function minima_and_maxima(array $array){
$maxima = [];
$minima = [];
$maxima[] = $array[0];
for($i = 1; $i < count($array) - 1; $i++){
$more_than_last = $array[$i] > $array[$i-1];
$more_than_next = $array[$i] > $array[$i+1];
$next_is_equal = $array[$i] == $array[$i+1];
if($next_is_equal) {
continue;
}
if ($i == 0) {
if ($more_than_next) {
$maxima[] = $array[$i];
} else {
$minima[] = $array[$i];
}
} elseif ($i == count($array)-1) {
if ($more_than_last) {
$maxima[] = $array[$i];
} else {
$minima[] = $array[$i];
}
} else {
if ($more_than_last && $more_than_next) {
$maxima[] = $array[$i];
} elseif (!$more_than_last && !$more_than_next) {
$minima[] = $array[$i];
}
}
}
for ($i = 0; $i < count($maxima); $i++) {
$current_maxima = $maxima[$i];
$next_maxima = $maxima[$i+1];
if ($current_maxima > $next_maxima) {
unset($maxima[$i+1]);
}
}
for ($i = 0; $i < count($minima); $i++) {
$current_minima = $minima[$i];
$next_minima = $minima[$i+1];
if ($next_minima < $current_minima) {
unset($minima[$i]);
}
}
return [
'maxima' => array_values($maxima),
'minima' => array_values($minima),
];
}
function get_turning_points($data)
{
$mins_and_maxs = minima_and_maxima($data);
$turning_points = [];
for ($i = 0; $i < count($mins_and_maxs['maxima']) - 1; $i++) {
$turning_points[] = $mins_and_maxs['maxima'][$i];
$turning_points[] = $mins_and_maxs['minima'][$i];
}
$turning_points[] = $mins_and_maxs['maxima'][count($mins_and_maxs['maxima'])-1];
return $turning_points;
}
print_r(get_turning_points($data));
This gives you:
Array
(
[0] => 5
[1] => 0
[2] => 22
[3] => 12
[4] => 40
)
Demo: https://eval.in/832708
Hope this helps :)
I'm having trouble making a simple count work. Right now 0 is constantly displayed when I run the code and I know it's because I set count to 0. But it should be displaying the number of times "Fizz" is displayed.
I'm sure it's simple but I just can't see what!
public function __construct($firstParam, $secondParam, $firstSound = "Fizz", $secondSound = "Buzz", $numbers = 100) {
$this->firstParam = $firstParam;
$this->secondParam = $secondParam;
$this->firstSound = $firstSound;
$this->secondSound = $secondSound;
$this->numbers = $numbers;
$this->numsArray = $numsArray;
}
public function __toString() {
$count = 0;
for ($i = 0; $i < count($this->numsArray); $i++){
$val = $this->numsArray[$i];
if ($val == $this->firstSound) {
$count++;
}
}
$print = "Number of Fizzes: ".$count;
return $print;
}
public function execute() {
$this->numsArray = array();
if ($this->secondParam > $this->firstParam) {
for ($i = 1; $i <= $this->numbers; $i++){
if ($i % $this->firstParam == 0 && $i % $this->secondParam == 0) {
$this->numsArray[] = "\n".$this->firstSound.$this->secondSound."\n";
} elseif ($i % $this->firstParam == 0) {
$this->numsArray[] = "\n".$this->firstSound."\n";
} elseif ($i % $this->secondParam == 0) {
$this->numsArray[] = "\n".$this->secondSound."\n";
} else {
$this->numsArray[] = "\n".$i."\n";
}
echo $this->numsArray[$i-1];
}
} else {
echo "\n".' First Number Bigger Than Second '."\n";
}
}
In your execute you are not assigning the values to numsArray[i] also you inject new line characters that will not match the equality you just when checking $val. Also I notice you use zero index to check them and index 1 to load it. Change execute to:
for ($i = 0; $i < $this->numbers; $i++){
if ($i % $this->firstParam == 0 && $i % $this->secondParam == 0) {
$this->numsArray[i] = $this->firstSound.$this->secondSound;
} elseif ($i % $this->firstParam == 0) {
$this->numsArray[i] = $this->firstSound;
} elseif ($i % $this->secondParam == 0) {
$this->numsArray[i] = $this->secondSound;
} else {
$this->numsArray[i] = $i;
}
echo $this->numsArray[$i];
This is a better binary string comparison for php...
if (strcmp($val, $this->firstSound) == 0)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
So I have created an html form which then posts the results to a php file that overlays them on a PDF and then emails that PDF to myself and the email that was put in the form. All I want to do now is find a simple way to make it so that the PDF includes a sequential number.
For example: When the form is filled out for the first time the number 0001 is input automatically into the PDF and 0002 for the second time and so on.
Is there an easy PHP function to accomplish this?
Essentially I am creating an online invoicing form so when I do service calls I can create an invoice on the spot from a web browser which is then emailed to my office and the client.
Any help would be greatly appreciated.
For an incrementing number, you could keep a number in a database and then extract it, add 1 to it, use it, and then put it back in the DB for next time, but this seems complicated. Somebody in the comments mentioned using the timestamp, which would be done like so:
$invoicenumber = time(); //This number will always be unique
The time function works like so (copied from w3schools):
The time() function returns the current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
Since actual seconds can only go up (increment), this number will never be the same twice.
I hope this is helpful.
-Edit
You can also display this date/time in a readable format like so:
$time = time();
echo date("Y-m-d H:i:s",$time);
-Edit 2
If you want an incrementing number, you basically need a very simple database to save it, which might be as simple as a table called invoices, with a column called invoicenumber, which stores your invoice number in it. You could / probably should use this to store other invoice information in it too, so you'd have each invoice number saved (which means we want to only get the highest one)
Then your code would look like this, for each time you want to use it:
Firstly you'd have a database information file (settings.php or something similar) with your database definitions in it, which might look like this:
define('DB_HOST', 'localhost');
define('DB_USER', 'db_username');
define('DB_PASS', 'db_password');
define('DB_NAME', 'database_name');
Your code would look like this:
//Establish a mysql connection
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//Set up a query to get the highest number
$query = "SELECT invoicenumber FROM invoices ORDER BY invoicenumber DESC LIMIT 1";
//Get the result
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
//If we have a record
if($row){
//New invoice number
$invoicenumber = $row['invoicenumber']++;
//Else (database is empty, so start at the beginning)
}else{
$invoicenumber = 1;
}
//Now we have our invoice number, so do whatever you want with it
/**
* Code here to use the number
* */
//Now we wanna add the new invoice to the database, so
/**
* Add any other info to this statement if you want.
* If any of it is user submitted data, be sure to use prepared statements
* (just look at php.net's documentation on prepared statements)
* w3schools also has some nice tutorials on how to safely insert stuff
* in to a database, so check it all out :)
* */
$query = "INSERT INTO invoices(invoicenumber) VALUES($invoicenumber)";
//Execute the query
if($mysqli->query($query)){
//Show success
echo "Invoice $invoicenumber has been added to the database.";
}else{
//Show error
echo "Unfortunately we could not add invoice $invoicenumber to the database.";
}
//Now we can clear up our resources
$stmt->free_result(); $stmt->close(); $mysqli->close();
Please note: this is a very basic example. Yours will have additions and enhanced security if you are using user submitted data, so please do your homework and make sure that you fully understand each line of this code before you proceed to use it.
I do exactly the same with patient accession numbers on patient reports.
include('/home/user/php/class.pdf2text.php');
$p2t = new PDF2Text();
$p2t->setFilename($pdf);
$p2t->decodePDF();
$data = $p2t->output();
$len = strlen($data);
$pos = strpos($data,$accession);
if (pos){
$in .= "$accession,";
$checked++;
}
else{
$missingPDF += 1;echo "\n<p> <span class='bold red'>INCORRECT ACCESSION NUMBER c=$row[0] p=$row[1]</span>\n";
}
if ($checked > 0){
$in = substr($in,0,-1) . ')';
$sql = "UPDATE `Patient` SET `PDF`=1 WHERE $in";
}
pdf2text.php
class PDF2Text {
// Some settings
var $multibyte = 4; // Use setUnicode(TRUE|FALSE)
var $convertquotes = ENT_QUOTES; // ENT_COMPAT (double-quotes), ENT_QUOTES (Both), ENT_NOQUOTES (None)
var $showprogress = true; // TRUE if you have problems with time-out
// Variables
var $filename = '';
var $decodedtext = '';
function setFilename($filename) {
// Reset
$this->decodedtext = '';
$this->filename = $filename;
}
function output($echo = false) {
if($echo) echo $this->decodedtext;
else return $this->decodedtext;
}
function setUnicode($input) {
// 4 for unicode. But 2 should work in most cases just fine
if($input == true) $this->multibyte = 4;
else $this->multibyte = 2;
}
function decodePDF() {
// Read the data from pdf file
$infile = #file_get_contents($this->filename, FILE_BINARY);
if (empty($infile))
return "";
// Get all text data.
$transformations = array();
$texts = array();
// Get the list of all objects.
preg_match_all("#obj[\n|\r](.*)endobj[\n|\r]#ismU", $infile . "endobj\r", $objects);
$objects = #$objects[1];
// Select objects with streams.
for ($i = 0; $i < count($objects); $i++) {
$currentObject = $objects[$i];
// Prevent time-out
#set_time_limit ();
if($this->showprogress) {
// echo ". ";
flush(); ob_flush();
}
// Check if an object includes data stream.
if (preg_match("#stream[\n|\r](.*)endstream[\n|\r]#ismU", $currentObject . "endstream\r", $stream )) {
$stream = ltrim($stream[1]);
// Check object parameters and look for text data.
$options = $this->getObjectOptions($currentObject);
if (!(empty($options["Length1"]) && empty($options["Type"]) && empty($options["Subtype"])) )
// if ( $options["Image"] && $options["Subtype"] )
// if (!(empty($options["Length1"]) && empty($options["Subtype"])) )
continue;
// Hack, length doesnt always seem to be correct
unset($options["Length"]);
// So, we have text data. Decode it.
$data = $this->getDecodedStream($stream, $options);
if (strlen($data)) {
if (preg_match_all("#BT[\n|\r](.*)ET[\n|\r]#ismU", $data . "ET\r", $textContainers)) {
$textContainers = #$textContainers[1];
$this->getDirtyTexts($texts, $textContainers);
} else
$this->getCharTransformations($transformations, $data);
}
}
}
// Analyze text blocks taking into account character transformations and return results.
$this->decodedtext = $this->getTextUsingTransformations($texts, $transformations);
}
function decodeAsciiHex($input) {
$output = "";
$isOdd = true;
$isComment = false;
for($i = 0, $codeHigh = -1; $i < strlen($input) && $input[$i] != '>'; $i++) {
$c = $input[$i];
if($isComment) {
if ($c == '\r' || $c == '\n')
$isComment = false;
continue;
}
switch($c) {
case '\0': case '\t': case '\r': case '\f': case '\n': case ' ': break;
case '%':
$isComment = true;
break;
default:
$code = hexdec($c);
if($code === 0 && $c != '0')
return "";
if($isOdd)
$codeHigh = $code;
else
$output .= chr($codeHigh * 16 + $code);
$isOdd = !$isOdd;
break;
}
}
if($input[$i] != '>')
return "";
if($isOdd)
$output .= chr($codeHigh * 16);
return $output;
}
function decodeAscii85($input) {
$output = "";
$isComment = false;
$ords = array();
for($i = 0, $state = 0; $i < strlen($input) && $input[$i] != '~'; $i++) {
$c = $input[$i];
if($isComment) {
if ($c == '\r' || $c == '\n')
$isComment = false;
continue;
}
if ($c == '\0' || $c == '\t' || $c == '\r' || $c == '\f' || $c == '\n' || $c == ' ')
continue;
if ($c == '%') {
$isComment = true;
continue;
}
if ($c == 'z' && $state === 0) {
$output .= str_repeat(chr(0), 4);
continue;
}
if ($c < '!' || $c > 'u')
return "";
$code = ord($input[$i]) & 0xff;
$ords[$state++] = $code - ord('!');
if ($state == 5) {
$state = 0;
for ($sum = 0, $j = 0; $j < 5; $j++)
$sum = $sum * 85 + $ords[$j];
for ($j = 3; $j >= 0; $j--)
$output .= chr($sum >> ($j * 8));
}
}
if ($state === 1)
return "";
elseif ($state > 1) {
for ($i = 0, $sum = 0; $i < $state; $i++)
$sum += ($ords[$i] + ($i == $state - 1)) * pow(85, 4 - $i);
for ($i = 0; $i < $state - 1; $i++) {
try {
if(false == ($o = chr($sum >> ((3 - $i) * 8)))) {
throw new Exception('Error');
}
$output .= $o;
} catch (Exception $e) { /*Dont do anything*/ }
}
}
return $output;
}
function decodeFlate($data) {
return #gzuncompress($data);
}
function getObjectOptions($object) {
$options = array();
if (preg_match("#<<(.*)>>#ismU", $object, $options)) {
$options = explode("/", $options[1]);
#array_shift($options);
$o = array();
for ($j = 0; $j < #count($options); $j++) {
$options[$j] = preg_replace("#\s+#", " ", trim($options[$j]));
if (strpos($options[$j], " ") !== false) {
$parts = explode(" ", $options[$j]);
$o[$parts[0]] = $parts[1];
} else
$o[$options[$j]] = true;
}
$options = $o;
unset($o);
}
return $options;
}
function getDecodedStream($stream, $options) {
$data = "";
if (empty($options["Filter"]))
$data = $stream;
else {
$length = !empty($options["Length"]) ? $options["Length"] : strlen($stream);
$_stream = substr($stream, 0, $length);
foreach ($options as $key => $value) {
if ($key == "ASCIIHexDecode")
$_stream = $this->decodeAsciiHex($_stream);
elseif ($key == "ASCII85Decode")
$_stream = $this->decodeAscii85($_stream);
elseif ($key == "FlateDecode")
$_stream = $this->decodeFlate($_stream);
elseif ($key == "Crypt") { // TO DO
}
}
$data = $_stream;
}
return $data;
}
function getDirtyTexts(&$texts, $textContainers) {
for ($j = 0; $j < count($textContainers); $j++) {
if (preg_match_all("#\[(.*)\]\s*TJ[\n|\r]#ismU", $textContainers[$j], $parts))
$texts = array_merge($texts, array(#implode('', $parts[1])));
elseif (preg_match_all("#T[d|w|m|f]\s*(\(.*\))\s*Tj[\n|\r]#ismU", $textContainers[$j], $parts))
$texts = array_merge($texts, array(#implode('', $parts[1])));
elseif (preg_match_all("#T[d|w|m|f]\s*(\[.*\])\s*Tj[\n|\r]#ismU", $textContainers[$j], $parts))
$texts = array_merge($texts, array(#implode('', $parts[1])));
}
}
function getCharTransformations(&$transformations, $stream) {
preg_match_all("#([0-9]+)\s+beginbfchar(.*)endbfchar#ismU", $stream, $chars, PREG_SET_ORDER);
preg_match_all("#([0-9]+)\s+beginbfrange(.*)endbfrange#ismU", $stream, $ranges, PREG_SET_ORDER);
for ($j = 0; $j < count($chars); $j++) {
$count = $chars[$j][1];
$current = explode("\n", trim($chars[$j][2]));
for ($k = 0; $k < $count && $k < count($current); $k++) {
if (preg_match("#<([0-9a-f]{2,4})>\s+<([0-9a-f]{4,512})>#is", trim($current[$k]), $map))
$transformations[str_pad($map[1], 4, "0")] = $map[2];
}
}
for ($j = 0; $j < count($ranges); $j++) {
$count = $ranges[$j][1];
$current = explode("\n", trim($ranges[$j][2]));
for ($k = 0; $k < $count && $k < count($current); $k++) {
if (preg_match("#<([0-9a-f]{4})>\s+<([0-9a-f]{4})>\s+<([0-9a-f]{4})>#is", trim($current[$k]), $map)) {
$from = hexdec($map[1]);
$to = hexdec($map[2]);
$_from = hexdec($map[3]);
for ($m = $from, $n = 0; $m <= $to; $m++, $n++)
$transformations[sprintf("%04X", $m)] = sprintf("%04X", $_from + $n);
} elseif (preg_match("#<([0-9a-f]{4})>\s+<([0-9a-f]{4})>\s+\[(.*)\]#ismU", trim($current[$k]), $map)) {
$from = hexdec($map[1]);
$to = hexdec($map[2]);
$parts = preg_split("#\s+#", trim($map[3]));
for ($m = $from, $n = 0; $m <= $to && $n < count($parts); $m++, $n++)
$transformations[sprintf("%04X", $m)] = sprintf("%04X", hexdec($parts[$n]));
}
}
}
}
function getTextUsingTransformations($texts, $transformations) {
$document = "";
for ($i = 0; $i < count($texts); $i++) {
$isHex = false;
$isPlain = false;
$hex = "";
$plain = "";
for ($j = 0; $j < strlen($texts[$i]); $j++) {
$c = $texts[$i][$j];
switch($c) {
case "<":
$hex = "";
$isHex = true;
$isPlain = false;
break;
case ">":
$hexs = str_split($hex, $this->multibyte); // 2 or 4 (UTF8 or ISO)
for ($k = 0; $k < count($hexs); $k++) {
$chex = str_pad($hexs[$k], 4, "0"); // Add tailing zero
if (isset($transformations[$chex]))
$chex = $transformations[$chex];
$document .= html_entity_decode("&#x".$chex.";");
}
$isHex = false;
break;
case "(":
$plain = "";
$isPlain = true;
$isHex = false;
break;
case ")":
$document .= $plain;
$isPlain = false;
break;
case "\\":
$c2 = $texts[$i][$j + 1];
if (in_array($c2, array("\\", "(", ")"))) $plain .= $c2;
elseif ($c2 == "n") $plain .= '\n';
elseif ($c2 == "r") $plain .= '\r';
elseif ($c2 == "t") $plain .= '\t';
elseif ($c2 == "b") $plain .= '\b';
elseif ($c2 == "f") $plain .= '\f';
elseif ($c2 >= '0' && $c2 <= '9') {
$oct = preg_replace("#[^0-9]#", "", substr($texts[$i], $j + 1, 3));
$j += strlen($oct) - 1;
$plain .= html_entity_decode("&#".octdec($oct).";", $this->convertquotes);
}
$j++;
break;
default:
if ($isHex)
$hex .= $c;
elseif ($isPlain)
$plain .= $c;
break;
}
}
$document .= "\n";
}
return $document;
}
}
So I'm looking how to make a checkboard but with a spiral in it instead of the default checkerboard made like this:
$checkerboard=array();
for($row=0;$row<10;$row++){
if($row%2==0){
for($col=0;$col<10;$col++){
if($col%2==0){
$checkerboard[$row][$col]="white";
}else{
$checkerboard[$row][$col]="black";
}
}
}else{
for($col=0;$col<10;$col++){
if($col%2==0){
$checkerboard[$row][$col]="black";
}else{
$checkerboard[$row][$col]="white";
}
}
}
}
I also tried it with 2 diagonals like this:
$diagonal=array();
for($row=0;$row<10;$row++){
for($col=0;$col<10;$col++){
if($row==$col){
$diagonal[$row][$col]='black';
}else{
$diagonal[$row][$col]='white';
}
if($row+$col==9){
$diagonal[$row][$col]='black';
}
}
}
And then echo'd simply like this:
echo "<table>";
for($row=0;$row<count($checkerboard);$row++){
echo "<tr>";
for($col=0;$col<count($checkerboard);$col++){
echo "<td width='50px' height='50px' bgcolor='".$checkerboard[$row][$col]."'></td>";
}
echo "</tr>";
}
I'd like to keep the code simple because I've not been coding php for a very long time and it has to work with an array.
I tried this here:
$spiral=array();
for($row=0;$row<10;$row++){
for($col=0;$col<10;$col++){
$spiral[$row][$col]='white';
if($row==0 or $row==9 or $col==0 or $col==9){
$spiral[$row][$col]='black';
}if($row==1 and $col==0){
$spiral[$row][$col]='white';
}if($row==2 and $col<8){
$spiral[$row][$col]='black';
}if($row>1 and $row<8 and $col==7){
$spiral[$row][$col]='black';
}if($row==7 and $col>1 and $col<8){
$spiral[$row][$col]='black';
}if($row>3 and $row<7 and $col==2){
$spiral[$row][$col]='black';
}if($row==4 and $col>2 and $col<6){
$spiral[$row][$col]='black';
}if($row==5 and $col==5){
$spiral[$row][$col]='black';
}
}
}
But if the checkerboard becomes bigger it will be very hard to change. It there a way to make it easier?
Try this out:
I create an empty board then start drawing horizontal & vertical lines, starting from the edges each time. The code might need some tweaking but it's a good start
$checkerboard=array();
$size = 12;
for ($row=0; $row<$size; $row++) {
for ($col=0; $col<$size; $col++) {
$checkerboard[$row][$col]="red";
}
}
//horizontal
$pair = 0 ;
while ($pair < (int) $size / 2) {
//drawing top half rows
$row = 2 * $pair;
$end = min($row, $size - $row);
$start = $end - 2;
for ($col = $start; ($col < $size - $end) && ($row < $size / 2); $col++){
$checkerboard[$row][$col]="black";
}
//drawing bottom half rows
$far_row = $size - 1 - 2 * $pair;
$end = min($far_row, $size - $far_row) + 1 - 2;
$start = $end ;
for ($col = $start; ($col < $size - $end) && ($far_row > $size / 2 ); $col++){
$checkerboard[$far_row][$col]="black";
}
$pair++;
}
$pair = 0;
//vertical
while ($pair < (int) $size / 2) {
//drawing left half columns
$col = 2 * $pair;
$end = min($col, $size - $col);
$start = $end +2 ;
for ($row = $start; ($row < $size - $end) && ($col < $size / 2); $row++){
$checkerboard[$row][$col]="black";
}
//drawing right half columns
$far_columns = $size - 1 - 2 * $pair;
$end = min($far_columns, $size - $far_columns) - 1;
$start = $end ;
for ($row = $start; ($row < $size - $end) && ($far_columns >= ($size / 2 ) ); $row++){
$checkerboard[$row][$far_columns]="black";
}
$pair++;
}
echo "<table>";
for($row=0;$row< $size;$row++){
echo "<tr>";
for($col=0; $col< $size; $col++){
echo "<td width='50px' height='50px' bgcolor='".$checkerboard[$row][$col]."'></td>";
}
echo "</tr>";
}
You can just change the $size variable for different dimensions
Here is my attempt at the problem:
function buildSpiral($gridSize)
{
/**
* Origin is at the top left handcorner
*/
$x = 0;
$y = 0;
$xMin = 0;
$xMax = $gridSize-1;
$yMin = 2;
$yMax = $gridSize-1;
$pattern = [];
$size = $gridSize;
$collision = function($p, $limit) {
return (bool) ($p == $limit);
};
// increment x
$shadeRight = function(&$x, $y) use (&$pattern, &$xMin, &$xMax, $collision) {
if ($xMin > $xMax) {
return;
}
do {
$pattern[$y][$x] = 1;
} while (!$collision($x++, $xMax));
if ($x >= $xMax) {
$x=$xMax;
}
$xMax-=2;
};
// increment y
$shadeDown = function($x, &$y) use (&$pattern, &$yMin, &$yMax, $collision) {
while ($y < $yMax && $yMin > $yMax) {
$pattern[++$y][$x] = 1;
}
if ($yMin > $yMax) {
return;
}
do {
$pattern[$y][$x] = 1;
} while (!$collision($y++, $yMax));
if ($y >= $yMax) {
$y = $yMax;
}
$yMax-=2;
};
// decrement x
$shadeLeft = function(&$x, $y) use (&$pattern, &$xMin, &$xMax, $collision, $gridSize) {
if ($xMin > $xMax) {
return;
}
do {
$pattern[$y][$x] = 1;
} while (!$collision($x--, $xMin));
if ($x < $xMin) {
$x=$xMin;
}
$xMin+=2;
};
// decrement y
$shadeUp = function($x, &$y) use (&$pattern, &$yMin, &$yMax, $collision, $gridSize) {
while ($y > $yMin && $yMin > $yMax) {
$pattern[--$y][$x] = 1;
}
if ($yMin > $yMax) {
return;
}
do {
$pattern[$y][$x] = 1;
} while(!$collision(--$y, $yMin));
if ($y < $yMin) {
$y = $yMin;
}
$yMin+=2;
};
while ($size > 0) {
$shadeRight($x, $y);
$shadeDown($x, $y);
$shadeLeft($x, $y);
$shadeUp($x, $y);
$size-=2;
}
return $pattern;
}
for ($i = 1; $i <= 25; $i++) {
$checkboard = buildSpiral($i);
echo "<h1>$i</h1>";
echo "<table style='margin-bottom: 2em;'>";
for($row=0;$row<count($checkboard);$row++){
echo "<tr>";
for($col=0;$col<count($checkboard);$col++){
if (!isset($checkboard[$row][$col])) {
echo "<td width='50px' height='50px' bgcolor=\"red\"></td>";
} else {
echo "<td width='50px' height='50px' bgcolor=\"black\"></td>";
}
}
echo "</tr>";
}
echo "</table>";
}
I stop each shading direction when a limit is hit.
Update Let's say I want the spirals to start from the top right corner, then we just need to set the new origin and call the shaders in the way we want the spiral to go like so:
function buildSpiral($gridSize)
{
/**
* Origin is at the top left handcorner
*/
$x = $gridSize-1;
$y = 0;
$xMin = 0;
$xMax = $gridSize-1;
$yMin = 2;
$yMax = $gridSize-1;
$pattern = [];
$size = $gridSize;
$collision = function($p, $limit) {
return (bool) ($p == $limit);
};
// increment x
$shadeRight = function(&$x, $y) use (&$pattern, &$xMin, &$xMax, $collision) {
if ($xMin > $xMax) {
return;
}
do {
$pattern[$y][$x] = 1;
} while (!$collision($x++, $xMax));
if ($x >= $xMax) {
$x=$xMax;
}
$xMax-=2;
};
// increment y
$shadeDown = function($x, &$y) use (&$pattern, &$yMin, &$yMax, $collision) {
while ($y < $yMax && $yMin > $yMax) {
$pattern[++$y][$x] = 1;
}
if ($yMin > $yMax) {
return;
}
do {
$pattern[$y][$x] = 1;
} while (!$collision($y++, $yMax));
if ($y >= $yMax) {
$y = $yMax;
}
$yMax-=2;
};
// decrement x
$shadeLeft = function(&$x, $y) use (&$pattern, &$xMin, &$xMax, $collision, $gridSize) {
if ($xMin > $xMax) {
return;
}
do {
$pattern[$y][$x] = 1;
} while (!$collision($x--, $xMin));
if ($x < $xMin) {
$x=$xMin;
}
$xMin+=2;
};
// decrement y
$shadeUp = function($x, &$y) use (&$pattern, &$yMin, &$yMax, $collision, $gridSize) {
while ($y > $yMin && $yMin > $yMax) {
$pattern[--$y][$x] = 1;
}
if ($yMin > $yMax) {
return;
}
do {
$pattern[$y][$x] = 1;
} while(!$collision(--$y, $yMin));
if ($y < $yMin) {
$y = $yMin;
}
$yMin+=2;
};
while ($size > 0) {
$shadeLeft($x, $y);
$shadeDown($x, $y);
$shadeRight($x, $y);
$shadeUp($x, $y);
$size-=2;
}
return $pattern;
}
for ($i = 1; $i <= 25; $i++) {
$checkboard = buildSpiral($i);
echo "<h1>$i</h1>";
echo "<table style='margin-bottom: 2em;'>";
for($row=0;$row<count($checkboard);$row++){
echo "<tr>";
for($col=0;$col<count($checkboard);$col++){
if (!isset($checkboard[$row][$col])) {
echo "<td width='50px' height='50px' bgcolor=\"red\"></td>";
} else {
echo "<td width='50px' height='50px' bgcolor=\"black\"></td>";
}
}
echo "</tr>";
}
echo "</table>";
}