Skip to content

Commit c99bcdb

Browse files
aspizuadazem009
authored andcommitted
Implement method randintExcept for RandomGenerator.
1 parent 3f38846 commit c99bcdb

File tree

4 files changed

+37
-0
lines changed

4 files changed

+37
-0
lines changed

src/engine/internal/irandomgenerator.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ class IRandomGenerator
1212

1313
virtual long randint(long start, long end) const = 0;
1414
virtual double randintDouble(double start, double end) const = 0;
15+
virtual long randintExcept(long start, long end, long except) const = 0;
1516
};
1617

1718
} // namespace libscratchcpp

src/engine/internal/randomgenerator.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,16 @@ double RandomGenerator::randintDouble(double start, double end) const
4141
std::uniform_real_distribution<double> distribution(start, end);
4242
return distribution(*m_generator);
4343
}
44+
45+
long RandomGenerator::randintExcept(long start, long end, long except) const
46+
{
47+
if (start > end) {
48+
std::swap(start, end);
49+
}
50+
std::uniform_int_distribution<long> distribution(start, end);
51+
long value = distribution(*m_generator);
52+
if (value == except) {
53+
return randintExcept(start, end, except);
54+
}
55+
return value;
56+
}

src/engine/internal/randomgenerator.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ class RandomGenerator : public IRandomGenerator
2020

2121
long randint(long start, long end) const override;
2222
double randintDouble(double start, double end) const override;
23+
long randintExcept(long start, long end, long except) const;
2324

2425
private:
2526
static std::shared_ptr<RandomGenerator> m_instance;

test/randomgenerator/randomgenerator_test.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,25 @@ TEST(RandomGeneratorTest, RandIntDouble)
4343
ASSERT_LE(num, 5.081);
4444
}
4545
}
46+
47+
TEST(RandomGeneratorTest, RandInt)
48+
{
49+
auto rng = RandomGenerator::instance();
50+
ASSERT_TRUE(rng);
51+
52+
long num;
53+
54+
for (int i = 0; i < 25; i++) {
55+
num = rng->randintExcept(-2, 3, 0);
56+
ASSERT_GE(num, -2);
57+
ASSERT_LE(num, 3);
58+
ASSERT_NE(num, 0);
59+
}
60+
61+
for (int i = 0; i < 25; i++) {
62+
num = rng->randintExcept(5, -3, 2);
63+
ASSERT_GE(num, -3);
64+
ASSERT_LE(num, 5);
65+
ASSERT_NE(num, 2);
66+
}
67+
}

0 commit comments

Comments
 (0)