summaryrefslogtreecommitdiff
path: root/2023/include/util.h
diff options
context:
space:
mode:
authorFederico Igne <undyamon@disroot.org>2023-12-19 02:06:02 +0100
committerFederico Igne <undyamon@disroot.org>2023-12-19 02:06:02 +0100
commite3c9f0c73077de51167491ca1ba4d5ccba005435 (patch)
tree792f18313a1e1fdbe2d0e97356631acd7ca65386 /2023/include/util.h
parentfe385ca1e5cd219478aef8f982d07182e4c8ad0d (diff)
downloadaoc-e3c9f0c73077de51167491ca1ba4d5ccba005435.tar.gz
aoc-e3c9f0c73077de51167491ca1ba4d5ccba005435.zip
aoc(2318): Lavaduct Lagoon
Diffstat (limited to '2023/include/util.h')
-rw-r--r--2023/include/util.h39
1 files changed, 39 insertions, 0 deletions
diff --git a/2023/include/util.h b/2023/include/util.h
index e396e3c..3152719 100644
--- a/2023/include/util.h
+++ b/2023/include/util.h
@@ -6,6 +6,7 @@
6#include <stdexcept> 6#include <stdexcept>
7#include <string> 7#include <string>
8#include <string_view> 8#include <string_view>
9#include <type_traits>
9 10
10namespace util 11namespace util
11{ 12{
@@ -119,6 +120,44 @@ std::basic_istream<CharT, Traits>& skip(std::basic_istream<CharT, Traits>& strea
119 return stream; 120 return stream;
120} 121}
121 122
123/* @brief Compute the area of a planar simple polygon.
124 *
125 * @tparam Int integral coordinate type.
126 * @param first start of an iterator over pairs of 'Int'.
127 * @param last end of an iterator over pairs of 'Int'.
128 *
129 * @see https://en.wikipedia.org/wiki/Shoelace_formula#Triangle_formula
130 */
131template<typename Int, typename InputIt, typename = std::enable_if_t<std::is_integral_v<Int>,Int>>
132Int shoelace(InputIt first, InputIt last)
133{
134 Int result{};
135 auto [x1, y1] = *first;
136 while(first++ != last)
137 {
138 auto [x2, y2] = *first;
139 result += x1 * y2 - x2 * y1;
140 x1 = x2; y1 = y2;
141 }
142 return std::abs(result / 2);
143}
144
145/* @brief Return the number of integral coordinates inside a planar
146 * simple polygon.
147 *
148 * @tparam Int integral return type.
149 * @param area the area of the polygon.
150 * @param border the number of integral coordinates on the polygon's
151 * boundary.
152 *
153 * @see https://en.wikipedia.org/wiki/Pick%27s_theorem#Formula
154 */
155template<typename Int = int, typename = std::enable_if_t<std::is_integral_v<Int>,Int>>
156Int pick(Int area, Int border)
157{
158 return area - border / 2 + 1;
159}
160
122} // namespace util 161} // namespace util
123 162
124#endif //UTIL_H 163#endif //UTIL_H