-
Notifications
You must be signed in to change notification settings - Fork 0
/
sonar.cpp
87 lines (76 loc) · 1.94 KB
/
sonar.cpp
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
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright (c) Omar Boukli-Hacene. All rights reserved.
// Distributed under an MIT-style license that can be
// found in the LICENSE file.
// SPDX-License-Identifier: MIT
#include "forfun/sonar.hpp"
#include <algorithm>
#include <cstdlib>
namespace forfun::sonar {
[[nodiscard]] auto count_ships(sonar const& sonar, area const area) noexcept
-> int
{
if (!sonar.ping(area))
{
return 0;
}
int const width{std::abs(area.right - area.left)};
int const height{std::abs(area.bottom - area.top)};
if ((width + height) == 0)
{
return 1;
}
int const mw0{area.left + (width / 2)};
int const mw1{mw0 + 1};
int const mh0{area.top + (height / 2)};
int const mh1{mh0 + 1};
// clang-format off
return (
count_ships(
sonar,
{
.top = area.top,
.bottom = mh0,
.left = area.left,
.right = mw0,
}
) +
count_ships(
sonar,
{
.top = area.top,
.bottom = mh0,
.left = mw1,
.right = area.right,
}
) +
count_ships(
sonar,
{
.top = mh1,
.bottom = area.bottom,
.left = area.left,
.right = mw0,
}
) +
count_ships(
sonar,
{
.top = mh1,
.bottom = area.bottom,
.left = mw1,
.right = area.right,
}
)
);
// clang-format on
}
[[nodiscard]] auto sonar::ping(area const area) const noexcept -> bool
{
return std::ranges::any_of(coords_, [&area](coord const& coord) noexcept {
return coord.x >= area.top
&& coord.x <= area.bottom
&& coord.y >= area.left
&& coord.y <= area.right;
});
}
} // namespace forfun::sonar