Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored weightArrayElement #511

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 8 additions & 11 deletions include/faker-cxx/Helper.h
Original file line number Diff line number Diff line change
Expand Up @@ -132,21 +132,18 @@ class Helper
throw std::invalid_argument{"Sum of weights is zero."};
}

const std::integral auto targetWeightValue = Number::integer<unsigned>(sumOfWeights);

const std::integral auto targetWeightValue = Number::integer<unsigned>(1, sumOfWeights);
unsigned currentSum = 0;
size_t currentIdx = 0;

for (const auto& element : data)
{
currentSum += element.weight;

if (targetWeightValue <= currentSum)
{
return element.value;
}
while (currentIdx < data.size()) {
currentSum += data[currentIdx].weight;
if (currentSum >= targetWeightValue)
break;
currentIdx++;
}

return data.at(data.size() - 1).value;
return data.at(currentIdx).value;
}

/**
Expand Down
11 changes: 11 additions & 0 deletions src/modules/helper/HelperTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,17 @@ TEST_F(HelperTest, WeightedArrayElement)
{ return result == element.value; }));
}

TEST_F(HelperTest, WeightedArrayZeroSum) {
std::vector<Helper::WeightedElement<std::string>> data{{0, "hello"}, {0, "world"}};
ASSERT_THROW(Helper::weightedArrayElement(data), std::invalid_argument);
}

TEST_F(HelperTest, WeightedArrayEmptyData) {
std::vector<Helper::WeightedElement<std::string>> data{};
ASSERT_THROW(Helper::weightedArrayElement(data), std::invalid_argument);
}


TEST_F(HelperTest, ShuffleString)
{
std::string input = "Hello World!";
Expand Down
Loading