text stringlengths 1 2.12k | source dict |
|---|---|
c++, c++11, locking, wrapper, raii
auto stuff = writer_1->take_stuff();
writer_2->give_stuff(std::move(stuff));
// both (hidden!) locks automatically release at end of scope
Piece of cake.
Except…
Somewhere else in your program, a different, though very similar, transaction is happening. And, perchance, it happens to be coded like this:
writer_2 = data_2.writer();
writer_1 = data_1.writer();
// transaction happens here, locks auto-released at end of scope | {
"domain": "codereview.stackexchange",
"id": 43227,
"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++, c++11, locking, wrapper, raii",
"url": null
} |
c++, c++11, locking, wrapper, raii
// transaction happens here, locks auto-released at end of scope
And now, without warning or ceremony, you start discovering that your program crashes… sometimes. Not always! It’s the absolute worst kind of bug; the kind that only happens periodically, frustrating your attempts to drill down what’s causing it.
Well, obviously, there are only six lines of code shown here, so it has to be one of those. Won’t be that simple in a real program, of course.
To understand the bug, imagine we’re running that first code block in thread 1, and immediately after the first line, the OS scheduler puts the thread to sleep, and gives thread 2 its time slice. So, in thread 1, data_1 is locked, data_2 is not.
Now thread 2, running that second code block comes to life. It locks data_2, then tries to lock data_1… but, oh, it can’t. data_1 is already locked (by thread 1). No problem, this is a blocking wait, so we’ll just put thread 2 to sleep, and go back to thread 1.
Thread 1 wakes up, and tries to lock data_2… but, oh, it can’t. data_2 is already locked by thread 2.
Both threads are now blocked, with no hope of release. Deadlock.
And as bad as that is, the worst part by far, in my mind, is that when I look at both code blocks above, I see absolutely no indication that there is any locking going on there. I have absolutely no reason to suspect that a deadlock might occur in either block.
The actual deadlock problem is trivial to solve in C++17 and better, but even way back in C++11, it’s not that hard. Assuming all the data members of MemDB were public, you’d do something like this:
// thread 1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
std::lock(data_1.mtx, data_2.mtx);
auto lock_1 = std::lock_guard<std::mutex>{data_1.mtx, std::adopt_lock};
auto lock_2 = std::lock_guard<std::mutex>{data_2.mtx, std::adopt_lock};
auto stuff = data_1.data->take_stuff();
data_2.data->give_stuff(std::move(stuff));
// both (NOT hidden!) locks automatically release at end of scope | {
"domain": "codereview.stackexchange",
"id": 43227,
"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++, c++11, locking, wrapper, raii",
"url": null
} |
c++, c++11, locking, wrapper, raii
// both (NOT hidden!) locks automatically release at end of scope
// thread 2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
std::lock(data_2.mtx, data_1.mtx);
auto lock_2 = std::lock_guard<std::mutex>{data_2.mtx, std::adopt_lock};
auto lock_1 = std::lock_guard<std::mutex>{data_1.mtx, std::adopt_lock};
// transaction happens here, locks auto-released at end of scope
// C++17 solution //////////////////////////////////////////////
// thread 1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
auto lock = std::scoped_lock{data_1.mtx, data_2.mtx};
auto stuff = data_1.data->take_stuff();
data_2.data->give_stuff(std::move(stuff));
// lock automatically releases at end of scope
// thread 2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
auto lock = std::scoped_lock{data_2.mtx, data_1.mtx};
// transaction happens here, lock auto-released at end of scope | {
"domain": "codereview.stackexchange",
"id": 43227,
"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++, c++11, locking, wrapper, raii",
"url": null
} |
c++, c++11, locking, wrapper, raii
But, as you can see, that pretty much invalidates the entire point of MemDB and Accessor.
As I said, I get the impulse to hide the synchronization primitives… but I think that’s misguided. In both versions above—C++11 and C++17—the locking is clearly visible, and act as red flags so I know there are dangers here. If I want do do anything else in either transaction operation that might require another lock, I have a flashing indicator that I can’t just randomly do that lock anywhere I want… which might just lead to another deadlock. Instead, I can see, very, very visibly, that I need to also lock that lock right up at the top with the other locks. That’s why hiding locks is such a terrible idea.
And, by the way, this is just the tip of a very large iceberg. Because there isn’t just the possibility of multiple locks, there may be multiple lock types. For example, I may only want to attempt to lock the data, and if that fails because it’s already locked, I may decide to do something else instead. This may be particularly useful for idle saving; I may want to only save opportunistically, when the data isn’t being written elsewhere, so it’s basically a free action… but if the data is locked, then I may want to move on to something else. And it’s not just try-locking; there are tons of other useful patterns, like shared locking. In fact, shared locking for shared, mutable data can be an enormous optimization. But it’s not possible if you hide away the synchronization primitives. | {
"domain": "codereview.stackexchange",
"id": 43227,
"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++, c++11, locking, wrapper, raii",
"url": null
} |
c++, c++11, locking, wrapper, raii
The real moral here is that if you need locks—especially multiple locks—maybe you need to rethink your larger program design. That is why I think it is a good thing to leave all that locking and such clearly visible and out in the open. If you are worried about people screwing around with that mutable, shared data without properly locking it… then I’d say the problem you have to fix is either the mutable, shared data… or the incompetents you’re letting in your code base. Putting a band-aid on the mutable, shared data to hide it from view is not really a wise fix.
Aside from all that, there really doesn’t seem to be a lot of thought put into the design. Like, it’s riddled from top to bottom with weirdness and problems, big and small.
Like, why is save() private? That makes no sense at all. With your public API, I can’t unconditionally save whenever I want. I can only call idle(), which may not save if the timing is wrong. So if I’ve just done something important or am about to do something dangerous, you don’t want me to be sure the data is actually saved first?
And why is the save interval only settable at construction, and never possible to query? I might want to bump up the save interval at a critical portion of the program, but the rest of the time keep it very low, for efficiency reasons.
And why is the destructor virtual? Nothing else is virtual, so it’s impossible to modify any behaviour.
As for an example of a big problem, consider this:
auto data = MemDB<whatever>{...}; | {
"domain": "codereview.stackexchange",
"id": 43227,
"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++, c++11, locking, wrapper, raii",
"url": null
} |
c++, c++11, locking, wrapper, raii
auto reader = data.reader();
data.idle();
In other words: calling any two member functions of the class in the same scope is dangerous… sometimes. The culprit? Hidden locks. There doesn’t seem to be any way to make the class’s interface safe.
And so on and so forth. All in all, this just looks haphazardly slapped together with no real concern for making it actually usable in a real-world program. And, the fact that it just doesn’t work, which even the most basic testing would have revealed, testifies to how slapdash the whole thing is.
Code review
You are missing all the headers you need to make this work. You are also lacking any comments, documentation, usage examples, and—most importantly—tests. And, believe me, tests really would have helped you out here.
template <class DataType>
class MemDB {
std::mutex mtx;
Hard-coding the mutex type may make sense in C++11. But C++17 brought us the wonderful std::shared_mutex. For shared, mutable data that is rarely mutated but often read, a shared mutex can be a substantial performance improvement.
So it might make more sense to allow the mutex type to be parameterized.
DataType *data; | {
"domain": "codereview.stackexchange",
"id": 43227,
"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++, c++11, locking, wrapper, raii",
"url": null
} |
c++, c++11, locking, wrapper, raii
I’m not entirely sure why you chose to use a pointer here. It doesn’t really make much sense. Normally using a pointer in a case like this would mean either that the data is being managed elsewhere, or that you are opting to make the type cheaply-movable (at the expense of costing more to construct). But the second case can’t apply here, because having a mutex data member means the class is non-movable in any case.
So… is the intention that the data is externally managed? That would be something that the documentation would explain. None of the rest of the API helps; the constructor also takes a pointer, with no explanation whatsoever. Is it supposed to be an owning pointer? Does this class take over ownership? I mean, I guess not because the destructor doesn’t clean it up… but then again, the constructor doesn’t work either (more on that in a bit). It’s all a mystery.
This also causes weirdness and confusion with const. What does a const instance of MemDB mean? I mean, on the surface, it means nothing now, because you can’t do anything with it (because none of the operations are const). But normally const means “read-only”. So… shouldn’t a const MemDB allow reading, but not writing? Why not?
std::atomic_bool data_changed;
atomic<bool> is probably not the right type to use here, though your choice is limited prior to C++20. But in any case, you could get significant speed-ups on some hardware by using acquire-release semantics.
For example, in save(), instead of:
data_changed = false;
You’d do:
data_changed.store(false, std::memory_order_release);
And when reading, you’d do an acquire.
But as of C++20, rather than a bool, a better choice here would be an atomic flag. (The reason you need C++20 is that prior to C++20, there is no way to non-destructively test an atomic flag.)
time_t last_save_time, save_interval; | {
"domain": "codereview.stackexchange",
"id": 43227,
"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++, c++11, locking, wrapper, raii",
"url": null
} |
c++, c++11, locking, wrapper, raii
Using the C time functions here is wrong, for a very tricky and subtle reason. I mean, generally using C library stuff in C++ is wrong, for a number of reasons, usually boiling down to “the C library version is hot garbage, and that’s why we made a new version for C++”. But in this case, there are subtle issues that go beyond the usual.
Okay, first of all, let’s get all the usual “the C library is garbage” stuff out of the way. The C library does not define… anything… about time_t… other than that it’s an arithmetic type. You assume that it has a resolution granular enough for your save delay… but for all you know, the resolution might be days.
That also means that, for example, when you write something like time_t save_interval = 300, you’ve just written gibberish. You assume that means 300 seconds… but there’s no reason why it has to be. time_t could be a floating point type measured in years. That’s perfectly legal. Your default save interval may be in centuries.
You also seem to assume that time_t{0} is sometime “before” any other time. But… it doesn’t have to be. time_t{0} could very well be in the future. It could even be decades in the future.
Okay, okay, but maybe you’re assuming that POSIX standards apply, which require that time_t is an integer, the resolution is seconds, and the epoch is January whatever in the 70s. Everything solved, right?
Well… this is where the subtle part comes in. You see, you are using std::time(nullptr) to get the current time, and using that in arithmetic operations to compute durations. And that’s just fine… assuming the time doesn’t change.
You see, whatever clock std::time() is using, it isn’t guaranteed to be steady. That means that you might end up in a situation like this: | {
"domain": "codereview.stackexchange",
"id": 43227,
"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++, c++11, locking, wrapper, raii",
"url": null
} |
c++, c++11, locking, wrapper, raii
Some program/daemon/whatever is running, and save() is called, which gets the current time as 21 October, 2022, 7:28 AM.
The user realizes, oops, I accidentally travelled in time to the 80s, so the current time is actually 26 October, 1985, 1:21 AM. They reset the computer’s clock to match. (I joke, but such time shifts could easily happen when testing. It could also happen in legit operation when a machine is moved across time zones. I mean… maybe not a 35-year time shift, but, yanno.)
In that program/daemon/whatever, idle() now gets called, and discovers that it will be almost 40 years before it needs to save the data again.
Now you’re counting on the data being periodically saved… but it ain’t.
What you should be doing here is using a steady clock. And there’s been one in C++ since C++11.
That will fix all of your problems.
A steady clock will never regress. That’s the whole point of it. So you can always be 100% sure that if two calls to the clock say 10 seconds have passed, then 10 seconds have actually passed, and vice versa.
You want to specify 300 seconds? Then specify it: save_interval = 300s. Want 300 milliseconds? save_interval = 300ms. No mysteries here.
You want to be sure that the resolution is at least a second? Well, you can’t control that… but you can check it at compile time, which is better than nothing.
Also, you get the benefit of type safety, because it turns out that there is an important, but subtle difference between last_save_time and save_interval. One is a point in time. The other is a duration.
So, after dumping all the C library time keeping (I use the term loosely here) garbage, you might write this:
template <class DataType>
class MemDB {
// ... [snip] ...
std::steady_clock::time_point last_save_time;
std::steady_clock::duration save_interval; | {
"domain": "codereview.stackexchange",
"id": 43227,
"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++, c++11, locking, wrapper, raii",
"url": null
} |
c++, c++11, locking, wrapper, raii
std::steady_clock::time_point last_save_time;
std::steady_clock::duration save_interval;
// Note I just used the default duration for std::steady_clock for the
// save interval. You could use a specific duration type instead, like
// storing the duration as std::chrono::seconds, if you like.
// ... [snip] ...
void save() {
// ... [snip] ...
last_save_time = std::steady_clock::now();
}
// ... [snip] ...
MemDB(DataType* data, std::steady_clock::duration save_interval = std::chrono::seconds(300))
// ... [snip] ...
, last_save_time{std::steady_clock::now()}
, save_interval{save_interval}
{}
// ... [snip] ...
void idle() {
if (data_changed && ((std::steady_clock::now() - last_save_time) > save_interval))
save();
}
// ...
Which, as you can see, is more or less identical to the C library implementation… except better in every way.
(Note that if you really, really must use the C library, std::clock() may be a better option than std::time(). std::clock_t’s resolution and such will still be a mystery, but std::clock() may be steady. (I can’t confirm this, and don’t care to research it.))
void save() {
std::lock_guard<std::mutex> lock(mtx);
data->save();
data_changed = false;
last_save_time = time(0);
}
Not sure of the logic of making this function private. Why hide it?
MemDB(DataType *data, time_t save_interval = 300)
: data_changed(false), last_save_time(0), save_interval(save_interval)
{}
You have a pretty glaring bug here that should have been caught very easily had bothered not only to test your code, but even just compiling it with warnings on. See what’s missing?
virtual ~MemDB() {
save();
} | {
"domain": "codereview.stackexchange",
"id": 43227,
"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++, c++11, locking, wrapper, raii",
"url": null
} |
c++, c++11, locking, wrapper, raii
Eeeeh…. Okay, this seems pretty risky, if DataType::save() isn’t noexcept… and it’s hard to imagine that it could be.
In a realistic use case, I would expect that if saving the data failed, I’d get an error. That’s kinda important. If the save fails, and nothing informs me… that’s bad.
Okay, so DataType::save() throws on fail, which means I expect that if I manually save, via idle() or via reader()->save(), I can expect an exception. All good.
But that means this destructor is a time bomb. And worse, it’s a time bomb I can’t defuse.
Saving in the destructor isn’t necessarily bad if you give the use the option of doing it in two phases. If I want to be sure the data is properly saved, I would like to be able to do something like:
// assuming: auto data = MemDB<whatever>{&some_data};
// I've done everything I wanted to do, now time to clean up:
data.save(); // unconditionally save (idle() would be silly, because it might not save)
// data.~MemDB<whatever>(); // safe, because it won't try to save, because I already did
But there’s just no way to do this with the current API.
There’s no way to unconditionally save, because for some bizarre reason, save() is private. All I’ve got is idle() which may not save… and I’d have no way to know. (I mean, technically I could do data.reader()->save()… but that’s silly.)
There’s no way to stop the destructor from unnecessarily locking and saving and doing all the other time-checking gymnastics.
I mean, the fix is simple:
~MemDB()
{
if (data_changed.load(std::memory_order::acquire))
{
try
{
auto lock = std::scoped_lock{mtx};
data->save();
}
catch (...)
{
// do nothing
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43227,
"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++, c++11, locking, wrapper, raii",
"url": null
} |
c++, c++11, locking, wrapper, raii
(The try block is optional, but given that data->save() should be considered high-risk, I think it’s a good idea.)
void idle() {
if (data_changed && time(0)-last_save_time > save_interval)
save();
}
This is fine, I guess, but it would probably be handy to return a bool indicating whether or not a save actually happened. Why throw away useful information?
template <class AccessDataType>
class Accessor {
std::lock_guard <std::mutex> lock;
AccessDataType data;
So, the intention here is that whenever you have MemDB<T>, then AccessDataType is either T* or T const*. AccessDataType will never be U* or T& or anything else. Only T* or T const*.
So writing the type this way is too permissive. It’s also too verbose, because now you have to write MemDB<T>::AccessDataType<T const*> or MemDB<T>::AccessDataType<T*>. It would be much nicer to be able to write MemDB<T>::ReadAccess or MemDB<T>::WriteAccess.
An easy way to do this without code duplication is simply:
template <class DataType>
class MemDB
{
private:
template <bool Const>
class AccessT
{
private:
using DataTypePtr = std::conditional_t<Const, DataType const*, DataType*>;
std::lock_guard<std::mutex> lock;
DataTypePtr data;
AccessT(std::lock_guard<std::mutex> lock, DataTypePtr data)
: lock{std::move(lock)}
, data{data}
{}
public:
// Moveable.
AccessT(AccessT&&) noexcept = default;
auto operator=(AccessT&&) noexcept -> AccessT& = default;
// Non-copyable.
AccessT(AccessT const&) = delete;
auto operator=(AccessT const&) -> AccessT& = delete;
// If you're restricting *some* fundamental ops, it's a good idea to
// explicitly enable the ones you're allowing.
~AccessT() = default;
auto operator->() const noexcept -> DataTypePtr { return data; }
friend class MemDB;
}: | {
"domain": "codereview.stackexchange",
"id": 43227,
"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++, c++11, locking, wrapper, raii",
"url": null
} |
c++, c++11, locking, wrapper, raii
friend class MemDB;
}:
public:
using ReadAccess = AccessT<false>;
using WriteAccess = AccessT<true>;
auto reader() -> ReadAccess
{
return ReadAccess{std::lock_guard<std::mutex>{mtx}, data};
}
auto writer() -> WriteAccess
{
auto lock = std::lock_guard<std::mutex>{mtx};
data_changed.store(true, std::memory_order::release);
return WriteAccess{std::move(lock), data};
}
// etc.
};
The constructor for the inner class is private, so we make the outer class a friend. Now the only way for users to create one of the access objects is via the reader() or writer() function.
Note that I’ve enabled the move ops, which are implicitly deleted in your version. Things shouldn’t even compile using your version in C++11… what’s likely happening is (assuming you tried to compile it at all), you accidentally compiled it in C++17 mode, which mandates RVO, which means you could return your access objects without needing move ops. (Which, really, is the universe telling you to move on from C++11, and use more modern standards.) | {
"domain": "codereview.stackexchange",
"id": 43227,
"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++, c++11, locking, wrapper, raii",
"url": null
} |
c#
Title: SemaphoreSlim throttling
Question: I am trying to throttle SemaphoreSlim (i.e. allow initialization with a negative initialCount). A scenario could be that you're hitting an API and may notice degradation due to a server overload, so you'd want to start throttling requests to, say, 10 concurrent requests. However, you would be keeping count of the concurrent requests and know that at this time there are 25 concurrent requests, but you can't start a SemaphoreSlim(-15, 10).
I tried making an implementation that allows this, but I'm not 100% sure whether or not this is thread-safe and if it could be optimized (e.g. doing without the locks).
public class SemaphoreSlimThrottle : SemaphoreSlim
{
private volatile int _throttleCount;
private readonly object _lock = new object();
public SemaphoreSlimThrottle(int initialCount)
: base(initialCount)
{
}
public SemaphoreSlimThrottle(int initialCount, int maxCount)
: base(Math.Max(0, initialCount), maxCount)
{
_throttleCount = Math.Min(0, initialCount);
}
public new int CurrentCount => _throttleCount + base.CurrentCount;
public new int Release()
{
if (_throttleCount < 0)
{
lock (_lock)
{
if (_throttleCount < 0)
{
_throttleCount++;
return _throttleCount - 1;
}
}
}
return base.Release();
}
public new int Release(int releaseCount)
{
if (releaseCount < 1)
{
base.Release(releaseCount); // throws exception
}
if (releaseCount + _throttleCount <= 0)
{
lock (_lock)
{
if (releaseCount + _throttleCount <= 0)
{
_throttleCount += releaseCount;
return _throttleCount - releaseCount;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43228,
"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#",
"url": null
} |
c#
if (_throttleCount < 0)
{
lock (_lock)
{
if (_throttleCount < 0)
{
int output = CurrentCount;
base.Release(releaseCount + _throttleCount);
_throttleCount = 0;
return output;
}
}
}
return base.Release(releaseCount);
}
}
I've packaged this as a NuGet package with source available on GitHub.
Answer: First the "new" keyword. If casting this class back down to SemaphoreSlim then none of the code that has the new keyword would be used and just the base SemaphoreSlim code would execute.
Since we want the new code to execute I would suggest not inheriting from SemaphoreSlim but rather wrap it and then chain the calls down into the wrapped SemaphoreSlim. Something like, I didn't put in all the method this just an example of the approach.
public class SemaphoreSlimThrottle : IDisposable
{
private volatile int _throttleCount;
private readonly SemaphoreSlim _semaphore;
private readonly object _lock = new object();
private bool _turnOffThrottleCheck = false;
public SemaphoreSlimThrottle(int initialCount, int maxCount)
{
if (initialCount < 0)
{
_semaphore = new SemaphoreSlim(0, maxCount);
_turnOffThrottleCheck = true;
}
else
{
_semaphore = new SemaphoreSlim(initialCount, maxCount);
_turnOffThrottleCheck = true;
}
}
public WaitHandle AvailableWaitHandle => _semaphore.AvailableWaitHandle;
public int CurrentCount => _throttleCount + _semaphore.CurrentCount;
public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) => _semaphore.Wait(timeout, cancellationToken);
public int Release() => Release(1);
public void Dispose()
{
_semaphore.Dispose();
}
} | {
"domain": "codereview.stackexchange",
"id": 43228,
"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#",
"url": null
} |
c#
public void Dispose()
{
_semaphore.Dispose();
}
}
The other optimization that can be preformed is to not have the volatile field accessed once the "extra" have been used up. Also calling into the base outside the lock to have the locks short as possible.
Warning I did not test this code there could be typo or bugs in it - use as a gist
public int Release(int releaseCount)
{
// using bool property to avoid unnecessary volatile accesses in happy path
if (releaseCount < 1 || _turnOffThrottleCheck)
{
return _semaphore.Release(releaseCount);
}
int remainingCount;
var returnCount = 0;
lock (_lock)
{
var throttleCount = _throttleCount;
if (throttleCount == 0) // Different thread release all them just call into base
{
remainingCount = releaseCount;
}
else if (releaseCount + throttleCount < 0) // Releasing less than throttle just decrease
{
_throttleCount += releaseCount;
remainingCount = 0;
returnCount = throttleCount;
}
else // releasing all the throttles
{
_throttleCount = 0;
_turnOffThrottleCheck = true;
returnCount = throttleCount;
remainingCount = releaseCount + throttleCount;
}
}
// doing outside lock
if (remainingCount > 0) // call into base if more locks to be released
{
return _semaphore.Release(releaseCount) + returnCount;
}
return returnCount + _semaphore.CurrentCount;
}
This way we don't access _throttleCount in the happy path. We also release the lock and just call into the SemaphoreSlim outside the lock. | {
"domain": "codereview.stackexchange",
"id": 43228,
"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#",
"url": null
} |
programming-challenge, interview-questions, swift, tic-tac-toe
Title: Finding the winner of a tic-tac-toe game in Swift | {
"domain": "codereview.stackexchange",
"id": 43229,
"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": "programming-challenge, interview-questions, swift, tic-tac-toe",
"url": null
} |
programming-challenge, interview-questions, swift, tic-tac-toe
Question: Working on the problem Find Winner on a Tic Tac Toe Game, I took several hours longer than an artificial time constraint the site had for mock interview purposes. This leads me to wonder if my solution is needlessly complex or unclear. Curious to hear from others. The only part that would have to stay the same upon review is the function signature func tictactoe(_ moves: [[Int]]) -> String for the web editor to accept it.
class Solution {
func tictactoe(_ moves: [[Int]]) -> String {
let populatedBoard = populatedBoard(with: moves)
if let winner = checkWon(board: populatedBoard) {
return winner
}
if moves.count < 9 {
return "Pending"
} else {
return "Draw"
}
}
func populatedBoard(with moves: [[Int]]) -> [[Character]] {
var playerAMoves = [[Int]]()
var playerBMoves = [[Int]]()
var board: [[Character]] = [
[" ", " ", " "],
[" ", " ", " "],
[" ", " ", " "]
]
for (index, move) in moves.enumerated() where index % 2 == 0 {
playerAMoves.append(move)
}
for (index, move) in moves.enumerated() where index % 2 == 1 {
playerBMoves.append(move)
}
for move in playerAMoves {
board[move[0]][move[1]] = "X"
}
for move in playerBMoves {
board[move[0]][move[1]] = "O"
}
return board
}
func checkWon(board: [[Character]]) -> String? {
for index in 0...2 {
// Player won horizontally in a row.
if board[index][0] == board[index][1] && board[index][0] == board[index][2] {
if board[index][0] == "X" {
return "A"
} else if board[index][0] == "O" {
return "B"
}
} | {
"domain": "codereview.stackexchange",
"id": 43229,
"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": "programming-challenge, interview-questions, swift, tic-tac-toe",
"url": null
} |
programming-challenge, interview-questions, swift, tic-tac-toe
return "B"
}
}
// Player won vertically in a column.
if board[0][index] == board[1][index] && board[0][index] == board[2][index] {
if board[0][index] == "X" {
return "A"
} else if board[0][index] == "O" {
return "B"
}
}
}
// Player won diagonally between the top left and bottom right.
if board[0][0] == board[1][1] && board[0][0] == board[2][2] {
if board[0][0] == "X" {
return "A"
} else if board[0][0] == "O" {
return "B"
}
}
// Player won diagonally between the top right and bottom left.
if board[0][2] == board[1][1] && board[0][2] == board[2][0] {
if board[0][2] == "X" {
return "A"
} else if board[0][2] == "O" {
return "B"
}
}
return nil
}
} | {
"domain": "codereview.stackexchange",
"id": 43229,
"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": "programming-challenge, interview-questions, swift, tic-tac-toe",
"url": null
} |
programming-challenge, interview-questions, swift, tic-tac-toe
Answer: Your code is written clearly, and works correctly as far as I can see. Some things can be improved, in my opinion.
Avoid magic constants
The characters " ", "O", "X" are used as possible values for the values of a field on the board. That is error-prone because the compiler would not detect typographical errors. If you assign "0" instead of "O" to a field then the program will behave incorrectly, but it may take some time to find the error. It is better to use an enumeration instead:
enum Piece: Character, Equatable {
case empty = " "
case X = "X"
case O = "O"
}
The raw Character value is not needed for this challenge, but makes it easier to print the fields for debugging purposes. The conformance to Equatable makes it possible to compare fields easily.
The enumeration is more memory efficient (each value is stored as a single byte) and possibly more time efficient, because comparing bytes is easier than comparing Characters (which represent “extended grapheme clusters” in Swift and consist of one or more Unicode scalar values).
The other magic constants are "A", "B", "Draw" and "Pending", which are prescribed by the problem description. But we can still use an enumeration for the internal representation of the game state
enum State {
case pending
case draw
case win(Piece)
}
and translate that to the requested strings at a single place.
Avoid repetition
There are four occurrences of code like
if board[index][0] == "X" {
return "A"
} else if board[index][0] == "O" {
return "B"
}
in your program. One could make the checkWon() function return a piece ("X" or "O") instead, so that the translation to "A" and "B" is done only once in the calling function.
Use a type to represent the game board
With a struct TicTacToeBoard one can encapsulate the game logic in a (reusable) type, and hide the internal representation of the board from the outside. With a public interface like
struct TicTacToeBoard {
enum Piece { ... } | {
"domain": "codereview.stackexchange",
"id": 43229,
"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": "programming-challenge, interview-questions, swift, tic-tac-toe",
"url": null
} |
programming-challenge, interview-questions, swift, tic-tac-toe
enum Piece { ... }
enum State { ... }
subscript(row: Int, col: Int) -> Piece
func state() -> State
}
the main function becomes
func tictactoe(_ moves: [[Int]]) -> String {
var board = TicTacToeBoard()
for (index, move) in moves.enumerated() {
let isPlayerA = index.isMultiple(of: 2)
board[move[0], move[1]] = isPlayerA ? .X : .O
}
switch board.state() {
case .draw:
return "Draw"
case .pending:
return "Pending"
case .win(let piece):
return piece == .X ? "A" : "B"
}
}
which is easy to read and to understand. Without changing the algorithm of your logic to detect the winner, an implementation could look like this:
struct TicTacToeBoard {
enum Piece: Character, Equatable {
case empty = " "
case X = "X"
case O = "O"
}
enum State {
case pending
case draw
case win(Piece)
}
private var grid: [[Piece]] =
[
[.empty, .empty, .empty],
[.empty, .empty, .empty],
[.empty, .empty, .empty]
]
private var numMoves = 0
subscript(row: Int, col: Int) -> Piece {
get {
return grid[row][col]
}
set {
precondition(grid[row][col] == .empty)
grid[row][col] = newValue
numMoves += 1
}
}
func state() -> State {
for index in 0...2 {
// Player won horizontally in a row.
if grid[index][0] != .empty && grid[index][0] == grid[index][1]
&& grid[index][0] == grid[index][2] {
return .win(grid[index][0])
}
// Player won vertically in a column.
if grid[0][index] != .empty && grid[0][index] == grid[1][index]
&& grid[0][index] == grid[2][index] {
return .win(grid[index][0])
}
} | {
"domain": "codereview.stackexchange",
"id": 43229,
"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": "programming-challenge, interview-questions, swift, tic-tac-toe",
"url": null
} |
programming-challenge, interview-questions, swift, tic-tac-toe
// Player won diagonally between the top left and bottom right.
if grid[0][0] != .empty && grid[0][0] == grid[1][1]
&& grid[0][0] == grid[2][2] {
return .win(grid[0][0])
}
// Player won diagonally between the top right and bottom left.
if grid[0][2] != .empty && grid[0][2] == grid[1][1]
&& grid[0][2] == grid[2][0] {
return .win(grid[0][2])
}
return numMoves == 9 ? .draw : .pending
}
}
The use of string and character literals has been greatly reduced to a single place in the main function. Piece and State are “nested types” to that naming collisions with other code can not happen.
For debugging purposes you may want to add
extension TicTacToeBoard : CustomStringConvertible {
var description: String {
// I'll leave the implementation as an exercise ... :)
}
}
so that print(board) prints a nice representation of the game board, either in the code or in the debugger.
Performance improvements
Some suggestions which may make your code faster:
Define an array of all “winning combinations” which are then checked in a single loop, or:
Check for a winner after every move. That makes more checks, but you only have to check the row and the column changed by the last move, and possibly the diagonals. | {
"domain": "codereview.stackexchange",
"id": 43229,
"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": "programming-challenge, interview-questions, swift, tic-tac-toe",
"url": null
} |
c++, object-oriented, game, game-of-life, sfml
Title: Game of life with options like windows and board size
Question: Mainly I am looking for a better way to control the user input in the game loop which is in the first file. Since the nested switch with many case statements are a headache and error-prone.
Also, a way to extract the drawing process out of the Game class.
I am not looking for performance, but extendability.
Minor problems are also described in some of the comments.
The quick version of the logic:
You get a menu with 3 options (Play, Options, Exit), move with the arrows.
The Options allow you to change the size of the window and the board.
When you select Play or done with the settings you can LMB to make a cell alive, and RMB to pause/unpause.
Do you have any advice on handling user input and decoupling drawing logic?
// game.hpp
#include <cmath>
#include "board.hpp"
#include "menu.hpp"
#include "settings.hpp"
#include "SFML/Window.hpp"
class Game
{
Settings settings;
Board board = Board(&settings);
Menu menu = Menu(&settings);
public:
void runLoop()
{
// Some initial steps before starting the game
// also sometimes SFML forces you to use floating point numbers, so I have to cast often
float CELL_WIDTH = settings.WINDOW_WIDTH / static_cast<float>(settings.BOARD_WIDTH);
float CELL_HEIGHT = settings.WINDOW_HEIGHT / static_cast<float>(settings.BOARD_HEIGHT);
// flags like these feel like they belong as member variables, but also they are only used in this function so feels like a waste
bool rightClickPressed = false; // flag indicating weather to accept mouse inputs (left clicks); works like a pause button
bool playSelected = false;
// create the window
sf::RenderWindow window(sf::VideoMode(settings.WINDOW_WIDTH, settings.WINDOW_HEIGHT), "Game of Life");
window.setVerticalSyncEnabled(true);
window.clear(sf::Color::Black); | {
"domain": "codereview.stackexchange",
"id": 43230,
"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, game, game-of-life, sfml",
"url": null
} |
c++, object-oriented, game, game-of-life, sfml
// draw the menu
menu.draw(window);
window.display();
// The actual game loop
/*
* 1. handle user input
* 2. update game state
* 3. draw
*/
while (window.isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
// window closed
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyReleased:
switch (event.key.code)
{
case sf::Keyboard::Up:
menu.moveUp();
window.clear(sf::Color::Black);
menu.draw(window);
window.display();
break;
case sf::Keyboard::Down:
menu.moveDown();
window.clear(sf::Color::Black);
menu.draw(window);
window.display();
break; | {
"domain": "codereview.stackexchange",
"id": 43230,
"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, game, game-of-life, sfml",
"url": null
} |
c++, object-oriented, game, game-of-life, sfml
case sf::Keyboard::Enter:
switch (menu.getPressedItem())
{
case 0:
// Play button pressed
playSelected = true;
window.clear(sf::Color::Black);
window.display();
break;
case 1:
{
// Option button pressed -> waiting for new window size
window.clear(sf::Color::Black);
window.display();
int resolutionWidth;
int resolutionHeight;
std::cin >> resolutionWidth >> resolutionHeight;
int numCellsRow;
int numCellsCol;
std::cin >> numCellsRow >> numCellsCol;
if (numCellsRow < resolutionWidth && numCellsCol < resolutionHeight)
{
settings.WINDOW_HEIGHT = resolutionHeight;
settings.WINDOW_WIDTH = resolutionWidth;
settings.BOARD_HEIGHT = numCellsCol;
settings.BOARD_WIDTH = numCellsRow;
CELL_WIDTH = settings.WINDOW_WIDTH / static_cast<float>(settings.BOARD_WIDTH); // recalculating. narrowing conversion from float -> int
CELL_HEIGHT = settings.WINDOW_HEIGHT / static_cast<float>(settings.BOARD_HEIGHT);
}
window.setSize(sf::Vector2u(settings.WINDOW_WIDTH, settings.WINDOW_HEIGHT));
window.display();
board = Board(&settings); | {
"domain": "codereview.stackexchange",
"id": 43230,
"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, game, game-of-life, sfml",
"url": null
} |
c++, object-oriented, game, game-of-life, sfml
board = Board(&settings);
window.clear(sf::Color::Black);
playSelected = true;
// with this library you have to reset this view object, when you change the size of the window
sf::View view;
sf::Vector2<float> position(0, 0);
sf::Vector2<float> size(settings.WINDOW_WIDTH, settings.WINDOW_HEIGHT);
sf::Rect<float> re(position, size);
view.reset(static_cast<const sf::Rect<float> &>(re));
window.setView(view);
window.display();
break;
}
case 2:
// Exit selected
window.close();
break;
default:
break;
}
break;
default:
break;
}
// mouse pressed
case sf::Event::MouseButtonPressed:
{
if (playSelected)
{
if (event.mouseButton.button == sf::Mouse::Right)
{
rightClickPressed = !rightClickPressed;
break;
}
if (event.mouseButton.button == sf::Mouse::Left && !rightClickPressed)
{
window.clear(sf::Color::Black);
window.display();
auto n = static_cast<int>(floor(event.mouseButton.x / CELL_WIDTH));
auto m = static_cast<int>(floor(event.mouseButton.y / CELL_HEIGHT)); | {
"domain": "codereview.stackexchange",
"id": 43230,
"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, game, game-of-life, sfml",
"url": null
} |
c++, object-oriented, game, game-of-life, sfml
board.arr[m][n] = true; // the change !!!
// draw the cells
window.clear(sf::Color::Black);
for (auto i = 0; i < settings.BOARD_HEIGHT; ++i)
{
for (auto j = 0; j < settings.BOARD_WIDTH; ++j)
{
sf::RectangleShape rectangle(sf::Vector2f(CELL_WIDTH, CELL_HEIGHT));
rectangle.setPosition(sf::Vector2f(CELL_WIDTH * static_cast<float>(j), CELL_HEIGHT * static_cast<float>(i)));
if (!board.getCellValue(i, j))
rectangle.setFillColor(sf::Color(0, 0, 0)); //else it's white by default
window.draw(rectangle);
}
}
window.display();
break;
}
break;
}
break;
}
default:
break;
}
}
// game should be calculating/changing state
if (rightClickPressed && playSelected)
{
board.applyRulesOnce();
window.clear(sf::Color::Black);
// draw the cells
for (auto i = 0; i < settings.BOARD_HEIGHT; ++i)
for (auto j = 0; j < settings.BOARD_WIDTH; ++j)
{
sf::RectangleShape rectangle(sf::Vector2f(CELL_WIDTH, CELL_HEIGHT));
rectangle.setPosition(sf::Vector2f(CELL_WIDTH * static_cast<float>(j), CELL_HEIGHT * static_cast<float>(i))); | {
"domain": "codereview.stackexchange",
"id": 43230,
"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, game, game-of-life, sfml",
"url": null
} |
c++, object-oriented, game, game-of-life, sfml
if (!board.getCellValue(i, j)) // if is dead set color black (0, 0, 0)
rectangle.setFillColor(sf::Color(0, 0, 0)); //else it's white by default
window.draw(rectangle);
}
window.display();
// end the current frame
}
}
}
};
I am alright with the files below, but still here for completeness
// board.hpp
#ifndef BOARD_HPP
#define BOARD_HPP
#include <vector>
#include <iostream>
#include "settings.hpp"
class Board
{
friend class Game;
Settings* settings;
std::vector<std::vector<bool>> arr;
private:
// whether the value of the cell should change
bool checkNeighbours(const int& i, const int& j, const bool& value)
{
auto aliveCount = 0;
for (auto ii = i - 1; ii <= i + 1; ++ii)
{
for (auto jj = j - 1; jj <= j + 1; ++jj)
{
if (ii == i && jj == j) // don't check the cell itself
continue;
if (isSafe(ii, jj))
{
if (arr[ii][jj])
++aliveCount; // you can break early if > 3
}
}
}
if (value && (aliveCount == 2 || aliveCount == 3)) // rule 1
return false;
if (!value && (aliveCount == 3)) // rule 2
return true;
return value; // else change if alive or stay if dead
}
public:
Board(Settings* settings) : settings(settings), arr(std::vector<std::vector<bool>>(settings->BOARD_HEIGHT, std::vector<bool>(settings->BOARD_WIDTH, false)))
{}
bool getCellValue(const int& i, const int& j) const
{
return arr.at(i).at(j);
} | {
"domain": "codereview.stackexchange",
"id": 43230,
"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, game, game-of-life, sfml",
"url": null
} |
c++, object-oriented, game, game-of-life, sfml
bool getCellValue(const int& i, const int& j) const
{
return arr.at(i).at(j);
}
/*
* 1. Any live cell with two or three live neighbours survives.
2. Any dead cell with three live neighbours becomes a live cell.
3. All other alive cells die in the next generation. Similarly, all other dead cells stay dead
*/
void applyRulesOnce()
{
Board nextState(settings);
for (auto i = 0; i < settings->BOARD_HEIGHT; ++i)
{
for (auto j = 0; j < settings->BOARD_WIDTH; ++j)
{
if (checkNeighbours(i, j, arr[i][j]))
{
if (nextState.arr[i][j] == arr[i][j])
nextState.arr[i][j] = !nextState.arr[i][j];
}
else if (nextState.arr[i][j] != arr[i][j])
nextState.arr[i][j] = !nextState.arr[i][j];
}
}
*this = std::move(nextState);
}
bool isSafe(const int& i, const int& j)
{
return (i >= 0 && i < settings->BOARD_HEIGHT &&
j >= 0 && j < settings->BOARD_WIDTH);
}
};
#endif // BOARD_HPP
//menu.hpp
#ifndef MENU_HPP
#include <array>
#include <iostream>
#include "settings.hpp"
#include "SFML/Graphics.hpp"
constexpr int MAX_NUMBER_OF_ITEMS = 3;
class Menu
{
public:
Menu(Settings* settings)
{
if (!font.loadFromFile("../../../fonts/arial.ttf"))
{
std::cout << "font error\n";
}
data[0].setFont(font);
data[0].setFillColor(sf::Color::Red);
data[0].setString("Play");
data[0].setPosition(sf::Vector2f(settings->WINDOW_WIDTH / 2.F, settings->WINDOW_HEIGHT / (MAX_NUMBER_OF_ITEMS + 1) * 1.F));
data[1].setFont(font);
data[1].setFillColor(sf::Color::White);
data[1].setString("Options");
data[1].setPosition(sf::Vector2f(settings->WINDOW_WIDTH / 2.F, settings->WINDOW_HEIGHT / (MAX_NUMBER_OF_ITEMS + 1) * 2.F)); | {
"domain": "codereview.stackexchange",
"id": 43230,
"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, game, game-of-life, sfml",
"url": null
} |
c++, object-oriented, game, game-of-life, sfml
data[2].setFont(font);
data[2].setFillColor(sf::Color::White);
data[2].setString("Exit");
data[2].setPosition(sf::Vector2f(settings->WINDOW_WIDTH / 2.F, settings->WINDOW_HEIGHT / (MAX_NUMBER_OF_ITEMS + 1) * 3.F));
selectedItemIndex = 0;
}
void draw(sf::RenderWindow& window)
{
for (auto& el : data)
window.draw(el);
}
void moveUp()
{
if (selectedItemIndex - 1 >= 0)
{
data[selectedItemIndex].setFillColor(sf::Color::White);
selectedItemIndex--;
data[selectedItemIndex].setFillColor(sf::Color::Red);
}
}
void moveDown()
{
if (selectedItemIndex + 1 < MAX_NUMBER_OF_ITEMS)
{
data[selectedItemIndex].setFillColor(sf::Color::White);
selectedItemIndex++;
data[selectedItemIndex].setFillColor(sf::Color::Red);
}
}
int getPressedItem() const { return selectedItemIndex; }
private:
sf::Font font;
std::array<sf::Text, MAX_NUMBER_OF_ITEMS> data;
int selectedItemIndex;
};
#endif // MENU_HPP
A simple Settings class
#ifndef SETTINGS_HPP
#define SETTINGS_HPP
struct Settings
{
int WINDOW_WIDTH = 800;
int WINDOW_HEIGHT = 800;
int BOARD_WIDTH = 10;
int BOARD_HEIGHT = 10;
};
#endif // SETTINGS_HPP
And this is how I run it.
#include "game.hpp"
int main()
{
Game game;
game.runLoop();
return 0;
}
Update: Here is a link to a repository (the branch - "latest" is this version of the project)
Answer: Frames
Simulations or games usually have the concept of a "frame" within their main loop, which is used interchangeably to refer to the process of preparing a single image, and for that image itself. Each frame involves executing the following stages:
while (true)
{
getInput();
update();
render();
} | {
"domain": "codereview.stackexchange",
"id": 43230,
"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, game, game-of-life, sfml",
"url": null
} |
c++, object-oriented, game, game-of-life, sfml
Both getInput() and update() update the simulation data in preparation for rendering a frame, and there might be some overlap between the two, but the general idea there is to separate "update logic responding to user input" from "update logic that happens every frame, or at a set time".
To be as responsive as possible, we generally want to avoid blocking on input (e.g. waiting for std::cin), and we want to process input events as soon as we get them. For the Game of Life, we probably want to do the update logic at fixed timesteps (i.e. check a timer every frame, and then update when necessary), and do the input processing and rendering every frame.
States
We also want to be able to switch between different modes or "states", in which we do quite different things at each stage of the main loop. So in the code above, we'd have three separate states, each with their own main loop:
void doMainMenu()
{
while (true)
{
// ... do frame
}
}
void doOptions()
{
while (true)
{
// ... do frame
}
}
void doGameOfLife()
{
while (true)
{
// ... do frame
}
}
We then need a way to switch between the states, without nesting or introducing extra complexity. One way of doing this is to write a "state factory" class. Each state returns a "state factory", which is just a function that, when called, begins the next state. This is an indirect way of calling the next state function, so we don't have an ever-increasing stack of function calls.
So our factory class looks like this:
struct StateFactory
{
std::function<StateFactory(sf::RenderWindow&)> m_function;
};
and our main() function would then do this:
auto factory = StateFactory{ [] (sf::RenderWindow& window) { return doMainMenu(window); } };
while (factory.m_function)
factory = factory.m_function(window); | {
"domain": "codereview.stackexchange",
"id": 43230,
"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, game, game-of-life, sfml",
"url": null
} |
c++, object-oriented, game, game-of-life, sfml
while (factory.m_function)
factory = factory.m_function(window);
So to switch from the main menu state to the game state, we'd return a function that calls the game state:
StateFactory doMainMenu(sf::RenderWindow& window)
{
auto menu = Menu(window.getSize()); // we can use your `Menu` class as a local variable here.
while (true)
{
// get input
{
auto event = sf::Event();
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
return { }; // done! return a state factory with no "next state" function
if (event.type == sf::Event::MouseButtonPressed) // or whatever...
return { [] (sf::RenderWindow& window) { return doGameOfLife(window); } }; // when mouse is pressed, go to game state
}
}
// ... update
// ... draw
}
}
StateFactory doGameOfLife(sf::RenderWindow& window)
{
// ...
}
In this way, we can keep the logic for our different "states" entirely separate, which makes things much simpler.
(We might want to pass the settings between states as well as the window).
Review
So to look at the actual code!
Game:
As mentioned, the menu, options, and game logic should be split up.
Member variables should also be split up: we don't need the menu to exist when we're running the game, and we don't need the board to exist when we're in the menu.
The game logic could be placed in a function doGameOfLife(), with the board as a local variable inside it - we don't really need a class here at all.
We could add a timer to run the update logic at fixed intervals, so the simulation is easier to see, e.g.:
using clock = std::chrono::steady_clock;
auto lastUpdate = clock::now();
auto const updatePeriod = std::chrono::milliseconds(500);
while (true)
{
// ... get input | {
"domain": "codereview.stackexchange",
"id": 43230,
"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, game, game-of-life, sfml",
"url": null
} |
c++, object-oriented, game, game-of-life, sfml
while (true)
{
// ... get input
// update
{
auto const now = clock::now();
if (now - lastUpdate >= updatePeriod)
{
lastUpdate = now;
// UPDATE STEP!
std::cout << "update!\n";
}
}
// ... render
}
The code is much cleaner if we do the rendering / drawing as a separate phase every frame, instead of mixing it in with the update logic (we could perhaps use a boolean flag to avoid inefficiency and redraw only when necessary).
Board:
We should avoid using friend classes. It looks like we need a setCellValue function to go with getCellValue. The normal C++ approach for something like this is to use overloading:
bool& cell(std::size_t x, std::size_t y) { return arr.at(x).at(y); }
bool const& cell(std::size_t x, std::size_t y) const { return arr.at(x).at(y); }
But somehow the C++ Standards Comittee still haven't fixed vector<bool>... So we need separate get and set functions:
void setCell(std::size_t x, std::size_t y, bool value) { arr.at(x).at(y) = value; }
bool getCell(std::size_t x, std::size_t y) { return arr.at(x).at(y); }
Note the use of the correct index type for std::vector, which is std::size_t. We should also pass small POD types like int or std::size_t by value - passing by reference is just an unnecessary complication (even if it probably gets optimized to the same thing by the compiler). Note that the names x and y convey more meaning than i and j.
We generally want to avoid "vectors of vectors" - it adds unnecessary overhead (storing an extra size with each inner vector), and may spread data out in memory, which can make accessing it slower. Instead, we can store a flat vector of (width * height) size:
std::size_t width, height;
std::vector<bool> board;
and calculate the indices of the cells using the formula: index = y * width + x inside the setCell and getCell functions.
Menu: | {
"domain": "codereview.stackexchange",
"id": 43230,
"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, game, game-of-life, sfml",
"url": null
} |
c++, object-oriented, game, game-of-life, sfml
Menu:
We don't need to pass the Settings class in the constructor, just the window size passed in as an sf::Vector2f. Thus we avoid including the settings header.
The positioning could definitely be neater. I'm just going to point out that we can get the size of an sf::Text using text.getLocalBounds().width and text.getLocalBounds().height. We can also get a reasonable height for a line of text by doing font.getLineSpacing(text.getCharacterSize()). Either of these could help to lay out the buttons more neatly.
Options:
Using std::cin is bad! It makes our app unresponsive to normal input and means we can't render anything.
Could provide a simple widget with a plus and minus button to change the size, e.g.: "Simulation size: [-] 20 [+]".
This could be part of the menu state, or a similar but separate state.
One other thing: it's a good idea to put all your code into a namespace. :) | {
"domain": "codereview.stackexchange",
"id": 43230,
"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, game, game-of-life, sfml",
"url": null
} |
python, python-3.x, regex
Title: Breaking Bad name generator
Question: I've created a script to print all periodic table symbolic permutations of a string. As seen in the opening credits of each episode of Breaking Bad:
© 2010-2022 AMC Networks Entertainment LLC.
Aaron Paul contains the symbol for Argon (Ar) which is highlighted green, and overwrites the casing on the original (ar).
I have made this just for fun, and given the script the following restrictions/scope (which are inherited from the TV show):
Text replaced by an element's symbol must:
Be green
Have the casing of the element as seen in the periodic table (H,Ar)
There is only one replacement per permutation A[Ar]on and Aaro[N] are seperate. I.e, don't have any more than 1 symbol in the string at a time
Case is ignored for matches (h & H should both be replaced with a green H)
And an extra that's not in the show:
Print the element's name afterwards
Example output: A[Ar]on - Argon
This is what I have created on a basic level (no user input or text entering loops).
import colorama as col
import re | {
"domain": "codereview.stackexchange",
"id": 43231,
"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, python-3.x, regex",
"url": null
} |
python, python-3.x, regex
data = {'H': 'Hydrogen', 'He': 'Helium', 'Li': 'Lithium', 'Be': 'Beryllium', 'B': 'Boron', 'C': 'Carbon', 'N': 'Nitrogen', 'O': 'Oxygen', 'F': 'Fluorine', 'Ne': 'Neon', 'Na': 'Sodium', 'Mg': 'Magnesium', 'Al': 'Aluminium', 'Si': 'Silicon', 'P': 'Phosphorus', 'S': 'Sulphur', 'Cl': 'Chlorine', 'Ar': 'Argon', 'K': 'Potassium', 'Ca': 'Calcium', 'Sc': 'Scandium', 'Ti': 'Titanium', 'V': 'Vanadium', 'Cr': 'Chromium', 'Mn': 'Manganese', 'Fe': 'Iron', 'Co': 'Cobalt', 'Ni': 'Nickel', 'Cu': 'Copper', 'Zn': 'Zinc', 'Ga': 'Gallium', 'Ge': 'Germanium', 'As': 'Arsenic', 'Se': 'Selenium', 'Br': 'Bromine', 'Kr': 'Krypton', 'Rb': 'Rubidium', 'Sr': 'Strontium', 'Y': 'Yttrium', 'Zr': 'Zirconium', 'Nb': 'Niobium', 'Mo': 'Molybdenum', 'Tc': 'Technetium', 'Ru': 'Ruthenium', 'Rh': 'Rhodium', 'Pd': 'Palladium', 'Ag': 'Silver', 'Cd': 'Cadmium', 'In': 'Indium', 'Sn': 'Tin', 'Sb': 'Antimony', 'Te': 'Tellurium', 'I': 'Iodine', 'Xe': 'Xenon', 'Cs': 'Caesium', 'Ba': 'Barium', 'La': 'Lanthanum', 'Ce': 'Cerium', 'Pr': 'Praseodymium', 'Nd': 'Neodymium', 'Pm': 'Promethium', | {
"domain": "codereview.stackexchange",
"id": 43231,
"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, python-3.x, regex",
"url": null
} |
python, python-3.x, regex
'Sm': 'Samarium', 'Eu': 'Europium', 'Gd': 'Gadolinium', 'Tb': 'Terbium', 'Dy': 'Dysprosium', 'Ho': 'Holmium', 'Er': 'Erbium', 'Tm': 'Thulium', 'Yb': 'Ytterbium', 'Lu': 'Lutetium', 'Hf': 'Hafnium', 'Ta': 'Tantalum', 'W': 'Tungsten', 'Re': 'Rhenium', 'Os': 'Osmium', 'Ir': 'Iridium', 'Pt': 'Platinum', 'Au': 'Gold', 'Hg': 'Mercury', 'Tl': 'Thallium', 'Pb': 'Lead', 'Bi': 'Bismuth', 'Po': 'Polonium', 'At': 'Astatine', 'Rn': 'Radon', 'Fr': 'Francium', 'Ra': 'Radium', 'Ac': 'Actinium', 'Th': 'Thorium', 'Pa': 'Protactinium', 'U': 'Uranium', 'Np': 'Neptunium', 'Pu': 'Plutonium', 'Am': 'Americium', 'Cm': 'Curium', 'Bk': 'Berkelium', 'Cf': 'Californium', 'Es': 'Einsteinium', 'Fm': 'Fermium', 'Md': 'Mendelevium', 'No': 'Nobelium', 'Lr': 'Lawrencium', 'Rf': 'Rutherfordium', 'Db': 'Dubnium', 'Sg': 'Seaborgium', 'Bh': 'Bohrium', 'Hs': 'Hassium', 'Mt': 'Meitnerium', 'Ds': 'Darmstadtium', 'Rg': 'Roentgenium', 'Cn': 'Copernicium', 'Nh': 'Nihonium', 'Fl': 'Flerovium', 'Mc': 'Moscovium', 'Lv': 'Livermorium', 'Ts': 'Tennessine', 'Og': 'Oganesson'} | {
"domain": "codereview.stackexchange",
"id": 43231,
"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, python-3.x, regex",
"url": null
} |
python, python-3.x, regex
user_input = "Aaron"
for symbol, name in data.items():
for i in [x.start() for x in re.finditer(symbol, user_input, re.IGNORECASE)]:
temp = list(user_input)
temp[i:i+len(symbol)] = col.Fore.GREEN + symbol + col.Fore.RESET
# [V]ince - Vanadium
print(f"{''.join(temp)} - {name}")
How could I improve on the cleanliness and efficiency of the text substitution? As I'm literally just putting it in a list and replacing with re index matches:
temp = list(user_input)
temp[i:i+len(symbol)] = col.Fore.GREEN + symbol + col.Fore.RESET
And what other general constructive comments can be made about my attempt? | {
"domain": "codereview.stackexchange",
"id": 43231,
"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, python-3.x, regex",
"url": null
} |
python, python-3.x, regex
And what other general constructive comments can be made about my attempt?
Answer: Define a proper constant for the elements. The name data is both vague
and improperly formatted for a constant. One option would be something like
ELEMENTS.
Put your code in functions. Even for small scripts.
Parameterize the script. Take the name from the command line.
Don't use an extra layer of iteration as a workaround for a simple assignment.
Drop the innermost iteration and just use this instead: i = x.start(). [And after some further edits, you might not need i at all.]
You don't need to listify the name. Python strings are already sequences,
so converting from string to list doesn't help in this situation. Just grab
the substrings you need and glue everything together.
Don't print in the function responsible for core computation. The function
to compute the breaking-bad names already has a primary job. Leave the printing
to a different part of the program. Among other benefits, this type of discipline
aids testing.
Optionally, shift some of the calculation out of the innermost
loop. Values derived from the symbol can be computed at
the level of the outer loop, and making this change has some
benefits in terms of readability and to instill good habits. In
a different context -- where performance is a consideration --
you don't want to repeat calculations than can be done once at
a higher level.
import colorama as col
import sys
import re
ELEMENTS = {...}
def main(args):
name = args[0]
for display, element in breaking_bad_names(name):
print(display, element)
def breaking_bad_names(name):
for symbol, element in ELEMENTS.items():
green_sym = col.Fore.GREEN + symbol + col.Fore.RESET
for m in re.finditer(symbol, name, re.IGNORECASE):
display = name[0 : m.start()] + green_sym + name[m.end() :]
yield (display, element)
if __name__ == '__main__':
main(sys.argv[1:]) | {
"domain": "codereview.stackexchange",
"id": 43231,
"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, python-3.x, regex",
"url": null
} |
python, object-oriented, sharepoint
Title: List all files and folders within a SharePoint document library
Question: Background:
I have made two classes. The first is SharePointHandler, and contains a few functions that I intend on using to automate some actions on SharePoint. A simplified version of this is shown below:
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.folders.folder import Folder
from office365.sharepoint.files.file import File
from path_handler import PathHandler
class SharePointHandler(object):
def __init__(self, username:str, password:str, company_site:str) -> None:
self.username = username
self.password = password
self.company_site = company_site
self.client_context:ClientContext
self.create_client_context()
def create_client_context(self) -> None:
try:
ctx_authorization = AuthenticationContext(self.company_site)
ctx_authorization.acquire_token_for_user(self.username, self.password)
self.client_context = ClientContext(self.company_site, ctx_authorization)
print(f"\nSharePoint authentication successful.")
except Exception as e:
print(f"\nSharePoint authentication failed. The following exception has occured:\n{e}\n")
def map_folder(self, to_map:PathHandler) -> tuple[list[PathHandler], list[PathHandler]]:
file_handler_list, folder_handler_list = [], []
def enum_folder(parent_folder):
parent_folder.expand(["Files", "Folders"]).get().execute_query()
for file in parent_folder.files: # In the event that the directory ends in a file.
file_handler_list.append(PathHandler(to_map.get_scheme_and_root_from_absolute() + file.serverRelativeUrl)) | {
"domain": "codereview.stackexchange",
"id": 43232,
"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, object-oriented, sharepoint",
"url": null
} |
python, object-oriented, sharepoint
for folder in parent_folder.folders: # In the event that the directory ends in a folder.
folder_handler_list.append(PathHandler(to_map.get_scheme_and_root_from_absolute() + folder.serverRelativeUrl))
enum_folder(folder)
root_folder = self.client_context.web.get_folder_by_server_relative_url(to_map.get_relative_from_absolute())
enum_folder(root_folder)
print(f"\nMapping complete. {len(file_handler_list)} file/s + {len(folder_handler_list)} folder/s found.")
return file_handler_list, folder_handler_list
The first function create_client_context creates a ClientContext instance using the user credentials (necessary for accessing the SharePoint site). The second function map_folder is used to recursively append all PathHandler instances of all files and folders to their own lists.
The second class is PathHandler, which I've made in an attempt to simplify the way that I make alterations to the urls / local paths as I need them, eg: sometimes I'll need a relative url exclusive of scheme and site name. This class is shown below:
import os
import urllib.parse
from pathlib import Path
class PathHandler(object):
def __init__(self, absolute_path:str) -> None:
self.absolute_path = absolute_path
def get_filename_from_absolute(self) -> str: # COMPLETE ✓
parsed_url = urllib.parse.urlparse(self.absolute_path)
return os.path.basename(parsed_url.path)
def strip_filename(self) -> str: # COMPLETE ✓
return self.absolute_path[:-len(self.get_filename_from_absolute())]
def get_relative_from_absolute(self) -> str: # COMPLETE ✓
parsed_url = urllib.parse.urlparse(self.absolute_path)
return parsed_url.path
def get_parent_folder_from_absolute(self) -> str: # COMPLETE ✓
parsed_url = urllib.parse.urlparse(self.absolute_path)
return os.path.dirname(parsed_url.path) | {
"domain": "codereview.stackexchange",
"id": 43232,
"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, object-oriented, sharepoint",
"url": null
} |
python, object-oriented, sharepoint
return os.path.dirname(parsed_url.path)
def get_scheme_and_root_from_absolute(self) -> str: # COMPLETE ✓ - Not to be used for local paths
parsed_url = urllib.parse.urlparse(self.absolute_path)
return f"{parsed_url.scheme}://{parsed_url.netloc}"
def convert_to_absolute_local(self, local_root:str, global_root:str) -> str: # COMPLETE ✓
temporary_path = local_root + self.absolute_path[len(global_root):]
return temporary_path.replace("//", os.sep)
def convert_to_absolute_global(self, local_root:str, global_root:str) -> str: # COMPLETE ✓
return global_root + self.absolute_path[len(local_root):].replace(os.sep, "//")
My question:
The above scripts tie into quite a large project, and I am trying to simplify this by incorporating OOP. However, I've not worked in an OOP manner before, and am concerned that PathHandler exists unnecessarily. Many of my SharePointHandler methods can be simplified to return strings, but to remain consistent, I am encouraged to return instances of PathHandler.
Is this PathHandler class indeed adding unnecessary complexity to my code? Should I simply remove the class and use the functions as typical helper functions and make the necessary adjustments to the method inputs at the start of a function call? | {
"domain": "codereview.stackexchange",
"id": 43232,
"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, object-oriented, sharepoint",
"url": null
} |
python, object-oriented, sharepoint
Answer: Since you are using type hints you must be using Python 3 (good). So don't inherit from object.
Ideally all members of a class are first set in the constructor. So make your create_client_context return a ClientContext rather than mutating self.
Your prints should not exist in create_client_context. You can keep your try if you narrow Exception down to the actual exception type from the client context and rethrow using a custom application domain exception; or else don't try/except at all.
Recursing on enum_folder is risky. It's possible to blow the (fairly shallow) Python stack on a folder nesting level that is too deep.
You might want to use the built-in logger support from map_folder, but don't print.
You don't use password outside of create_client_context, so for safety's sake don't store it on self.
Move your urllib.parse.urlparse to a centralised call that occurs in the constructor of your PathHandler and stores the result on self, something like
def __init__(self, absolute_path:str) -> None:
self.absolute_path = absolute_path
self.parsed_url = urllib.parse.urlparse(self.absolute_path)
Delete your # COMPLETE ✓. All code should be considered complete if it doesn't throw. If you want to mark something incomplete, then raise a NotImplementedError (this is a reasonable way to write out skeletons). | {
"domain": "codereview.stackexchange",
"id": 43232,
"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, object-oriented, sharepoint",
"url": null
} |
java, programming-challenge, fizzbuzz, java-8
Title: The FizzBuzz challenge in Java 8 written in a short, readable and interesting way
Question: I decided to take on the FizzBuzz challenge with as twist that I would use Java 8 concepts to make it a bit modular, yet still let it be a short, readable and understandable program.
This in contrary to some gem I found on the net: FizzBuzzEnterpriseEdition
The problem description:
Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz"
Here's my code:
public class FizzBuzz {
private static Stream<String> fizzBuzz(final int min, final int max) {
if (min < 0) {
throw new IllegalArgumentException("min is negative: min = " + min);
}
if (min > max) {
throw new IllegalArgumentException("min > max: min = " + min + " / max = " + max);
}
return IntStream.rangeClosed(min, max)
.mapToObj(FizzBuzz::fizzBuzzify);
}
private static String fizzBuzzify(final int value) {
StringBuilder stringBuilder = new StringBuilder();
boolean toDefault = true;
if (value % 3 == 0) {
stringBuilder.append("Fizz");
toDefault = false;
}
if (value % 5 == 0) {
stringBuilder.append("Buzz");
toDefault = false;
}
return (toDefault) ? String.valueOf(value) : stringBuilder.toString();
}
public static void main(String[] args) {
fizzBuzz(1, 100).forEach(System.out::println);
}
} | {
"domain": "codereview.stackexchange",
"id": 43233,
"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, fizzbuzz, java-8",
"url": null
} |
java, programming-challenge, fizzbuzz, java-8
I'm still looking for a nicer way to write fizzBuzzify, my intention however is to not hardcode the if (value % 15 == 0) similarly if (value % 3 == 0 && value % 5 == 0), because it creates a sort of illogical operation precedence, being that you absolutely need to write the if (value % 15 == 0) case up front, followed by the 3-case and the 5-case (or vica versa).
Answer: A guideline that I use for deciding on a StringBuilder or not is that it depends on whether I know beforehand how many times it will be used or not. I believe I've come across this recommendation on some MSDN page once but I'm not entirely sure.
In your case, you know that there are only two possible uses of your StringBuilder, and that there are no values added inside a loop, so I would use normal string concatenation:
Now you can also change your code a little to what I consider more easily interpretable:
private static String fizzBuzzify(final int value) {
String result = "";
if (value % 3 == 0) {
result += "Fizz";
}
if (value % 5 == 0) {
result += "Buzz";
}
return result.length() > 0 ? result : Integer.toString(value);
} | {
"domain": "codereview.stackexchange",
"id": 43233,
"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, fizzbuzz, java-8",
"url": null
} |
c++, programming-challenge, c++17
Title: Find local maxima of a sequence
Question: I'm well versed in Python and Java, am just starting out with C++. Am enjoying the language and would really appreciate feedback on this solution.
kata:
Return positions and values of the "peaks" (or local maxima) of a numeric array
For example, the array arr = [0, 1, 2, 5, 1, 0] has a peak at position 3 with a value of 5 (since arr[3] equals 5).
The output will be returned as an object with two properties: pos and peaks. Both of these properties should be arrays. If there is no peak in the given array, then the output should be {pos: [], peaks: []}.
Example: pickPeaks([3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3]) should return {pos: [3, 7], peaks: [6, 3]} (or equivalent in other languages)
All input arrays will be valid integer arrays (although it could still be empty), so you won't need to validate the input.
The first and last elements of the array will not be considered as peaks (in the context of a mathematical function, we don't know what is after and before and therefore, we don't know if it is a peak or not).
Also, beware of plateaus !!! [1, 2, 2, 2, 1] has a peak while [1, 2, 2, 2, 3] does not. In case of a plateau-peak, please only return the position and value of the beginning of the plateau. For example: pickPeaks([1, 2, 2, 2, 1]) returns {pos: [1], peaks: [2]} (or equivalent in other languages)
Have fun!
Solution:
#include <vector>
#include <iostream>
struct PeakData {
std::vector<int> pos;
std::vector<int> peaks;
};
PeakData pick_peaks(const std::vector<int> &v) {
PeakData result;
for (auto& j : v) {
std::cout << j;
}
std::cout << std::endl;
bool plateau = false;
unsigned long plateau_start = 0;
for(unsigned long i = 1; i < (v.size() - 1); i++) {
// if we are going down hill, skip.
if ( v[i] < v[i-1] ) {
continue;
}
if ( v[i] == v[i-1] && !plateau ) {
continue;
} | {
"domain": "codereview.stackexchange",
"id": 43234,
"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++, programming-challenge, c++17",
"url": null
} |
c++, programming-challenge, c++17
if ( v[i] == v[i-1] && !plateau ) {
continue;
}
if( v[i] > v[i+1] ) {
result.pos.push_back(plateau ? plateau_start : i);
result.peaks.push_back(v[i]);
plateau = false;
continue;
}
if ( ( v[i] == v[i+1] ) && ! plateau) {
plateau_start = i;
plateau = true;
continue;
}
if ( v[i] < v[i+1] ) {
plateau = false;
}
}
return result;
}
Answer: Style:
In C++ (unlike C) we place the type modifers with the type.
PeakData pick_peaks(const std::vector<int> &v) {
Normally I would expect it to look like this:
PeakData pick_peaks(const std::vector<int>& v) {
^^^
Personally, I like the const on the right (though nobody is going to complain about the left either).
PeakData pick_peaks(std::vector<int> const& v) {
The reason I like the right is that const binds to the type on the left, unless it is on the very left hand end then it binds right. To make things easier to read when you have multiple const always place it on the right side of the thing that is consta.
char const * const t; // ie. This
const char * const t; // rather than this (though they mean the same).
Const correctness:
Mark things const (especially references) if you don't plan on modifying the item as a hint to the compiler.
for (auto const& j : v) {
^^^^^
Don't use std::endl
The std::endl modifier adds a new line and forces a flush of the buffer.
std::cout << std::endl;
99.999999% of the time this makes the code less efficient. The buffer will be automatically flushed when it needs to be flushed so ther is no need to do it manually.
std::cout << "\n"; // Note prefer "\n" over '\n'
// As outputting a character builds a string internally. | {
"domain": "codereview.stackexchange",
"id": 43234,
"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++, programming-challenge, c++17",
"url": null
} |
c++, programming-challenge, c++17
Indexes may not be unsigned long
Its probably safe, but don't make assumptions. There is a specific type to represent array/ container indexes. std::size_t.
unsigned long plateau_start = 0;
Use:
std::size_t plateau_start = 0; | {
"domain": "codereview.stackexchange",
"id": 43234,
"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++, programming-challenge, c++17",
"url": null
} |
python, python-3.x, algorithm, time-limit-exceeded, combinatorics
Title: Find non-overlapping pairs of elements in a list whose difference is less than some given threshold
Question: I have the following task: Let us have a list (denoted by L, and for simplicity, the elements come from the interval [0,1]). We are given a parameter (denoted by C), and we want to find as many pairs as we cane (without using the same element twice) in our list, whose difference is at most C.
Example: For the input L=[0, 0.2, 0.4, 0.5, 0.6, 1] and C=0.2, my output should be [0, 0.2] and [0.4, 0.5]. If I had C=0.1, the output would be [0.4, 0.5], and with C=0.4, the output would also contain the pair [0.6, 1]. Getting a single solution is enough, as I know that there are more possible partitions. Note: the input list is not necessary sorted, therefore the pairs don't need to be adjacent.
This is the code that I have created. It tries to search all the possible partitions, then filter the good 2-partitions. As far as I know, it gives the correct solution. My only problem is the runtime: if the list is larger than 20 elements, I can't get the output in a normal time.
def partition(collection):
if len(collection) == 1:
yield [ collection ]
return
first = collection[0]
for smaller in partition(collection[1:]):
# insert `first` in each of the subpartition's subsets
for n, subset in enumerate(smaller):
yield smaller[:n] + [[ first ] + subset] + smaller[n+1:]
# put `first` in its own subset
yield [ [ first ] ] + smaller
def filter_partition(partition):
for elem in partition:
if len(elem) not in (1, 2):
return False
return True | {
"domain": "codereview.stackexchange",
"id": 43235,
"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, python-3.x, algorithm, time-limit-exceeded, combinatorics",
"url": null
} |
python, python-3.x, algorithm, time-limit-exceeded, combinatorics
def get_good_partitions(lista, C):
lista = lista.tolist()
all_partitions = list(partition(lista))
two_partitions = [p for p in all_partitions if filter_partition(p)]
max_pairs = 0
ret = []
for p in two_partitions:
is_ok = 0
for elem in p:
if len(elem) > 1:
diff = abs(elem[0] - elem[1])
if diff <= C or math.isclose(diff, C):
is_ok += 1
if is_ok > max_pairs:
max_pairs = is_ok
ret = p
return [elem for elem in ret if len(elem) == 2 and math.isclose(abs(elem[0] - elem[1]), C) or abs(elem[0] - elem[1]) <= C]
#test
L = numpy.array([random.uniform(0, 1) for _ in range(8)])
C = 0.1
res = get_good_partitions(L, C)
print(res)
Answer: Your code is doing far too much work.
If we sort the list before we start, then we need only compare adjacent elements as candidates. Whenever we find a pair that satisfies our predicate, then add it to the output and skip forward one step (so we don't consider the second value as a candidate).
Example with the list of the question and the threshold for adjacent difference set to 0.125 (which is an exact binary fraction, so avoids problems with floating-point rounding on common platforms):
Sorted list is [0, 0.2, 0.4, 0.5, 0.6, 1]
Candidate pair [0, 0.2]: 0.2 > 0.125
Candidate pair [0.2, 0.4]: 0.2 > 0.125
Candidate pair [0.4, 0.5]: 0.1 ≤ 0.125 ⇒ accept
([0.5, 0.6] is not a candidate, because we just accepted a pair)
Candidate pair [0.6, 1]: 0.4 > 0.125
Result: [0.4, 0.5] only.
A second example, with threshold of 10 this time:
Input: [11, 50, 55, 45, 0, 51, 33, 19]
Sorted: 0 11 15 19 33 45 50 51 55
Paired: 0 [11 15] 19 33 [45 50] [51 55]
Result: [11, 15], [45 50], [51 55]
Note that this algorithm doesn't need any special care to return the maximal number of matching pairs - that will naturally happen because we consider them in sorted order. | {
"domain": "codereview.stackexchange",
"id": 43235,
"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, python-3.x, algorithm, time-limit-exceeded, combinatorics",
"url": null
} |
go, generics, mongodb
Title: MongoDB abstraction in Go with generics
Question: I'm working on a new project with go. So I figured I would give this new feature a run (it's fun!). Although, I'm not sure I'm implementing this the way it's suposed to be.
I've read the following guides before writing my code :
Golang official generics tutorial
Another nice and complete tutorial by bitfieldconsulting
For reference this is a simple package where I connect to mongo and get/create/update documents.
Please note the switch part in the following code. Casting it into an empty interface to be able to get the struct type seems way too hacky and not the "golang way". I know for now they didn't add any support to get the type from a generic. So this is what I did to make it work.
// I use an interface to constraint the structs types I want to work with
type Restrains interface {
demande.Patient | demande.DemandTransport | demande.Configuration | demande.Prestataire | demande.Team
}
func setConnection[T Restrains](db *mongo.Client, object T) *mongo.Collection {
var coll *mongo.Collection
//This is where it gets "hacky" and I don't really like it
switch (interface{})(object).(type) {
case demande.Patient:
coll = db.Database(databaseName).Collection(patientCollection)
case demande.DemandTransport:
coll = db.Database(databaseName).Collection(demandeCollection)
case demande.Configuration:
coll = db.Database(databaseName).Collection(configurationCollection)
case demande.Prestataire:
coll = db.Database(databaseName).Collection(prestatairesCollection)
case demande.Team:
coll = db.Database(databaseName).Collection(teamsCollection)
default:
return nil
}
return coll
} | {
"domain": "codereview.stackexchange",
"id": 43236,
"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": "go, generics, mongodb",
"url": null
} |
go, generics, mongodb
//Here is a simple, nice Save Object T function
//I use a pointer to be able to return nil in case of error, so I don't need to search for the type. (Not sure if this is good practice either)
func SaveObject[T Restrains](db *mongo.Client, object T) (*T, error) {
coll := setConnection(db, object)
obj, err := coll.InsertOne(context.TODO(), object)
if err != nil {
log.Error(err)
return nil, err
}
obj.InsertedID.(primitive.ObjectID).String()
return &object, nil
}
//This is a function where we get a single obj by ID from mongo
// GetOneObject needs an empty object to know which type of object to get (is this clean?)
func GetOneObject[T Restrains](db *mongo.Client, id string, object T) (T, error) {
var foundobj T
chs := setConnection(db, object)
did, errId := primitive.ObjectIDFromHex(id)
if errId != nil {
log.Error(errId)
return foundobj, errId
}
filter := bson.M{"_id": did}
findErr := chs.FindOne(context.Background(), filter).Decode(&foundobj)
if findErr != nil {
if findErr != mongo.ErrNoDocuments {
log.Error(findErr)
return foundobj, findErr
}
}
return foundobj, nil
}
As you can see, I'm questioning this is a good method. Either I keep my usual and well-known workflow for this kind of implementation, or I go down this road. I don't find it particularly difficult to maintain/read, but it might my my lack of experience with go, and/or generics. Any lights on this would be appreciated.
I understand that mongo (the official driver) handles already interfaces, but I like the idea of using constraints to keep it clear.
Answer: OK, so your setConnection implementation just looks to me to be using generics for the sake of using them. Functionally, there would be no difference between your function being written as either
func setConnection[T any](db *mongo.Client, object T) *mongo.Collection | {
"domain": "codereview.stackexchange",
"id": 43236,
"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": "go, generics, mongodb",
"url": null
} |
go, generics, mongodb
or simply
func setConnection(db *mongo.Client, object interface{}) *mongo.Collection
The setConnection function is not exported, and called by functions that all have the [T Restraints] constraint already, so whatever is passed to setConnection is pretty much guaranteed to work already. What you have now, as you already know, is a bit of a hack. Clearly, each type has a corresponding collection variable associated with it already. You're using a type assertion to work out what variable you want to use. That's something was quite easily done before generics were introduced to the language already:
type Collection interface {
CollectionName() string
}
// then in your object types:
package demande
func (_ Patient) CollectionName() string {
return patientCollection // a const or something
}
Then, in your setConnection function, you'd simply write:
func setConnection(db *mongo.Client, object Collection) *mongo.Collection {
return db.Database(dbName).Collection(object.CollectionName())
}
Nice and easy.
If the collection argument isn't something you can have in the code as a const, or you can't/don't want to have it anywhere but in the package where you interact with mongo, you can just keep the same interface, and use a simple map:
package mongostuff
var collections = map[string]collectionType{
demande.PatientName: patientCollection, // and so on
}
and your setConnection function would then look something like this:
func setConnection(db *mongo.Client, object Collection) *mongo.Collection {
return db.Database(dbName).Collection(collections[object.CollectionName()])
}
If you don't even want to bother going through the interface/constant route, you could (but really shouldn't) go and use the reflection package:
var collections = map[reflect.Type]CollectionT{
reflect.TypeOf(demande.Patient{}): patientCollection,
} | {
"domain": "codereview.stackexchange",
"id": 43236,
"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": "go, generics, mongodb",
"url": null
} |
go, generics, mongodb
In which case setConnection turns in to this:
func setConnection(db *mongo.Client, object interface{}) *mongo.Collection {
return db.Database(dbName).Collection(collections[reflect.TypeOf(object)])
}
The type of the object argument could be whatever makes most sense overall. You're using reflection though, which is bad, so once again: don't use this. Much like generics: you shouldn't use reflection just because you can. You should only use it if you can't use anything else.
As for your other functions, I'd simply remove the word object from them, and just call them Save and GetOne, and instead of passing in object T, I'd probably use object *T so the caller knows not to mess with the objects that are being passed in, and you avoid code like this:
obj := demande.Patient{} // initialise this
// some code
savedObj, err := dbpkg.SaveObject(db, obj)
if err != nil {
// handle error
}
If the object argument is a pointer, the whole thing can be shortened to an equally (or arguably more) readable:
obj := &demande.Patient{}
if err := dbpkg.Save(db, obj); err != nil {
// handle error
}
// obj now has the ID set and can be used as the most up-to-date value as stored in the collection | {
"domain": "codereview.stackexchange",
"id": 43236,
"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": "go, generics, mongodb",
"url": null
} |
go, generics, mongodb
Other comments/observations/recommendations:
Something that kind of bugs me when reading through this is the use of the word Restraints when defining a type constraint. The thing that I dislike most is that it doesn't communicate at all what the constraint actually is. A constraint like Number or comparable gives you an idea of what data is being handled by the function. Are Restraints things that are supposed to filter data sets, like a map reduce kind of thing? Are they validation steps on some data? Are they malicious things that hog 80% of system resources? I would call them something like DTO or MModel (short for MongoModel) or something like that. It at least communicates clearly that we're expecting types that represent data that is stored in some capacity.
A second pet peeve is that you're not passing in the context.Context argument, and instead are using context.Background() hard coded. Just create a context.WithCancel(context.Background()) in your main function, defer the cancel call in said main function (where you'll probably handle signals, start the application, any servers you might be running, etc... and pass the context in. At the very least, by doing that, if your application receives a kill signal while saving a load of data, the context gets cancelled and routines that have access to this context can be made aware of the program exiting by checking <-ctx.Done(). | {
"domain": "codereview.stackexchange",
"id": 43236,
"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": "go, generics, mongodb",
"url": null
} |
c++, multithreading
Title: tiny thread pool implementation
Question: I wanted to write a minimal thread pool implementation.
You can submit tasks and get a future.
When the pool goes out of scope, all pending tasks will complete and join all workers.
In an earlier revision, i made a separate join() member function that joins the workers but then it would keep the thread pool in an unusable state.
thread_pool.hpp
#ifndef RDX_THREAD_POOL_HPP
#define RDX_THREAD_POOL_HPP
#include <cstddef>
#include <future>
#include <queue>
#include <mutex>
#include <thread>
#include <condition_variable>
namespace rdx {
/*
/brief A thread pool that spawns a specified number of workers.
Worker threads wait for the queue to be filled with tasks.
Enqueueing tasks return futures so that they can return asynchronous values.
Destructor will join all workers.
*/
class thread_pool {
private:
std::queue<std::function<void()>> task_queue;
std::mutex queue_mutex;
std::condition_variable queue_notification;
std::vector<std::thread> workers;
bool should_stop;
void worker_function();
public:
// constructs a thread pool with the given number of workers
thread_pool(std::size_t num_workers = std::thread::hardware_concurrency());
~thread_pool();
//enqueues a task to be performed and returns a future for that task
template<class F, class... Args>
std::future<typename std::result_of<F(Args...)>::type> enqueue(F&& f, Args&&... args);
thread_pool(thread_pool&&) = delete;
thread_pool(const thread_pool&) = delete;
thread_pool& operator=(thread_pool&&) = delete;
thread_pool& operator=(const thread_pool&) = delete;
}; | {
"domain": "codereview.stackexchange",
"id": 43237,
"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++, multithreading",
"url": null
} |
c++, multithreading
template<class F, class ...Args>
inline std::future<typename std::result_of<F(Args ...)>::type> thread_pool::enqueue(F&& f, Args && ...args) {
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
task_queue.emplace([task]() { (*task)(); });
}
queue_notification.notify_one();
return res;
}
}
#endif // !RDX_THREAD_POOL_H
thread_pool.cpp
#include "thread_pool.hpp"
namespace rdx {
void thread_pool::worker_function() {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queue_mutex);
queue_notification.wait(lock, [this]() {
return should_stop || !task_queue.empty();
});
if (should_stop && task_queue.empty()) {
break;
}
if (task_queue.empty()) {
continue;
}
task = task_queue.front();
task_queue.pop();
}
task();
}
}
thread_pool::thread_pool(std::size_t num_workers) : should_stop(false) {
for (auto i = 0; i < num_workers; i++) {
workers.emplace_back(&thread_pool::worker_function,this);
}
}
thread_pool::~thread_pool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
should_stop = true;
}
queue_notification.notify_all();
for (auto& worker : workers) {
worker.join();
}
}
}
repository can be found here | {
"domain": "codereview.stackexchange",
"id": 43237,
"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++, multithreading",
"url": null
} |
c++, multithreading
repository can be found here
Answer: A solid approach to a simple threadpool
There are only a few minor things that I noticed which can be improved.
To start off, a single argument constructor should usually be marked explicit:
// constructs a thread pool with the given number of workers
explicit thread_pool(std::size_t num_workers = std::thread::hardware_concurrency());
You exclusively use std::unique_lock<std::mutex>, which is fine, but std::lock_guard<std::mutex> has slightly less overhead. Unless you need the extra features of a unique_lock, consider using a lock_guard instead. In fact, the only times you need a unique_lock in your current code is when passing the lock to the condition_variable for the wait call.
Speaking of condition_variable, I feel like your worker_function is slightly more complex than it needs to be. You also missed an optimization opportunity by not trying to move the task out of the queue:
void thread_pool::worker_function() {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queue_mutex);
// Loop here in case of a spurious wakeup
while(task_queue.empty()) {
if(should_stop) {
// Only return when queue is empty and should_stop
return;
}
// Wait until notified or woken up spuriously
queue_notification.wait(lock);
}
task = std::move(task_queue.front());
task_queue.pop();
}
task();
}
}
In the destructor, consider checking whether a thread is joinable before joining it:
thread_pool::~thread_pool() {
{
std::lock_guard<std::mutex> lock(queue_mutex);
should_stop = true;
}
queue_notification.notify_all();
for (auto& worker : workers) {
if (worker.joinable()) {
worker.join();
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43237,
"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++, multithreading",
"url": null
} |
c++, multithreading
In general, you currently have no exception handling at all. Especially when creating a class which accepts user given functions and executes them, you should consider what happens when someone "accidentally" tries to enqueue a task which raises an exception in one of your worker threads.
By default, the worker thread just silently dies in the background since exceptions are not propagated back to the main thread. You may (or not) get a broken_promise exception when calling get on the returned future, but you should try to handle things differently than that.
Additionally, your constructor doesn't handle possible exceptions raised during the creation of the threads. The problem is that, when an exception occurs inside a constructor, no destructor is called to stop and join any already created threads, leaving you in a problematic situation. In that case you should clean up the threads by yourself:
thread_pool::thread_pool(std::size_t num_workers) : should_stop(false) {
// If you know the size beforehand, just reserve it directly
workers.reserve(num_workers);
try {
for (auto i = 0; i < num_workers; i++) {
workers.emplace_back(&thread_pool::worker_function,this);
}
}
catch (...) { // catch all
{
std::lock_guard<std::mutex> lock(queue_mutex);
should_stop = true;
}
queue_notification.notify_all();
for (auto& worker : workers) {
if (worker.joinable()) {
worker.join();
}
}
throw; // rethrow the caught exception
}
} | {
"domain": "codereview.stackexchange",
"id": 43237,
"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++, multithreading",
"url": null
} |
c++, multithreading
Finally, speaking from personal experience, it is likely worth splitting the "queue logic" from the "threadpool logic". Having a separate threadsafe queue class, which supports the waiting functionality of the condition_variable, let's you easily reuse your code in different threadpools or even different projects. Most importantly though, it drastically improves the readability and maintainability since each part would be nicely encapsulated. | {
"domain": "codereview.stackexchange",
"id": 43237,
"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++, multithreading",
"url": null
} |
c#, beginner, homework, checksum
Title: Implementation of an algorithm to calculate a check digit for a five-digit number
Question: I'm a newbie in programming, just started about 6 months ago and just finding my way around in C# (clean) code. This is the toy task we have received from our teacher.
This is what it should do:
New article numbers are assigned in your company. They consist of 5
numbers and a check digit.
You are to design a program that reads in 5 single-digit numbers, calculates the check digit and outputs it to the console. It is up
to you how you deal with incorrect entries.
You get the following information for the calculation of the check digit:
even numbers are added, odd numbers are multiplied by 3 and then added.
The check digit results from the last digit of the sum.
Example:
27493 => 2+4 = 6;
7*3+9*3+3*3 = 57;
6 + 57 = 63 => check digit 3
Item number = 27493-3
Since I'm a newbie, i dont have any own style at all and would love to hear all your suggetions. I have only heard about Clean Code, the book from Uncle Bob is already ordered. Maybe you have suggestions what I can look for first in such code, and of course what is common or not in a big business. I'm looking for a efficient and common way of writing code. I appreciate all your suggestions, even you find it obvious, i'm learning. Please suggest any do's and don'ts.
public static void JugglingWithNumbers()
{
int[] numbers = new int[5];
int[] evenNumber = new int [5];
int[] oddNumber = new int [5];
int sumEvenNumbers = 0;
int sumOddNumbers = 0;
int summeSusumme;
Console.WriteLine( $" 5 numbers (1 digit) please:"); | {
"domain": "codereview.stackexchange",
"id": 43238,
"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, homework, checksum",
"url": null
} |
c#, beginner, homework, checksum
Console.WriteLine( $" 5 numbers (1 digit) please:");
for (int i = 0; i <5; i++)
{
bool ok;
ok = int.TryParse(Console.ReadLine(), out numbers[i]);
if (!ok)
{
Console.WriteLine($"This is not a valid input");
Console.WriteLine($"PLease try again");
i--;
}
}
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i]%2 == 0)
{
evenNumber[i] = numbers[i];
sumEvenNumbers += evenNumber[i];
}
else
{
oddNumber[i] = numbers[i];
sumOddNumbers += numbers[i] * 3;
}
}
Console.WriteLine($"Here are your numbers one more time - control output:");
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
Console.WriteLine($"Even numbers");
for (int i = 0; i < evenNumber.Length; i++)
{
Console.WriteLine(evenNumber[i]);
}
Console.WriteLine($"Odd Numbers");
for (int i = 0; i < oddNumber.Length; i++)
{
Console.WriteLine(oddNumber[i]);
}
Console.WriteLine($"Sum even numbers: {sumEvenNumbers}");
Console.WriteLine($"Sum odd numbers: {sumOddNumbers}");
summeSusumme = sumEvenNumbers + sumOddNumbers; | {
"domain": "codereview.stackexchange",
"id": 43238,
"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, homework, checksum",
"url": null
} |
c#, beginner, homework, checksum
summeSusumme = sumEvenNumbers + sumOddNumbers;
Console.WriteLine($"Your checksum: ");
for (int i = 0; i < numbers.Length; i++)
{
Console.Write(numbers[i]);
}
Console.Write("-");
Console.Write(summeSusumme%10);
}
static void Main(string[] args)
{
JugglingWithNumbers();
Console.ReadLine();
}
}
Answer: You have a lot of very similar code repeated. This is a good hint that you can benefit from introducing a helper method to remove the duplication. For example, you have the need to output a list of numbers to the console multiple times. Start off by just extracting your code:
private static void PrintNumbers(string heading, int[] numbers)
{
Console.WriteLine(heading);
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
}
You can now change the printing in the middle of your code to something much easier to read:
PrintNumbers("Here are your numbers one more time - control output:", numbers);
PrintNumbers("Even numbers", evenNumber);
PrintNumbers("Odd Numbers", oddNumber);
As well as being easier to read, you can now be sure that all the output is consistent.
It's worth now refactoring the implementation of PrintNumbers:
private static void PrintNumbers(string heading, IEnumerable<int> numbers)
{
Console.WriteLine(heading);
Console.WriteLine(string.Join(Environment.NewLine, numbers));
} | {
"domain": "codereview.stackexchange",
"id": 43238,
"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, homework, checksum",
"url": null
} |
c#, beginner, homework, checksum
This uses string.Join instead of multiple calls to Console.WriteLine, the input also uses the most general type* we can. * well, without adding generics. Learn to love string.Join - it's incredibly useful.
You've used fixed size datastructures (array) for each of the numbers, oddNumber and evenNumber variables. However, you know that oddNumber and evenNumber can't both be full - a List<int> is a much better choice for those:
var oddNumbers = new List<int>();
var evenNumbers = new List<int>();
int evenSum, oddSum;
foreach (var n in numbers)
{
if (n % 2 == 0)
{
evenNumbers.Add(n);
evenSum += n;
}
else
{
oddNumbers.Add(n);
oddSum += n * 3;
}
}
Notice that we can now use a foreach loop and not worry about indexes at all.
If you don't want to output all numbers/evens/odds and intermediate sums, you can make the code much more concise:
public static void JugglingWithNumbers()
{
var numbers = GetUserInput();
var checkDigit = CalculateCheckDigit(numbers);
Console.WriteLine($"Your checksum: {string.Join("", numbers)}-{checkDigit}");
}
private static int CalculateCheckDigit(IEnumerable<int> numbers)
{
var sum = numbers
.Select(n => n % 2 == 0 ? n : n * 3)
.Sum();
return sum % 10;
}
private static IEnumerable<int> GetUserInput()
{
// Left as exercise
} | {
"domain": "codereview.stackexchange",
"id": 43238,
"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, homework, checksum",
"url": null
} |
python, beginner, number-guessing-game
Title: Console guessing game in Python
Question: What would make it better?
This is my first Python project. Do help in making it better, for me to learn something new.
secret="12345"
guess=""
count=0
limit=3
limited=False
while guess!=secret and not(limited):
if count<limit:
guess=input("Enter guess: ")
count +=1
else:
limit=True
if limited:
print("Out of guesses, You Lose!")
else:
print("You got it!")
Answer: So far, I think your initial approach is good. Your naming is clear and the code is pretty obvious in what it's trying to accomplish. Nice work!
Rethinking while
I think the while loop can actually be reduced to a for/else, because you are looping until a conditional is reached and marking a flag. So I'd do:
# iterate over the range of guesses
for _ in range(limit):
guess = input('Enter guess: ')
if guess == secret:
message = "You got it!"
break
else:
message = "Out of guesses, you lose!"
print(message)
Where the else here will only trigger if the loop didn't exit early:
# breaks early, no else fired
for i in range(3):
break
else:
print('finished')
# loop completes, else fires
for i in range(3):
continue
else:
print('finished')
finished
Style Items
It is good to include whitespace in between operators for assignment and comparison:
# go from this
secret="12345"
guess!=secret
count +=1
# to this
secret = "12345"
guess != secret
count += 1
The not keyword isn't a function and doesn't need parentheses:
not limited
Making code reusable
Right now, you have a hard-coded secret. This is sufficient for getting your program running, but what if you want a new game to have a new secret? Let's create one on the fly using the random module:
import random
from string import digits # imports "0123456789" as a string | {
"domain": "codereview.stackexchange",
"id": 43239,
"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, beginner, number-guessing-game",
"url": null
} |
python, beginner, number-guessing-game
def play_game(secret):
for _ in range(limit):
guess = input('Enter guess: ')
if guess == secret:
message = "You got it!"
break
else:
message = "Out of guesses, you lose!"
print(message)
# the 5 here is the length of the secret
secret = "".join(random.sample(digits, 5))
play_game(secret)
Now, the game should generate new secrets every time you play. The only new parameter we have is how long the secret is, which you can add a new prompt for:
# a user will input digits 0-9 ideally
# we can catch this by raising an error if they don't
try:
secret_length = int(input("How many digits should the secret have: "))
except ValueError:
# You can loop or raise, up to you on what you want the behavior to do
# but an error message is always helpful
raise ValueError("You need to provide a number!")
Wrapping up in a __main__ block
The if __name__ == "__main__" statement is something you'll see a lot of as you see more python programs out in the wild. Basically it is checking to see if the script is being run as the main program, if it is, it executes whatever is in the body of the if. This is called a guard, and can help when code is designed to be both imported and run as standalone.
import random
from string import digits # imports "0123456789" as a string
def play_game(secret):
for _ in range(limit):
guess = input('Enter guess: ')
if guess == secret:
message = "You got it!"
break
else:
message = "Out of guesses, you lose!"
print(message)
if __name__ == "__main__":
try:
secret_length = int(input("How many digits should the secret have: "))
except ValueError:
raise ValueError("You need to provide a number!")
secret = "".join(random.sample(digits, secret_length))
play_game(secret) | {
"domain": "codereview.stackexchange",
"id": 43239,
"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, beginner, number-guessing-game",
"url": null
} |
python, beginner, number-guessing-game
secret = "".join(random.sample(digits, secret_length))
play_game(secret)
Last, it might be helpful to add a main method so all of these functions aren't hanging around in global namespace. And returning the result of the game might make it more clear as to what is going on.
import random
from string import digits # imports "0123456789" as a string
def play_game(secret):
for _ in range(limit):
guess = input('Enter guess: ')
if guess == secret:
message = "You got it!"
break
else:
message = "Out of guesses, you lose!"
return message
def main():
try:
secret_length = int(input("How many digits should the secret have: "))
except ValueError:
raise ValueError("You need to provide a number!")
secret = "".join(random.sample(digits, secret_length))
game_result = play_game(secret)
print(game_result)
if __name__ == "__main__":
main()
This has the added benefit of being easy to loop if you want to play multiple games
if __name__ == "__main__":
keep_playing = 'y'
while keep_playing == 'y':
main()
keep_playing = input("Continue? (y/n) ").lower()
Docstrings
Let's add some documentation to our code. You can add docstrings to both your functions and the module.
# Up at the top of the file, a module-level docstring
"""Play a game of 'Guess the Secret!'
The secret is randomly generated and consists of an N-length string
of digits. You are prompted to pick the secret length
If you run out of guesses you lose, but guess it right and you win
"""
import random
from string import digits
def play_game(secret):
"""Plays the game with the secret provided as an argument.
Secret can be any string
Returns the result of the game as a message to the player
"""
for _ in range(limit):
guess = input('Enter guess: ') | {
"domain": "codereview.stackexchange",
"id": 43239,
"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, beginner, number-guessing-game",
"url": null
} |
python, beginner, number-guessing-game
if guess == secret:
message = "You got it!"
break
else:
message = "Out of guesses, you lose!"
return message
~rest of code~ | {
"domain": "codereview.stackexchange",
"id": 43239,
"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, beginner, number-guessing-game",
"url": null
} |
python, numpy
Title: How can i refactor python numpy code?
Question: def arr_func(arr,selected_pixels_list):
rows = 2
m = 0
n = 0
i =0
#Calculate the number of pixels selected
length_of_the_list = len(selected_pixels_list)
length_of_the_list = int(length_of_the_list/4)*4
cols = int(length_of_the_list/2)
result_arr = np.zeros((rows,cols))
while(i<length_of_the_list):
result_arr[m,n] = arr[selected_pixels_list[i]]
result_arr[m,n+1] = arr[selected_pixels_list[i+1]]
result_arr[m+1,n] = arr[selected_pixels_list[i+2]]
result_arr[m+1,n+1] = arr[selected_pixels_list[i+3]]
i = i+4
m = 0
n = n+2
return result_arr
import numpy as np
selected_pixel_data = np.load("coordinates.npy")
arr_data = np.load("arr.npy")
response = arr_func(arr_data, selected_pixel_data)
print(response)
I try using "for loop" but it is not refractory.
for i in range(0,len(selected_pixels_list),4):
n=i//2
result_arr[m,n] = arr[selected_pixels_list[i]]
result_arr[m,n+1] = arr[selected_pixels_list[i+1]]
result_arr[m+1,n] = arr[selected_pixels_list[i+2]]
result_arr[m+1,n+1] = arr[selected_pixels_list[i+3]]
For selected_pixel_data:
shape = (597616, 2)
dtype = int32
For arr_data:
shape = (1064, 590)
dtype = float64
Here arr_data is an array of data and selected_pixel_data is coordinates.
The function arr_func is used to create a new array with selected coordinates.
Is there any way to use the code more efficiently? | {
"domain": "codereview.stackexchange",
"id": 43240,
"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, numpy",
"url": null
} |
python, numpy
Answer: Add PEP484 type hints.
int(length/4)*4 can just use floor division, as in length//4*4.
Use np.empty instead of np.zeros.
Don't surround (i<length_of_the_list) in parens.
The first layer of simplification is identifying the repeating patterns in your indices and rewriting your loop such that it does index math and only one inner assignment:
def arr_func_sequential(arr: np.ndarray, selected_pixels: np.ndarray) -> np.ndarray:
n_selected = len(selected_pixels) // 4 * 4
result_arr = np.empty((2, n_selected // 2))
for i in range(0, n_selected, 4):
n = i // 2
for d in range(4):
j, k = selected_pixels[i + d]
result_arr[d // 2, n + d % 2] = arr[j, k]
return result_arr
But this is not nearly enough. You should do vectorised indexing. For your stated shapes, this should be equivalent:
def arr_func_vectorised(arr: np.ndarray, selected_pixels: np.ndarray) -> np.ndarray:
flat = arr[selected_pixels[:, 0], selected_pixels[:, 1]]
return flat.reshape((-1, 2, 2)).swapaxes(0, 1).reshape((2, -1))
Including basic regression tests, this looks like
import numpy as np
from numpy.random import default_rng
def arr_func_sequential(arr: np.ndarray, selected_pixels: np.ndarray) -> np.ndarray:
n_selected = len(selected_pixels) // 4 * 4
result_arr = np.empty((2, n_selected // 2))
for i in range(0, n_selected, 4):
n = i // 2
for d in range(4):
j, k = selected_pixels[i + d]
result_arr[d // 2, n + d % 2] = arr[j, k]
return result_arr
def arr_func_vectorised(arr: np.ndarray, selected_pixels: np.ndarray) -> np.ndarray:
flat = arr[selected_pixels[:, 0], selected_pixels[:, 1]]
return flat.reshape((-1, 2, 2)).swapaxes(0, 1).reshape((2, -1))
def test() -> None:
rand = default_rng(seed=0)
arr_size = 1_064, 590
arr_data = rand.random(size=arr_size, dtype=np.float64)
selected_pixel_data = rand.integers(arr_size, size=(597_616, 2), dtype=np.int32) | {
"domain": "codereview.stackexchange",
"id": 43240,
"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, numpy",
"url": null
} |
python, numpy
for method in (arr_func_sequential, arr_func_vectorised):
response = method(arr_data, selected_pixel_data)
assert response.shape == (2, 298_808)
assert np.isclose(6.867644672947648e-07, response.min())
assert np.isclose(0.9999967667212489, response.max())
assert np.isclose(0.4996104177145426, response.mean())
assert np.allclose(response[:, 0], np.array((0.12815171, 0.05691355)))
assert np.allclose(response[:, -1], np.array((0.27512743, 0.60253044)))
if __name__ == '__main__':
test() | {
"domain": "codereview.stackexchange",
"id": 43240,
"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, numpy",
"url": null
} |
c++, object-oriented, c++17
Title: C++ stack class design
Question: I am trying some hands on recent C++ standards. For the purpose of learning, I have implemented a Stack class as below which can hold any type of data member.
I would like everyone to review this class and give their suggestion on how any particular method should have been implement as to to adhere to SOLID principle's
#include <iostream>
#include <any>
#include <memory>
using namespace std;
class Stack
{
private:
#ifdef RAW
std::any *_data;
#else
unique_ptr<std::any[]> _data;
#endif
int _size;
int _capacity;
bool validSize() const
{
if(_size>0 && _size<=_capacity)
return true;
return false;
}
public:
int getSize() const {return _size;}
Stack(int _c=2):_capacity{_c},_size(0)
{
#ifdef RAW
_data = new std::any[_capacity];
#else
_data = make_unique<std::any[]>(_capacity);
#endif
}
Stack(const Stack &rhs): _size(rhs._size),_capacity(rhs._capacity)
{
#ifdef RAW
_data = new std::any[_capacity];
#else
_data = make_unique<std::any[]>(_capacity);
#endif
//copy(rhs._data[0],rhs._data[_capacity-1],_data);
for(int i=0; i < _capacity ; ++i)
_data[i] = rhs._data[i];
}
Stack(Stack &&rhs)
{
_data = std::move(rhs._data);
_size = rhs._size;
_capacity = rhs._capacity;
}
void push(const any &data)
{
if(_size<_capacity)
_data[_size++]=data;
else
throw "Out of memory &";
}
void push(any &&data)
{
if(_size<_capacity)
_data[_size++]=data;
else
throw "Out of memory &&";
} | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
#ifdef RAW
Stack& operator=(const Stack &rhs)
{
if(this != &rhs)
{
_capacity = rhs._capacity;
_size = rhs._size;
for(int i=0; i < _capacity ; ++i)
_data[i] = rhs._data[i];
}
return *this;
}
#else
void swap(Stack &rhs)
{
std::swap(_data,rhs._data);
std::swap(_size,rhs._size);
std::swap(_capacity,rhs._capacity);
}
Stack& operator=(Stack rhs)
{
swap(rhs);
return *this;
}
#endif
std::any top()
{
if(validSize())
return _data[_size-1];
throw string("Stack is empty");
}
void pop()
{
if(validSize())
--_size;
}
~Stack()
{
#ifdef RAW
delete []_data;
#endif
}
};
I have tried 2 ways, one using raw pointer and other using unique_ptr. Tried to implement copy and swap idiom when unique_ptr is used.
There is a commented line in the copy ctor which was expected to copy the data but I couldn't get it right for the unique_ptr array. If someone can help to fix it.
Answer: This design idea isn’t bad; a fixed-size heterogeneous stack could be useful. And this class’s interface is nice and minimal, yet completely useful.
Now, in real code, you would never see a class like this in use, for a couple of reasons: | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
In practice, an “any” type is… not really that useful. You never really have a use case where you have something that could be literally anything. There are many situations where you might have one of a small number of types… for that, there’s std::variant. But literally anything? Pretty much never.
Because you never really need literally anything, it would make more sense to make a stack restricted to a single type… just like the one in the standard library. (Well, the standard library stack is technically only an adapter that you wrap around a deque or vector, but, yanno.) A stack fixed to a single type will probably hundreds of times faster than a stack that holds literally anything—maybe even thousands of times faster—and much easier and safer to use (because you don’t need to futz around with converting to/from any, casting and such).
Even if you do need a small set of types, taking a single-type stack and using it with variant will be hundreds or thousands of times faster than using any, and easier and safer to use.
And in that ultra-rare case where you do actually need a stack of literally anything… you could just as easily take your single-type stack, and use any as the single type. It will be no less efficient than what you’re doing now. | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
So, in real code… you’d never make or use a class like this. But that doesn’t make it bad. If you were building a large program/library, this class would work as a quickie first pass, that you could later refactor and optimize. And if you really don’t care about efficiency at all, and you aren’t bothered about the clunky need to cast your types to/from any, then this class is just fine.
Okay, so this class isn’t going to be something you’ll find in a general-purpose library… but it’s still useful, so, let’s review it on its own terms.
Before we get into the actual code, let’s consider the interface. Whenever you are designing something that fits a standardized concept, you should make your interface fit that concept. In this case, you’re making a container, so your type should have the standard container interface. That means size() instead of getSize() (and it should return an unsigned type, which is not great, but, that’s the standard interface), and you need more functions, like empty(). You should also check out the table at the end of the container library page, to see what other functions are standard. In particular, you might want to look at the interface for std::stack.
There are three very important reasons to copy standard interfaces:
The standard interfaces have been designed by the best C++ experts in the world. If they’ve done something a certain way, there’s probably a damn good reason for it.
If your type uses standard interfaces, it will be easier for other coders to understand it, and use it.
If your type uses standard interfaces, it can interact with… pretty much anything. For example, if your type uses the standard range interface, then it will automatically work with range-for loops. Even something as simple using size() instead of getSize() will determine whether your type works with std::ranges::size() and std::sized_range… which could make your type work much faster with some algorithms (or make it work at all with some algorithms). | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
One last thing: you should always use a namespace for your own stuff. The global scope is a dangerous place, with lots of unique restrictions that don’t exist anywhere else. Using a namespace saves you from a lot of headaches.
Okay, onto the code.
#include <iostream>
#include <any>
#include <memory>
There are two problems with this set of headers.
It’s incomplete. There are things your class uses that aren’t included. Most notably, std::swap() isn’t covered by any of those headers.
It has irrelevant includes. You don’t need <iostream> for your class.
using namespace std;
Never, ever do this.
I know some people will offer caveats like “oh, it’s okay to use at function scope” or even “it’s okay to use in a .cpp file, but not a header”. I don’t truck with those unnecessary exceptions. There is never a good reason to use using namespace std; anywhere, and it will always be risky when you do. There may be less risk doing it in a small function, but the risk will never be zero.
Just never do it.
std::any *_data;
In C++, we prefer to put the type modifier with the type. In other words:
std::any *_data: This is C style.
std::any* _data: This is C++ style.
bool validSize() const
{
if(_size>0 && _size<=_capacity)
return true;
return false;
} | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
I have a problem with this function, and it is that it shouldn’t be necessary. The size should never not be valid. If the size is ever invalid… your class is broken.
Okay, but you’ve defined “valid size” to be non-zero, meaning an empty stack is an “invalid size”. Let’s put that aside for the moment and focus on the other part of the test: _size <= _capacity.
If the size is ever greater than the capacity, your class is broken. That should never, ever happen. So testing for it is specious. Why test for something that’s impossible? That’s just wasting cycles.
Okay, but maybe you’re paranoid, and you want to be 100% sure that the size never accidentally becomes larger than the capacity. Fine, but the place to do that test is any function where you modify either the capacity or the size. For example, at the end of push(), you could do assert(_size >= 0);, assert(_size <= _capacity);, and any other paranoid checks you want to do. Because they’re asserts, they’ll disappear in debug mode. But by making sure that your invariants hold at the end of every function, you can rest assured that at the start of every function, they’re good. That means for functions that don’t change anything, you don’t need to do any checks at all.
So the only test validSize() really needs is just _size > 0… which… is really just a test for whether the stack is empty.
And that makes perfect sense. Because that’s what you really need to check for in top() and pop()… not that the size is “valid” (which should always be true), but that the stack isn’t empty.
int getSize() const {return _size;}
First, this should really be named size(), to match the standard container interface.
But you really should add some more markup here:
constexpr int getSize() const noexcept {return _size;} | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
There is no way the function can fail, so marking it noexcept can not only add some performance benefits, it makes the function safe to use in no-fail situations.
And constexpr is really useful, when it can apply. As of C++20, unique_ptr is all constexpr (but make_unique() is not until C++23, sadly).
Stack(int _c=2):_capacity{_c},_size(0)
{
#ifdef RAW
_data = new std::any[_capacity];
#else
_data = make_unique<std::any[]>(_capacity);
#endif
}
I’m not a fan of default parameters, and in this case, it really seems specious. Why 2?
If you don’t want the capacity to be changeable, then it might make more sense to not have a default constructor at all. Just have a constructor that takes a capacity. If you do really want a default constructor, then maybe make it possible to change the capacity (and in the default constructor, create a “zero-capacity” stack).
But there’s a bigger problem here, and that is that your stack is implicitly convertible from integers. That’s ridiculous; there’s no way that could be what you want. I mean, it would allow code like this:
Stack s = 2 + 2; | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
That’s just weird.
At the very least, you’ll want to declare the constructor that takes an int as explicit. You should almost always declare single-argument constructors as explicit (and almost never declare any other constructors explicit, but that’s something that some people will dispute).
But even an explicit constructor taking just an int isn’t a great idea. If you didn’t know this class, and say auto s = Stack{2}, what would you think that’s doing? Is it creating a stack with a capacity of 2? Or is it creating a stack with a size of 2, initialized with 2 default-constructed objects? Or is it creating a stack with a single item: the integer 2? The only way to know is to go look up the class’s documentation, and any time you force users to run to the docs, you’ve failed as an interface designer.
A better idea is to use tags. You could do:
struct with_capacity_t
{
constexpr explicit with_capacity_t() noexcept = default;
};
inline constexpr auto with_capacity = with_capacity_t{};
class Stack
{
public:
constexpr Stack(with_capacity_t, int cap)
: _capacity{cap}
, _size{0}
, _data{new std::any[cap]}
{}
// ... [snip] ...
};
// usage:
auto s = Stack{with_capacity, 5};
Now there’s no mystery; it’s crystal clear what’s going on. You could even add other tags for other conditions.
Stack(const Stack &rhs): _size(rhs._size),_capacity(rhs._capacity)
{
#ifdef RAW
_data = new std::any[_capacity];
#else
_data = make_unique<std::any[]>(_capacity);
#endif
//copy(rhs._data[0],rhs._data[_capacity-1],_data);
for(int i=0; i < _capacity ; ++i)
_data[i] = rhs._data[i];
} | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
Okay, here’s where things are going to get complicated.
First let me answer your question: There are two reasons the commented code won’t work.
The first has to do with the fact that you are doing _data[0] and _data[_capacity - 1] as the input arguments. Firstly, for the latter, you probably mean _data[_capacity], because when you are using an iterator pair, the second iterator is one-past-the-end. But that’s wrong here… and that’s the problem: Both of those are std::anys, because the brackets dereference the pointer. x[n] is *(x + n). That’s not what you want; you just want (x + n), no dereferencing. You could do &(_data[0]) and &(_data[_capacity]), but that’s kinda silly (and wrong in the latter case). You really just want to do _data and _data + capacity. But that brings us to the second problem.
The second reason the commented code won’t work when using unique_ptr is because the last argument of std::copy() needs to be an output iterator. An output iterators needs two things, operator* (for dereferencing), and operator++ (for incrementing). unique_ptr has the first… but not the second; you can’t do ++ on a unique_ptr. Of course, raw pointers support both derferencing and incrementing. The fix for the unique_ptr case is simply to get the raw pointer out of it, using .get().
And, of course that’s also an issue for the first problem. _data works as an input iterator when it’s a raw pointer… not when it’s a unique_ptr. And _data + _capacity makes no sense with unique_ptr; you can’t do math with a unique_ptr. The solution here is the same: get the raw pointer out of the unique_ptr with .get(), and use that.
So:
Stack(const Stack &rhs): _size(rhs._size),_capacity(rhs._capacity)
{
#ifdef RAW
_data = new std::any[_capacity]; | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
// Note I only copy up to size, not capacity. There’s no point
// copying the empty elements at the end.
std::copy(rhs._data, rhs._data + rhs._size, _data);
#else
_data = make_unique<std::any[]>(_capacity);
std::copy(rhs._data.get(), rhs._data.get() + rhs._size, _data.get());
#endif
}
However… while the above is okay with the unique_ptr version, the raw pointer version has a bug.
The issue is exceptions, and specifically, what happens if, while copying the contents of rhs._data, an exception is thrown. If an exception is thrown during the copy, that memory just allocated in the line above will leak.
In practice, the usual way to fix that is to use… unique_ptr. Something like this:
Stack(Stack const& rhs)
: _size{rhs._size}
, _capacity{rhs._capacity}
{
#ifdef RAW
// Allocate the memory, and store it in a temporary unique_ptr.
auto p = std::make_unique<std::any[]>(_capacity);
// Copy everything from rhs. If anything throws here, no problem; the
// temporary unique_ptr will be cleaned up.
std::copy(rhs._data, rhs._data + rhs._size, p.get());
// Everything was successfully copied, so now we release the unique_ptr,
// and keep the pointer.
_data = p.release();
#else
_data = make_unique<std::any[]>(_capacity);
std::copy(rhs._data.get(), rhs._data.get() + rhs._size, _data.get());
#endif
}
Of course, if the point of RAW is to avoid unique_ptrs completely, then the above is a bit silly. What you’d need to do in that case is use try-catch:
Stack(Stack const& rhs)
: _size{rhs._size}
, _capacity{rhs._capacity}
{
#ifdef RAW
// Allocate the memory. If this fails, it will throw, so no problem.
_data = new std::any[_capacity]; | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
// Set up a try-catch block, so we can do emergency clean-up in the
// catch if necessary.
try
{
// Copy everything. If it succeeds, great! If it throws, we go to the
// catch block.
std::copy(rhs._data, rhs._data + rhs._size, _data);
}
catch (...)
{
// There was an error copying, so delete the allocated memory...
delete[] _data;
// ... and rethrow whatever error happened.
throw;
}
#else
// ... [snip] ...
#endif
}
But, frankly, if I see a try-catch block, that’s a code smell. And you can see why in this case: by using unique_ptr, everything because cleaner and safer.
Stack(Stack &&rhs)
{
_data = std::move(rhs._data);
_size = rhs._size;
_capacity = rhs._capacity;
}
It’s a very good idea to make all of your move ops noexcept, if possible. And with your stack class, it is possible. No-fail moves are crucial for correct code in some really gnarly situations (for example, you need no-fail moves to safely store your type in a vector), and really help with efficiency too.
You have another bug here, and, once again, it’s in the raw pointer version. The unique_ptr version is fine. (See a pattern?)
The issue is what std::move() does. For a unique_ptr it (presumably) does exactly what you think it does. It TAKES the pointer out of the source unique_ptr, leaving it empty, and puts that pointer in the target unique_ptr (which, if it wasn’t empty, gets reset first, but in this case, you know the target is empty). In fact, because unique_ptr behaves exactly the way you think it should when moving, you could even default this entire operation:
// works for unique_ptr version only
constexpr Stack(Stack&&) noexcept = default;
With raw pointers, though, a move is just a copy. In general, a move is just an optimized copy.* If the copy is already as optimal as possible… then a move is a copy. That’s true for all the built-in types… including pointers. | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
(Well, I mean, it’s more than just an optimized copy but… that’s getting too sophisticated for the discussion here.)
In other words, _data = std::move(rhs._data); is no different from _data = rhs._data;… which leaves rhs._data with its original value. When rhs gets destroyed, the memory gets freed… and then, later, when this gets destroyed, boom, double delete. Crash.
The fix is really easy, though. Just manually set the old pointer to null:
Stack(Stack&& rhs) noexcept
{
_data = std::move(rhs._data);
rhs._data = nullptr; // this line is unnecessary for unique_ptr... but
// doesn't hurt (other than wasting cycles)
_size = rhs._size;
_capacity = rhs._capacity;
}
As an aside, when I’m making a type, I usually don’t treat the move ops as fundamental ops. Instead, I usually treat swap as the fundamental operation, and define move ops—and sometimes the copy ops, too— in terms of swap(). If I were designing your stack class, I would do something like this:
class Stack
{
#ifdef RAW
std::any* _data = nullptr;
#else
unique_ptr<std::any[]> _data = {};
#endif
int _size = 0;
int _capacity = 0;
public:
constexpr Stack(Stack&& rhs) noexcept
{
// Because of the data member initializers, when we get here, it's
// basically an "empty stack". Size and capacity are zero, and data is
// a null pointer (or empty unique_ptr, same thing).
//
// Which means that when we do this swap, we are putting a null
// pointer into rhs, effectively leaving it empty. This is fine,
// because the only things you can do with a moved-from object are
// destroy it, or assign to it. (And we implement the assignment
// ops safely for all cases below.)
swap(*this, rhs);
} | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
swap(*this, rhs);
}
constexpr auto operator=(Stack&& rhs) noexcept -> Stack&
{
// Basically the same logic as in the move constructor applies here,
// except *this may not be empty. If it isn't, then when we do the
// swap, we are putting *this's current pointer into rhs, where it
// will presumably be deleted momentarily (when you are moving from
// something, that usually means it's about to be destroyed or
// assigned over).
swap(*this, rhs);
return *this;
}
friend constexpr auto swap(Stack& a, Stack& b) noexcept
{
using std::swap;
swap(a._data, b._data);
swap(a._size, b._size);
swap(a._capacity, b._capacity);
}
// ... rest of the class
// But I'll show the copy assignment operator as well:
constexpr auto operator=(Stack const& rhs) -> Stack&
{
// This copy is dangerous, but if it fails and throws... no big deal.
// We haven't even touched *this yet.
auto temp = rhs;
// Once we get here, all the dangerous work of copying is done.
// Swapping is no-fail, so:
swap(*this, temp);
// That's the copy-and-swap idiom.
return *this;
}
};
In practice, that means the only things you really need to implement are:
A default constructor, if you want one.
The copy constructor. This is usually the most expensive and most difficult operation to get right. (Remember yours had a bug for raw pointers!)
The destructor, if necessary. | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
The move constructor, move assignment, and copy assignment are always the same boilerplate: just swapping or copy-and-swapping.
However, that’s all just the default boilerplate you should start with. In practice, it may be possible to do some of the operations much more efficiently. It is often possible to do the copy assignment much more efficiently; the copy-and-swap can be very wasteful. However… in this case… because you’re using std::any, you have to assume the worst-case, always (because you never know what’s inside an std::any).
void push(const any &data)
{
if(_size<_capacity)
_data[_size++]=data;
else
throw "Out of memory &";
}
Throwing bare character pointers is unwise. You should use a standard exception class. In this case, probably std::length_error, or std::out_of_range. Or, if you prefer, you could make your own custom exception class, but you’ll probably want to derive it from std::logic_error.
void push(any &&data)
{
if(_size<_capacity)
_data[_size++]=data;
else
throw "Out of memory &&";
}
Since you are taking an r-value reference, you should move the data, not copy it. That’s the point of this overload, right? To avoid copies.
Incidentally, you should also consider adding an emplace() function, to allow in-place construction.
#ifdef RAW
Stack& operator=(const Stack &rhs)
{
if(this != &rhs)
{
_capacity = rhs._capacity;
_size = rhs._size;
for(int i=0; i < _capacity ; ++i)
_data[i] = rhs._data[i];
}
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
Okay, once again, this is a raw pointer operation… and you have a bug.
You set the size and capacity of *this, which is fine… but you never do anything with the data pointer. What if the initial capacity is 3, and the capacity of rhs is 10. You’re going to try to copy 10 objects into a 3-element array. Not good.
To do this not just correctly, but intelligently, you need to consider a number of situations. For example, what if the current capacity is larger than rhs._size? In that case, it would be silly to reallocate; we have enough space!
But there is another thing to consider, too: what happens if any of the items in the data array throw during the copy. If you’re not careful—as in the code above—you may end up with the data half-copied. That’s a bad look.
Because you’re using std::any, there’s really no choice other than to always assume that copying might throw. (If you had used a templated type, then you could check whether that type might throw on copy. Then things can get more complicated, but also, much, much more efficient.) So your only real option is the copy-and-swap idiom:
#ifdef RAW
auto operator=(Stack const& rhs) -> Stack&
{
if (this != &rhs) // not necessary, but meh
{
auto p = std::make_unique<std::any[]>(rhs._capacity);
// Note I only copy up to size, not capacity. There’s no point
// copying the empty elements at the end.
std::copy(rhs._data, rhs._data + rhs._size, p.get());
// Dangerous part's done. Everything from here on out is no-fail.
// It's safe to delete the old pointer now.
delete[] _data;
// And it's safe to get the new pointer out of the unique_ptr, and
// save it.
_data = p.release();
// And of course, these are safe.
_capacity = rhs._capacity;
_size = rhs._size;
}
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
return *this;
}
Which can be simplified to:
auto operator=(Stack const& rhs) -> Stack&
{
if (this != &rhs)
{
// Copy...
auto temp = rhs;
// ... and swap.
swap(*this, temp);
}
return *this;
}
And since self-assignment is vanishingly rare, you can remove the if check, and just get:
auto operator=(Stack const& rhs) -> Stack&
{
auto temp = rhs;
swap(*this, temp);
return *this;
}
Which works for both raw pointers and unique_ptr.
void swap(Stack &rhs)
{
std::swap(_data,rhs._data);
std::swap(_size,rhs._size);
std::swap(_capacity,rhs._capacity);
}
This is not how you use std::swap. The correct way is to do the std::swap two-step:
void swap(Stack& rhs) noexcept // noexcept is important for swap!
{
using std::swap;
swap(_data,rhs._data);
swap(_size,rhs._size);
swap(_capacity,rhs._capacity);
}
You should pretty much always do that when swapping. (I cheat in some of the code blocks above, because I know I don’t need the using std::swap;. But it really should still be there.)
As of C++20, you don’t need to do the std::swap two-step anymore if you do this:
void swap(Stack& rhs) noexcept
{
std::ranges::swap(_data,rhs._data);
std::ranges::swap(_size,rhs._size);
std::ranges::swap(_capacity,rhs._capacity);
}
In other words, use std::ranges::swap() rather than std::swap().
Stack& operator=(Stack rhs)
{
swap(rhs);
return *this;
}
This… is not a great idea.
The issue is that you really, really, really want the move assignment to be noexcept… but the copy assignment can’t be noexcept. So you need two functions; you can’t be clever and cheat and get away with one.
std::any top()
{
if(validSize())
return _data[_size-1];
throw string("Stack is empty");
} | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
First, this should probably be const.
Second, it seems a bit silly to copy the top element of the stack. Maybe the user doesn’t need their own copy of it; maybe they just want to peek at it to read it. Why not just return a reference to it? And if you’re going to do that, you should probably have both const and non-const versions.
Finally, as mentioned above, throwing a string is not a great idea. You should throw an actual exception object. In this case, std::out_of_range is probably the best choice:
constexpr auto top() -> std::any&
{
if (empty())
throw std::out_of_range{"Stack is empty"};
return _data[_size - 1];
}
constexpr auto top() const -> std::any const&
{
if (empty())
throw std::out_of_range{"Stack is empty"};
return _data[_size - 1];
}
If you really want to be stylish, you could also add rvalue versions, that intelligently return a copy, rather than a reference (which will probably dangle):
constexpr auto top() & -> std::any&
{
if (empty())
throw std::out_of_range{"Stack is empty"};
return _data[_size - 1];
}
constexpr auto top() const& -> std::any const&
{
if (empty())
throw std::out_of_range{"Stack is empty"};
return _data[_size - 1];
}
constexpr auto top() && -> std::any
{
if (empty())
throw std::out_of_range{"Stack is empty"};
return std::move(_data[_size - 1]);
}
constexpr auto top() const&& -> std::any
{
if (empty())
throw std::out_of_range{"Stack is empty"};
return _data[_size - 1];
}
It’s a bit repetitive, but that’s the best we can do until C++23.
void pop()
{
if(validSize())
--_size;
} | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
There is a very subtle bug here. If you just decrement the size, you still leave the object in the array.
Consider this. Suppose I have a type that counts how many instances exist:
struct counting_type
{
static int count = 0;
counting_type() noexcept { ++count; }
counting_type(counting_type const&) noexcept { ++count; }
counting_type(counting_type&&) noexcept { ++count; }
~counting_type() { --count; }
auto operator=(counting_type const&) noexcept -> counting_type& = default
auto operator=(counting_type&&) noexcept -> counting_type& = default
}
Now I create a stack, put 3 of those in, and then pop them out:
std::cout << counting_type::count << '\n'; // prints 0
auto s = Stack{3};
stack.push(counting_type{});
stack.push(counting_type{});
stack.push(counting_type{});
std::cout << counting_type::count << '\n'; // prints 3
stack.pop();
stack.pop();
stack.pop();
std::cout << counting_type::count << '\n'; // prints ???
What do you think the last line should print.
I think just about anyone would guess that the last line prints 0. But… it doesn’t. It prints 3, because those 3 objects were just… left… sitting there in the stack after they were popped.
What you should do is not just decrement the size, but also clear the object being popped:
void pop()
{
if (empty())
throw std::out_of_range{"Stack is empty"};
_data[--_size].reset();
} | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c++, object-oriented, c++17
_data[--_size].reset();
}
Now when you pop an object off the stack, it is actually destroyed.
Finally, there are some useful functions you’re missing. empty() would be very handy. clear() would be nice, too. It would be neat if the capacity weren’t fixed at construction time, and you could reserve(). emplace() would be useful, too.
You can see there’s really no benefit to using raw pointers. When you do, you still end up having to use unique_ptrs anyway, for proper exception safety. I suppose you could use try-catch blocks if you really must… but unique_ptrs will be simpler, clearer, and probably more efficient. unique_ptrs can be a little clunkier, because you can’t use them directly in most algorithms as iterators; you need to get the raw pointers out of them for that. But I think all-in-all, unique_ptr is the only way to go, in practice. | {
"domain": "codereview.stackexchange",
"id": 43241,
"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, c++17",
"url": null
} |
c#, performance, reflection
Title: Best way to get an arbitrary property for a C# class?
Question: I have close to a hundred classes where I need to get arbitrary properties from them at runtime. The calling class knows which properties it wants at run time, but not at compile time. Looking for any suggestions on a quick way to do this.
My ideas so far:
Option 1: Add "public object Get(string prop) {...}" to all classes, then invoke myClass.Get(prop)
Option 2: Use reflection: typeof(myClass).GetProperty(prop).GetValue(myClass)
Option 3: Use ComponentModel: TypeDescriptor.GetProperties(typeof(myClass))[prop].GetValue(myClass);
Option 4: HyperTypeDescriptionProvider
Trying these out gave me runtimes of:
301ms (baseline accessing the property directly)
1308ms Option 1
4383ms Option 2
5229ms Option 3
Option 4 threw System.TypeInitializationException constantly and never completed.
Full Executable sample:
//using Hyper.ComponentModel;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection; | {
"domain": "codereview.stackexchange",
"id": 43242,
"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, reflection",
"url": null
} |
c#, performance, reflection
namespace Sandbox2
{
public class MyTable
{
public string col0 {get;set;}
public int col1 { get; set; }
public string[] col2 { get; set; }
public object col3 { get; set; }
public string col4 { get; set; }
public object Get(string prop)
{
switch(prop)
{
case "col0":
return col0;
case "col1":
return col1;
case "col2":
return col2;
case "col3":
return col3;
case "col4":
return col4;
}
throw new InvalidOperationException("Non-existent prop");
}
}
class Program
{
static void Main(string[] args)
{
const int CYCLES = 5000000;
//const int CYCLES = 1;
GC.Collect();
Stopwatch timer = new Stopwatch();
string[] goalProps = { "col2", "col0", "col4" };
MyTable myTable = new MyTable();
timer.Start();
for (int i = 0; i < CYCLES; ++i)
{
object[] res = { myTable.col2, myTable.col0, myTable.col4 };
}
timer.Stop();
System.Diagnostics.Debug.WriteLine("Elapsed: " + timer.ElapsedMilliseconds);
GC.Collect();
timer.Start();
for (int i=0; i<CYCLES; ++i)
{
object[] res = { myTable.Get(goalProps[0]), myTable.Get(goalProps[1]), myTable.Get(goalProps[2]) };
}
timer.Stop();
System.Diagnostics.Debug.WriteLine("Elapsed: " + timer.ElapsedMilliseconds);
timer.Reset();
GC.Collect();
timer.Start();
for (int i = 0; i < CYCLES; ++i)
{
Type t = myTable.GetType(); | {
"domain": "codereview.stackexchange",
"id": 43242,
"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, reflection",
"url": null
} |
c#, performance, reflection
{
Type t = myTable.GetType();
PropertyInfo[] goalPropsInfo = { t.GetProperty(goalProps[0]), t.GetProperty(goalProps[1]), t.GetProperty(goalProps[2]) };
object[] res = { goalPropsInfo[0].GetValue(myTable), goalPropsInfo[1].GetValue(myTable), goalPropsInfo[2].GetValue(myTable) };
}
timer.Stop();
System.Diagnostics.Debug.WriteLine("Elapsed: " + timer.ElapsedMilliseconds);
timer.Reset();
GC.Collect();
timer.Start();
for (int i = 0; i < CYCLES; ++i)
{
Type t = myTable.GetType();
//HyperTypeDescriptionProvider.Add(t);
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(t);
PropertyDescriptor[] goalPropsInfo = { props[goalProps[0]], props[goalProps[1]], props[goalProps[2]] };
object[] res = { goalPropsInfo[0].GetValue(myTable), goalPropsInfo[1].GetValue(myTable), goalPropsInfo[2].GetValue(myTable) };
}
timer.Stop();
System.Diagnostics.Debug.WriteLine("Elapsed: " + timer.ElapsedMilliseconds);
}
}
}
```` | {
"domain": "codereview.stackexchange",
"id": 43242,
"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, reflection",
"url": null
} |
c#, performance, reflection
Answer: A way to optimize is to use a static constructor to automatically prefill a static lookup table (dictionary) to map property names to the property getters.
This being static is done once for the class and reused across all instances so it has a low overhead since the cost is amortized across all instance usages. Also can be easily done for all properties as shown below or only for selected ones as required.
After that extracting the property value is trivial.
public class MyTable
{
// map of property names to functions which retrieve the property
static Dictionary<string, Func<object, object>> _props =
new Dictionary<string, Func<object, object>>();
static MyTable()
{
foreach(var property in typeof(MyTable).GetProperties())
_props[property.Name] = property.GetValue;
// Note: property.GetValue may be easier to understand as
// (obj => property.GetValue(obj)) where object is an instance of the class
}
public string col0 { get; set; }
public int col1 { get; set; }
public string[] col2 { get; set; }
public object col3 { get; set; }
public string col4 { get; set; }
public object Get(string prop)
{
Func<object, object> getProp;
if (_props.TryGetValue(prop, out getProp))
return getProp(this);
throw new InvalidOperationException("Non-existent prop");
}
}
Usage example
public static void Main()
{
var myTable = new MyTable();
myTable.col0 = "0";
var col0 = myTable.Get("col0");
Console.WriteLine(col0);
} | {
"domain": "codereview.stackexchange",
"id": 43242,
"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, reflection",
"url": null
} |
java, array
Title: Practicing with array
Question: The class "post" only has simple methods like getters for the ID(long) and number of likes(long). Is how I wrote my method below accomplishing anything? Is it doing what I want it to do? I am a beginner so I am sorry if my question is too stupid.
public class PracticeStats {
Given an array of posts, this method finds the ID of the post that has the most likes. Return -1 if the array is of length 0. If two posts have the same number of likes, return the number of likes of either post. return ID of the post with most likes if the array is non-empty, 0 otherwise
public static long mostLikedPost(Post[] posts) {
long max = 0;
for (int i = 0; i< posts.length; i++) {
long curr = posts[i].getNumLikes();
if(curr > max) {
curr = max;
}
return posts[i].getID();
}
return max;
}
Answer: Advice 1
Judging from the method name mostLikedPost, you expect the most liked post and not its number of likes, so you must have
public static Post mostLikedPost(Post[] posts) ...
^^^^
Advice 2
return posts[i].getID();
The above will terminate the entire loop at the very first iteration.
Advice 3
You could use a foreach loop.
Alternative implementation
public static Post mostLikedPost(Post[] posts) {
long maxLikes = 0;
Post favoritePost = null;
for (Post post : posts) {
long currentLikes = post.getNumLikes();
if (maxLikes < currentLikes) {
maxLikes = currentLikes;
favoritePost = post;
}
}
return favoritePost;
}
With streams API:
public static Post mostLikedPost(Post[] posts) {
return Arrays.stream(posts)
.max((p1, p2) -> {
return Long.compare(p1.getNumLikes(),
p2.getNumLikes());
}).orElse(null);
}
Hope that helps. | {
"domain": "codereview.stackexchange",
"id": 43243,
"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, array",
"url": null
} |
python, beginner, python-3.x, reinventing-the-wheel, binary-search
Title: Binary search algorithm (Python 3.9)
Question: New to using this platform and would like to familiarise myself with it so would just like to ask if I am exhibiting good practice with my programming.
Started the online CS50 course today and thought I would try to write my own program to execute a binary search with the small amount of programming I learnt in school, since it was mentioned within the lecture, took a little while but I figured it out.
Would just like my learning journey to be as effective as possible, so would be grateful for any improvements for efficiency within my code or point out if I have any bad habits, thanks!
import random
array = list(range(1,600))
x = random.randint(1,600)
highest = 600
length = len(array)
middle = (highest//2)
array_middle = length//2
found = False
hi = array[-1]
lo = array[0]
middle = (hi + lo)/ 2
while found == False:
if x > hi:
print("Your number is not in the list")
found = True
break
elif x < (middle):
array = array[:array_middle]
highest = array[-1]
lowest = array[0]
middle = (highest + lowest)/2
length = len(array)
array_middle = length//2
print(array)
print(x)
elif x > (middle):
array = array[array_middle:]
highest = array[-1]
lowest = array[0]
middle = (highest + lowest)/2
length = len(array)
array_middle = length//2
print(array)
print(x)
else:
print(x)
found = True | {
"domain": "codereview.stackexchange",
"id": 43244,
"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, beginner, python-3.x, reinventing-the-wheel, binary-search",
"url": null
} |
python, beginner, python-3.x, reinventing-the-wheel, binary-search
Answer: Your binary search is flawed in various ways, but don't feel bad. It's a
deceptively difficult
algorithm to get right.
The primary problem: confusion between indexes and values. Some of your
code bisects the sequence using index-based logic; other parts rely on
value-based logic (taking the average of highest and lowest values).
In addition to overcomplicating the implementation, that creates some bugs:
Given [1, 3] and 2.
Incorrectly says 2 is in the sequence.
Given [1, 5] and 2.
Gets stuck in an endless loop. | {
"domain": "codereview.stackexchange",
"id": 43244,
"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, beginner, python-3.x, reinventing-the-wheel, binary-search",
"url": null
} |
python, beginner, python-3.x, reinventing-the-wheel, binary-search
Given [1, 5] and 2.
Gets stuck in an endless loop.
An edge case bug: empty sequences. Given an empty sequence, binary
search should return None; your code blows up with an IndexError.
A performance problem: data copying. Your code makes copies of the input
sequence. That's not needed if we stick entirely to index-based logic for
bisecting.
A software engineering problem: binary search should be written as a
function. Put your code in functions, even in small scripts. There are many
reasons for this, and those reasons are particularly compelling when writing
algorithmic code like binary search. Such a function should take the sequence
and target value as input and return the target's index or None. It should not
print messages to the user: leave that to a different part of the program. When
you put the algorithm inside a side-effect-free function you make it much
easier to test. And a problem like binary search, with its many pitfalls,
requires some real testing.
Start on a good foundation: functions. We need a binary search function and
a main function to exercise the code with some tests. We already have some test
cases: the bugs noted above. As you write the code, try to
think of the various edge cases to be explored and write a test for each one.
def main():
TESTS = [
([], 2, None),
([1, 3], 2, None),
([1, 5], 2, None),
([1, 2, 3], 2, 1),
]
for test in TESTS:
xs, target, expected = test
result = binary_search(xs, target)
if result == expected:
print('ok')
else:
print(f'{test} : {result}')
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43244,
"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, beginner, python-3.x, reinventing-the-wheel, binary-search",
"url": null
} |
python, beginner, python-3.x, reinventing-the-wheel, binary-search
if __name__ == '__main__':
main()
Binary search: do the bisecting with indexes, not values. Here's
a good starting point. You can fill in the rest of the logic.
def binary_search(xs, target):
i = 0
j = len(xs) - 1
while i <= j:
mid = (i + j) // 2
# Compare xs[mid] to the target, either returning mid
# or modifying i and j.
...
return None | {
"domain": "codereview.stackexchange",
"id": 43244,
"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, beginner, python-3.x, reinventing-the-wheel, binary-search",
"url": null
} |
javascript, authentication, jwt
Title: User registration and login service using JWT
Question: I have created service to communicate with my backend for user registration and login. I use the JS fetch API and send all data through HTTPS. I use JWT tokens to authenticate queries once I have logged, and this is stored in the window local storage.
The API details are stored in a config.json file.
Two things that I'm not sure if I can improve are:
Should I use local storage for storing the JWT token or is there a better alternative?
Is it ok to send the password without hashing it first on the client side? On the server side it is hashed and salted before storage so no plaintext passwords are stored.
import config from "../config.json"
let jwtToken = null;
const login = async (email, pass) => {
const loginData = {
"email": email,
"password": pass
}
const loginResponse = await fetch(config.host + config.loginUrl, {
body: JSON.stringify(loginData),
method: "POST",
headers: {
'Content-Type': 'application/json'
}
})
if(loginResponse.ok)
{
jwtToken = await loginResponse.text();
window.localStorage.setItem("jwtToken", jwtToken);
return true;
}
return false;
}
const register = async ({ firstName,
lastName,
email,
password
}) => {
const registrationData = {
"firstName":firstName,
"lastName":lastName,
"email": email,
"password":password
};
const registerResponse = await fetch(config.host + config.usersUrl, {
body: JSON.stringify(registrationData),
method: "POST",
headers: {
'Content-Type': 'application/json'
}
})
return registerResponse.ok;
}
const logout = () =>
{
window.localStorage.removeItem("jwtToken", null);
}
const isLoggedIn = () => !(window.localStorage.getItem("jwtToken") === null); | {
"domain": "codereview.stackexchange",
"id": 43245,
"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": "javascript, authentication, jwt",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.