Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Test tasks solving by Ruslan <retratserif@gmail.com> for cloud-team.ru
- * Version 2
- */
- // Task 1: Strings
- /**
- * Task 1.1
- * Count word occurrence. Alternative realisation using preg_split
- * @param string $string input string.
- * @param string $word word to count
- * @return int.
- */
- function wordsCount(string $string, string $word)
- {
- $word = mb_strtolower($word);
- $string = mb_strtolower($string);
- // Get list of words.
- $matches = usplit($string);
- // Get words stats.
- $result = array_count_values($matches);
- // Return stat for requested word.
- return $result[$word];
- } // wordsCount()
- /**
- * Task 1.2
- * Compare strings.
- * @param string $str1 Input string 1.
- * @param string $str2 Input string 2.
- * @return bool
- */
- function wordsOrderDiffers(string $str1, string $str2)
- {
- $str1 = mb_strtolower($str1);
- $str2 = mb_strtolower($str2);
- // convert strings to list of words
- $words1 = usplit($str1);
- $words2 = usplit($str2);
- // Return compare result.
- return $words1 != $words2;
- }
- /**
- * Helper function to split string to words with unicode support.
- * @param string $string Input string.
- * @return array Array of words.
- */
- function usplit(string $string)
- {
- $matches = null;
- preg_match_all('/\p{L}+/u', $string, $matches);
- return $matches[0];
- }
- // Task 2: Dates
- /**
- * Task 2.1
- * Return current date in format 2017/04/20 - 09:25.
- * @return string
- */
- function myTimestamp()
- {
- return date('Y/m/d - H:i');
- } // mytimestamp()
- /**
- * Task 2.2
- * Count week days
- * @param int $weekday weekday to count.
- * @param int $year year to count weekdays in.
- * @param return int
- */
- function countWeekDays(int $weekday, int $year)
- {
- if ($weekday > 6 || $weekday < 0)
- throw new Error('Weekday must be from 0 (sunday) to 6 (saturday).');
- // UNIX timestamp of January 1
- $startTime = mktime(0, 0, 0, 1, 1, $year);
- // UNIX timestamp of December 31
- $endTime = mktime(0, 0, 0, 12, 31, $year);
- $day = 60 * 60 * 24;
- $count = 0;
- for ($i = $startTime; $i <= $endTime; $i+=$day)
- {
- $date = getDate($i);
- if ($date['wday'] == $weekday)
- $count++;
- }
- return $count;
- } // countWeekDays()
- /**
- * Task 2.3
- * Get next sunday timestamp.
- * @return string
- */
- function nextSunday()
- {
- $date = getdate();
- // Current day:
- $currentDay = $date['wday'];
- // offset to the sunday:
- $offsetDays = 7 - $currentDay;
- $offsetSeconds = $offsetDays * 24 * 60 * 60;
- // Next sunday in Unix format
- $nextSundayTime = time() + $offsetSeconds;
- $sundayDate = date('Y-m-d', $nextSundayTime);
- return $sundayDate;
- } // nextSunday()
- // Task 3: Arrays
- /**
- * Task 3.1
- * Sort array by array
- * @param array $arr1 Array to sort.
- * @param array $arr2 Array to sort by.
- * @return array
- */
- function sortArrayByArray(array $arr1, array $arr2)
- {
- // Throw an error if wrong type of input.
- if (!is_array($arr1) || !is_array($arr2))
- throw new Error('This function accepts arrays only.');
- // Throw error if lengths of the arrays are not equal.
- if (count($arr1) != count($arr2))
- throw new Error('Input arrays must have equal length.');
- // Throw error if input arrays are not sequential.
- if (!isSeqArray($arr1) || !isSeqArray($arr2))
- throw new Error('Arrays must be sequential.');
- // Now create new sorted array.
- $newArr = array();
- foreach ($arr2 as $key)
- {
- $k = $key - 1;
- if(!isset($arr1[$k]))
- throw new Error("Key $key not exist, wrong data in array2.");
- $newArr[$k] = $arr1[$k];
- }
- return $newArr;
- } // sortArrayByArray()
- /**
- * Task 3.2
- * array_merge alalog.
- * @param array $arrays arrays to merge.
- * @return array Merged array.
- */
- function ArrayMerge(...$arrays)
- {
- // Get first array.
- $array1 = array_shift($arrays);
- if (!is_array($array1))
- throw new Exception('ArrayMerge() accepts arrays only.');
- // Process each input array
- foreach($arrays as $arr)
- {
- if (!is_array($arr))
- throw new Exception('ArrayMerge() accepts arrays only.');
- foreach($arr as $k => $v)
- {
- if (is_integer($k))
- $array1[] = $v;
- else
- $array1[$k] = $v;
- }
- }
- return $array1;
- } // ArrayMerge()
- /**
- * Task 3.3
- * Sum all elements of multidimensional array
- * @param array $arr Input array
- * @return int
- */
- function sumArrayElements(array $arr)
- {
- $sum = 0;
- // Walk through array (using recurse for multidimensional).
- foreach($arr as $val)
- {
- if (is_array($val))
- {
- if(!isSeqArray($val))
- throw new Error('This function supports sequentional arrays only.');
- $sum += sumArrayElements($val);
- }
- elseif (is_integer($val))
- {
- $sum += $val;
- }
- else
- {
- throw new Error('Input data must contain arrays of integers only. Multidimensional arrays also supported.');
- }
- }
- return $sum;
- } // sumArrayElements()
- /**
- * Task 3.4
- * Find equal values in arrays.
- * @param array $arrays
- * @return array
- */
- function equalValuesOfArrays(...$arrays)
- {
- $result = array();
- if (count($arrays) < 2)
- throw new Error('equalValuesOfArrays() expects at least 2 arguments.');
- foreach ($arrays as $array1)
- {
- foreach($arrays as $array2)
- {
- if (!is_array($array2))
- throw new Error('equalValuesOfArrays() accepts arrays only.');
- if ($array1 == $array2)
- continue;
- // Find intersect
- $intersectArray = array_intersect($array1, $array2);
- // Store only unique values.
- $diffArray = array_diff($intersectArray, $result);
- $result = array_merge($result, $diffArray);
- }
- }
- return $result;
- } // equalValuesOfArrays()
- /**
- * Task 4:
- * Factorial:
- * @param int $n facrorial size
- * @return int
- */
- function factorial(int $n)
- {
- if ($n > 1)
- return $n * factorial($n-1);
- else
- return 1;
- }
- /**
- * Helper function.
- * Check if array is sequential.
- * @param array $arr Array to check.
- * @return bool
- */
- function isSeqArray(array $arr)
- {
- return array_keys($arr) === range(0, count($arr) - 1);
- }
- // Testing:
- function test()
- {
- echo "Task 1.1:\n";
- echo " WordsCount('Никогда не qwerty,, (ыафыва)!!никогда', 'никогда'):
- should return 2: " . wordsCount('Никогда не qwerty,, (ыафыва)!!никогда', 'никогда');
- echo "\n\n";
- echo "Task 1.2:\n";
- echo " WordsOrderDiffers('Мама мыла раму', 'Мыла раму мама'): " . var_export(WordsOrderDiffers('Мама мыла раму', 'Мыла раму мама'), true);
- echo "\n";
- echo " WordsOrderDiffers('Мама мыла раму', 'мама мыла раму'): " . var_export(WordsOrderDiffers('Мама мыла раму', 'мама мыла раму'), true);
- echo "\n\n";
- echo "Task 2.1:\n";
- echo " myTimestamp(): " . myTimestamp();
- echo "\n\n";
- echo "Task 2.2\n";
- echo " countWeekDays(1, 2019): Count mondays of this year: " . countWeekDays(1, 2019);
- echo "\n";
- echo " countWeekDays(5, 2019): Count fridays of this year: " . countWeekDays(5, 2019);
- echo "\n\n";
- echo "Task 2.3:\n";
- echo " nextSunday(): " . nextSunday();
- echo "\n\n";
- echo "Task 3.1:\n";
- echo " SortArrayByArray(['x', 'm', 'g', 's', 'a'], [3, 5, 1, 4, 2]):
- " . var_export(SortArrayByArray(['x', 'm', 'g', 's', 'a'], [3, 5, 1, 4, 2]), true);
- echo "\n\n";
- echo "Task 3.2:\n";
- echo " ArrayMerge([1, 2, 'a' => 'A', 3], [4, 5, 'b' => 'B'], [6, 'a' => 'AA', 7]):
- " . var_export(ArrayMerge([1, 2, 'a' => 'A', 3], [4, 5, 'b' => 'B'], [6, 'a' => 'AA', 7]), true);
- echo "\n\n";
- echo "Task 3.3:\n";
- echo " sumArrayElements([ [12, 18 ], 40, [ 4, 6, [ 10 ] ] ]): " .
- sumArrayElements([ [12, 18 ], 40, [ 4, 6, [ 10 ] ] ]);
- echo "\n\n";
- echo "Task 3.4:\n";
- echo " equalValuesOfArrays([1, 5, 6, 8], [2, 3, 4, 5, 4], [10, 3, 12, 7]): " .
- var_export(equalValuesOfArrays([1, 5, 6, 8], [2, 3, 4, 5, 4], [10, 3, 12, 7]), true);
- echo "\n\n";
- echo "Task 4:\n";
- echo " factorial(5): " . factorial(5);
- echo "\n";
- } // test()
- // Run tests if called with --test arg.
- if (count($argv) > 1 && $argv[1] == '--test')
- test();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement