Advertisement
Guest User

Test task

a guest
Sep 20th, 2019
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 8.96 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  *  Test tasks solving by Ruslan <retratserif@gmail.com> for cloud-team.ru
  5.  *  Version 2
  6.  */
  7.  
  8. // Task 1: Strings
  9.  
  10. /**
  11.  * Task 1.1
  12.  * Count word occurrence. Alternative realisation using preg_split
  13.  * @param string $string input string.
  14.  * @param string $word   word to count
  15.  * @return int.
  16.  */
  17. function wordsCount(string $string, string $word)
  18. {
  19.     $word = mb_strtolower($word);
  20.     $string = mb_strtolower($string);
  21.    
  22.     // Get list of words.
  23.     $matches = usplit($string);
  24.    
  25.     // Get words stats.
  26.     $result = array_count_values($matches);
  27.    
  28.     // Return stat for requested word.
  29.     return $result[$word];
  30. } // wordsCount()
  31.  
  32. /**
  33.  * Task 1.2
  34.  * Compare strings.
  35.  * @param string $str1  Input string 1.
  36.  * @param string $str2  Input string 2.
  37.  * @return bool
  38.  */
  39. function wordsOrderDiffers(string $str1, string $str2)
  40. {
  41.     $str1 = mb_strtolower($str1);
  42.     $str2 = mb_strtolower($str2);
  43.    
  44.     // convert strings to list of words
  45.     $words1 = usplit($str1);
  46.     $words2 = usplit($str2);
  47.        
  48.     // Return compare result.
  49.     return $words1 != $words2;
  50. }
  51.  
  52. /**
  53.  * Helper function to split string to words with unicode support.
  54.  * @param string $string  Input string.
  55.  * @return array          Array of words.
  56.  */
  57. function usplit(string $string)
  58. {
  59.     $matches = null;
  60.     preg_match_all('/\p{L}+/u', $string, $matches);
  61.     return $matches[0];
  62. }
  63.  
  64.  
  65. // Task 2: Dates
  66.  
  67. /**
  68.  * Task 2.1
  69.  * Return current date in format 2017/04/20 - 09:25.
  70.  * @return string
  71.  */
  72. function myTimestamp()
  73. {
  74.     return date('Y/m/d - H:i');
  75. } // mytimestamp()
  76.  
  77. /**
  78.  * Task 2.2
  79.  * Count week days
  80.  * @param int $weekday weekday to count.
  81.  * @param int $year    year to count weekdays in.
  82.  * @param return int
  83.  */
  84. function countWeekDays(int $weekday, int $year)
  85. {
  86.     if ($weekday > 6 || $weekday < 0)
  87.         throw new Error('Weekday must be from 0 (sunday) to 6 (saturday).');
  88.    
  89.     // UNIX timestamp of January 1
  90.     $startTime = mktime(0, 0, 0, 1, 1, $year);
  91.     // UNIX timestamp of December 31
  92.     $endTime = mktime(0, 0, 0, 12, 31, $year);
  93.    
  94.     $day = 60 * 60 * 24;
  95.    
  96.     $count = 0;
  97.    
  98.     for ($i = $startTime; $i <= $endTime; $i+=$day)
  99.     {
  100.         $date = getDate($i);
  101.         if ($date['wday'] == $weekday)
  102.             $count++;
  103.     }
  104.    
  105.     return $count;
  106. } // countWeekDays()
  107.  
  108. /**
  109.  * Task 2.3
  110.  * Get next sunday timestamp.
  111.  * @return string
  112.  */
  113. function nextSunday()
  114. {
  115.     $date = getdate();
  116.    
  117.     // Current day:
  118.     $currentDay = $date['wday'];
  119.    
  120.     // offset to the sunday:
  121.     $offsetDays = 7 - $currentDay;
  122.     $offsetSeconds = $offsetDays * 24 * 60 * 60;
  123.    
  124.     // Next sunday in Unix format
  125.     $nextSundayTime = time() + $offsetSeconds;
  126.    
  127.     $sundayDate = date('Y-m-d', $nextSundayTime);
  128.    
  129.     return $sundayDate;
  130. } // nextSunday()
  131.  
  132.  
  133. // Task 3: Arrays
  134.  
  135. /**
  136.  * Task 3.1
  137.  * Sort array by array
  138.  * @param array $arr1  Array to sort.
  139.  * @param array $arr2  Array to sort by.
  140.  * @return array
  141.  */
  142. function sortArrayByArray(array $arr1, array $arr2)
  143. {
  144.     // Throw an error if wrong type of input.
  145.     if (!is_array($arr1) || !is_array($arr2))
  146.         throw new Error('This function accepts arrays only.');
  147.    
  148.     // Throw error if lengths of the arrays are not equal.
  149.     if (count($arr1) != count($arr2))
  150.         throw new Error('Input arrays must have equal length.');
  151.    
  152.     // Throw error if input arrays are not sequential.
  153.     if (!isSeqArray($arr1) || !isSeqArray($arr2))
  154.         throw new Error('Arrays must be sequential.');
  155.    
  156.     // Now create new sorted array.
  157.     $newArr = array();
  158.     foreach ($arr2 as $key)
  159.     {
  160.         $k = $key - 1;
  161.        
  162.         if(!isset($arr1[$k]))
  163.             throw new Error("Key $key not exist, wrong data in array2.");
  164.        
  165.         $newArr[$k] = $arr1[$k];
  166.     }
  167.    
  168.     return $newArr;
  169.    
  170. } // sortArrayByArray()
  171.  
  172. /**
  173.  * Task 3.2
  174.  * array_merge alalog.
  175.  * @param array $arrays arrays to merge.
  176.  * @return array  Merged array.
  177.  */
  178. function ArrayMerge(...$arrays)
  179. {
  180.     // Get first array.
  181.     $array1 = array_shift($arrays);
  182.    
  183.     if (!is_array($array1))
  184.         throw new Exception('ArrayMerge() accepts arrays only.');
  185.    
  186.     // Process each input array
  187.     foreach($arrays as $arr)
  188.     {
  189.         if (!is_array($arr))
  190.             throw new Exception('ArrayMerge() accepts arrays only.');
  191.        
  192.         foreach($arr as $k => $v)
  193.         {
  194.             if (is_integer($k))
  195.                 $array1[] = $v;
  196.             else
  197.                 $array1[$k] = $v;
  198.         }
  199.     }
  200.    
  201.     return $array1;
  202. } // ArrayMerge()
  203.  
  204. /**
  205.  * Task 3.3
  206.  * Sum all elements of multidimensional array
  207.  * @param array $arr  Input array
  208.  * @return int
  209.  */
  210. function sumArrayElements(array $arr)
  211. {
  212.     $sum = 0;
  213.    
  214.     // Walk through array (using recurse for multidimensional).
  215.     foreach($arr as $val)
  216.     {
  217.         if (is_array($val))
  218.         {
  219.             if(!isSeqArray($val))
  220.                 throw new Error('This function supports sequentional arrays only.');
  221.            
  222.             $sum += sumArrayElements($val);
  223.         }
  224.         elseif (is_integer($val))
  225.         {
  226.             $sum += $val;
  227.         }
  228.         else
  229.         {
  230.             throw new Error('Input data must contain arrays of integers only. Multidimensional arrays also supported.');
  231.         }
  232.     }
  233.    
  234.     return $sum;
  235. } // sumArrayElements()
  236.  
  237. /**
  238.  * Task 3.4
  239.  * Find equal values in arrays.
  240.  * @param array $arrays
  241.  * @return array
  242.  */
  243. function equalValuesOfArrays(...$arrays)
  244. {
  245.     $result = array();
  246.    
  247.     if (count($arrays) < 2)
  248.         throw new Error('equalValuesOfArrays() expects at least 2 arguments.');
  249.    
  250.     foreach ($arrays as $array1)
  251.     {
  252.         foreach($arrays as $array2)
  253.         {
  254.             if (!is_array($array2))
  255.                 throw new Error('equalValuesOfArrays() accepts arrays only.');
  256.            
  257.             if ($array1 == $array2)
  258.                 continue;
  259.            
  260.             // Find intersect
  261.             $intersectArray = array_intersect($array1, $array2);
  262.            
  263.             // Store only unique values.
  264.             $diffArray = array_diff($intersectArray, $result);
  265.             $result = array_merge($result, $diffArray);
  266.         }
  267.     }
  268.        
  269.     return $result;
  270. } // equalValuesOfArrays()
  271.  
  272. /**
  273.  * Task 4:
  274.  * Factorial:
  275.  * @param int $n  facrorial size
  276.  * @return int
  277.  */
  278. function factorial(int $n)
  279. {
  280.     if ($n > 1)
  281.         return $n * factorial($n-1);
  282.     else
  283.         return 1;
  284. }
  285.  
  286.  
  287. /**
  288.  * Helper function.
  289.  * Check if array is sequential.
  290.  * @param array $arr  Array to check.
  291.  * @return bool
  292.  */
  293. function isSeqArray(array $arr)
  294. {
  295.     return array_keys($arr) === range(0, count($arr) - 1);
  296. }
  297.  
  298.  
  299. // Testing:
  300. function test()
  301. {
  302.     echo "Task 1.1:\n";
  303.     echo "  WordsCount('Никогда не qwerty,, (ыафыва)!!никогда', 'никогда'):
  304.    should return 2: " . wordsCount('Никогда не qwerty,, (ыафыва)!!никогда', 'никогда');
  305.     echo "\n\n";
  306.    
  307.     echo "Task 1.2:\n";
  308.     echo "  WordsOrderDiffers('Мама мыла раму', 'Мыла раму мама'): " . var_export(WordsOrderDiffers('Мама мыла раму', 'Мыла раму мама'), true);
  309.     echo "\n";
  310.  
  311.     echo "  WordsOrderDiffers('Мама мыла раму', 'мама мыла раму'): " . var_export(WordsOrderDiffers('Мама мыла раму', 'мама мыла раму'), true);
  312.     echo "\n\n";
  313.    
  314.     echo "Task 2.1:\n";
  315.     echo "  myTimestamp(): " . myTimestamp();
  316.     echo "\n\n";
  317.    
  318.     echo "Task 2.2\n";
  319.     echo "  countWeekDays(1, 2019): Count mondays of this year: " . countWeekDays(1, 2019);
  320.     echo "\n";
  321.     echo "  countWeekDays(5, 2019): Count fridays of this year: " . countWeekDays(5, 2019);
  322.     echo "\n\n";
  323.    
  324.     echo "Task 2.3:\n";
  325.     echo "  nextSunday(): " . nextSunday();
  326.     echo "\n\n";
  327.    
  328.     echo "Task 3.1:\n";
  329.     echo "  SortArrayByArray(['x', 'm', 'g', 's', 'a'], [3, 5, 1, 4, 2]):
  330. " . var_export(SortArrayByArray(['x', 'm', 'g', 's', 'a'], [3, 5, 1, 4, 2]), true);
  331.     echo "\n\n";
  332.    
  333.     echo "Task 3.2:\n";
  334.     echo "  ArrayMerge([1, 2, 'a' => 'A', 3], [4, 5, 'b' => 'B'], [6, 'a' => 'AA', 7]):
  335. " . var_export(ArrayMerge([1, 2, 'a' => 'A', 3], [4, 5, 'b' => 'B'], [6, 'a' => 'AA', 7]), true);
  336.     echo "\n\n";
  337.  
  338.     echo "Task 3.3:\n";
  339.     echo "  sumArrayElements([ [12, 18 ], 40, [ 4, 6, [ 10 ] ] ]): " .
  340.     sumArrayElements([ [12, 18 ], 40, [ 4, 6, [ 10 ] ] ]);
  341.     echo "\n\n";
  342.    
  343.     echo "Task 3.4:\n";
  344.     echo "  equalValuesOfArrays([1, 5, 6, 8], [2, 3, 4, 5, 4], [10, 3, 12, 7]): " .
  345.     var_export(equalValuesOfArrays([1, 5, 6, 8], [2, 3, 4, 5, 4], [10, 3, 12, 7]), true);
  346.     echo "\n\n";
  347.    
  348.     echo "Task 4:\n";
  349.     echo "  factorial(5): " . factorial(5);
  350.     echo "\n";
  351. } // test()
  352.  
  353. // Run tests if called with --test arg.
  354. if (count($argv) > 1 && $argv[1] == '--test')
  355.     test();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement