text stringlengths 1 2.12k | source dict |
|---|---|
c++, recursion, template, c++20, constrained-templates
// recursive_transform implementation (the version with unwrap_level, with execution policy)
template<std::size_t unwrap_level = 1, class ExPo, class T, class F>
requires (unwrap_level <= recursive_depth<T>() && // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235
std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_transform(ExPo execution_policy, const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
recursive_variadic_invoke_result_t<unwrap_level, F, T> output{};
output.resize(input.size());
std::mutex mutex;
std::transform(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[&](auto&& element)
{
std::lock_guard lock(mutex);
return recursive_transform<unwrap_level - 1>(execution_policy, element, f);
});
return output;
}
else
{
return f(input);
}
}
}
/* recursive_reduce_all template function performs operation on input container exhaustively
*/
template<arithmetic T>
constexpr auto recursive_reduce_all(const T& input)
{
return input;
}
template<std::ranges::input_range T>
requires (arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
recursive_depth<T>() == 1)
constexpr auto recursive_reduce_all(const T& input)
{
return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input));
} | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// overload for std::array
template<template<class, std::size_t> class Container,
typename T,
std::size_t N>
requires (arithmetic<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> &&
recursive_depth<Container<T, N>>() == 1)
constexpr auto recursive_reduce_all(const Container<T, N>& input)
{
return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input));
}
template<std::ranges::input_range T>
requires (arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::ranges::input_range<recursive_unwrap_type_t<1, T>>)
constexpr auto recursive_reduce_all(const T& input)
{
auto result = recursive_reduce_all(
UL::recursive_transform<recursive_depth<T>() - 1>(input, [](auto&& element){ return recursive_reduce_all(element); })
);
return result;
}
// recursive_reduce_all template function with execution policy
template<class ExPo, arithmetic T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input)
{
return input;
}
template<class ExPo, std::ranges::input_range T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
recursive_depth<T>() == 1)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input)
{
return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input));
} | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_all template function with execution policy, overload for std::array
template<class ExPo, template<class, std::size_t> class Container,
typename T,
std::size_t N>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmetic<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> &&
recursive_depth<Container<T, N>>() == 1)
constexpr auto recursive_reduce_all(ExPo execution_policy, const Container<T, N>& input)
{
return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input));
}
template<class ExPo, std::ranges::input_range T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::ranges::input_range<recursive_unwrap_type_t<1, T>>)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input)
{
auto result = recursive_reduce_all(
UL::recursive_transform<recursive_depth<T>() - 1>(
execution_policy,
input,
[&](auto&& element){ return recursive_reduce_all(execution_policy, element); }
)
);
return result;
}
// recursive_reduce_all template function with initial value
template<arithmetic T>
constexpr auto recursive_reduce_all(const T& input1, const T& input2)
{
return input1 + input2;
}
template<std::ranges::input_range T, class TI>
requires (arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> &&
recursive_depth<T>() == 1)
constexpr auto recursive_reduce_all(const T& input, TI init)
{
return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input), init);
} | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_all template function with initial value, overload for std::array
template<template<class, std::size_t> class Container,
typename T,
std::size_t N,
class TI>
requires (arithmetic<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> &&
std::same_as<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, TI> &&
recursive_depth<Container<T, N>>() == 1)
constexpr auto recursive_reduce_all(const Container<T, N>& input, TI init)
{
return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input), init);
}
template<std::ranges::input_range T, class TI>
requires (arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::ranges::input_range<recursive_unwrap_type_t<1, T>> &&
std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI>)
constexpr auto recursive_reduce_all(const T& input, TI init)
{
auto result = init + recursive_reduce_all(
UL::recursive_transform<recursive_depth<T>() - 1>(
input,
[&](auto&& element){ return recursive_reduce_all(element); })
);
return result;
}
// recursive_reduce_all template function with execution policy and initial value
template<class ExPo, arithmetic T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input1, const T& input2)
{
return input1 + input2;
} | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<class ExPo, std::ranges::input_range T, class TI>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> &&
recursive_depth<T>() == 1)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input, TI init)
{
return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), init);
}
// recursive_reduce_all template function with execution policy and initial value, overload for std::array
template<class ExPo,
template<class, std::size_t> class Container,
typename T,
std::size_t N,
class TI>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmetic<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> &&
std::same_as<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, TI> &&
recursive_depth<Container<T, N>>() == 1)
constexpr auto recursive_reduce_all(ExPo execution_policy, const Container<T, N>& input, TI init)
{
return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), init);
} | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<class ExPo, std::ranges::input_range T, class TI>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::ranges::input_range<recursive_unwrap_type_t<1, T>> &&
std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI>)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input, TI init)
{
auto result = init + recursive_reduce_all(
UL::recursive_transform<recursive_depth<T>() - 1>(
execution_policy,
input,
[&](auto&& element){ return recursive_reduce_all(execution_policy, element); })
);
return result;
}
// recursive_reduce_all template function with initial value and specified operation
template<arithmetic T, class BinaryOp>
requires (std::regular_invocable<BinaryOp, T, T>)
constexpr auto recursive_reduce_all(const T& input1, const T& input2, BinaryOp binary_op)
{
return std::invoke(binary_op, input1, input2);
}
template<std::ranges::input_range T, class TI, class BinaryOp>
requires (arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> &&
recursive_depth<T>() == 1 &&
std::regular_invocable<
BinaryOp,
recursive_unwrap_type_t<recursive_depth<T>(),T>,
recursive_unwrap_type_t<recursive_depth<T>(), T>>
)
constexpr auto recursive_reduce_all(const T& input, TI init, BinaryOp binary_op)
{
return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input), init, binary_op);
} | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_all template function with initial value and specified operation, overload for std::array
template<template<class, std::size_t> class Container,
typename T,
std::size_t N,
class TI,
class BinaryOp>
requires (arithmetic<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> &&
std::same_as<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, TI> &&
recursive_depth<Container<T, N>>() == 1 &&
std::regular_invocable<
BinaryOp,
recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>,
recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>>
)
constexpr auto recursive_reduce_all(const Container<T, N>& input, TI init, BinaryOp binary_op)
{
return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input), init, binary_op);
}
template<std::ranges::input_range T, class TI, class BinaryOp>
requires (arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::ranges::input_range<recursive_unwrap_type_t<1, T>> &&
std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> &&
std::regular_invocable<
BinaryOp,
recursive_unwrap_type_t<recursive_depth<T>(),T>,
recursive_unwrap_type_t<recursive_depth<T>(), T>>
)
constexpr auto recursive_reduce_all(const T& input, TI init, BinaryOp binary_op)
{
auto result = init + recursive_reduce_all(
UL::recursive_transform<recursive_depth<T>() - 1>(
input,
[&](auto&& element){ return recursive_reduce_all(element, init, binary_op); })
);
return result;
} | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_all template function with execution policy, initial value and specified operation
template<class ExPo, arithmetic T, class BinaryOp>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
std::regular_invocable<BinaryOp, T, T>)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input1, const T& input2, BinaryOp binary_op)
{
return std::invoke(binary_op, input1, input2);
}
template<class ExPo, std::ranges::input_range T, class TI, class BinaryOp>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> &&
recursive_depth<T>() == 1 &&
std::regular_invocable<
BinaryOp,
recursive_unwrap_type_t<recursive_depth<T>(),T>,
recursive_unwrap_type_t<recursive_depth<T>(), T>>
)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input, TI init, BinaryOp binary_op)
{
return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), init, binary_op);
} | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_reduce_all template function with execution policy, initial value and specified operation, overload for std::array
template<class ExPo,
template<class, std::size_t> class Container,
typename T,
std::size_t N,
class TI, class BinaryOp>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmetic<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>> &&
std::same_as<recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>, TI> &&
recursive_depth<Container<T, N>>() == 1 &&
std::regular_invocable<
BinaryOp,
recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>,
recursive_array_unwrap_type_t<recursive_depth<Container<T, N>>(), Container<T, N>>>
)
constexpr auto recursive_reduce_all(ExPo execution_policy, const Container<T, N>& input, TI init, BinaryOp binary_op)
{
return std::reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), init, binary_op);
} | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<class ExPo, std::ranges::input_range T, class TI, class BinaryOp>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>> &&
arithmetic<recursive_unwrap_type_t<recursive_depth<T>(), T>> &&
std::ranges::input_range<recursive_unwrap_type_t<1, T>> &&
std::same_as<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI> &&
std::regular_invocable<
BinaryOp,
recursive_unwrap_type_t<recursive_depth<T>(),T>,
recursive_unwrap_type_t<recursive_depth<T>(), T>>
)
constexpr auto recursive_reduce_all(ExPo execution_policy, const T& input, TI init, BinaryOp binary_op)
{
auto result = init + recursive_reduce_all(
UL::recursive_transform<recursive_depth<T>() - 1>(
execution_policy,
input,
[&](auto&& element){ return recursive_reduce_all(execution_policy, element, init, binary_op); })
);
return result;
}
template<class T>
requires (std::ranges::input_range<T>)
constexpr auto recursive_print(const T& input, const int level = 0)
{
T output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::transform(input.cbegin(), input.cend(), output.begin(),
[level](auto&& x)
{
std::cout << std::string(level, ' ') << x << std::endl;
return x;
}
);
return output;
}
template<class T>
requires (std::ranges::input_range<T> &&
std::ranges::input_range<std::ranges::range_value_t<T>>)
constexpr T recursive_print(const T& input, const int level = 0)
{
T output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::transform(input.cbegin(), input.cend(), output.begin(),
[level](auto&& element)
{
return recursive_print(element, level + 1);
}
);
return output;
} | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
void recursive_reduce_all_tests_vector()
{
auto test_vectors = n_dim_container_generator<std::vector, 4, double>(1, 4);
std::cout << "Play with test_vectors:\n\n";
std::cout << "Pure recursive_reduce_all function test: \n";
auto recursive_reduce_all_result1 = recursive_reduce_all(test_vectors);
std::cout << recursive_reduce_all_result1 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::seq): \n";
auto recursive_reduce_all_result2 = recursive_reduce_all(std::execution::seq, test_vectors);
std::cout << recursive_reduce_all_result2 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par): \n";
auto recursive_reduce_all_result3 = recursive_reduce_all(std::execution::par, test_vectors);
std::cout << recursive_reduce_all_result3 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par_unseq): \n";
auto recursive_reduce_all_result4 = recursive_reduce_all(std::execution::par_unseq, test_vectors);
std::cout << recursive_reduce_all_result4 << "\n\n";
std::cout << "recursive_reduce_all function test with initial value: \n";
auto recursive_reduce_all_result5 = recursive_reduce_all(test_vectors, static_cast<double>(1));
std::cout << recursive_reduce_all_result5 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::seq) and initial value: \n";
auto recursive_reduce_all_result6 = recursive_reduce_all(std::execution::seq, test_vectors, static_cast<double>(1));
std::cout << recursive_reduce_all_result6 << "\n\n"; | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par) and initial value: \n";
auto recursive_reduce_all_result7 = recursive_reduce_all(std::execution::par, test_vectors, static_cast<double>(1));
std::cout << recursive_reduce_all_result7 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par_unseq) and initial value: \n";
auto recursive_reduce_all_result8 = recursive_reduce_all(std::execution::par_unseq, test_vectors, static_cast<double>(1));
std::cout << recursive_reduce_all_result8 << "\n\n";
std::cout << "recursive_reduce_all function test with initial value and specified operation: \n";
auto recursive_reduce_all_result9 = recursive_reduce_all(test_vectors, static_cast<double>(1), [](auto&& input1, auto&& input2) { return input1 * input2; });
std::cout << recursive_reduce_all_result9 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::seq), initial value and specified operation: \n";
auto recursive_reduce_all_result10 = recursive_reduce_all(std::execution::seq, test_vectors, static_cast<double>(1), [](auto&& input1, auto&& input2) { return input1 * input2; });
std::cout << recursive_reduce_all_result10 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par), initial value and specified operation: \n";
auto recursive_reduce_all_result11 = recursive_reduce_all(std::execution::par, test_vectors, static_cast<double>(1), [](auto&& input1, auto&& input2) { return input1 * input2; });
std::cout << recursive_reduce_all_result11 << "\n\n"; | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par_unseq), initial value and specified operation: \n";
auto recursive_reduce_all_result12 = recursive_reduce_all(std::execution::par_unseq, test_vectors, static_cast<double>(1), [](auto&& input1, auto&& input2) { return input1 * input2; });
std::cout << recursive_reduce_all_result12 << "\n\n";
return;
}
void recursive_reduce_all_tests_array()
{
auto test_array = std::array<double, 4>{1, 1, 1, 1};
std::cout << "Play with test_array:\n\n";
std::cout << "Pure recursive_reduce_all function test: \n";
auto recursive_reduce_all_result1 = recursive_reduce_all(test_array);
std::cout << recursive_reduce_all_result1 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::seq): \n";
auto recursive_reduce_all_result2 = recursive_reduce_all(std::execution::seq, test_array);
std::cout << recursive_reduce_all_result2 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par): \n";
auto recursive_reduce_all_result3 = recursive_reduce_all(std::execution::par, test_array);
std::cout << recursive_reduce_all_result3 << "\n\n"; | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par_unseq): \n";
auto recursive_reduce_all_result4 = recursive_reduce_all(std::execution::par_unseq, test_array);
std::cout << recursive_reduce_all_result4 << "\n\n";
std::cout << "recursive_reduce_all function test with initial value: \n";
auto recursive_reduce_all_result5 = recursive_reduce_all(test_array, static_cast<double>(1));
std::cout << recursive_reduce_all_result5 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::seq) and initial value: \n";
auto recursive_reduce_all_result6 = recursive_reduce_all(std::execution::seq, test_array, static_cast<double>(1));
std::cout << recursive_reduce_all_result6 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par) and initial value: \n";
auto recursive_reduce_all_result7 = recursive_reduce_all(std::execution::par, test_array, static_cast<double>(1));
std::cout << recursive_reduce_all_result7 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par_unseq) and initial value: \n";
auto recursive_reduce_all_result8 = recursive_reduce_all(std::execution::par_unseq, test_array, static_cast<double>(1));
std::cout << recursive_reduce_all_result8 << "\n\n";
std::cout << "recursive_reduce_all function test with initial value and specified operation: \n";
auto recursive_reduce_all_result9 = recursive_reduce_all(test_array, static_cast<double>(1), [](auto&& input1, auto&& input2) { return input1 * input2; });
std::cout << recursive_reduce_all_result9 << "\n\n"; | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::cout << "recursive_reduce_all function test with execution policy (std::execution::seq), initial value and specified operation: \n";
auto recursive_reduce_all_result10 = recursive_reduce_all(std::execution::seq, test_array, static_cast<double>(1), [](auto&& input1, auto&& input2) { return input1 * input2; });
std::cout << recursive_reduce_all_result10 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par), initial value and specified operation: \n";
auto recursive_reduce_all_result11 = recursive_reduce_all(std::execution::par, test_array, static_cast<double>(1), [](auto&& input1, auto&& input2) { return input1 * input2; });
std::cout << recursive_reduce_all_result11 << "\n\n";
std::cout << "recursive_reduce_all function test with execution policy (std::execution::par_unseq), initial value and specified operation: \n";
auto recursive_reduce_all_result12 = recursive_reduce_all(std::execution::par_unseq, test_array, static_cast<double>(1), [](auto&& input1, auto&& input2) { return input1 * input2; });
std::cout << recursive_reduce_all_result12 << "\n\n";
return;
}
int main()
{
auto start = std::chrono::system_clock::now();
recursive_reduce_all_tests_vector();
recursive_reduce_all_tests_array();
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n';
return 0;
}
The output of the test code above:
Play with test_vectors:
Pure recursive_reduce_all function test:
256
recursive_reduce_all function test with execution policy (std::execution::seq):
256
recursive_reduce_all function test with execution policy (std::execution::par):
256 | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
recursive_reduce_all function test with execution policy (std::execution::par):
256
recursive_reduce_all function test with execution policy (std::execution::par_unseq):
256
recursive_reduce_all function test with initial value:
257
recursive_reduce_all function test with execution policy (std::execution::seq) and initial value:
257
recursive_reduce_all function test with execution policy (std::execution::par) and initial value:
257
recursive_reduce_all function test with execution policy (std::execution::par_unseq) and initial value:
257
recursive_reduce_all function test with initial value and specified operation:
65
recursive_reduce_all function test with execution policy (std::execution::seq), initial value and specified operation:
65
recursive_reduce_all function test with execution policy (std::execution::par), initial value and specified operation:
65
recursive_reduce_all function test with execution policy (std::execution::par_unseq), initial value and specified operation:
65
Play with test_array:
Pure recursive_reduce_all function test:
4
recursive_reduce_all function test with execution policy (std::execution::seq):
4
recursive_reduce_all function test with execution policy (std::execution::par):
4
recursive_reduce_all function test with execution policy (std::execution::par_unseq):
4
recursive_reduce_all function test with initial value:
5
recursive_reduce_all function test with execution policy (std::execution::seq) and initial value:
5
recursive_reduce_all function test with execution policy (std::execution::par) and initial value:
5
recursive_reduce_all function test with execution policy (std::execution::par_unseq) and initial value:
5
recursive_reduce_all function test with initial value and specified operation:
1
recursive_reduce_all function test with execution policy (std::execution::seq), initial value and specified operation:
1 | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
recursive_reduce_all function test with execution policy (std::execution::par), initial value and specified operation:
1
recursive_reduce_all function test with execution policy (std::execution::par_unseq), initial value and specified operation:
1
Computation finished at Thu Jun 29 05:09:13 2023
elapsed time: 0.00150533
Godbolt link is here.
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
A recursive_sum Template Function Implementation with Unwrap Level in C++ and
A recursive_unwrap_type_t Struct Implementation in C++.
What changes has been made in the code since last question?
I am trying to implement recursive_reduce_all() template function in C++ which performs operation on input container exhaustively.
Why a new review is being asked for?
Please review the recursive_reduce_all() template function implementation and its testing function recursive_reduce_all_tests. | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Answer: Be more precise with your type constraints
By using incorrect constraints, you greatly reduced the number of types your recursive_reduce_all() works on. std::is_arithmetic_v<> checks whether the type is basically an integer or a float, nothing else will match. There are many more types that std::reduce()'s default binary operator std::plus<> works on.
Note that std::is_arithmetic_v<> doesn't check whether a given type supports arithmetic operations, it only checks if it's a basic integer or floating point type. Even something like std::is_arithmetic_v<std::complex<float>> will be false.
Later on you use std::regular_invocable<BinaryOp, T, T>, which is a much better constraint to use. However, there is also an issue here. Look at std::reduce(), and note how the init parameter can have a different type than the iterator's value type. This allows you, for example, to sum an array of std::uint32_ts into a std::uint64_t without having to worry about integer overflows, or it allows you to have an array of std::chrono::durations and add them all to an initial std::chrono::time_point.
It might be worthwhile to create a concept reducible, that checks whether given an iterator type, init type (defaulting to the iterator's value type) and binary operator (defaulting to std::plus<>), reduction is possible.
So for example:
template<typename T> // No constraint since we're not reducing anything here!
constexpr auto recursive_reduce_all(const T& input)
{
return input;
}
template<std::ranges::input_range T>
requires (recursive_depth<T>() == 1 && reducible<T>) // = reducible<T, T, std::plus<T>>
constexpr auto recursive_reduce_all(const T& input)
{
return std::reduce(std::ranges::cbegin(input), std::ranges::cend(input));
}
…
template<std::ranges::input_range T, class TI, class BinaryOp>
requires reducible<recursive_unwrap_type_t<recursive_depth<T>(), T>, TI, BinaryOp>
constexpr auto recursive_reduce_all(const T& input, TI init, BinaryOp binary_op)
{
…
} | {
"domain": "codereview.stackexchange",
"id": 44864,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
python, performance, comparative-review, numpy
Title: Pairwise Euclidean distance search algorithm
Question:
x and y are two-dimensional arrays with dimensions (AxN) and (BxN), i.e. they have the same number of columns.
I need to get a matrix of Euclidean distances between each pair of rows from x and y.
I have already written four different methods that give equally good results. But the first three methods are not fast enough, and the fourth method consumes too much memory.
1:
from scipy.spatial import distance
def euclidean_distance(x, y):
return distance.cdist(x, y)
2:
import numpy as np
import math
def euclidean_distance(x, y):
res = []
one_res = []
for i in range(len(x)):
for j in range(len(y)):
one_res.append(math.sqrt(sum(x[i] ** 2) + sum(y[j] ** 2) - 2 *
np.dot(x[i], np.transpose(y[j]))))
res.append(one_res)
one_res = []
return res
3:
import numpy as np
def euclidean_distance(x, y):
distances = np.zeros((x.T[0].shape[0], y.T[0].shape[0]))
for x, y in zip(x.T, y.T):
distances = np.subtract.outer(x, y) ** 2 + distances
return np.sqrt(distances)
4:
import numpy as np
def euclidean_distance(x, y):
x = np.expand_dims(x, axis=1)
y = np.expand_dims(y, axis=0)
return np.sqrt(((x - y) ** 2).sum(-1))
It looks like the second way could still be improved, and it also shows the best timing. Can you help me with the optimization, please?
Answer: Performance:
A way to use broadcasting but avoid allocating the 3d array is to separate the distance formula into $(x - y) ** 2 = x^2 + y^2 - 2xy$.
squared_matrix = np.sum(A ** 2,axis=1 )[:,np.newaxis] - 2 * (A@B.T) + np.sum(B ** 2,axis=1 )[np.newaxis,:]
distance_matrix = np.sqrt(squared_matrix)
Check:
np.allclose(distance_matrix,euclidean_distance(A,B))
>>> True | {
"domain": "codereview.stackexchange",
"id": 44865,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, comparative-review, numpy",
"url": null
} |
c#, beginner, console
Title: Stopwatch exception implementation in C#
Question: I'm new to C# programming and has been following a certain intermediate tutorial that has asked me to write a stopwatch simulation code that includes an exception system:
Exercise 1: Design a Stopwatch
Design a class called Stopwatch. The job of this class is to simulate a stopwatch. It should provide two methods: Start and Stop. We call the start method first, and the stop method next. Then we ask the stopwatch about the duration between start and stop. Duration should be a value in Timespan. Display the duration on the console.
We should also be able to use a stopwatch multiple times. So we may start and stop it and then start and stop it again. Make sure the duration value each time is calculated properly.
We should not be able to start a stopwatch twice in a row (because that may overwrite the initial start time). So the class should throw an InvalidOperationException is it's started twice.
Educational tip: The aim of this exercise is to make you understand that a class should be always in a valid state. We use encapsulation and information hiding to achieve that. The class should not reveal its implementation detail. It only reveals a little bit, like a black box. From the outside, you should not be able to misuse a class because you shouldn't be able to see the implementation detail.
Transcribed from:
I have implemented code that does this exactly, however, I want to learn how to optimize my code to use fewer lines and make it more readable.
using System;
namespace Stopwatch_Training
{
class Program
{
public class Stopwatch
{
private DateTime _startTime;
private DateTime _stopTime;
private TimeSpan _duration;
public DateTime StartTime()
{
_startTime = DateTime.Now;
return _startTime;
}
public DateTime Stoptime() | {
"domain": "codereview.stackexchange",
"id": 44866,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
public DateTime Stoptime()
{
_stopTime = DateTime.Now;
return _stopTime;
}
}
static void Main(string[] args)
{
var stopwatch = new Stopwatch();
int input1;
DateTime starTime;
DateTime endTime;
double duration;
int counter = 0;
while (true)
{
Console.Write("1-Start Timer\n2-Stop Timer\n");
input1 = Convert.ToInt32(Console.ReadLine());
if (input1 == 1)
{
starTime = stopwatch.StartTime();
counter = 1;
}
else
{
throw (new InvalidOperationException("Please Start the timer with 1"));
}
Console.WriteLine("Please enter '2' to stop the timer whenever you want");
input1 = Convert.ToInt32(Console.ReadLine());
if (input1 == 2)
{
endTime = stopwatch.Stoptime();
counter = 0;
}
else
{
throw (new InvalidOperationException("Please end the timer with 2"));
}
if (counter == 1)
{
throw (new InvalidOperationException("stuff"));
}
duration = (endTime - starTime).TotalSeconds;
if (duration > 60.0)
{
duration = (endTime - starTime).TotalMinutes;
Console.WriteLine(duration + "m");
}
else
{
Console.WriteLine(duration + "s");
}
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44866,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
}
}
}
}
Answer: You have the beginning of a stopwatch representation—you have its data. You still need to add its behavior.
Approach your design of the class as if the class should stand on its own. Input/output will be handled by something else, like the console, but the stopwatch should be the authority on its internal state.
The simplest stopwatch has a start/stop button and a display. We'll interpret "having a display" to mean "a way to get the stored elapsed time".
This means we'll need to provide three methods:
Start: Sets the stopwatch in a running state.
Stop: Sets the stopwatch in an idle state.
TimeElapsed: Reads out the currently elapsed time.
Additionally, Start and Stop have the requirement that they should throw InvalidOperationException when the stopwatch is not a compatible state. Our stopwatch will need a notion of running to do this.
Let's look how we can modify the stopwatch class to adopt this behavior. I've annotated some below:
public class Stopwatch
{
private DateTime _startTime; // we need this
private DateTime _stopTime; // ? either this or duration
private TimeSpan _duration;
public DateTime StartTime() // why do we return a value here?
{
// we still need to check whether we are already running
_startTime = DateTime.Now;
return _startTime;
}
public DateTime Stoptime() // why do we return a value here?
{
// we still need to check whether we are still running
_stopTime = DateTime.Now;
return _stopTime;
}
// We still need the notion of 'currently running'
}
// First attempt
public class Stopwatch
{
private DateTime _startTime;
private DateTime _stopTime;
private Boolean _running; | {
"domain": "codereview.stackexchange",
"id": 44866,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
public void StartTime()
{
if ( _running )
{
throw new InvalidOperationException("Cannot start: already running");
}
_startTime = DateTime.Now;
_running = true;
}
public void Stoptime()
{
if ( !_running )
{
throw new InvalidOperationException("Cannot stop: not running");
}
_stopTime = DateTime.Now;
_running = false;
}
public TimeSpan ElapsedTime()
{
if ( _running )
{
return DateTime.Now - _startTime;
}
else
{
return _stopTime - _startTime;
}
}
}
Note that we check if the stopwatch is currently running when asking for elapsed time: otherwise, we're going to get a very strange reading.
Now we can 'clean up' a little bit to follow conventions:
Class members are implicitly private, so we don't need to add the private modifier.
Members should start with a capital letter.
Which gives us:
public class Stopwatch
{
DateTime StartTime;
Boolean IsRunning;
DateTime StopTime;
public void Start()
{
if (IsRunning)
{
throw new InvalidOperationException("Cannot start: already running");
}
StartTime = DateTime.Now;
IsRunning = true;
}
public void Stop()
{
if (!IsRunning)
{
throw new InvalidOperationException("Cannot stop: not running");
}
IsRunning = false;
StopTime = DateTime.Now;
} | {
"domain": "codereview.stackexchange",
"id": 44866,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
public TimeSpan ElaspedTime()
{
if (IsRunning)
{
return DateTime.Now - StartTime;
}
else
{
return StopTime - StartTime;
}
}
}
And a quick Main to play around with it:
static void Main(string[] args)
{
var stopwatch = new Stopwatch();
int choice;
do
{
Console.Write("1-Start Timer\n2-Stop Timer\n3-Read Timer\n0-Quit\n");
choice = Convert.ToInt32(Console.ReadLine());
switch (choice)
{
case 1: stopwatch.Start(); break;
case 2: stopwatch.Stop(); break;
case 3: Console.WriteLine(stopwatch.ElaspedTime()); break;
}
} while (choice != 0);
} | {
"domain": "codereview.stackexchange",
"id": 44866,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c++, performance, multithreading, io
Title: Multithreaded O_DIRECT file read-and-process program
Question: Here is my code. It reads a file and returns the sum of all the bytes in the file:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <malloc.h>
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
#include <condition_variable>
#define BUFSIZE 134217728
// globals
std::mutex mut;
unsigned char* buffers[12]; // global array of pointers to buffers where file will be read
int bytes_read[12] = {0};
std::condition_variable cv;
// write_head is the shared variable associated with cv
int write_head = 0; // index of buffer currently being written to
void producer_thread()
{
int fd;
const char* fname = "1GB.txt";
if ((fd = open(fname, O_RDONLY|O_DIRECT)) < 0) {
printf("%s: cannot open %s\n", fname);
exit(2);
}
for (int i = 0; i < 12; ++i){
unsigned char* buf = buffers[i];
int n = read(fd,buf,BUFSIZE);
bytes_read[i] = n;
// wake up consumer thread
{
std::lock_guard<std::mutex> lk(mut);
write_head = i + 1;
}
cv.notify_all();
if ( n == 0 ){ // if we have reached end of file
std::cout << "Read to end of file" << std::endl;
std::cout << "Buffers used: " << i << std::endl;
return;
}
}
}
void consumer_thread(){
unsigned long result = 0;
for (int i = 0; i < 12; ++i){
// wait for buffer to become available for reading
{
std::unique_lock<std::mutex> lk(mut);
cv.wait(lk, [&]() { return i < write_head; });
}
int n = bytes_read[i];
if ( n == 0 ) {
std::cout << "Result: " << result;
return ;
}
// now process the data
unsigned char* buf = buffers[i];
for (int j=0; j<n; ++j)
result += buf[j];
}
} | {
"domain": "codereview.stackexchange",
"id": 44867,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, multithreading, io",
"url": null
} |
c++, performance, multithreading, io
int main (int argc, char* argv[]) {
using std::chrono::high_resolution_clock;
using std::chrono::duration_cast;
using std::chrono::duration;
using std::chrono::milliseconds;
puts("Allocating buffers");
auto start = high_resolution_clock::now();
int alignment = 4096;
// allocate 10 buffers and put them into the global buffers array
for (int i = 0; i < 10; ++i){
unsigned char* buf = (unsigned char*) memalign(alignment, BUFSIZE);
buffers[i] = buf;
}
auto end = high_resolution_clock::now();
/* Getting number of milliseconds as a double. */
duration<double, std::milli> ms_double = end - start;
puts("finished allocating buffers");
std::cout << "time taken: " << ms_double.count() << "ms\n";
// start producer and consumer threads
std::thread t1(producer_thread), t2(consumer_thread);
t1.join();
t2.join();
return 0;
}
(Note: replacing unsigned long with int seems to reduce running time by about 0.06 seconds, I'm not sure why. There is no integer overflow going on since the input file is all zeroes.)
This code takes around 0.97 to 1.03 seconds to run on my machine, which is the same as the fread version.
I thought O_DIRECT would be faster as it bypasses cache, but it seems like there is no difference, maybe because I'm using disk encryption.
Is there any way to make this code faster?
P.S I'm pretty sure there is no race condition but if you notice any please say!
Answer: Bypassing the cache might not be wise
I thought O_DIRECT would be faster as it bypasses cache,
You do know that caches are made to make things faster, right? Bypassing it might thus make your code even slower. There are a few reasons why you might want to bypass a cache: | {
"domain": "codereview.stackexchange",
"id": 44867,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, multithreading, io",
"url": null
} |
c++, performance, multithreading, io
You know for sure that nothing else will read that file a second time. In that case, using O_DIRECT avoids cache memory being wasted. It won't make reading the file the first time any faster though.
You know much better what the access pattern of the file is than the kernel can predict. In that case, you can avoid the kernel doing incorrect prefetching for example, which wastes cache space and can increase latency of subsequent reads. You can perhaps also ensure cached data is not evicted before it is reused. So this would have some performance benefit.
However, you are just reading the whole file in linearly. The kernel can easily see what the access pattern is, and start preloading the next chunk even before the second read() call happens in the for-loop.
You've already seen that using O_DIRECT makes no difference, so you are better of not using it.
Avoid unnecessary C-isms
You're already making quite good use of C++ functionality, however there are some C-isms that can be avoided.
Instead of using macros to define constants, use constexpr:
static constexpr std::size_t BUFSIZE = 128 * 1024 * 1024;
Use std::cout instead of printf(). Note that since C++20 there's std::format() that helps format strings, and in C++23 we will get the best of both worlds with std::print().
Use std::vector and std::array to allocate memory instead of using C functions. You can use alignas() to specify the required alignment:
struct aligned_buffer {
alignas(4096) std::array<char, BUFSIZE> data;
};
std::vector<aligned_buffer> buffers(12);
If you don't need O_DIRECT anymore, then use std::fstream instead of open() or fopen().
When including standard header files for C functions in C++ code, use the C++ version of those header files:
#include <cstdio>
#include <cstdlib> | {
"domain": "codereview.stackexchange",
"id": 44867,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, multithreading, io",
"url": null
} |
c++, performance, multithreading, io
Waiting for the producer
You have implemented a correct thread-safe algorithm for the consumer to block for the producer to have read in more buffers. However, since C++20 some new concurrency primitives have been introduced that allow you to do the same in a somewhat simpler way.
First, there is std::counting_semaphore. The producer can simply call release() when it has finished reading in a buffer, and the consumer can call acquire() to wait for a buffer to be ready. It correctly handles the case where the producer is multiple buffers ahead of the consumer.
Second, you can use a std::atomic_int to count how far the producer is. Since C++20 you can call wait() on an atomic variable to wait until it has changed its value. However, I would recommend using the std::counting_semaphore instead, as it does exactly what you want, and is harder to use incorrectly. | {
"domain": "codereview.stackexchange",
"id": 44867,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, multithreading, io",
"url": null
} |
beginner, bash
Title: Protein databank file chain, segment and residue number modifier
Question: My first non-trivial bash script after fully moving to Linux Mint last week is attached (modify_cccp_bundles.in). The script performs on protein databank (PDB) files that have been generated using an online CCCP (Coiled-coil Crick Parameterization) server. To use the generated PDB files for my own ends, I am using Rosetta (protein folding software) and phenix (protein modification software) that I have either set in my .bashrc file or have set a source file in my home to. The operations are:
add side chains and hydrogens to the CCCP templates using Rosetta
clear the segment IDs of the PDBs
change the residue sequences for all 4 chains so that they are continuous based on chain A (increment_resseq, there are 28 residues per chain)
add a segment ID of A to the files (first awk, segment ID is in column 75)
remove terminating lines from the file (there are 3 in-between the 4 chains that need removing)
change the chain IDs of all the chains to A (chain ID is in column 22)
Once finished, I have files that are continuously numbered, the same segment ID and chain ID with side chains and hydrogen added that look like this:
Loops are added by another process afterwards. This is my code:
#!/bin/bash
# --- bash script to modify CCCP server generated PDB bundle templates
#
# CCCP: https://www.grigoryanlab.org/cccp/
# Phenix: https://phenix-online.org/documentation/index.html
# Rosetta: https://www.rosettacommons.org/
# ------------------------------------------------------------------- FUNCTIONS
# --- extract first character from string and return capitalised
res_one_letter_cap () {
abbrev=$(printf %.1s "$1")
Abbrev="${abbrev^}"
echo $Abbrev
} | {
"domain": "codereview.stackexchange",
"id": 44868,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, bash",
"url": null
} |
beginner, bash
# --- write Rosetta residue file for all Ala or Gly
write_resfiles () {
res_abbrev=$(res_one_letter_cap $1)
file_name="all_${1}_resfile.res"
if [ -e $file_name ] # delete existing resfile so it is not being appended
then
rm $file_name
fi
echo -e $"PIKAA ${res_abbrev}\nstart" >> $file_name
}
# --- run rosetta fix backbone to add side chains and hydrogen
run_rosetta_fixbb () {
for pdb in ../../../CCCP/poly-${1}/*; do
fixbb.default.linuxgccrelease -s $pdb -resfile ../all_${1}_resfile.res \
-nstruct 1 -ex1 -ex2 -database $ROSETTA3_DB
done
}
# ------------------------------------------------------------------- CONSTANTS
residues='ala gly' # residue names
segID=A # segment ID
chainID=A # chain ID
# ------------------------------------------------------------------- SOURCE
#source ~/set_Phenix.sh # if path needs setting to phenix (set in ~/.bashrc)
source ~/set_Rosetta.sh # path to script containing rosetta_###/main/source/bin
# and the rosetta database path $ROSETTA3_DB
# ------------------------------------------------------------------- MAIN
# --- Rosetta fixed backbone: add side chains and hydrogen to PDB structures
mkdir ./rosetta && cd "$_"
for res in $residues; do
write_resfiles $res
mkdir ./poly_${res} && cd "$_"
run_rosetta_fixbb $res
rm scores.sc # scores.sc file not needed
cd ../
for pdb in ./poly_${res}/*; do # remove '_0001' Rosetta adds to filenames
ext="${pdb##*.}"
filename="${pdb%.*}"
mv $pdb "${filename%?????}".$ext
done
done
# --- phenix tools: change chain, segment ID's and renumber residues from
# --- constant offset defined in CONSTANTS
tmpfile="$(mktemp)"
phenixtmp=phenix.pdb
mkdir ../phenix/ && cd "$_" | {
"domain": "codereview.stackexchange",
"id": 44868,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, bash",
"url": null
} |
beginner, bash
tmpfile="$(mktemp)"
phenixtmp=phenix.pdb
mkdir ../phenix/ && cd "$_"
for res in $residues; do
mkdir -p ../templates/poly_${res}
for file in ../rosetta/poly_${res}/*; do
filename="${file##*/}"
cp $file $filename
phenix.pdbtools $filename clear_seg_id=true output.filename=$phenixtmp
phenix.pdbtools $phenixtmp modify.selection="chain B" \
increment_resseq=28 output.filename=$phenixtmp
phenix.pdbtools $phenixtmp modify.selection="chain C" \
increment_resseq=56 output.filename=$phenixtmp
phenix.pdbtools $phenixtmp modify.selection="chain D" \
increment_resseq=84 output.filename=$phenixtmp
# to add 'A' as segment
awk '{print substr($0,1,75) v substr($0,76)}' v=$segID $phenixtmp \
> "$tmpfile" && mv "$tmpfile" $phenixtmp
# remove TER lines
awk '!/TERA/' $phenixtmp > "$tmpfile" && mv "$tmpfile" $phenixtmp
# change chain to A
awk '{print substr($0,1,21) v substr($0,23)}' v=$chainID $phenixtmp\
> "$tmpfile" && mv "$tmpfile" $phenixtmp
# copy to template dir
mv $phenixtmp ../templates/poly_${res}/$filename
rm $filename
done
done
The folder structure looks like this afterwards (using just two PDBs, I have 64 but could in the future be more):
CCCP/
poly-ala/
ala_0001.pdb
ala_0002.pdb
poly-gly/
gly_0001.pdb
gly_0002.pdb
cccp_template_mods/
modify_cccp_bundles.in
rosetta/
poly_ala/
ala_0001.pdb
ala_0001.pdb
poly_gly/
gly_0001.pdb
gly_0001.pdb
all_ala_resfile.res
all_gly_resfile.res
phenix/
templates/
poly_ala/
ala_0001.pdb
ala_0002.pdb
poly_gly/
gly_0001.pdb
gly_0002.pdb | {
"domain": "codereview.stackexchange",
"id": 44868,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, bash",
"url": null
} |
beginner, bash
The ~/set_Rosetta.sh file contains:
export PATH=/usr/local/rosetta.source.release-340/main/source/bin:$PATH
export PYTHONPATH=/usr/local/rosetta.source.release-340/main/pyrosetta_scripts/apps/:$PYTHONPATH
export ROSETTA3=/usr/local/rosetta.source.release-340/main/
export ROSETTA3_DB=/usr/local/rosetta.source.release-340/main/database/
export LD_LIBRARY_PATH=/usr/local/lib:/usr/local/rosetta.source.release-340/main/source/build/external/release/linux/5.15/64/x86/gcc/11/default:$LD_LIBRARY_PATH
The generated all_{ala/gly}_resfile.res contain (# is a for ala, g for gly):
PIKAA #
start
There is no extra ending blank line as this breaks Rosetta functions. Each numbered PDB is the same but with different residue names i.e. ala_0001.pdb is the alanine equivalent of the glycine backbone gly_0001.pdb.
The code could be improved by removing the non-templates directories but I am hesitant to include rm -rf in a bash script, I think it could all be done in one loop too. The phenix software will not accept a relative file in the input hence the need for phenixtmp. I considered using a case function for the phenix modifications but couldn't work out the best way to do so other than a loop through chains in a list and times the magic number 28 by an index whilst calling the phenix.pdbtools.
I am more used to TeX.SE etiquette so if I have missed something out of this question please let me know.
Answer: lint
You should run shellcheck on this, and follow its advice.
Maybe your directory names lack SPACE characters ATM,
but that might change in future, so it's worthwhile
to habitually quote $file_name expressions.
In write_resfiles, it's enough to
unconditionally rm -f "$file_name".
No harm done if it doesn't exist, so no need to check beforehand.
portability
I found this a little hard to read:
echo -e $"PIKAA ${res_abbrev}\nstart" | {
"domain": "codereview.stackexchange",
"id": 44868,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, bash",
"url": null
} |
beginner, bash
echo -e $"PIKAA ${res_abbrev}\nstart"
I think you were (roughly) writing echo $"\n",
same as echo -e "\n".
To use both left me scratching my head.
Typical solution would be to prefer printf over echo, here.
You should document the versions of tools you tested against,
including $BASH_VERSINFO and the MacOS or linux distro OS version.
conservative globbing
for pdb in ../../../CCCP/poly-${1}/*; do
The trailing /* is perhaps a little more permissive than necessary.
If those files share *.pdb or another common suffix,
recommend you include that in the glob.
Not putting do on its own line is idosyncratic, but ok, whatever.
Bash displays the parsed code a bit differently
with: $ type run_rosetta_fixbb.
idempotency
mkdir ./rosetta
Sometimes things don't go smoothly and we need to edit / re-run several times.
Consider using mkdir -p here, so it's not an error if
the directory already exists.
use conservative settings
Consider putting "strict mode" near the top of this file:
set -u -e -o pipefail
That causes
unset / typo variable names to give error rather than empty string,
immediate bailout on error (any command's non-zero return status), and
same bailout if command within a pipeline fails
That would make it easier to reason about
"what is $PWD ?" after several {mkdir, cd} combos.
directory changing
Consider writing a helper function: mkdir -p "$DIR"; cd "$DIR"
cd ../
Certainly one can write cd foo; cmd1; cd ..; cmd2
You may find it more convenient to fork a subshell:
(cd foo && cmd1)
cmd2
$CWD changes in the subshell, but not in the parent,
so cmd2 does not run down in the foo folder.
You have several stanzas of "do stuff in a subdir"
and then next stanza will move on to another subdir to do more stuff.
Consider breaking out each stanza into a named function,
so your top-level logic is short and simple.
use conservative regex
awk '!/TERA/' $phenixtmp | {
"domain": "codereview.stackexchange",
"id": 44868,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, bash",
"url": null
} |
beginner, bash
use conservative regex
awk '!/TERA/' $phenixtmp
Maybe that's perfect the way it is.
But if you can anchor with ^ caret, /^TERA/,
or anchor with $ dollar, /TERA$/, then do so.
It cuts down on surprises, and it makes your regex go faster.
Consider using grep -v for this simple task.
Consider using sed -i to filter in place, without needing a mv.
user feedback
Not sure how long this takes to run,
nor whether 100% of all runs go successfully to the end.
You might want to set user expectations by using du
to estimate the amount of input data to be processed.
Logging "working on X" every minute or every few seconds
might be helpful.
Even if that's too chatty,
printing out "Finished" at the end wouldn't hurt.
Some scripts do one thing well, and compose nicely in pipelines.
This script seems a bit bigger than that.
Consider doing this for a command cmd that takes a while to run:
(set -x && cmd some_input.pdb)
The ( ) subshell limits the effect of -x
to just displaying the single command along with its arguments.
This code appears to achieve its design goals.
It relies on working versions of several tools
to be installed.
Adding the install procedures,
with an example console session,
would reduce the cost of onboarding a newly hired engineer.
It would be helpful to maintainers to
freeze a set of example inputs and output,
together with generated console output,
perhaps in a .ZIP archive.
Given that, I would be willing to delegate or accept
maintenance tasks on this script. | {
"domain": "codereview.stackexchange",
"id": 44868,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, bash",
"url": null
} |
beginner, dart, flutter
Title: Remove else-if statement from multi-conditional logic
Question: INTRODUCTION
I am studying the book Five Lines of Code (2021) by Christian Clause. The book covers several techniques regarding refactoring legacy code. I am learning much and applying several of its refactoring patterns.
The book gives rules that makes a lot of sense and I have been applying them to great success.
RULE: NEVER USE IF WITH ELSE
is one that I agree with, and I am trying to use apply it in my code. However, there is a situation that I have found where I cannot refactor - multi-conditioned logic. Now, I am a hobbyist programmer and I have been studying refactoring and design patterns earnestly for the last six months and definitely am not an expert/professional.
PROBLEM
In my Dart code, which I have reproduced using a simplified example in DartPad, I have commented where I am having the difficulty in refactoring.
QUESTION
I am wondering what is the best way to refactor the following code to eliminate the else-if statement without using a switch statement? Ideally, I would like to use a design pattern. An example solution would be most appreciated.
void main() {
List<BoardPeice> tiles = [];
var pacman = Player(name: 'PacMan');
var ghost = Ghost(name: 'Red ghost');
var lvl1 = Game()..isStarted = true;
for (int i = 0; i < 20; i++) {
tiles.add(drawMap(pacman, ghost, lvl1, i));
}
for (int i = 0; i < tiles.length; i++) {
print(tiles[i]);
}
} | {
"domain": "codereview.stackexchange",
"id": 44869,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, dart, flutter",
"url": null
} |
beginner, dart, flutter
for (int i = 0; i < tiles.length; i++) {
print(tiles[i]);
}
}
BoardPeice drawMap(Character player, Character ghost, Game game, int index) {
// TODO: else-if statement that I would like to refactor.
if (player.location == index) {
return PlayerTile(hero: player);
} else if (ghost.location == index) {
return GhostTile(minion: ghost);
} else if (game.barriers.contains(index)) {
return BlueBarrierTile(index: index);
} else if (game.pellets.contains(index) || !game.isStarted) {
return FoodTokenTile(index: index);
} else {
return EmptyTile(index: index);
}
}
abstract class Character {
Character({required this.name});
String name;
late int location;
late String color;
}
class Player implements Character {
Player({required this.name});
@override
String name;
@override
int location = 11;
@override
String color = 'Gold';
}
class Ghost implements Character {
Ghost({required this.name});
@override
String name;
@override
int location = 12;
@override
String color = 'Black';
}
abstract class BoardPeice {
String? name;
@override
String toString() => name!;
}
class PlayerTile extends BoardPeice {
PlayerTile({required this.hero}) {
name = hero.name;
}
final Character hero;
}
class GhostTile extends BoardPeice {
GhostTile({required this.minion}) {
name = minion.name;
}
final Character minion;
}
class BlueBarrierTile extends BoardPeice {
BlueBarrierTile({required this.index}) {
name = 'barrier: ${index.toString()}';
}
final int index;
}
class FoodTokenTile extends BoardPeice {
FoodTokenTile({required this.index}) {
name = 'pellet: ${index.toString()}';
}
final int index;
}
class EmptyTile extends BoardPeice {
EmptyTile({required this.index}) {
name = 'empty: ${index.toString()}';
}
final int index;
}
class Game {
var barriers = [0, 1, 2, 3, 4, 5];
var pellets = [6, 7, 8, 9, 10];
var isStarted = false;
} | {
"domain": "codereview.stackexchange",
"id": 44869,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, dart, flutter",
"url": null
} |
beginner, dart, flutter
REFACTORED CODE
For completeness, I include the refactored code according to the comments.
void main() {
List<BoardPiece> tiles = [];
var pacman = Player(name: 'PacMan');
var ghost = Ghost(name: 'Red ghost');
var lvl1 = Game()..isStarted = true;
for (int i = 0; i < 20; i++) {
tiles.add(drawMap(pacman, ghost, lvl1, i));
}
for (int i = 0; i < tiles.length; i++) {
print(tiles[i]);
}
}
List<BoardPieceStrategy> boardPieceStrategies = [
PlayerTileCheck(),
GhostTileCheck(),
BlueBarrierTileCheck(),
FoodTileCheck(),
DefaultTileCheck(),
];
class Context {
Character player;
Character ghost;
Game game;
int index;
Context({
required this.player,
required this.ghost,
required this.game,
required this.index,
});
}
abstract class BoardPieceStrategy {
bool isRelevant(Context context);
BoardPiece getTile(Context context);
}
//strategy objects
class GhostTileCheck implements BoardPieceStrategy {
@override
bool isRelevant(Context context) {
return context.ghost.location == context.index;
}
@override
BoardPiece getTile(Context context) {
return GhostTile(minion: context.ghost);
}
}
class DefaultTileCheck implements BoardPieceStrategy {
@override
bool isRelevant(Context context) {
return true;
}
@override
BoardPiece getTile(Context context) {
return EmptyTile(index: context.index);
}
}
class PlayerTileCheck implements BoardPieceStrategy {
@override
bool isRelevant(Context context) {
return context.player.location == context.index;
}
@override
BoardPiece getTile(Context context) {
return PlayerTile(hero: context.player);
}
}
class BlueBarrierTileCheck implements BoardPieceStrategy {
@override
bool isRelevant(Context context) {
return context.game.barriers.contains(context.index);
}
@override
BoardPiece getTile(Context context) {
return BlueBarrierTile(index: context.index);
}
} | {
"domain": "codereview.stackexchange",
"id": 44869,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, dart, flutter",
"url": null
} |
beginner, dart, flutter
class FoodTileCheck implements BoardPieceStrategy {
@override
bool isRelevant(Context context) {
return context.game.pellets.contains(context.index);
}
@override
BoardPiece getTile(Context context) {
return FoodTile(index: context.index);
}
}
BoardPiece drawMap(Character player, Character ghost, Game game, int index) {
var context = Context(player: player, ghost: ghost, game: game, index: index);
var boardPieceStrategy = boardPieceStrategies
.firstWhere((strategy) => strategy.isRelevant(context));
return boardPieceStrategy.getTile(context);
}
abstract class Character {
Character({required this.name});
String name;
late int location;
late String color;
}
class Player implements Character {
Player({required this.name});
@override
String name;
@override
int location = 11;
@override
String color = 'Gold';
}
class Ghost implements Character {
Ghost({required this.name});
@override
String name;
@override
int location = 12;
@override
String color = 'Black';
}
abstract class BoardPiece {
String? name;
@override
String toString() => name!;
}
class PlayerTile extends BoardPiece {
PlayerTile({required this.hero}) {
name = hero.name;
}
final Character hero;
}
class GhostTile extends BoardPiece {
GhostTile({required this.minion}) {
name = minion.name;
}
final Character minion;
}
class BlueBarrierTile extends BoardPiece {
BlueBarrierTile({required this.index}) {
name = 'barrier: ${index.toString()}';
}
final int index;
}
class FoodTile extends BoardPiece {
FoodTile({required this.index}) {
name = 'pellet: ${index.toString()}';
}
final int index;
}
class EmptyTile extends BoardPiece {
EmptyTile({required this.index}) {
name = 'empty: ${index.toString()}';
}
final int index;
}
class Game {
var barriers = [0, 1, 2, 3, 4, 5];
var pellets = [6, 7, 8, 9, 10];
var isStarted = false;
} | {
"domain": "codereview.stackexchange",
"id": 44869,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, dart, flutter",
"url": null
} |
beginner, dart, flutter
Answer: In these situations, I like to use a mix of the strategy pattern and the chain of command pattern.
I define an interface with two methods: a predicate whose boolean result tells me if the strategy is applicable to the parameter (this replaces the if condition), and the main method that returns the result.
(I don't know Dart, so please excuse syntax errors or non-idiomatic code -- I trust you can translate the concepts into something more suitable.)
class Context {
Character player;
Character ghost;
Game game;
int index;
Context(this.player, this.ghost, this.game, this.index) {
}
}
abstract class BoardPieceStrategy {
bool isRelevant(Context context);
BoardPiece getTile(Context context);
}
Each if block gets its own strategy object. For example:
class GhostTileCheck implements BoardPieceStrategy {
bool isRelevant(Context context) {
return context.ghost.location == context.index;
}
BoardPiece getTile(Context context) {
return GhostTile(minion: context.ghost);
}
}
class DefaultTileCheck implements BoardPieceStrategy {
bool isRelevant(Context context) { return true; }
BoardPiece getTile(Context context) {
return EmptyTile(index: context.index);
}
}
Now, instead of your if/else, you make an array of the strategies and iterate over them to select the first applicable one.
var boardPieceStrategies = <BoardPieceStrategy>[
// one of these for each if block you had, and put them in order
new GhostTileCheck(),
// ...
new DefaultTileCheck()
];
BoardPiece drawMap(Character player, Character ghost, Game game, int index) {
var context = Context(player, ghost, game, index);
var boardPieceStrategy = boardPieceStrategies.firstWhere((strategy) => strategy.isRelevant(context));
return boardPieceStrategy.getTile(context);
} | {
"domain": "codereview.stackexchange",
"id": 44869,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, dart, flutter",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
Title: Entity Component System Using C++
Question: Introduction
I'm a new to C++ so please take me easy :) I am currently working on a low-level game engine using C++, OpenGL, and GLFW; I've implemented the Event System and the Input Manager, which you can check out here: Improved Event System & InputManager Using C++.
Graph
For clarity, I've included a graph:
Components | {
"domain": "codereview.stackexchange",
"id": 44870,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
Components
Entity: This is a simple type alias for size_t. Each entity in the
system is represented by a unique Entity ID.
Component: This is an abstract base class for all components.
Components are the data that entities can possess.
System: This is an abstract base class for all systems. Systems are
where the logic of the game lives. Each system operates on entities
that have a specific set of components. For example, a MovementSystem
might operate on all entities that have both PositionComponent and
VelocityComponent.
BaseComponentPool and ComponentPool: These classes manage the storage
of components. Each type of component has its own ComponentPool. The
BaseComponentPool is an interface that allows the ComponentManager to
store a collection of ComponentPool objects of different types.
ComponentManager: This class manages all the ComponentPools. It
provides methods to add and retrieve components to/from entities.
EntityManager: This class manages the creation and destruction of
entities.
SystemContext: This class provides the context for systems to
operate. It provides access to the EntityManager and
ComponentManager, allowing systems to query entities and their
components.
SystemManager: This class manages all the systems. It provides
methods to add, remove, enable, and disable systems. It also provides
a method to update all systems, which is typically called once per
game loop.
ECSManager: This is the main interface to the ECS. It provides
methods to create and destroy entities, add components to entities,
and add systems. It also provides a method to update all systems,
which is typically called once per game loop. | {
"domain": "codereview.stackexchange",
"id": 44870,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
Control Flow
The flow of the ECS is as follows:
Entities are created using the ECSManager.
Components are added to entities using the ECSManager, which delegates to the ComponentManager.
Systems are added using the ECSManager, which delegates to the SystemManager.
Each game loop, the ECSManager's updateSystems method is called, which delegates to the SystemManager's updateSystems method.
Each system is updated, operating on the entities and their components as needed.
Concerns
Question: Should I replace the simple Entity = size_t, with an
Object Entity? This would improve type safety but would also reduce
speed and increase complexity, since now every call to get
the Entity's ID would be through the interface of the object.
Problem: This design does not adhere to the dependecy inversion
principle, because SystemContext, which is a high-level object, is
exported to the Systems (which are low-level). Normally, this would be solved by using
interfaces, but not here, because the SystemCotext object consits of
templated methods, which cannot be virtual. However, I do not think this is a mark of
bad design becuase the DIP is just a principle, not a hard-rule.
Any feedback/suggestions would be very much appreciated.
Source Code
Entity.h
#pragma once
using Entity = size_t;
Component.h
#pragma once
class Component
{
public:
virtual ~Component() = default;
};
ComponentPoolExceptions.h
#pragma once
#include <stdexcept>
#include "Entity.h"
class ComponentEntityNotFoundException : public std::runtime_error
{
public:
ComponentEntityNotFoundException(Entity entity, const std::string& componentType)
: std::runtime_error(entity + " not found in component pool: " + componentType) { }
};
ComponentPool.h
#pragma once
#include <stdexcept>
#include <vector>
#include <memory>
#include "Component.h"
#include "ComponentPoolExceptions.h" | {
"domain": "codereview.stackexchange",
"id": 44870,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
#include "Component.h"
#include "ComponentPoolExceptions.h"
class BaseComponentPool
{
public:
virtual ~BaseComponentPool() = default;
virtual void destroyEntityComponent(Entity entity) = 0;
virtual bool hasComponent(Entity entity) const = 0;
};
template <typename ComponentType>
class ComponentPool : public BaseComponentPool
{
public:
void addComponent(Entity entity, std::unique_ptr<ComponentType> component)
{
if (entity >= pool.size())
pool.resize(entity + 1);
pool[entity] = std::move(component);
}
void destroyEntityComponent(Entity entity) override
{
if (entity < pool.size())
pool[entity].reset();
}
const ComponentType& getComponent(Entity entity) const
{
if (entity >= pool.size() || pool[entity] == nullptr)
throw ComponentEntityNotFoundException(entity, typeid(ComponentType).name());
return *pool[entity];
}
bool hasComponent(Entity entity) const override
{
return entity < pool.size() && pool[entity] != nullptr;
}
private:
std::vector<std::unique_ptr<ComponentType>> pool;
};
ComponentManager.h
#pragma once
#include <typeindex>
#include "ComponentPool.h"
class ComponentManager
{
public:
template<typename ComponentType, typename... Args>
void addComponent(Entity entity, Args&&... args)
{
auto component = std::make_unique<ComponentType>(std::forward(args)...);
getComponentPool<ComponentType>().addComponent(entity, std::move(component));
}
template<typename ComponentType>
const ComponentType& getComponent(Entity entity)
{
return getComponentPool<ComponentType>().getComponent(entity);
}
template<typename ComponentType>
bool hasComponent(Entity entity)
{
return getComponentPool<ComponentType>().hasComponent(entity);
} | {
"domain": "codereview.stackexchange",
"id": 44870,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
void destroyEntityComponents(Entity entity)
{
for (auto& [type, pool] : componentPools)
pool->destroyEntityComponent(entity);
}
private:
template<typename ComponentType>
ComponentPool<ComponentType>& getComponentPool()
{
std::type_index typeIndex(typeid(ComponentType));
auto it = componentPools.find(typeIndex);
if (it == componentPools.end()) {
auto newPool = std::make_unique<ComponentPool<ComponentType>>();
it = componentPools.emplace(typeIndex, std::move(newPool)).first;
}
return static_cast<ComponentPool<ComponentType>&>(*it->second);
}
private:
std::unordered_map<std::type_index, std::unique_ptr<BaseComponentPool>> componentPools;
};
EntityExceptions.h
#pragma once
#include <stdexcept>
#include <string>
#include "Entity.h"
class EntityOutOfBoundsException : std::runtime_error
{
public:
EntityOutOfBoundsException(Entity entity)
: runtime_error("Entity: " + std::to_string(entity) + " is out of bounds!") { }
};
EntityManager.h
#pragma once
#include <queue>
#include <unordered_set>
#include "Entity.h"
class EntityManager
{
public:
Entity createEntity();
void destroyEntity(Entity entity);
const std::unordered_set<Entity>& getActiveEntities() const { return activeEntities; }
private:
std::queue<Entity> freeEntities;
std::unordered_set<Entity> activeEntities;
Entity nextEntity = 0;
};
EntityManager.cpp
#include "EntityManager.h"
#include "EntityExceptions.h"
Entity EntityManager::createEntity()
{
Entity entity;
if (!freeEntities.empty()) {
entity = freeEntities.front();
freeEntities.pop();
}
else {
entity = nextEntity++;
}
activeEntities.insert(entity);
return entity;
}
void EntityManager::destroyEntity(Entity entity)
{
if (activeEntities.find(entity) == activeEntities.end())
throw EntityOutOfBoundsException(entity); | {
"domain": "codereview.stackexchange",
"id": 44870,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
freeEntities.push(entity);
activeEntities.erase(entity);
}
SystemContext.h
#pragma once
#include "ComponentManager.h"
#include "EntityManager.h"
class SystemContext
{
public:
SystemContext(EntityManager& EntityManager, ComponentManager& componentManager)
: EntityManager(EntityManager), componentManager(componentManager) { }
template<typename ComponentType>
requires std::derived_from<ComponentType, Component>
const ComponentType& getComponent(Entity entity)
{
return componentManager.getComponent<ComponentType>(entity);
}
template<typename ComponentType>
requires std::derived_from<ComponentType, Component>
bool hasComponent(Entity entity)
{
return componentManager.hasComponent<ComponentType>(entity);
}
template<typename... ComponentTypes>
requires (std::derived_from<ComponentTypes, Component> && ...)
std::vector<Entity> getEntitiesWithComponents()
{
std::vector<Entity> entities;
auto& activeEntites = EntityManager.getActiveEntities();
for (const auto& entity : activeEntites)
if ((componentManager.hasComponent<ComponentTypes>(entity) && ...))
entities.push_back(entity);
return entities;
}
private:
EntityManager& EntityManager;
ComponentManager& componentManager;
};
System.h
#pragma once
#include "SystemContext.h"
class System
{
public:
virtual ~System() = default;
virtual void onAdded() = 0;
virtual void update(float deltaTime, SystemContext& context) = 0;
virtual void onRemoved() = 0;
void enable(bool enabled) { this->enabled = enabled; }
bool isEnabled() const { return enabled; }
private:
bool enabled = true;
};
SystemExceptions.h
#pragma once
#include <stdexcept>
class SystemNotFoundException : public std::runtime_error
{
public:
SystemNotFoundException(const std::string& systemType)
: std::runtime_error("System not found: " + systemType) {}
}; | {
"domain": "codereview.stackexchange",
"id": 44870,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
class SystemAlreadyAddedException : public std::runtime_error
{
public:
SystemAlreadyAddedException(const std::string& systemType)
: std::runtime_error("System is already added: " + systemType) {}
};
SystemManager.h
#pragma once
#include <list>
#include <memory>
#include <stdexcept>
#include <unordered_map>
#include "System.h"
#include "SystemExceptions.h"
class SystemManager
{
public:
template<typename SystemType, typename... Args>
void addSystem(Args&&... args)
{
std::type_index typeIndex(typeid(SystemType));
if (systemLookup.find(typeIndex) != systemLookup.end())
throw SystemAlreadyAddedException(typeid(SystemType).name());
std::unique_ptr<System> system = std::make_unique<SystemType>(std::forward<Args>(args)...);
system->onAdded();
systems.emplace_back(std::move(system));
systemLookup[typeIndex] = systems.size() - 1;
}
template<typename SystemType>
void removeSystem()
{
std::type_index typeIndex(typeid(SystemType));
auto it = systemLookup.find(typeIndex);
if (it == systemLookup.end())
throw SystemNotFoundException(typeid(SystemType).name());
systems[it->second]->onRemoved();
systems.erase(systems.begin() + it->second);
systemLookup.erase(it);
}
template<typename SystemType>
bool hasSystem() const
{
std::type_index typeIndex(typeid(SystemType));
return systemLookup.find(typeIndex) != systemLookup.end();
}
template<typename SystemType>
void enableSystem(bool enabled)
{
auto system = getSystem<SystemType>();
system->enabled(enabled);
}
void updateSystems(float deltaTime, SystemContext& context) const
{
for (auto& system : systems)
if(system->isEnabled())
system->update(deltaTime, context);
} | {
"domain": "codereview.stackexchange",
"id": 44870,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
private:
std::vector<std::unique_ptr<System>> systems;
std::unordered_map<std::type_index, size_t> systemLookup;
};
ECSManager.h
#pragma once
#include "SystemManager.h"
class ECSManager
{
public:
ECSManager()
: context(entityManager, componentManager) { }
Entity createEntity()
{
return entityManager.createEntity();
}
void destroyEntity(Entity entity)
{
componentManager.destroyEntityComponents(entity);
entityManager.destroyEntity(entity);
}
template<typename ComponentType, typename... Args>
requires std::derived_from<ComponentType, Component>
void addComponent(Entity entity, Args&&... args)
{
componentManager.addComponent<ComponentType>(entity, std::forward(args)...);
}
template<typename SystemType, typename... Args>
requires std::derived_from<SystemType, System>
void addSystem(Args&&... args)
{
systemManager.addSystem<SystemType>(std::forward<Args>(args)...);
}
template<typename SystemType>
requires std::derived_from<SystemType, System>
void removeSystem()
{
systemManager.removeSystem<SystemType>();
}
template<typename SystemType>
requires std::derived_from<SystemType, System>
bool hasSystem() const
{
return systemManager.hasSystem<SystemType>();
}
template<typename SystemType>
requires std::derived_from<SystemType, System>
void enableSystem(bool enabled)
{
systemManager.enableSystem<SystemType>(enabled);
}
void updateSystems(float deltaTime)
{
systemManager.updateSystems(deltaTime, context);
}
private:
EntityManager entityManager;
ComponentManager componentManager;
SystemManager systemManager;
SystemContext context;
};
Answer: About your concerns | {
"domain": "codereview.stackexchange",
"id": 44870,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
Answer: About your concerns
Question: Should I replace the simple Entity = size_t, with an Object Entity? This would improve type safety but would also reduce speed and increase complexity, since now every call to get the Entity's ID would be through the interface of the object.
It would indeed improve type safety, but there is no reason why this would reduce speed, and only perhaps a little complexity is added to the source code. Consider:
struct Entity {
std::size_t id;
};
Now consider how we have to rewrite, for example, hasComponent() to use this:
bool hasComponent(Entity entity) const override
{
return entity.id < pool.size() && pool[entity.id] != nullptr;
}
Nothing changed except the addition of a few .ids. Also, since this struct only contains a std::size_t, the assembly code generated by the compiler will be exactly the same as when using Entity = std::size_t, even with optimization disabled!
Problem: This design does not adhere to the dependecy inversion principle, because SystemContext, which is a high-level object, is exported to the Systems (which are low-level). Normally, this would be solved by using interfaces, but not here, because the SystemContext object consists of templated methods, which cannot be virtual. However, I do not think this is a mark of bad design because the DIP is just a principle, not a hard-rule. | {
"domain": "codereview.stackexchange",
"id": 44870,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
As long as you only depend on the public interface, not the internals, I think it's fine. You don't need to make an abstract base class for everything.
Technically speaking, you can still replace SystemContext with a completely different implementation, and if it has the same interface, your code will still compile fine. The only drawback of not having an abstract base class is that you cannot call System::update() with different types of derived SystemContexts. You probably could make it work by using type erasure, but that would require drastic changes to your code base.
Unused class Component
What does class Component actually do? I don't see it used in any of the code. It also only has a virtual destructor, no other members, so the only thing you could use it for is to store pointers-to-base in a std::vector. But you're not doing that in your code. I would just remove it, otherwise it will just add dead weight to classes that inherit from it.
ComponentPool can store components without using std::unique_ptr
Since an instance of ComponentPool will only ever store components of the same type, there is no need to use std::unique_ptr to store them in a std::vector, you could just write:
std::vector<ComponentType> pool;
Of course, that only makes sense if ComponentPool::addComponent() gets the component as a raw value or reference, but that's easy: just make ComponentManager::addComponent() pass a component by value. Or even better: have it forward Args...:
class ComponentManager
{
public:
template<typename ComponentType, typename... Args>
void addComponent(Entity entity, Args&&... args)
{
getComponentPool<ComponentType>().addComponent(
entity,
std::forward<Args>(args)...
);
}
…
}; | {
"domain": "codereview.stackexchange",
"id": 44870,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
template <typename ComponentType>
class ComponentPool: public BaseComponentPool
{
public:
template<typename... Args>
void addComponent(Entity entity, Args&&... args)
{
if (entity >= pool.size())
pool.resize(entity + 1);
pool[entity] = Component(std::forward<Args>(args)...);
}
…
private:
std::vector<ComponentType> pool;
};
One issue now is how to have ComponentPool know whether a given entity actually has a valid component associated with it. You could keep track of that in a separate datastructure, like a std::vector<bool> hasComponent, or you can store std::optional<ComponentType>s in the std::vector pool.
Another reason not to do this is if ComponentType is a large type: this would waste space in the pool for entities that don't have that component associated with them. But more about that below.
Avoid temporary memory allocations
It looks like in a system's update() function, it's supposed to call context.getEntitiesWithComponents() to get a std::vector<Entity> with all the entities that have the required components. This requires several memory allocations, as that std::vector is being grown dynamically. Then the caller has to loop over that vector to do its update thing on each entity in that std::vector. However, that is unnecessary; consider instead having a way to pass a function to SystemContext that it will apply to any matching entities:
template<typename... ComponentTypes>
requires (std::derived_from<ComponentTypes, Component> && ...)
updateEntitiesWithComponents(std::function<void(Entity)> update)
{
auto& activeEntites = entityManager.getActiveEntities();
for (const auto& entity : activeEntites)
if ((componentManager.hasComponent<ComponentTypes>(entity) && ...))
update(entity);
}
} | {
"domain": "codereview.stackexchange",
"id": 44870,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
Performance
The code looks clean and functionally correct. However, especially since Entity Component Systems were designed to handle lots of objects, you might want to think about performance, both in terms of CPU efficiency and memory efficiency.
Consider for example something like activeEntities. This is a std::unordered_set<Entity>. You might think that since it has \$O(1)\$ insertions and lookups, it will be fast. However, each insertion will cause memory to be allocated for a single Entity and some associated bookkeeping for the hash table. All the allocations might be spread around instead of being close together in memory. When doing a lookup, a hash value has to be calculated and pointers have to be followed.
What if you had used a std::vector<bool> instead to keep track of which entity IDs are active? With most C++ standard library implementations, this uses only one bit per entity ID, and all those bits are stored sequentially in memory. Doing an insertion and lookup is just a few assembler instructions. The only drawback is that if you have very little active entities compared to the largest entity ID, then you might be wasting more memory than std::unordered_set, although you'll probably never reach that point in practice in a well-designed game. | {
"domain": "codereview.stackexchange",
"id": 44870,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
I already mentioned that you can avoid the need for std::unique_ptr in ComponentPool, and the need for temporary storage when updating systems. However, there still is the issue that each time update() is called, it has to scan through all entities to find out which ones it should update. And the set of entities to update might not even change since the last time update() as called. Ideally, a System has a densely packed std::vector<Entity> of all the entities belonging to that system. In that case, each time update() is called it can just loop over that vector, without having to do any other checks. This would require some bookkeeping though, and might increase the overhead of adding and removing entities from the ECS.
Related to that, it would also be nice if ComponentPools would have densely packed std::vector<ComponentType>s to store the components. When updating a system with only one component, you can then just linearly go through one such vector. For systems with multiple components it's not that easy, but you'd still save memory by densely packing components. The drawback of course is that you need some other forms of bookkeeping to keep track of which entities have which components.
Consider using static inline template member variables
It's quite likely that you only need one ECS in a given program. In that case, you can make use of static inline template member variables, which have been possible since C++17. This is how it looks:
class ComponentManager
{
public:
template<typename ComponentType, …>
void addComponent(Entity entity, …)
{
componentPools<ComponentType>.addComponent(entity, …);
}
…
private:
template<typename ComponentType>
static inline ComponentPool<ComponentType> componentPools;
}; | {
"domain": "codereview.stackexchange",
"id": 44870,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
The static and template part are just how they always worked. The inline ensures that even if multiple source files cause instantiations of pools of the same ComponentType, they will be merged at link time (see also the One Definition Rule).
Take inspiration from existing ECS frameworks
You might want to look at some existing ECS frameworks to get some inspiration for the interface and/or performance optimizations. A well known framework for C++ is EnTT. | {
"domain": "codereview.stackexchange",
"id": 44870,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
windows, winapi, device-driver
Title: Windows: Programmatically uninstall the NumberPad from ASUS ZenBook
Question: Now I have this funny program. I bought an ASUS ZenBook which includes NumberPad. The downside of it is that it turns on with a slightest touch on its upper right corner so that I start write numeric gibberish in my code.
This one, disables the NumberPad (must be run as the admin):
#pragma comment (lib, "Setupapi.lib")
#include <windows.h>
#include <setupapi.h>
#include <iostream>
int main() {
GUID guid;
HRESULT hResult =
CLSIDFromString(
L"{4d36e96b-e325-11ce-bfc1-08002be10318}",
(LPCLSID) &guid);
if (hResult == CO_E_CLASSSTRING) {
std::cerr << "ERROR: Bad GUID string.\n";
return EXIT_FAILURE;
}
HDEVINFO hDeviceInfo =
SetupDiGetClassDevsExA(
&guid,
NULL,
NULL,
DIGCF_PRESENT,
NULL,
NULL,
NULL);
if (hDeviceInfo == INVALID_HANDLE_VALUE) {
std::cerr << "ERROR: Could not obtain HDEVINFO.\n";
return EXIT_FAILURE;
}
SP_DEVINFO_DATA deviceInfoData;
deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
deviceInfoData.ClassGuid = guid;
BOOL deviceEnumerated =
SetupDiEnumDeviceInfo(
hDeviceInfo,
0,
&deviceInfoData);
if (!deviceEnumerated) {
std::cerr << "ERROR: Could not enumerate the SP_DEVINFO_DATA.\n";
return EXIT_FAILURE;
}
BOOL removeStatus =
SetupDiCallClassInstaller(
DIF_REMOVE,
hDeviceInfo,
&deviceInfoData);
if (!removeStatus) {
std::cerr << "ERROR: Could not remove the device.\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Critique request
So, how could I improve it?
Answer: Low hanging fruits: | {
"domain": "codereview.stackexchange",
"id": 44871,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "windows, winapi, device-driver",
"url": null
} |
windows, winapi, device-driver
Critique request
So, how could I improve it?
Answer: Low hanging fruits:
L"{4d36e96b-e325-11ce-bfc1-08002be10318}" looks like a magic number to me. If I understand correctly, it is a GUID of NumberPad; if so, make it a properly named constant.
Aside, it looks like this program has a capability to disable other features (just supply a different GUID). Consider passing a GUID via a command line.
It would be nice to have an option to re-enable a disabled feature.
Error reporting is sloppy. Consider using GetLastError. | {
"domain": "codereview.stackexchange",
"id": 44871,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "windows, winapi, device-driver",
"url": null
} |
python
Title: Finding the first item in a python list which is big/small enough
Question: Here is how I intend to do it:
def index_of_first_item_less_or_equal_than(lst, threshold):
return next((i for i, x in enumerate(lst) if x <= threshold), math.inf)
def index_of_first_item_greater_or_equal_than(lst, threshold):
return next((i for i, x in enumerate(lst) if x >= threshold), math.inf)
Answer: Good enough: maybe not. Tastes and purposes vary, but I would say no. (1)
The current implementation is needlessly specific and repetitive. (2) The
defaults are not parameterized and their values are puzzling: the function is
supposed to return an index, unless in fails to find a match, in which case it
defaults to infinite? (3) The naming convention is awkwardly long and does not
scale well should you find yourself needing more functions like this.
Start with a flexible foundation. Because it's easy to do, we can begin
with a general utility function that borrows its name from
more-itertools.
def locate_first(xs, predicate, default = None):
gen = (i for i, x in enumerate(xs) if predicate(x))
return next(gen, default)
Add convenience helpers as needed. Maybe that function is good enough for your
use case. If not, you can create conveniences like this:
def locate_first_gte(xs, threshold, default = None):
pred = lambda x: x >= threshold
return locate_first(xs, pred, default) | {
"domain": "codereview.stackexchange",
"id": 44872,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python, performance, python-3.x, tree
Title: AutoComplete-Esque Tree
Question: I've written a tree data structure that takes in input from the user, and stores the each letter based on the previous letter in the text. I'm not sure what this is called, but the closest I can find is an auto complete type of tree, where someone would traverse this tree to find the next letter with the highest frequency, then build off that to form a word to suggest.
I'm mainly looking for performace/algorithm critiques and suggestions, specifically in the add_node function. This is where I had the most problems while writing this, and the excess amount of comments are me "thinking aloud" to myself while working through the problem.
"""
Letter Frequency Tree. This populates a tree based on the users input, keeping track of words entered and the
frequency of each letter the user inputs.
@author Ben Antonellis
"""
import string
class Node:
def __init__(self, letter: str) -> None:
self.letter = letter
self.count = 0
self.nodes = [] | {
"domain": "codereview.stackexchange",
"id": 44873,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, tree",
"url": null
} |
python, performance, python-3.x, tree
def add_node(self, node: object) -> None:
# Check if the string is currently empty:
if node.letter == "":
# Now we return since we're all out of letters
return
# Determine if letter is already a child node
next_node = self.__has_letter_node(node.letter[0])
# If there is no child node for that letter
if next_node == None:
# We need to create a new node with the new letter
new_node = Node(node.letter[0])
# Because there is no child, we increment the count by 1
new_node.count += 1
# Now we add the node to the nodes list
self.nodes.append(new_node)
# Now we need to work with the rest of the letters on the new node, skipping the front letter
new_node.add_node(Node(node.letter[1:]))
# If there is a child node present
else:
# We need to add the count to that letter
next_node.count += 1
# Now we add the next letters to the current node
next_node.add_node(Node(node.letter[1:]))
def __has_letter_node(self, letter: str) -> object | None:
for node in self.nodes:
if node.letter == letter:
return node
return None
def has_nodes(self) -> bool:
return self.nodes != []
def __str__(self, level=0) -> str:
# Martijn Pieters: https://stackoverflow.com/a/20242504/8968906
ret = "\t" * level + repr(self.letter) + str(self.count) + "\n"
for child in self.nodes:
ret += child.__str__(level + 1)
return ret
def __repr__(self) -> str:
return self.__str__()
class AutoCompleteTree:
def __init__(self) -> None:
self.roots = [ Node(c) for c in string.ascii_lowercase ] | {
"domain": "codereview.stackexchange",
"id": 44873,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, tree",
"url": null
} |
python, performance, python-3.x, tree
def __init__(self) -> None:
self.roots = [ Node(c) for c in string.ascii_lowercase ]
def get_root_letter_node(self, letter: str) -> Node:
for node in self.roots:
if node.letter == letter:
return node
def print_tree(self) -> None:
for root in self.roots:
if root.has_nodes():
print(root)
def store_input(self, text: str) -> None:
node = self.get_root_letter_node(text[0])
node.count += 1
node.add_node(Node(text[1:]))
def main():
tree = AutoCompleteTree()
while True:
text = input(">>> ")
tree.store_input(text)
tree.print_tree()
if __name__ == '__main__':
main()
Answer: All in all I think your implementation is well done. Clearly, if I didn't have at least a few comments, I wouldn't be taking the trouble to post an answer. Admittedly some (hopefully not all) of my comments could be considered "nitpicking."
Improved Data Structures
The Node.nodes attribute is a list when, as I believe you now know, making it a dict that maps a letter to a Node instance would permit faster searching. Likewise for the AutoCompleteTree.roots attribute which should also be a dictionary that maps a letter to a Node instance.
Type Hints
If you are going to do use type hints, there might be some room for improvement. Function __has_letter_node is defined as follows:
def __has_letter_node(self, letter: str) -> object | None:
I believe ideally you would want to use -> Node | None, but Node has not been defined yet (also using operator | is not supported on my Python 3.8.5). So the changes I had to make for this to run was to predefine an empty class Node and then to redefine it. There may be a better, alternate method that I am not aware of:
from typing import Union # Needed for Python < 3.10
# So we can reference Node in class Node:
class Node:
pass
# Redefinition of Node:
class Node:
... | {
"domain": "codereview.stackexchange",
"id": 44873,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, tree",
"url": null
} |
python, performance, python-3.x, tree
# Redefinition of Node:
class Node:
...
def has_letter_node(self, letter: str) -> Union[Node, None]:
But in fact, if we use the correct data structure for Node.nodes, then we don't even really need this function, a call to which can be replaced with the expression self.nodes.get(letter), which will return either the Node instance or None.
Don't Do More Work Than Necessary
AutoCompleteTree.store_input calls node.add_node(Node(text[1:])) and in method Node.add_node we have the recursive calls new_node = Node(node.letter[0]) and next_node.add_node(Node(node.letter[1:])). In both instances you are first constructing a Node instance to be passed to add_node but add_node is only referencing the string held in node.letter. There is not much point in constructing a Node when we could simply be passing instead the string that would otherwise be stored in node.letter. Also, I would suggest that a better name for the method is Node.add_nodes because the method is called in general to add multiple nodes (this is one of the nitpicking recommendations!).
Remove Tail Recursion
Method Node.add_node uses recursion of a special form, i.e. tail recursion. This is where the recursive calls are the final action performed in the function/method before it returns. With such functions iteration can easily replace recursion making for a more efficient implementation.
Some More Nitpicking Recommendations
Most of the attributes and methods used in these two classes are not to be accessed by client code and as such should have names starting with an underscore ('_') to suggest that these entities are "private."
You have taken a standard instance method, __str__ and added an additional, nonstandard argument, level. My preference would be to instead define a new private method _to_string: | {
"domain": "codereview.stackexchange",
"id": 44873,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, tree",
"url": null
} |
python, performance, python-3.x, tree
def _to_string(self, level=0):
# Martijn Pieters: https://stackoverflow.com/a/20242504/8968906
the_string = "\t" * level + repr(self.letter) + str(self.count) + "\n"
for child in self.nodes.values():
the_string += child._to_string(level + 1)
return the_string
def __repr__(self) -> str:
return self._to_string()
Method __repr__ just delegates to the new method. We don't need to define a __str__ method since Node.__repr__ will be called in its absence. Note that I have also replaced variable name ret with the_string.
Method Node.has_nodes could be coded as:
def has_nodes(self) -> bool:
return True if self.nodes else False
This works whether self.nodes is a list or dictionary.
Your main function loops indefinitely. You might want to test and terminate for empty input.
Suggestions Put Into Code
If you were to adopt all of the above suggestions, the code would look like the following (it may also assist you if some of my comments above were not as clear as I would have liked):
"""
Letter Frequency Tree. This populates a tree based on the users input, keeping track of words entered and the
frequency of each letter the user inputs.
@author Ben Antonellis
"""
import string
class _Node:
def __init__(self, letter: str) -> None:
self._letter = letter
self._count = 0
self._nodes = {} | {
"domain": "codereview.stackexchange",
"id": 44873,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, tree",
"url": null
} |
python, performance, python-3.x, tree
def add_nodes(self, text: str) -> None:
current_node = self
# Check if the string is currently empty:
for letter in text:
# Determine if letter is already a child node
next_node = current_node._nodes.get(letter)
# If there is no child node for that letter
if next_node is None:
# We need to create a new node with the new letter
new_node = _Node(letter)
# Because there is no child, we increment the count by 1
new_node._count += 1
# Now we add the node to the nodes list
current_node._nodes[letter] = new_node
# Now we need to work with the rest of the letters on the new node, skipping the front letter
current_node = new_node
# If there is a child node present
else:
# We need to add the count to that letter
next_node._count += 1
# Now we add the next letters to the current node
current_node = next_node
def has_nodes(self) -> bool:
return True if self._nodes else False
def _to_string(self, level=0):
# Martijn Pieters: https://stackoverflow.com/a/20242504/8968906
the_string = "\t" * level + repr(self._letter) + str(self._count) + "\n"
for child in self._nodes.values():
the_string += child._to_string(level + 1)
return the_string
def __repr__(self) -> str:
return self._to_string()
class AutoCompleteTree:
def __init__(self) -> None:
self._roots = {c: _Node(c) for c in string.ascii_lowercase}
def _get_root_letter_node(self, letter: str) -> _Node:
return self._roots[letter]
def print_tree(self) -> None:
for root in self._roots.values():
if root.has_nodes():
print(root) | {
"domain": "codereview.stackexchange",
"id": 44873,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, tree",
"url": null
} |
python, performance, python-3.x, tree
def store_input(self, text: str) -> None:
node = self._get_root_letter_node(text[0])
node._count += 1
node.add_nodes(text[1:])
def main():
tree = AutoCompleteTree()
while True:
text = input(">>> ")
if not text:
break
tree.store_input(text)
tree.print_tree()
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 44873,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, tree",
"url": null
} |
c++, geospatial
Title: Geohash library in C++17
Question: GeoHash library in C++17
no allocations and no std::strings. It uses fixed buffer GeoHash::buffer_t.
optimized nearby search, if possible, it search 2x2 or 2x3 cells, instead of 3x9 cells GeoHash::nearbyCells.
suppose to work correctly on latitudes over 65-70' where the geohash cell is really "narrow".
Here is the code:
https://github.com/nmmmnu/geohash/
geohash.h
#ifndef GEOHASH_H_
#define GEOHASH_H_
#include <cstdint>
#include <array>
#include <string_view>
#include <string>
#include <cmath>
namespace GeoHash {
constexpr static size_t MAX_SIZE = 12;
using buffer_t = std::array<char, 32>;
// ------------------------------
struct Point{
double lat;
double lon;
constexpr Point fix() const{
auto _ = [](double x){
constexpr size_t p = 1'00'000;
return round(x * p) / p;
};
return { _(lat), _(lon) };
}
};
struct GeoSphere;
struct Rectangle{
Point sw;
Point ne;
constexpr auto n_lat() const{
return ne.lat;
};
constexpr auto s_lat() const{
return sw.lat;
};
constexpr auto e_lon() const{
return ne.lon;
};
constexpr auto w_lon() const{
return sw.lon;
};
// ------------------------------
constexpr Point ne_p() const{
return { n_lat(), e_lon() };
};
constexpr Point nw_p() const{
return { n_lat(), w_lon() };
};
constexpr Point se_p() const{
return { s_lat(), e_lon() };
};
constexpr Point sw_p() const{
return { s_lat(), w_lon() };
};
// ------------------------------
constexpr Point center() const{
return {
(sw.lat + ne.lat) / 2,
(sw.lon + ne.lon) / 2
};
} | {
"domain": "codereview.stackexchange",
"id": 44874,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, geospatial",
"url": null
} |
c++, geospatial
// ------------------------------
double height(GeoSphere const &sphere) const;
double width(GeoSphere const &sphere) const;
double area(GeoSphere const &sphere) const;
};
enum class Direction : uint8_t{
n = 0,
s = 1,
e = 2,
w = 3
};
// ------------------------------
struct GeoSphere{
std::string_view sphere;
std::string_view units;
double radius;
double cells[12] {
CELLS_ABSOLUTE[ 0] * radius, // 1
CELLS_ABSOLUTE[ 1] * radius, // 2
CELLS_ABSOLUTE[ 2] * radius, // 3
CELLS_ABSOLUTE[ 3] * radius, // 4
CELLS_ABSOLUTE[ 4] * radius, // 5
CELLS_ABSOLUTE[ 5] * radius, // 6
CELLS_ABSOLUTE[ 6] * radius, // 7
CELLS_ABSOLUTE[ 7] * radius, // 8
CELLS_ABSOLUTE[ 8] * radius, // 9
CELLS_ABSOLUTE[ 9] * radius, // 10
CELLS_ABSOLUTE[10] * radius, // 11
CELLS_ABSOLUTE[11] * radius // 12
};
public:
constexpr static double RADIUS_EARTH_KM = 6371;
constexpr static double RADIUS_EARTH_MI = 3956;
private:
constexpr static double CELL_SHRINK_FACTOR = 0.6666;
constexpr static double CELL_SHRINK = CELL_SHRINK_FACTOR / RADIUS_EARTH_KM;
constexpr static inline double CELLS_ABSOLUTE[12] {
4'992.600 * CELL_SHRINK, // 1
624.100 * CELL_SHRINK, // 2
156.100 * CELL_SHRINK, // 3
19.500 * CELL_SHRINK, // 4
4.900 * CELL_SHRINK, // 5
0.609'4 * CELL_SHRINK, // 6
0.152'4 * CELL_SHRINK, // 7
0.019'0 * CELL_SHRINK, // 8
0.004'8 * CELL_SHRINK, // 9
0.000'595 * CELL_SHRINK, // 10
0.000'149 * CELL_SHRINK, // 11
0.000'019 * CELL_SHRINK // 12
};
}; | {
"domain": "codereview.stackexchange",
"id": 44874,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, geospatial",
"url": null
} |
c++, geospatial
constexpr GeoSphere EARTH_KM { "Earth", "km", GeoSphere::RADIUS_EARTH_KM };
constexpr GeoSphere EARTH_METERS { "Earth", "m", EARTH_KM.radius * 1000 };
constexpr GeoSphere EARTH_MI { "Earth", "mi", GeoSphere::RADIUS_EARTH_MI };
constexpr GeoSphere EARTH_YD { "Earth", "yd", EARTH_MI.radius * 1760 };
constexpr GeoSphere MOON_KM { "Moon", "km", 1737.1 };
constexpr GeoSphere MOON_METERS { "Moon", "m", MOON_KM.radius * 1000 };
constexpr GeoSphere MARS_KM { "Mars", "km", 3389.5 };
constexpr GeoSphere MARS_METERS { "Mars", "m", MARS_KM.radius * 1000 };
// ------------------------------
struct HashVector{
constexpr auto begin() const{
return data;
}
constexpr auto end() const{
return data + size;
}
private:
friend HashVector nearbyCells(double, double, double, GeoSphere const &);
friend HashVector nearbyCells(std::string_view) noexcept;
std::string_view data[9];
size_t size;
buffer_t buffer[9];
};
// ------------------------------
std::string_view encode(double lat, double lon, size_t precision, buffer_t &buffer) noexcept;
inline auto encode(Point p, size_t precision, buffer_t &buffer){
return encode(p.lat, p.lon, precision, buffer);
}
inline std::string encode(double lat, double lon, size_t precision){
buffer_t buffer;
return std::string{
encode(lat, lon, precision, buffer)
};
}
Rectangle decode(std::string_view hash);
std::string_view adjacent(std::string_view geohash, Direction direction, buffer_t &buffer) noexcept;
[[deprecated]]
HashVector nearbyCells(std::string_view hash) noexcept;
// ------------------------------ | {
"domain": "codereview.stackexchange",
"id": 44874,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, geospatial",
"url": null
} |
c++, geospatial
// ------------------------------
double distance_radians(double lat1, double lon1, double lat2, double lon2) noexcept;
inline double distance(double lat1, double lon1, double lat2, double lon2, GeoSphere const &sphere){
auto _ = [](double degree){
// toRadians
constexpr double one_deg = M_PI / 180;
return one_deg * degree;
};
return distance_radians(_(lat1), _(lon1), _(lat2), _(lon2)) * sphere.radius;
}
inline auto distance(Point p1, Point p2, GeoSphere const &sphere){
return distance(p1.lat, p1.lon, p2.lat, p2.lon, sphere);
}
// ------------------------------
HashVector nearbyCells(double lat, double lon, double radius, GeoSphere const &sphere);
inline auto nearbyCells(Point p, double radius, GeoSphere const &sphere){
return nearbyCells(p.lat, p.lon, radius, sphere);
}
// ------------------------------
inline double Rectangle::height(GeoSphere const &sphere) const{
// return distance(sw.lat, sw.lon, ne.lat, sw.lon, sphere);
return distance(ne_p(), se_p(), sphere);
}
inline double Rectangle::width(GeoSphere const &sphere) const{
// return distance(sw.lat, sw.lon, sw.lat, ne.lon, sphere);
return distance(ne_p(), nw_p(), sphere);
}
inline double Rectangle::area(GeoSphere const &sphere) const{
return width(sphere) * height(sphere);
}
}
#endif
geohash.c
#include "geohash.h"
#include <cassert>
#include <stdexcept>
namespace GeoHash {
// based on https://www.movable-type.co.uk/scripts/geohash.html
constexpr double LAT_MIN = -90;
constexpr double LAT_MAX = 90;
constexpr double LON_MIN = -180;
constexpr double LON_MAX = 180;
constexpr inline static std::string_view BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"; // geohash-specific Base32 map
// ------------------------------ | {
"domain": "codereview.stackexchange",
"id": 44874,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, geospatial",
"url": null
} |
c++, geospatial
// ------------------------------
std::string_view encode(double lat, double lon, size_t precision, buffer_t &buffer) noexcept{
assert(precision > 0 && precision <= MAX_SIZE);
size_t ixb = 0; // index of the buffer
size_t idx = 0; // index into base32 map
uint8_t bit = 0; // each char holds 5 bits
auto evenBit = true;
auto latMin = LAT_MIN;
auto latMax = LAT_MAX;
auto lonMin = LON_MIN;
auto lonMax = LON_MAX;
while (ixb < precision){
if (evenBit){
// bisect E-W longitude
auto const lonMid = (lonMin + lonMax) / 2;
if (lon >= lonMid){
idx = idx * 2 + 1;
lonMin = lonMid;
} else {
idx = idx * 2;
lonMax = lonMid;
}
}else{
// bisect N-S latitude
auto const latMid = (latMin + latMax) / 2;
if (lat >= latMid){
idx = idx * 2 + 1;
latMin = latMid;
} else {
idx = idx * 2;
latMax = latMid;
}
}
evenBit = !evenBit;
if (++bit == 5){
// 5 bits gives us a character, append it and start over
buffer[ixb++] = BASE32[idx];
bit = 0;
idx = 0;
}
}
buffer[ixb] = '\0';
return std::string_view{ buffer.data(), ixb };
}
Rectangle decode(std::string_view hash){
assert(hash.size() > 0 && hash.size() <= MAX_SIZE);
auto evenBit = true;
auto latMin = LAT_MIN;
auto latMax = LAT_MAX;
auto lonMin = LON_MIN;
auto lonMax = LON_MAX; | {
"domain": "codereview.stackexchange",
"id": 44874,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, geospatial",
"url": null
} |
c++, geospatial
for (size_t i = 0; i < hash.size(); ++i){
auto const chr = hash[i];
auto const idx = BASE32.find(chr, 0);
if (idx == BASE32.npos)
throw std::logic_error("Invalid geohash");
for (ssize_t n = 4; n >= 0; --n){
auto const bitN = (idx >> n) & 1;
if (evenBit){
// longitude
auto const lonMid = (lonMin + lonMax) / 2;
if (bitN){
lonMin = lonMid;
}else{
lonMax = lonMid;
}
}else{
// latitude
auto const latMid = (latMin + latMax) / 2;
if (bitN){
latMin = latMid;
}else{
latMax = latMid;
}
}
evenBit = !evenBit;
}
}
return {
Point{ latMin, lonMin },
Point{ latMax, lonMax }
};
}
namespace{
std::string_view adjacent_calc_(size_t const size, Direction direction_, buffer_t &buffer){
// based on github.com/davetroy/geohash-js
constexpr static std::string_view neighbour[4][2] {
{ "p0r21436x8zb9dcf5h7kjnmqesgutwvy", "bc01fg45238967deuvhjyznpkmstqrwx" },
{ "14365h7k9dcfesgujnmqp0r2twvyx8zb", "238967debc01fg45kmstqrwxuvhjyznp" },
{ "bc01fg45238967deuvhjyznpkmstqrwx", "p0r21436x8zb9dcf5h7kjnmqesgutwvy" },
{ "238967debc01fg45kmstqrwxuvhjyznp", "14365h7k9dcfesgujnmqp0r2twvyx8zb" }
};
constexpr static std::string_view border[4][2] {
{ "prxz", "bcfguvyz" },
{ "028b", "0145hjnp" },
{ "bcfguvyz", "prxz" },
{ "0145hjnp", "028b" }
}; | {
"domain": "codereview.stackexchange",
"id": 44874,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, geospatial",
"url": null
} |
c++, geospatial
auto const direction = static_cast<uint8_t>(direction_);
auto const lastCh = buffer[size - 1];
auto const type = size % 2;
// check for edge-cases which don't share common prefix
if (border[direction][type].find(lastCh) != std::string::npos && size - 1 > 0)
adjacent_calc_(size - 1, direction_, buffer);
// append letter for direction to parent
buffer[size - 1] = BASE32[ neighbour[direction][type].find(lastCh) ];
return { buffer.data(), size };
}
} // anonymous namespace
std::string_view adjacent(std::string_view geohash, Direction direction, buffer_t &buffer) noexcept{
assert(geohash.size() > 0 && geohash.size() <= MAX_SIZE);
// copy into buffer
std::copy(std::begin(geohash), std::end(geohash), std::begin(buffer));
return adjacent_calc_(geohash.size(), direction, buffer);
}
double distance_radians(double lat1, double lon1, double lat2, double lon2) noexcept{
// Haversine Formula
double const delta_lon = lon2 - lon1;
double const delta_lat = lat2 - lat1;
double const result =
pow(sin(delta_lat / 2), 2) +
pow(sin(delta_lon / 2), 2) * cos(lat1) * cos(lat2)
;
return 2 * asin(sqrt(result));
}
// ------------------------------
namespace{
size_t selectCellsSize_(double radius, GeoSphere const &sphere){
if (radius > sphere.cells[0])
return 0;
size_t i = 0;
for(auto &cell : sphere.cells){
// works OK until lat = 60.0,
// but we shrink the cells sizes by 66% so is OK until 70.0
if (radius > cell)
break;
++i;
}
return i;
}
} | {
"domain": "codereview.stackexchange",
"id": 44874,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, geospatial",
"url": null
} |
c++, geospatial
return i;
}
}
HashVector nearbyCells(double lat, double lon, double radius, GeoSphere const &sphere){
constexpr bool ENABLE_OPTIMIZATIONS = 1;
HashVector v;
auto const size = selectCellsSize_(radius, sphere);
if (!size){
v.size = 0;
return v;
}
v.data[0] = encode(lat, lon, size, v.buffer[0]);
// we can do this, but code becomes unreadable
//
// auto adj = [&v](size_t index, size_t src, Direction dir) mutable{
// v.data[index] = adjacent(v.data[src], dir, v.data[buffer]);
// };
if constexpr(ENABLE_OPTIMIZATIONS){
auto const bbox = decode(v.data[0]);
auto const bbox_w = bbox.width(sphere);
auto const bbox_h = bbox.height(sphere);
if (bbox_h > 2 * radius){
auto const bbox_center = bbox.center();
if (bbox_w > 2 * radius){
// OPTIMIZED - 2 x 2 = 4
v.size = 4;
if (lat < bbox_center.lat){
// north
if (lon < bbox_center.lon){
// north west
v.data[1] = adjacent(v.data[0], Direction::n, v.buffer[1]);
v.data[2] = adjacent(v.data[0], Direction::w, v.buffer[2]);
v.data[3] = adjacent(v.data[1], Direction::w, v.buffer[3]);
return v;
}else{
// north east
v.data[1] = adjacent(v.data[0], Direction::n, v.buffer[1]);
v.data[2] = adjacent(v.data[0], Direction::e, v.buffer[2]);
v.data[3] = adjacent(v.data[1], Direction::e, v.buffer[3]); | {
"domain": "codereview.stackexchange",
"id": 44874,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, geospatial",
"url": null
} |
c++, geospatial
return v;
}
}else{
// south
if (lon < bbox_center.lon){
// south west
v.data[1] = adjacent(v.data[0], Direction::s, v.buffer[1]);
v.data[2] = adjacent(v.data[0], Direction::w, v.buffer[2]);
v.data[3] = adjacent(v.data[1], Direction::w, v.buffer[3]);
return v;
}else{
// south east
v.data[1] = adjacent(v.data[0], Direction::s, v.buffer[1]);
v.data[2] = adjacent(v.data[0], Direction::e, v.buffer[2]);
v.data[3] = adjacent(v.data[1], Direction::e, v.buffer[3]);
return v;
}
}
}
// This still apply:
//
// bbox_h > 2 * radius
// OPTIMIZED - 3 x 2 = 6
v.size = 6;
if (lat > bbox_center.lat){
// north
v.data[1] = adjacent(v.data[0], Direction::n, v.buffer[1]);
v.data[2] = adjacent(v.data[0], Direction::e, v.buffer[2]);
v.data[3] = adjacent(v.data[0], Direction::w, v.buffer[3]);
v.data[4] = adjacent(v.data[1], Direction::e, v.buffer[4]);
v.data[5] = adjacent(v.data[1], Direction::w, v.buffer[5]);
return v;
}else{
// south
v.data[1] = adjacent(v.data[0], Direction::s, v.buffer[1]);
v.data[2] = adjacent(v.data[0], Direction::e, v.buffer[2]);
v.data[3] = adjacent(v.data[0], Direction::w, v.buffer[3]); | {
"domain": "codereview.stackexchange",
"id": 44874,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, geospatial",
"url": null
} |
c++, geospatial
v.data[4] = adjacent(v.data[1], Direction::e, v.buffer[4]);
v.data[5] = adjacent(v.data[1], Direction::w, v.buffer[5]);
return v;
}
}
if (bbox_w > 2 * radius){
auto const bbox_center = bbox.center();
// OPTIMIZED - 2 x 3 = 6
// no need to check lat, it was already checked
v.size = 6;
if (lon < bbox_center.lon){
// west
v.data[1] = adjacent(v.data[0], Direction::w, v.buffer[1]);
v.data[2] = adjacent(v.data[0], Direction::n, v.buffer[2]);
v.data[3] = adjacent(v.data[0], Direction::s, v.buffer[3]);
v.data[4] = adjacent(v.data[1], Direction::n, v.buffer[4]);
v.data[5] = adjacent(v.data[1], Direction::s, v.buffer[5]);
return v;
}else{
// east
v.data[1] = adjacent(v.data[0], Direction::e, v.buffer[1]);
v.data[2] = adjacent(v.data[0], Direction::n, v.buffer[2]);
v.data[3] = adjacent(v.data[0], Direction::s, v.buffer[3]);
v.data[4] = adjacent(v.data[1], Direction::n, v.buffer[4]);
v.data[5] = adjacent(v.data[1], Direction::s, v.buffer[5]);
return v;
}
}
} // if constexpr(ENABLE_OPTIMIZATIONS)
// NOT OPTIMIZED 3 x 3 = 9
v.size = 9;
v.data[1] = adjacent(v.data[0], Direction::n, v.buffer[1]); // n
v.data[2] = adjacent(v.data[0], Direction::s, v.buffer[2]); // s
v.data[3] = adjacent(v.data[0], Direction::e, v.buffer[3]); // e
v.data[4] = adjacent(v.data[0], Direction::w, v.buffer[4]); // w | {
"domain": "codereview.stackexchange",
"id": 44874,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, geospatial",
"url": null
} |
c++, geospatial
v.data[5] = adjacent(v.data[1], Direction::e, v.buffer[5]); // ne
v.data[6] = adjacent(v.data[1], Direction::w, v.buffer[6]); // nw
v.data[7] = adjacent(v.data[2], Direction::e, v.buffer[7]); // se
v.data[8] = adjacent(v.data[2], Direction::w, v.buffer[8]); // sw
return v;
}
[[deprecated]]
HashVector nearbyCells(std::string_view hash) noexcept{
HashVector v;
v.size = 8;
v.data[0] = adjacent(hash, Direction::n, v.buffer[0]); // n
v.data[1] = adjacent(hash, Direction::s, v.buffer[1]); // s
v.data[2] = adjacent(hash, Direction::e, v.buffer[2]); // e
v.data[3] = adjacent(hash, Direction::w, v.buffer[3]); // w
v.data[4] = adjacent(v.data[0], Direction::e, v.buffer[4]); // ne
v.data[5] = adjacent(v.data[0], Direction::w, v.buffer[5]); // nw
v.data[6] = adjacent(v.data[1], Direction::e, v.buffer[6]); // se
v.data[7] = adjacent(v.data[1], Direction::w, v.buffer[7]); // sw
return v;
}
}
usage
#include "geohash.h"
#include <iostream>
#include <utility>
struct Place{
GeoHash::Point point;
std::string_view name;
double supposed_distance;
GeoHash::buffer_t buffer;
std::string_view hash = GeoHash::encode(point, 12, buffer);
}; | {
"domain": "codereview.stackexchange",
"id": 44874,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, geospatial",
"url": null
} |
c++, geospatial
std::string_view hash = GeoHash::encode(point, 12, buffer);
};
Place const places[] {
{ { 42.69210669738513, 23.32489318092748 }, "Level Up" , 10 },
{ { 42.69238509863727, 23.32476304836964 }, "Luchiano" , 42 },
{ { 42.69175842097124, 23.32523636032996 }, "Bohemian Hall" , 42 },
{ { 42.69269382372572, 23.32491086796810 }, "Umamido" , 74 },
{ { 42.69199298885176, 23.32411779452691 }, "McDonald's" , 74 },
{ { 42.69141486008349, 23.32517469905046 }, "Ceiba" , 74 },
{ { 42.69210516803149, 23.32626916568055 }, "Happy" , 110 },
{ { 42.69151957227103, 23.32366568780231 }, "Ugo" , 130 },
{ { 42.69151957227103, 23.32654779876320 }, "Il Theatro" , 140 },
{ { 42.69205716858902, 23.32266435016691 }, "Nicolas" , 200 },
{ { 42.68970992959111, 23.32455331244497 }, "Manastirska Magernitsa" , 300 },
{ { 42.69325388808822, 23.32118939756011 }, "The Hadjidragana Tavern" , 330 },
{ { 42.69174997126510, 23.32100561258516 }, "Boho" , 330 },
{ { 42.69205885495273, 23.33781274367048 }, "Stastlivetza" , 400 },
{ { 42.68999839888917, 23.31970366848597 }, "Franco's Pizza" , 500 },
{ { 42.69074017093236, 23.31785351529929 }, "Villa Rosiche" , 620 },
{ { 42.68342508736217, 23.31633975360111 }, "Chevermeto" , 1200 }
};
constexpr GeoHash::Point me{ 42.69207945916779, 23.325029867108032 };
namespace{
void mySearchNearby(GeoHash::Point me, double radius, GeoHash::GeoSphere const &sphere){
auto const cells = GeoHash::nearbyCells(me, radius, sphere);
for(auto &hash : cells){
std::cout << "Searching cell: " << hash << '\n';
// send query to DB
for(auto &p : places){
if (p.hash.size() < hash.size() || std::equal(std::begin(hash), std::end(hash), std::begin(p.hash)) == false)
continue; | {
"domain": "codereview.stackexchange",
"id": 44874,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, geospatial",
"url": null
} |
c++, geospatial
auto const dist = distance(me, p.point, sphere);
if (dist > radius)
continue;
std::cout << '\t' << p.name << '\t' << dist << ' ' << sphere.units << '\n';
}
}
}
}
// if for some strange reason we want distances in decameters...
//constexpr auto UNITS = GeoHash::GeoSphere{ "Earth", "dm", GeoHash::EARTH_METERS.radius / 10 };
//constexpr auto UNITS = GeoHash::EARTH_YA;
constexpr auto UNITS = GeoHash::EARTH_METERS;
int main(){
// 80 m - 3x3
// 60 m - 2x3
// 50 m - 2x2
// 12 m - 3x2
auto const radius = 80;
mySearchNearby(me, radius, UNITS);
}
Answer:
constexpr static size_t MAX_SIZE = 12;
Misspelt std::size_t. Also, most style guides reserve all-caps identifiers for macros (which don't respect namespaces, for instance). It's quite plausible that code which includes this header also includes some library with a MAX_SIZE macro defined, which will cause a baffling parse error.
constexpr size_t p = 1'00'000;
This looks like a typo for 1'000'000. Remove the extraneous separator to prevent future maintainers attempting to correct this.
I don't like the name _ for the approximation function. In Python, and increasingly in C++, it's a convention for a value that is ignored. And I think I've seen it used as a function-like macro, which again would cause a tricky error here.
It's not clear what this fix() function is for, especially given that 1 / 100'000 is not an exact double value.
It's also unclear why we're using floating-point for values evenly distributed in a small range - why not some fixed-point representation?
constexpr Point center() const{
return {
(sw.lat + ne.lat) / 2,
(sw.lon + ne.lon) / 2
};
}
Although overflow isn't likely with the small values we'll encounter here, it's worth being aware of std::midpoint() for safe mean of two values.
enum class Direction : uint8_t{ | {
"domain": "codereview.stackexchange",
"id": 44874,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, geospatial",
"url": null
} |
c++, geospatial
enum class Direction : uint8_t{
Misspelt std::uint8_t.
constexpr static double RADIUS_EARTH_KM = 6371;
constexpr static double RADIUS_EARTH_MI = 3956;
Apart from the all-caps naming, these are ambiguous: major or minor radius? Are these taken from a particular geoid model? A comment should be present here.
It's not immediately apparent what cells is for, nor why we need 12 of them. That magic number 12 pops up in a few places, and it's hard to see whether all refer to the same thing.
It's probably better to initialise cells directly from CELLS_ABSOLUTE and then std::transform its members to do the multiplication, rather than to repeat the calculations by hand.
HashVector has the magic constant 9 with no explanation in two places.
constexpr double one_deg = M_PI / 180;
That's well-named. But we never declared M_PI. I'm guessing this is intended to be std::numbers::pi?
inline double Rectangle::height(GeoSphere const &sphere) const{
// return distance(sw.lat, sw.lon, ne.lat, sw.lon, sphere);
return distance(ne_p(), se_p(), sphere);
}
inline double Rectangle::width(GeoSphere const &sphere) const{
// return distance(sw.lat, sw.lon, sw.lat, ne.lon, sphere);
return distance(ne_p(), nw_p(), sphere);
}
inline double Rectangle::area(GeoSphere const &sphere) const{
return width(sphere) * height(sphere);
}
Don't leave commented-out statements with no explanation.
These definitions look highly dodgy - why is height() measuring the longitudinal extent? And width() a latitudinal one? And the area of a Plate Carré projection has very little geodesic meaning, so what's the area() function for?
I've only glanced through the implementation file so far, but I noticed this:
if (border[direction][type].find(lastCh) != std::string::npos && size - 1 > 0)
The correct constant to use here would be std::string_view::npos. | {
"domain": "codereview.stackexchange",
"id": 44874,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, geospatial",
"url": null
} |
java, programming-challenge
Title: Minimise operations to reduce fuel level to one (Google Foobar level 3)
Question: Over the past few weeks, I've been doing the Google Foobar challenges and I've been progressing quite well. I'm currently ⅓ of the way through the third level. However, there were plenty of times over the past few weeks where I felt that my code could have been a lot better. So today I stumbled upon this community and I think that it will be a good idea to ask you guys to review my code.
So this is what I was instructed to do:
The fuel control mechanisms have three operations:
Add one fuel pellet
Remove one fuel pellet
Divide the entire group of fuel pellets by 2 (due to the destructive energy released when a quantum antimatter pellet is cut in half, the safety controls will only allow this to happen if there is an even number of pellets)
Write a function called answer(n) which takes a positive integer as a string and returns the minimum number of operations needed to transform the number of pellets to 1. The fuel intake control panel can only display a number up to 309 digits long, so there won't ever be more pellets than you can express in that many digits.
This is my solution:
public static int answer(String n) {
//convert n to BigInteger
BigInteger x = new BigInteger(n);
BigInteger two = new BigInteger("2");
BigInteger three = new BigInteger("3");
BigInteger y, z;
int counter = 0; | {
"domain": "codereview.stackexchange",
"id": 44875,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, programming-challenge",
"url": null
} |
java, programming-challenge
//Loop for as long as x is not equal to 1
while(!x.equals(BigInteger.ONE)){
//Check if x is divisible by 2
if(x.mod(two).equals(BigInteger.ZERO)){
//divide x by 2
x = x.divide(two);
} else {
//subtract x by 1 and then divide by 2 store in variable z
y = x.subtract(BigInteger.ONE);
z = y.divide(two);
//check if the result of that leaves a number that's divisible by 2, or check if x is equal to 3
if(z.mod(two).equals(BigInteger.ZERO) || x.equals(three)){
x = y;
} else {
x = x.add(BigInteger.ONE);
}
}
counter++;
}
return counter;
}
For this challenge, I'm a lot more confident and happy with the cleanliness of my code compared to the previous challenges. But seeing that I'm still very much a newbie and this being my first time using BigInteger, I'd very much like a review.
Answer: You could have used the bitwise methods in BigInteger.
You could get rid of both .mod(two) and BigInteger two and instead use !__.testBit(0).
Returns true if and only if the designated bit is set. (Computes ((this & (1<<n)) != 0).)
You could have also used .shiftRight(1) to divide by 2
Returns a BigInteger whose value is (this >> n). Sign extension is performed. The shift distance, n, may be negative, in which case this method performs a left shift. (Computes floor(this / 2n).)
I haven't put a ton of thought, but I think you could also find a clever way to get rid of 3 with testBit and bitLength, but I think that .compareTo/equals method is alright.
public static int answer(String n) {
//convert n to BigInteger
BigInteger x = new BigInteger(n);
BigInteger three = new BigInteger("3");
BigInteger y, z;
int counter = 0; | {
"domain": "codereview.stackexchange",
"id": 44875,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, programming-challenge",
"url": null
} |
java, programming-challenge
//Loop for as long as x is not equal to 1
while(!x.equals(BigInteger.ONE)){
//Check if x is divisible by 2
if(!x.testBit(0)){
//divide x by 2
x = x.shiftRight(1);
} else {
//subtract x by 1 and then divide by 2 store in variable z
y = x.subtract(BigInteger.ONE);
z = y.shiftRight(1);
//check if the result of that leaves a number that's divisible by 2, or check if x is equal to 3
if(!z.testBit(0) || x.equals(three)){
x = y;
} else {
x = x.add(BigInteger.ONE);
}
}
counter++;
}
return counter;
} | {
"domain": "codereview.stackexchange",
"id": 44875,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, programming-challenge",
"url": null
} |
java, reinventing-the-wheel, hash-map
Title: Set implementation
Question: I believe reinventing the wheel is in fact a good learning exercise. How can I improve my Set implementation without just copying HashSet?
No treeification/detreefication, please. I find it too time-consuming to implement.
I decided not to use anything but arrays and Lists as its underlying data structures.
Some aspects of design that you may find unusual may in fact serve some purpose (or at least, I believe so). Feel free to ask if something smells fishy to you.
package org.example.demos.mySet;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
public class MyHashSet<E> extends AbstractSet<E> {
private final Defaults defaults = new Defaults();
private List<E>[] hashTable;
private List<InternalAddress> addresses = defaults.addresses();
private final float LOAD_FACTOR;
@SuppressWarnings("unused")
public MyHashSet() {
LOAD_FACTOR = Defaults.LOAD_FACTOR;
initializeAndPrepareHashTable();
}
@SuppressWarnings("unused")
public MyHashSet(int initialCapacity) {
if (initialCapacity < 3) {
throw new IllegalArgumentException("Initial capacity should be equal to or greater than 3. Your value: " + initialCapacity);
}
LOAD_FACTOR = Defaults.LOAD_FACTOR;
initializeAndPrepareHashTable(initialCapacity);
} | {
"domain": "codereview.stackexchange",
"id": 44876,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reinventing-the-wheel, hash-map",
"url": null
} |
java, reinventing-the-wheel, hash-map
@SuppressWarnings("unused")
public MyHashSet(int initialCapacity, float loadFactor) {
if (initialCapacity * loadFactor < 2) {
throw new IllegalArgumentException("Initial capacity and load factor should be set in such a way " +
"as to allow at least one element before resizing. In other words, initialCapacity * loadFactor " +
"should be equal to or greater than 2. Your values: " + initialCapacity + ", " + loadFactor);
} else if (loadFactor > 1) {
throw new IllegalArgumentException("Load factor should not exceed 1. Your value: " + loadFactor);
}
LOAD_FACTOR = loadFactor;
initializeAndPrepareHashTable(initialCapacity);
}
private void initializeAndPrepareHashTable() {
hashTable = defaults.hashTable();
fillHashTableWithEmptyLists();
}
private void initializeAndPrepareHashTable(int initialCapacity) {
hashTable = defaults.hashTable(initialCapacity);
fillHashTableWithEmptyLists();
}
private void fillHashTableWithEmptyLists() {
fillHashTableWithEmptyLists(hashTable);
}
@SuppressWarnings("unchecked")
private void fillHashTableWithEmptyLists(List<E>[] hashTable) {
try {
Constructor<? extends List<E>> constructor = (Constructor<? extends List<E>>) hashTable.getClass()
.componentType()
.getDeclaredConstructor();
for (int i = 0; i < hashTable.length; i++) {
hashTable[i] = constructor.newInstance();
}
} catch (InstantiationException | IllegalAccessException |
InvocationTargetException | NoSuchMethodException exception) {
exception.printStackTrace();
}
} | {
"domain": "codereview.stackexchange",
"id": 44876,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reinventing-the-wheel, hash-map",
"url": null
} |
java, reinventing-the-wheel, hash-map
@Override
public boolean add(E elementToAdd) {
int bucketIndex = getBucketIndex(elementToAdd);
List<E> bucket = hashTable[bucketIndex];
for (E element : bucket) {
if (element == elementToAdd || element.equals(elementToAdd)) {
return false;
}
}
bucket.add(elementToAdd);
InternalAddress newElementAddress = new InternalAddress(bucketIndex, bucket.size() - 1);
addresses.add(newElementAddress);
Collections.sort(addresses);
checkFullness();
return true;
}
@Override
public boolean remove(Object object) {
int bucketIndex = getBucketIndex(object);
List<E> bucket = hashTable[bucketIndex];
for (ListIterator<E> iterator = bucket.listIterator(); iterator.hasNext(); ) {
E element = iterator.next();
if (object.equals(element)) {
iterator.remove();
InternalAddress removedElementAddress = new InternalAddress(bucketIndex,
iterator.previousIndex() + 1);
addresses.remove(removedElementAddress);
return true;
}
}
return false;
}
@Override
public boolean contains(Object o) {
List<E> bucket = hashTable[getBucketIndex(o)];
for (E element : bucket) {
if (o.equals(element)) {
return true;
}
}
return false;
}
@Override
public Iterator<E> iterator() {
return new MyHashSetIterator();
}
@Override
public int size() {
return addresses.size();
}
private int getBucketIndex(Object object) {
return object == null ? 0 : (hashTable.length - 1) & object.hashCode();
}
private int getBucketIndex(Object object, int hashTableLength) {
return object == null ? 0 : (hashTableLength - 1) & object.hashCode();
} | {
"domain": "codereview.stackexchange",
"id": 44876,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reinventing-the-wheel, hash-map",
"url": null
} |
java, reinventing-the-wheel, hash-map
private void checkFullness() {
if (size() >= hashTable.length * LOAD_FACTOR) {
resizeAndRehash();
}
}
private void resizeAndRehash() {
int newLength = defaults.newLength();
List<E>[] newHashTable = defaults.hashTable(newLength);
fillHashTableWithEmptyLists(newHashTable);
List<InternalAddress> newAddresses = defaults.addresses();
int processedBucketIndex = -1, currentBucketIndex;
for (InternalAddress address : addresses) {
currentBucketIndex = address.bucket;
if (currentBucketIndex == processedBucketIndex) {
continue;
}
for (E element : hashTable[currentBucketIndex]) {
int newBucketIndex = getBucketIndex(element, newLength);
List<E> newBucket = newHashTable[newBucketIndex];
newBucket.add(element);
newAddresses.add(new InternalAddress(newBucketIndex, newBucket.size() - 1));
}
processedBucketIndex = currentBucketIndex;
}
hashTable = newHashTable;
addresses = newAddresses;
}
List<E>[] getHashTable() {
return hashTable;
}
List<InternalAddress> getAddresses() {
return addresses;
}
private class MyHashSetIterator implements Iterator<E> {
private int cursor = -1;
@Override
public boolean hasNext() {
return cursor < addresses.size() - 1;
}
@Override
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
InternalAddress nextElementAddress = addresses.get(++cursor);
return hashTable[nextElementAddress.bucket]
.get(nextElementAddress.index);
} | {
"domain": "codereview.stackexchange",
"id": 44876,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reinventing-the-wheel, hash-map",
"url": null
} |
java, reinventing-the-wheel, hash-map
@Override
public void remove() {
if (cursor < 0) {
throw new IllegalStateException("To remove an element, this Iterator should first return it");
}
InternalAddress currentElementAddress = addresses.get(cursor);
hashTable[currentElementAddress.bucket].remove(currentElementAddress.index);
}
}
private record InternalAddress(int bucket, int index) implements Comparable<InternalAddress> {
@Override
public int compareTo(InternalAddress otherAddress) {
boolean differentBuckets = bucket != otherAddress.bucket;
if (differentBuckets) {
return bucket - otherAddress.bucket;
} else {
return index - otherAddress.index;
}
}
}
private class Defaults {
private static final int INITIAL_CAPACITY = 16;
private static final float LOAD_FACTOR = 0.75f;
@SuppressWarnings("unchecked")
private List<E>[] hashTable() {
return (LinkedList<E>[]) new LinkedList[INITIAL_CAPACITY];
}
@SuppressWarnings("unchecked")
private List<E>[] hashTable(int initialCapacity) {
return (LinkedList<E>[]) new LinkedList[initialCapacity];
}
private List<InternalAddress> addresses() {
return new LinkedList<>();
}
private int newLength() {
return hashTable.length << 1;
}
}
}
Answer: Adding entries causes the allocation to grow,
but removing entries will never cause it to shrink.
The supporting documentation on this submission is inadequate.
Its three bullet points are
a design constraint supported by a rationale: "no trees!", fair enough
an explanation of design choices: arrays + lists, good
"ask me" if something is unclear -- not helpful | {
"domain": "codereview.stackexchange",
"id": 44876,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reinventing-the-wheel, hash-map",
"url": null
} |
java, reinventing-the-wheel, hash-map
No references are cited.
It appears to conform to this
Set
contract, and is explicitly not a
HashSet.
As a user of this implementation,
here are the crucial guarantees I'm looking for:
This [HashSet] class offers constant time [O(1)] performance for the basic operations (add, remove, contains and size), ...
I mean, if O(N) performance was Good Enough, I would
just be using an array or list implementation, right?
Constant time is much of the whole value add for this class,
yet it offers no such guarantees.
Going forward, I shall cavalierly assume them,
and express disappointment if they are not met.
I will view fail-fast iterators as an advanced topic
that is out-of-scope.
Even a single sentence offering the high level overview of
"a power-of-two sized array holds the heads of LinkedLists"
would have been helpful.
Maybe followed by a sentence describing how
growth or shrinkage leads to re-hashing
with some prescribed amortized cost.
Reproducibility is important.
I see no maven instructions for compilation,
and no advice on what compiler switches or versions to use.
As it stands I cannot run what the Author ran
nor see what he saw.
Absent a repo link,
I don't know which compiler version we're targeting
or the intended set of switches.
The whole generics type-erasure "unchecked"
situation seems out of control w.r.t. the
interface we're trying to conform to.
For example this implementation
manages to implement the interface
in a type safe way,
apart from clone() and readObject().
There exist
techniques
for type safe access,
which are observed to work well in the wild.
We need some design discussion,
and commentary on support for
switches like -Xlint:all or -Xlint:unchecked.
I do not understand the default constructor's "unused"
annotation, and would appreciate a /* comment */ explaining it,
or a JUnit test suite that exercises constructors.
Maybe it was added early on, and then the code evolved
but it was never removed?
if (initialCapacity < 3) { | {
"domain": "codereview.stackexchange",
"id": 44876,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reinventing-the-wheel, hash-map",
"url": null
} |
java, reinventing-the-wheel, hash-map
if (initialCapacity < 3) {
I do not understand at all why we're rejecting a capacity of 2.
The thrown diagnostic appears to conflict with the one thrown
by the 2-arg ctor.
Better to just call it here, with 2nd arg
equal to default loadFactor, and let it throw if necessary.
It appears to me things would work fine with just two buckets.
private void initializeAndPrepareHashTable() {
hashTable = defaults.hashTable();
fillHashTableWithEmptyLists();
}
private void initializeAndPrepareHashTable(int initialCapacity) {
hashTable = defaults.hashTable(initialCapacity);
fillHashTableWithEmptyLists();
}
These don't make much sense.
They are private.
There should be just one of them (the 2nd one).
The default ctor should supply a default initialCapacity
to the 2nd one.
private void fillHashTableWithEmptyLists() {
fillHashTableWithEmptyLists(hashTable);
}
Why?
This private helper method is not pulling its weight.
Surely the caller could have supplied this.hashTable?
It's not like there's some Public API we need to conform to.
private void fillHashTableWithEmptyLists(List<E>[] hashTable) {
...
for (int i = 0; i < hashTable.length; i++) {
hashTable[i] = constructor.newInstance();
}
`hashTable` is a `List`, so this all checks out.
But the trouble is that it's implemented as a `LinkedList`,
so the complexity here is O(N^2) quadratic.
Better to maintain a pointer that you can push
a new entry onto in O(1) constant time.
Whoops.
On initial reading I mistook `[i]` as
a subscript into a LinkedList rather than array.
This isn't python; I should have anticipated a `.get(i)`.
I retract the remark.
} catch (InstantiationException | IllegalAccessException |
InvocationTargetException | NoSuchMethodException exception) {
exception.printStackTrace(); | {
"domain": "codereview.stackexchange",
"id": 44876,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reinventing-the-wheel, hash-map",
"url": null
} |
java, reinventing-the-wheel, hash-map
Arrggghhhh! zomg, no, do not swallow such exceptions.
Rather, re-throw them, in the hope it will be fatal.
If need be, to make the signature work out,
wrap it within RuntimeException
or an app-specific class which inherits from that.
if (element == elementToAdd || element.equals(elementToAdd)) {
What is going on here?
I mean, yes, I get it that address equality is
different from examining each attribute.
But why aren't we delegating such details to the element type?
A type can start its comparison by examining addresses.
There needs to be some discussion in the code or docs
about such micro optimizations,
with a citation describing observed timings.
Collections.sort(addresses);
Ok, now I'm astonished. add() just did an O(N log N) operation,
when caller will reasonably expect it to return in O(1) constant time?!?
Possibly the data structure you were looking for is a
heap,
with O(log N) insert time.
In a java context folks tend to view that as O(64),
which is O(1) constant.
public boolean remove(Object object) {
...
addresses.remove(removedElementAddress);
Oh, lookitdat, O(1) removal time from a linked list, excellent.
Near as I can tell, this seems to be the author's motivation
for employing a linked list.
There is a technique called
tombstones
which lets you delete an item in O(1) constant time,
by simply setting a "deleted" flag on the item.
As tombstones accumulate they become troublesome,
so at some point you'll want to copy out just the live items,
which still may have an attractive amortized cost.
A pointer dereference is hard for Intel to predict / prefetch,
so contiguous ArrayList entries with tombstone
may bench faster than a chain of LinkedList entries.
public boolean contains(Object o) {
...
if (o.equals(element)) {
Couple of items: | {
"domain": "codereview.stackexchange",
"id": 44876,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reinventing-the-wheel, hash-map",
"url": null
} |
java, reinventing-the-wheel, hash-map
Couple of items:
It troubles me that we're not doing the same address comparison as above. For example, what if the element type had a buggy .equals()? Then address comparison would mask that.
This "loop and compare" should be what other methods call, or it should be in a helper that contains() and other methods call. DRY
private int getBucketIndex(Object object) {
return object == null ? 0 : (hashTable.length - 1) & object.hashCode();
}
This method imposes a
class invariant
on MySet, so we're forced to allocate only power-of-two capacities.
This seems needlessly limiting.
We're comparing the elapsed time for int-divide
against bitwise AND.
On modern processors, it's not clear this is
going to add up to significant time, compared
to waiting on our cache misses and linked list prediction misses.
In microbenches we can do about two & AND operations
in the time it takes to do one % mod operation.
But masking forces us to at least double
the number of buckets when resizing,
as opposed to say 30% or 50% growth.
Doesn't seem like the tradeoff is worth it.
Example: ... % 8 is like ... & 7,
but % 9 has no easy masking equivalent.
Recommend you adopt the traditional % modulo approach, here.
Like many other methods, the resizeAndRehash() method
has a lovely name, very clear and descriptive.
I'm not going to read further; I bet it does the right thing.
The submission offered no unit tests or benchmark timings,
and essentially no supporting documentation,
for some core functionality that potentially
is of interest to many diverse callers.
If there were other considerations,
like "speed is not an issue",
they were not explicitly called out.
This codebase does not appear to achieve its design goals.
"Merge to main?"
Given the lack of functional and performance tests,
I would not be willing to delegate or accept maintenance
tasks on this code in its current form. | {
"domain": "codereview.stackexchange",
"id": 44876,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, reinventing-the-wheel, hash-map",
"url": null
} |
python, formatting
Title: Output a Python dictionary as a table with a custom format
Question: I have a Python directory containing some str: int key-value pairs, and my goal is to display that data in a tabular format.
I am unable to use the tabulate module because it seems that it cannot display data exactly as is required by the project sponsors (and as far as I know you cannot customise the formats), so I'm having to hand crank the simplest solution I can find.
Example of desired output
Name Passes
------------------
Name One 7
Name Two 1
Name Three 35
------------------
Total 43
Code
While the task is pretty simple, the code is pretty verbose. Is this the best way to do this, or is there a better way that would be more efficient (but still without using tabulate)?
def print_table(data: dict, spacer_length: int=2) -> None:
'''Print the given data dictionary in a table format.
Arguments:
data (dict): The data dictionary to ouput.
spacer_length (int=2): The number of spaces between each column.
Minimum value is 1 and maximum value is 10.
'''
# Transform the `pass_count` dict into and array of columns.
# At the same time, add the required headers and footers.
cols = [
['Name'] + list(data) + ['Total'],
['Passes'] + list(data.values()) + [sum([v for v in data.values()])]]
# Find the length of the longest item in each column.
col_widths = [max(len(str(v)) for v in c) for c in cols]
# Format items in each column to the length of the longest item.
cols = [[f'{v:{col_widths[i]}}' for v in c] for i, c in enumerate(cols)]
# Pop the column headers and footers.
headers = [c.pop(0) for c in cols]
footers = [c.pop() for c in cols]
# Construct the separator.
spacer_length = min((max((1, int(spacer_length))), 10))
spacer = ' ' * spacer_length
seperator = '-' * (sum(col_widths) + ((len(col_widths) - 1) * spacer_length)) | {
"domain": "codereview.stackexchange",
"id": 44877,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, formatting",
"url": null
} |
python, formatting
rows = [spacer.join(list(row)) for row in zip(cols[0], cols[1])]
print(spacer.join(headers), seperator,'\n'.join(rows),
seperator, spacer.join(footers), sep='\n')
pass_count = {
'Name One': 7,
'Name Two': 1,
'Name Three': 35,
}
print_table(pass_count)
Answer: After some further reading, it turns out that it is possible to do everything that is needed using the tabulate module.
As pointed out in this answer, it is possible to add a custom table format. Sadly the TableFormat object is a namedtuple, making it immutable, therefore it's required to create an entirely new format rather than update an existing one that is close to what is needed.
The other piece of the puzzle is the SEPARATING_LINE, which means a separator and then the footer can simply be appended to the table data. See the GitHub issue.
from tabulate import tabulate, TableFormat, Line, DataRow, SEPARATING_LINE
def main() -> None:
pass_count = {
'Name One': 7,
'Name Two': 1,
'Name Three': 35,
}
print(report(pass_count))
def report(data: dict) -> None:
# Create a custom table format.
tablefmt = TableFormat(
lineabove=Line('', '-', '', ''),
linebelowheader=Line('', '-', '', ''),
linebetweenrows=None,
linebelow=Line('', '-', '', ''),
headerrow=DataRow('', '', ''),
datarow=DataRow('', '', ''),
padding=0,
with_header_hide=['lineabove', 'linebelow']
)
# Make the data dictionary a list and append the separator and footer.
data_list = list(data.items())
data_list.append(SEPARATING_LINE)
data_list.append(('Total', sum(data.values())))
return tabulate(data_list, headers=('Name', 'Passes'), tablefmt=tablefmt)
if __name__ == '__main__':
main()
Thanks to all who contributed. | {
"domain": "codereview.stackexchange",
"id": 44877,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, formatting",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
Title: Improved Component-Entity-System Using C++
Question: Introduction
I am a newbie, so please take me easy :). I am writing a low-level game engine using C++, GLFW and also OpenGL. This is a continuation of Entity Component System Using C++ I've
implemented the sugestions.
Modifications
Here's a rundown of the changes I've made since the last iteration:
The entities are now stored in a contiguous array. Whenever an
entity is removed, the last entity is moved to its place. This
approach, however, raises a question: how can users identify each
Entity if their positions are constantly changing? To address this,
we provide users with an EntityKey, which contains a weak pointer to
the entity, instead of direct access to the internal Entity.
I've clearly differentiated between Entities and EntityKeys: The
ECSManager only interacts with EntityKeys, while the internals
(including the Systems) use Entities for their lightweight nature.
I've introduced TagTypes, which are designed to be faster than the
type_index used in the previous iteration. However, I'm uncertain
about the extent of the improvements this change brings—it might be
an overengineering effort. TagTypes allow us to tag Component types,
System types, and combinations of Variadic templates (for caching in
the SystemContext's update function). By using TagTypes, we can
avoid the need for maps (instead of std::unordered_map<type_index
...>), as they index from 0.
I've incorporated Archetypes into the system. Archetypes are
structures that hold a std::unordered_set of entities, categorized
based on the Components they contain. This feature could potentially
enhance the speed of finding all entities with certain components,
as we only need to perform an intersection operation. Before
intersecting all the std::unordered_set's, we first check if the
required data is available in the Cache. | {
"domain": "codereview.stackexchange",
"id": 44878,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
Self-critique
I believe the TypeTag.h could be better organized; it currently appears cluttered. Although the solution I've implemented is the best I could come up with, I'm certain there are more efficient alternatives out there. I have mixed feelings about the EntityKey being a friend of the ECSManager. While it is functionally correct—preventing end users from creating their own EntityKey and accessing the Entity—it still raises some concerns.
I'm skeptical about the performance improvements brought by the Archetypes. I suspect the primary performance boost will come from the Cache system rather than the Archetypes. Initially, I intended for the EntityKeys to own the Entities, so that when an EntityKey goes out of scope, its associated Entity is also removed from the ECS. However, this proved challenging as it would couple the EntityManager to the ComponentManager. This coupling would be necessary for the destructor (of the shared pointer that should have been inside EntityKey), as the removal of an entity should be reflected in both systems. I found this coupling unacceptable, so I opted for a different solution where the EntityManager owns the Entities directly.
I welcome any feedback or suggestions you may have. Your input is greatly appreciated.
Source Code
Archetype.h
#pragma once
#include <unordered_set>
#include "Entity.h"
namespace std
{
template<>
struct hash<Entity>
{
std::size_t operator()(const Entity& entity) const { return std::hash<size_t>{}(entity.index); }
};
}
inline bool operator==(const Entity& lhs, const Entity& rhs) { return lhs.index == rhs.index; }
class BaseArchetype
{
public:
virtual void addEntity(Entity entity) = 0;
virtual void removeEntity(Entity entity) = 0;
virtual const std::unordered_set<Entity>& getEntities() const = 0;
}; | {
"domain": "codereview.stackexchange",
"id": 44878,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
virtual const std::unordered_set<Entity>& getEntities() const = 0;
};
template<typename ComponentType>
class Archetype : public BaseArchetype
{
public:
void addEntity(Entity entity) override { entities.insert(entity); }
void removeEntity(Entity entity) override { entities.erase(entity); }
const std::unordered_set<Entity>& getEntities() const override { return entities; }
private:
std::unordered_set<Entity> entities;
};
ArchetypeManager.h
#pragma once
#include "Cache.h"
#include "ArchetypeQuery.h"
class ArchetypeManager
{
public:
ArchetypeManager()
: archetypeQuery(archetypeStorage) { }
template<typename ComponentType>
void addComponent(Entity entity)
{
archetypeStorage.addComponent<ComponentType>(entity);
cache.clear();
}
void removeEntity(Entity entity)
{
archetypeStorage.removeEntity(entity);
cache.clear();
}
template<typename ComponentType>
void removeComponent(Entity entity)
{
archetypeStorage.removeComponent<ComponentType>(entity);
cache.clear();
}
template<typename ComponentType>
const std::unordered_set<Entity>& getEntities() const
{
return archetypeStorage.getEntities<ComponentType>();
}
template<typename... ComponentTypes>
std::unordered_set<Entity> findCommonEntities()
{
auto cachedEntities = cache.retrieve<ComponentTypes...>();
if (cachedEntities) {
return *cachedEntities;
}
else {
std::unordered_set<Entity> entities = archetypeQuery.findCommonEntities<ComponentTypes...>();
cache.store<ComponentTypes...>(entities);
return entities;
}
}
void clearCache()
{
cache.clear();
}
private:
ArchetypeStorage archetypeStorage;
ArchetypeQuery archetypeQuery;
Cache<std::unordered_set<Entity>> cache;
};
ArchetypeQuery.cpp
#include "ArchetypeQuery.h" | {
"domain": "codereview.stackexchange",
"id": 44878,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
ArchetypeQuery.cpp
#include "ArchetypeQuery.h"
ArchetypeQuery::EntitySet ArchetypeQuery::findCommonEntities(const std::vector<EntitySet>& entitySets) const
{
auto smallestSetIt = findSmallestSet(entitySets);
if (smallestSetIt->empty())
return { };
EntitySet commonEntities = *smallestSetIt;
for (auto it = entitySets.begin(); it != entitySets.end(); ++it) {
if (it == smallestSetIt)
continue;
commonEntities = intersectUnorderedSets(commonEntities, *it);
}
return commonEntities;
}
std::vector<ArchetypeQuery::EntitySet>::const_iterator ArchetypeQuery::
findSmallestSet(const std::vector<EntitySet>& entitySets) const
{
return std::min_element(entitySets.begin(), entitySets.end(),
[](const EntitySet& a, const EntitySet& b) {
return a.size() < b.size();
});
}
ArchetypeQuery::EntitySet ArchetypeQuery::
intersectUnorderedSets(const EntitySet& set1, const EntitySet& set2) const
{
EntitySet intersection;
for (const auto& entity : set1)
if (set2.find(entity) != set2.end())
intersection.insert(entity);
return intersection;
}
ArchetypeQuery.h
#pragma once
#include <iterator>
#include <algorithm>
#include "ArchetypeStorage.h"
class ArchetypeQuery
{
public:
using EntitySet = std::unordered_set<Entity>;
ArchetypeQuery(ArchetypeStorage& archetypeStorage)
: archetypeStorage(archetypeStorage) { }
template<typename... ComponentTypes>
EntitySet findCommonEntities()
{
std::vector<EntitySet> entitySets;
(entitySets.push_back(archetypeStorage.getEntities<ComponentTypes>()), ...);
return findCommonEntities(entitySets);
} | {
"domain": "codereview.stackexchange",
"id": 44878,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
private:
EntitySet findCommonEntities(const std::vector<EntitySet>& entitySets) const;
std::vector<EntitySet>::const_iterator findSmallestSet(const std::vector<EntitySet>& entitySets) const;
EntitySet intersectUnorderedSets(const EntitySet& set1, const EntitySet& set2) const;
private:
ArchetypeStorage& archetypeStorage;
};
ArchetypeStorage.h
#pragma once
#include <memory>
#include <vector>
#include "Archetype.h"
#include "TypeTag.h"
class ArchetypeStorage
{
public:
template<typename ComponentType>
void addComponent(Entity entity)
{
getArchetype<ComponentType>().addEntity(entity);
}
void removeEntity(Entity entity)
{
for (auto& archetype : archetypes)
archetype->removeEntity(entity);
}
template<typename ComponentType>
void removeComponent(Entity entity)
{
getArchetype<ComponentType>().removeEntity(entity);
}
template<typename ComponentType>
const std::unordered_set<Entity>& getEntities()
{
return getArchetype<ComponentType>().getEntities();
}
private:
template<typename ComponentType>
Archetype<ComponentType>& getArchetype()
{
size_t index = ComponentTypeTag<ComponentType>::index;
if (index >= archetypes.size())
archetypes.resize(index + 1);
if (archetypes[index] == nullptr)
archetypes[index] = std::make_unique<Archetype<ComponentType>>();
return static_cast<Archetype<ComponentType>&>(*archetypes[index]);
}
private:
inline static std::vector<std::unique_ptr<BaseArchetype>> archetypes;
};
Cache.h
#pragma once
#include <optional>
#include <vector>
#include "TypeTag.h" | {
"domain": "codereview.stackexchange",
"id": 44878,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
Cache.h
#pragma once
#include <optional>
#include <vector>
#include "TypeTag.h"
template <typename ResultType>
class Cache
{
public:
template <typename... ComponentTypes>
void store(const ResultType& result)
{
size_t index = VariadicTypeTag<ComponentTypes...>::index;
if (index >= cache.size())
cache.resize(index + 1);
cache[index] = result;
}
template <typename... ComponentTypes>
std::optional<ResultType> retrieve() const
{
size_t index = VariadicTypeTag<ComponentTypes...>::index;
return index < cache.size() ? cache[index] : std::nullopt;
}
void clear()
{
cache.clear();
}
private:
inline static std::vector<std::optional<ResultType>> cache;
};
ComponentManager.h
#pragma once
#include "ComponentPool.h"
#include "TypeTag.h"
class ComponentManager
{
public:
template<typename ComponentType, typename... Args>
void addComponent(Entity entity, Args&&... args)
{
getComponentPool<ComponentType>().addComponent(entity, std::forward(args)...);
}
template<typename ComponentType>
ComponentType& getComponent(Entity entity)
{
return getComponentPool<ComponentType>().getComponent(entity);
}
template<typename ComponentType>
bool hasComponent(Entity entity)
{
return getComponentPool<ComponentType>().hasComponent(entity);
}
void removeEntity(Entity entity)
{
for (auto& pool : componentPools)
pool->relocateComponentToEntity(entity);
}
template<typename ComponentType>
void removeComponent(Entity entity)
{
getComponentPool<ComponentType>().removeComponentFromEntity(entity);
}
private:
template<typename ComponentType>
ComponentPool<ComponentType>& getComponentPool()
{
size_t index = ComponentTypeTag<ComponentType>::index;
if (index >= componentPools.size())
componentPools.resize(index + 1); | {
"domain": "codereview.stackexchange",
"id": 44878,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
if (index >= componentPools.size())
componentPools.resize(index + 1);
if (componentPools[index] == nullptr)
componentPools[index] = std::make_unique<ComponentPool<ComponentType>>();
return static_cast<ComponentPool<ComponentType>&>(*componentPools[index]);
}
private:
inline static std::vector<std::unique_ptr<BaseComponentPool>> componentPools;
};
ComponentPool.h
#pragma once
#include <stdexcept>
#include <memory>
#include <optional>
#include "EntityExceptions.h"
#include "ComponentPoolExceptions.h"
class BaseComponentPool
{
public:
virtual ~BaseComponentPool() = default;
virtual void removeComponentFromEntity(Entity entity) = 0;
virtual void relocateComponentToEntity(Entity entity) = 0;
virtual bool hasComponent(Entity entity) const = 0;
};
template <typename ComponentType>
class ComponentPool : public BaseComponentPool
{
public:
template<typename... Args>
void addComponent(Entity entity, Args&&... args)
{
if (entity.index >= pool.size())
pool.resize(entity.index + 1);
pool[entity.index] = ComponentType(std::forward<Args>(args)...);
}
void relocateComponentToEntity(Entity entity) override
{
if (entity.index >= pool.size())
throw EntityOutOfBoundsException(entity);
pool[entity.index] = std::move(pool.back());
pool.pop_back();
}
void removeComponentFromEntity(Entity entity) override
{
if (entity.index >= pool.size())
throw EntityOutOfBoundsException(entity);
pool[entity.index].reset();
}
ComponentType& getComponent(Entity entity) const
{
if (entity.index >= pool.size())
throw EntityOutOfBoundsException(entity);
if (!pool[entity.index])
throw ComponentOutOfBoundsException(entity);
return *pool[entity.index];
} | {
"domain": "codereview.stackexchange",
"id": 44878,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
return *pool[entity.index];
}
bool hasComponent(Entity entity) const override
{
return entity.index < pool.size() && pool[entity.index].has_value();
}
private:
inline static std::vector<std::optional<ComponentType>> pool;
};
ComponentPoolExceptions.h
#pragma once
#include <stdexcept>
#include <string>
#include "Entity.h"
class ComponentOutOfBoundsException : public std::runtime_error
{
public:
ComponentOutOfBoundsException(Entity entity)
: std::runtime_error(std::to_string(entity.index) + " is out of bounds!") { }
};
ECSManager.h
#pragma once
#include "SystemManager.h"
#include "EntityKey.h"
class ECSManager
{
public:
ECSManager()
: systemManager( SystemContext{ entityManager, componentManager, archetypeManager } ) { }
EntityKey createEntity()
{
archetypeManager.clearCache();
return { entityManager.createEntity() };
}
template<typename ComponentType, typename... Args>
void addComponent(const EntityKey& key, Args&&... args)
{
Entity entity = key.getEntity();
componentManager.addComponent<ComponentType>(entity, std::forward(args)...);
archetypeManager.addComponent<ComponentType>(entity);
}
void removeEntity(const EntityKey& key)
{
Entity entity = key.getEntity();
componentManager.removeEntity(entity);
archetypeManager.removeEntity(entity);
entityManager.removeEntity(entity);
}
template<typename ComponentType>
void removeComponent(const EntityKey& key)
{
Entity entity = key.getEntity();
componentManager.removeComponent<ComponentType>(entity);
archetypeManager.removeComponent<ComponentType>(entity);
}
template<typename SystemType, typename... Args>
requires std::derived_from<SystemType, System>
void addSystem(Args&&... args)
{
systemManager.addSystem<SystemType>(std::forward<Args>(args)...);
} | {
"domain": "codereview.stackexchange",
"id": 44878,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
c++, object-oriented, design-patterns, entity-component-system, constrained-templates
template<typename SystemType>
requires std::derived_from<SystemType, System>
void removeSystem()
{
systemManager.removeSystem<SystemType>();
}
template<typename SystemType>
requires std::derived_from<SystemType, System>
bool hasSystem() const
{
return systemManager.hasSystem<SystemType>();
}
template<typename SystemType>
requires std::derived_from<SystemType, System>
void enableSystem(bool enabled)
{
systemManager.enableSystem<SystemType>(enabled);
}
void updateSystems(float deltaTime)
{
systemManager.updateSystems(deltaTime);
}
private:
EntityManager entityManager;
ComponentManager componentManager;
ArchetypeManager archetypeManager;
SystemManager systemManager;
};
Entity.h
#pragma once
struct Entity
{
size_t index;
};
EntityExceptions.h
#pragma once
#include <stdexcept>
#include <string>
#include "Entity.h"
class EntityOutOfBoundsException : std::runtime_error
{
public:
EntityOutOfBoundsException(Entity entity)
: runtime_error("Entity: " + std::to_string(entity.index) + " is out of bounds!") { }
};
class EntityIsAlreadyDestroyedException : std::runtime_error
{
public:
EntityIsAlreadyDestroyedException()
: runtime_error("Attempted to access a destroyed entity") { }
};
EntityKey.h
#pragma once
#include <memory>
#include "EntityExceptions.h"
class EntityKey
{
public:
bool operator==(const EntityKey& other) { return id == other.id; }
bool isRemoved() const { return entity.expired(); }
private:
EntityKey(std::weak_ptr<Entity> entity)
: entity(std::move(entity)), id(IDCounter++) { }
Entity getEntity() const
{
if (entity.expired())
throw EntityIsAlreadyDestroyedException();
return *entity.lock();
}
private:
std::weak_ptr<Entity> entity;
size_t id;
private:
inline static size_t IDCounter = 0;
friend class ECSManager;
}; | {
"domain": "codereview.stackexchange",
"id": 44878,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns, entity-component-system, constrained-templates",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.