aboutsummaryrefslogtreecommitdiff
path: root/challenge-109/brtastic/php/ch-2.php
blob: 304967ffae5cb27f3c27fb2d0a987769be2758da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php

const EL_COUNT = 7;

function permute($what)
{
	if (count($what) == 1) {
		return [$what];
	}

	$options = [];

	foreach($what as $el) {
		$seen = 0;
		array_push($options, ...array_map(
			fn ($arr) => [$el, ...$arr],
			permute(
				array_filter(
					$what,
					fn ($subel)
						=> $subel != $el || $seen++
				)
			)
		));
	}

	return $options;
}

function four_squares($input)
{
	$results = [];

	if (count($input) != EL_COUNT) {
		return $results;
	}

	foreach (permute($input) as $case) {
		$real_case = [0, ...$case, 0];
		$summed_groups = array_map(
			fn ($el)
				=> array_sum(
					array_map(
						fn ($subel)
							=> $real_case[$subel],
					range($el, $el + 2))
				),
			array_filter(
				array_keys($real_case),
				fn ($el)
					=> $el % 2 == 0 && $el <= count($real_case) - 2
			)
		);

		$matching_first = array_filter(
			$summed_groups,
			fn ($el)
				=> $el == $summed_groups[0]
		);

		if (count($matching_first) == count($summed_groups)) {
			$case_results = [];
			for ($letter = 'a'; $letter != 'h'; ++$letter) {
				$case_results[$letter] = array_shift($case);
			}

			$results[] = $case_results;
		}
	}

	return $results;
}

var_dump(four_squares(range(1, 7)));