Advertisement
Mihail_Atnsv

arrayOperationsAdvanced

Oct 30th, 2018
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.86 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: Toshiba
  5.  * Date: 29.10.2018 г.
  6.  * Time: 18:10
  7.  */
  8.  
  9. $arr = array_map('intval', explode(" ", readline()));
  10. $line = readline();
  11.  
  12. while (true) {
  13.  
  14.     if ($line == "End"){
  15.         break;
  16.     }
  17.  
  18.     $tokens = explode(" ", $line);
  19.     $command = $tokens[0];
  20.  
  21.     switch ($command) {
  22.         case "Add":
  23.             $number = intval($tokens[1]);
  24.             $arr[] = $number;
  25.             break;
  26.         case "Insert":
  27.             $number = intval($tokens[1]);
  28.             $position = intval($tokens[2]);
  29.             if ($position >= 0 && $position < count($arr)) {
  30.                 array_splice($arr, $position, 0, $number);
  31.             }else{
  32.                 echo "Invalid index".PHP_EOL;
  33.             }
  34.             break;
  35.         case "Remove":
  36.             $index = intval($tokens[1]);
  37.             if ($index >= 0 && $index < count($arr)) {
  38.                 array_splice($arr, $index, 1);
  39.                 //unset($arr[$index]);
  40.                 //$arr = array_values($arr);
  41.             }else{
  42.                 echo "Invalid index".PHP_EOL;
  43.             }
  44.             break;
  45.         case "Shift":
  46.             $direction = $tokens[1];
  47.             $count = intval($tokens[2]);
  48.             if (count($arr) < 1){
  49.                 break;
  50.             }
  51.             if ($direction == "left") {
  52.                 for ($i = 0; $i < $count; $i++) {
  53.                     $current = array_shift($arr);
  54.                     array_push($arr, $current);
  55.                     $arr = array_values($arr);
  56.                 }
  57.             } elseif ($direction == "right") {
  58.                 $current = $arr[count($arr) - 1];
  59.                 array_pop($arr);
  60.                 array_unshift($arr, $current);
  61.                 $arr = array_values($arr);
  62.             }
  63.             break;
  64.     }
  65.  
  66.     $line = readline();
  67. }
  68.  
  69. echo implode(" ", $arr);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement