Passed
Push — master ( 228718...2540c1 )
by Tomáš
09:08
created

Functions::nestedCount()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
4
namespace TournamentGenerator\Helpers;
5
6
7
/**
8
 * Static helper functions
9
 *
10
 * @package TournamentGenerator\Helpers
11
 *
12
 * @author  Tomáš Vojík <[email protected]>
13
 *
14
 * @since   0.4
15
 */
16
class Functions
17
{
18
	/**
19
	 * Checks if the number is a power of 2
20
	 *
21
	 * @param int $x
22
	 *
23
	 * @return bool
24
	 */
25 12
	public static function isPowerOf2(int $x) : bool {
26 12
		return ($x !== 0) && ($x & ($x - 1)) === 0;
27
	}
28
29
	/**
30
	 * Get the next power of 2 larger than input
31
	 *
32
	 * @param int $x
33
	 *
34
	 * @return int
35
	 */
36 9
	public static function nextPowerOf2(int $x) : int {
37
		// Left bit shift by the bit length of the previous number
38 9
		return 1 << strlen(decbin($x));
39
	}
40
41
	/**
42
	 * Get the previous power of 2 smaller or equal than input
43
	 *
44
	 * @param int $x
45
	 *
46
	 * @return int
47
	 */
48 9
	public static function previousPowerOf2(int $x) : int {
49
		// Left bit shift by the bit length of the previous number
50 9
		return 1 << (strlen(decbin($x)) - 1);
51
	}
52
53
	/**
54
	 * Calculate a count of 2D array
55
	 *
56
	 * @param array[] $array
57
	 *
58
	 * @return int
59
	 */
60 10
	public static function nestedCount(array $array) : int {
61 10
		$count = 0;
62 10
		foreach ($array as $inner) {
63 9
			$count += count($inner);
64
		}
65 10
		return $count;
66
	}
67
68
	/**
69
	 * @param array $array
70
	 *
71
	 * @return array
72
	 */
73 4
	public static function sortAlternate(array &$array) : array {
74 4
		$new = [];
75 4
		$new2 = [];
76 4
		$count = count($array) / 2;
77 4
		for ($i = 0; $i < $count; $i++) {
78 4
			if ($i % 2 === 0) {
79 4
				$new[] = array_shift($array);
80 4
				$new[] = array_pop($array);
81
			}
82
			else {
83 4
				$new2[] = array_shift($array);
84 4
				$new2[] = array_pop($array);
85
			}
86
		}
87 4
		$array = array_values(array_filter(array_merge($new, array_reverse($new2))));
88 4
		return $array;
89
	}
90
}