Advertisement
Guest User

Problem3-TextGravity

a guest
Aug 31st, 2014
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.54 KB | None | 0 0
  1. <?php
  2.  
  3. $text = $_GET['text'];
  4. $lineLength = $_GET['lineLength'];
  5. $textLenght = strlen($text);
  6. $rowsLenght = ceil($textLenght/$lineLength); //round up the number of rows
  7. $textindex = 0;
  8.  
  9. //insert the data into $matrix
  10. for($row = 0; $row < $rowsLenght; $row++){
  11.     for($column = 0; $column < $lineLength; $column++){
  12.         if ($textindex < $textLenght) {
  13.             $matrix[$row][$column] = $text[$textindex];
  14.         }
  15.         else $matrix[$row][$column] = ' ';
  16.         $textindex++;
  17.     }
  18.  
  19.  
  20.     }
  21.  
  22. //now 'gravity' for
  23. for($row = $rowsLenght-1; $row > 0; $row--){ //for all the rows reverse
  24.     for($column = 0; $column < $lineLength; $column++){
  25.  
  26.         if ($matrix[$row][$column] == ' ') {
  27.             //swap values
  28.             //find next char upstream and swap
  29.  
  30.             for($rowswap = $row; $rowswap >= 0; $rowswap--){ //get the first char upstream and swap it
  31.                 if ($matrix[$rowswap][$column] != ' ') {
  32.                     $matrix[$row][$column] = $matrix[$rowswap][$column];
  33.                     $matrix[$rowswap][$column] = ' ';
  34.                     break;
  35.                 }
  36.             }
  37.  
  38.         }
  39.  
  40.  
  41.     }
  42. }
  43.  
  44.  
  45. printTable($matrix);
  46.  
  47. //from Nakov SampleExam lol
  48. function printTable($matrix) {
  49.     echo '<table>';
  50.     for ($row = 0; $row < count($matrix); $row++) {
  51.         echo '<tr>';
  52.         for ($col = 0; $col < count($matrix[$row]); $col++) {
  53.             echo '<td>' . htmlspecialchars($matrix[$row][$col]) . '</td>';
  54.         }
  55.         echo '</tr>';
  56.     }
  57.     echo '<table>';
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement