text stringlengths 1 2.12k | source dict |
|---|---|
c++, game, sfml
bool Pipes::score(float x)
{
if (x == s_top1.getPosition().x + 24)
{
return true;
}
else if (x == s_top2.getPosition().x + 24)
{
return true;
}
else
{
return false;
}
}
void Pipes::drawPipes()
{
data->window.draw(s_top1);
data->window.draw(s_down1);
data->window.draw(s_top2);
data->window.draw(s_down2);
}
const sf::Sprite& Pipes::getFirstTopSprite()
{
return s_top1;
}
const sf::Sprite& Pipes::getFirstDownSprite()
{
return s_down1;
}
const sf::Sprite& Pipes::getSecondTopSprite()
{
return s_top2;
}
const sf::Sprite& Pipes::getSecondDownSprite()
{
return s_down2;
}
ResourceHolder.h
#pragma once
#include <SFML/Graphics.hpp>
#ifndef RESOURCEHOLDER_H
#define RESOURCEHOLDER_H
template<typename ResourceType, typename KeyType>
class ResourceHolder
{
using MapType = std::map<KeyType, ResourceType*>;
public:
template<typename ... Args>
ResourceType* loadFromFile(const std::string& fileName, const KeyType& key, Args &&... args)
{
ResourceType*& resourceRef = mResources[key];
if (resourceRef != nullptr) {
return resourceRef;
}
resourceRef = new ResourceType();
if (!resourceRef->loadFromFile(fileName, std::forward<Args>(args)...)) {
delete resourceRef;
resourceRef = nullptr;
}
return resourceRef;
}
ResourceType* getResource(const KeyType& key)
{
typename MapType::iterator resourcePairIt = mResources.find(key);
if (resourcePairIt == mResources.end()) {
return nullptr;
}
return resourcePairIt->second;
}
~ResourceHolder()
{
for (auto& e : mResources) {
delete e.second;
}
} | {
"domain": "codereview.stackexchange",
"id": 43813,
"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++, game, sfml",
"url": null
} |
c++, game, sfml
ResourceHolder() = default;
ResourceHolder(const ResourceHolder&) = delete;
ResourceHolder(ResourceHolder&&) = delete;
ResourceHolder& operator=(const ResourceHolder&) = delete;
ResourceHolder& operator=(ResourceHolder&&) = delete;
private:
MapType mResources;
};
template<typename ResourceType, typename KeyType>
ResourceHolder<ResourceType, KeyType>& getGlobalResourceHolder()
{
static ResourceHolder<ResourceType, KeyType> holder;
return holder;
}
inline auto getGlobalTextureHolder = getGlobalResourceHolder<sf::Texture, std::string>;
inline auto getGlobalFontHolder = getGlobalResourceHolder<sf::Font, std::string>;
#endif
State.h
#pragma once
class State
{
public:
virtual void init() = 0;
virtual void handleInput() = 0;
virtual void update(float dt) = 0;
virtual void draw(float dt) = 0;
virtual void pause() {}
virtual void resume() {}
};
StateMachine.h
#pragma once
#include <stack>
#include <memory>
#include "State.h"
typedef std::unique_ptr <State> StateRef;
class StateMachine
{
private:
std::stack <StateRef> states;
StateRef newState;
bool isRemoving;
bool isAdding;
bool isReplacing;
public:
StateMachine() {}
void addState(StateRef _newState, bool _isReplacing = true);
void removeState();
void processStateChanges();
StateRef& getActiveState();
~StateMachine() {}
};
StateMachine.cpp
#include "StateMachine.h"
void StateMachine::addState(StateRef _newState, bool _isReplacing)
{
this->isAdding = true;
this->isReplacing = _isReplacing;
this->newState = std::move(_newState);
}
void StateMachine::removeState()
{
this->isRemoving = true;
}
void StateMachine::processStateChanges()
{
if (this->isRemoving && !this->states.empty())
{
this->states.pop();
if (!this->states.empty())
{
this->states.top()->resume();
}
this->isRemoving = false;
} | {
"domain": "codereview.stackexchange",
"id": 43813,
"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++, game, sfml",
"url": null
} |
c++, game, sfml
this->isRemoving = false;
}
if (this->isAdding)
{
if (!this->states.empty())
{
if (this->isReplacing)
{
this->states.pop();
}
else
{
this->states.top()->pause();
}
}
this->states.push(std::move(this->newState));
this->states.top()->init();
this->isAdding = false;
}
}
StateRef& StateMachine::getActiveState()
{
return this->states.top();
}
Answer: About your StateMachine
You can model some things as state machines, but writing a state machine class and having that implement your state machine logic is often more work and less clear than just writing what you want to do directly in C++. It's even worse if your state machine isn't used to encode all the possible states and their transitions up front, but when you dynamically add and remove states.
But perhaps it's just an issue of naming; maybe SceneManager would be better, as what you call a "state" is usually called a "scene" in game engines such as Godot and Unity. Then similarly, State should be renamed Scene.
Instead of addState() with a flag _isReplacing and removeState(), I would have member functions replace(), push() and pop().
Naming things
Naming things correctly is important. I would change the way these things are named:
GameDataRef: making a type alias is fine, but I would associate "Ref" with a reference, not with a std::shared_ptr<>. So GameDataPtr would be more appropriate.
game1: why the 1? That implies there is more than one. I would name it game, but in fact it doesn't need a name at all, you can just write:
int main() {
Game();
} | {
"domain": "codereview.stackexchange",
"id": 43813,
"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++, game, sfml",
"url": null
} |
c++, game, sfml
loadResource(): it loads multiple resources, so I would name it loadResources().
TextureSize: this is inconsistent with the way you name other variables, so it should be textureSize.
s_bird, so_die, t_score: it's weird to see you use a prefix only for some types of variables. I would avoid using a prefix, especially if they are abbreviated so much. Either write sprite_bird, sound_die and so on, or consider grouping them inside a struct, like so:
struct {
sf::Text score;
sf::Text bestScore;
} text;
Unnecessary use of this->
You almost never have to write this-> in C++. I would remove it everywhere.
Updating state
In Game::run(), you have the main loop which first calls processStateChanges(), but then goes into another loop that might call handleInput() and update() multiple times. This might be problematic, as this means there can be multiple changes submitted to the state machine before they are processed. Conversely, if accumulator < dt you call processStateChanges() unnecessarily, as nothing will have changed since the last call.
I would make sure processStateChanges() is called inside the inner while-loop. In fact, you'll have three function calls there that I would replace by just one, which then takes care of processing state changes, handling input and updating the state:
while (data->window.isOpen())
{
...
while (accumulator >= dt)
{
data->machine.update(dt);
}
...
data->machine.draw(interpolation);
}
Note that the above doesn't call getActiveState() anymore, but instead assumes update() and draw() are member functions of StateMachine. The latter should then handle getting the currently active state and calling the relevant member functions of the currently active State:
void StateMachine::update(float dt)
{
processStateChanges();
auto state = getActiveState();
state->handleInput();
state->update(dt);
} | {
"domain": "codereview.stackexchange",
"id": 43813,
"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++, game, sfml",
"url": null
} |
c++, game, sfml
Use of smart pointers
It's good to use smart pointers to avoid manual memory management. However, some types of smart pointers have some overhead, particularly std::shared_ptr<>. If you don't need the reference counted semantics, use std::unique_ptr<> and/or regular pointers or references instead. Sometimes you don't even need (smart) pointers, and should just store by value instead.
Consider Game::data. Instead of making that a std::shared_ptr<>, you can store it by value, and have classes that need to access that data store a reference to it instead, as the instance of Game is guaranteed to be alive while any of the other game objects are. So:
class Game
{
...
GameData data;
...
};
class Bird
{
GameData& data;
...
public:
Bird(GameData& _data);
...
};
Bird::Bird(GameData& _data): data(_data)
{
...
}
Another case where smart pointers are unnecessary is in ResourceHolder. A std::map already allocates memory for the keys and values, so you don't have to. Just store resources in them directly, for example:
template<typename ResourceType, typename KeyType>
class ResourceHolder
{
using MapType = std::map<KeyType, ResourceType>;
public:
template<typename ... Args>
ResourceType& loadFromFile(const std::string& fileName, const KeyType& key, Args&&... args)
{
if (auto it = mResources.find(key); it != mResources.end()) {
return it->second;
}
auto& resource = mResources[key];
if (!resource.loadFromFile(fileName, std::forward<Args>(args)...)) {
throw std::runtime_error("Could not load resource");
}
return resource;
}
ResourceType& getResource(const KeyType& key) {
return mResources.at(key);
}
...
}; | {
"domain": "codereview.stackexchange",
"id": 43813,
"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++, game, sfml",
"url": null
} |
c++, game, sfml
You also should either use std::unique_ptr<> for iM2 and camera2, or store them by value instead. At the moment those two variables will leak memory, since they are never deleted.
When you do use smart pointers, avoid manual calls to new. You can use std::make_unique<> instead. Note that a std::unique_ptr<Derived> can be assigned to a std::unique_ptr<Base>, so this is valid:
data->machine.addState(std::make_unique<MainMenuState>(data));
Make functions easy to use
Don't be afraid to modify or add more functions to take care of boring tasks. For example, addState() requires you to create a unique pointer first. Why not let addState() do that for you? It could look like this:
class StateMachine
{
...
template<typename T, typename... Args>
void addState(Args&&... args)
{
newState = std::make_unique<T>(std::forward<Args>(args)...);
}
...
};
And then it could be called like so:
data->machine.addState<GameOverState>(data, score);
Of course, with a variable number of arguments you really want to have two functions, say replace() and push(), to distinguish between adding and replacing a state.
You are already using using to avoid typing long names, but you can also make aliases for variables. Consider:
void GameOverState::draw(float dt)
{
auto& window = data->window;
window.clear();
window.draw(s_back);
window.draw(s_retryButton);
...
window.display();
} | {
"domain": "codereview.stackexchange",
"id": 43813,
"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++, game, sfml",
"url": null
} |
c++, game, sfml
Error handling
Make sure you handle errors correctly. If something goes wrong, print a clear error message to std::cerr (not std::cout), then make sure you exit the program with a non-zero exit code, preferrably EXIT_FAILURE. Alternatively, throw an exception; unhandled exceptions will cause a program to abort with an error message. Failure to do so will cause the program to continue running with incorrect data.
In the constructor of Game(), where you cannot return an error code, I would write:
if (!loadResources())
{
throw std::runtime_error("Could not load all resources");
}
However, if you are going to use exceptions, it's better to throw directly at the place where things actually go wrong. For resource loading, that's in ResourceHolder::loadFromFile().
When reading or writing a file, errors can happen at any point, not just when opening the file. Also note that .eof() is only true when the end of a file has been reached, but not when an error occured halfway. Your read loop in GameOverState::init() may thus loop indefinitely it it cannot read an int from the file.
Random number generation
I see you call srand(time(NULL)), and I was afraid you were going to use the rather bad C random number generator. However, you are using std::mt19937, which is great, but then you don't need to call srand() anymore.
However, you still seed the std::mt19937 generator using time(0). I recommend that you avoid any C functions, and use the C++ way where possible:
std::random_device rd;
std::mt19937 gen(rd());
Also note that creating a generator is costly, so you should only do it once. You can do so by making gen a static variable, or a member variable of Pipes. | {
"domain": "codereview.stackexchange",
"id": 43813,
"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++, game, sfml",
"url": null
} |
c++, datetime
Title: Unix epoch seconds corresponding to midnight in a local time zone
Question: I came up with the following function to obtain epoch seconds that correspond to previous midnight in a local time zone:
#include <iostream>
#include <chrono>
#include <date/date.h>
#include <date/tz.h>
long local_midnight_epoch() {
using namespace date;
using namespace std::chrono;
auto t = std::chrono::system_clock::now();
auto* zone = date::current_zone();
auto zt = make_zoned(zone, t);
zt = floor<days>(zt.get_local_time());
auto seconds_since_midnight = floor<seconds>(t - zt.get_sys_time());
std::chrono::time_point<std::chrono::system_clock> ts = std::chrono::system_clock::now();
auto epoch = std::chrono::duration_cast<std::chrono::seconds>(ts.time_since_epoch());
epoch -= seconds_since_midnight;
return epoch.count();
}
int main(void) {
std::cerr << local_midnight_epoch() << std::endl;
}
The code uses Howard Hinnant's date library. It first computes seconds passed since midnight in a local time zone, and then subtract that the current epoch. Is there an easier way to accomplish this? Thanks.
Answer: This is a good attempt at getting the UTC timestamp associated with the previous local midnight. For me it gets within a second or two of the correct answer.
Here's what I recommend, with each line commented with what it does:
long local_midnight_epoch2() {
using namespace date;
using namespace std::chrono;
// current time in seconds, UTC
auto now = floor<seconds>(system_clock::now());
// corresponding local time
zoned_seconds zt{current_zone(), now};
// reset to previous local midnight
zt = floor<days>(zt.get_local_time());
// get UTC corresponding to local midnight
auto epoch = zt.get_sys_time();
return epoch.time_since_epoch().count();
}
The biggest advantage over what you have is that it only calls system_clock::now() once. Otherwise it is quite similar to what you have. | {
"domain": "codereview.stackexchange",
"id": 43814,
"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++, datetime",
"url": null
} |
c++, algorithm, c++11, linked-list
Title: Queue using circular linked list
Question: I'm reading through Algorithms Fourth Edition by Sedgewick and doing some of the practice exercises in C++11 instead of Java. Exercise 1.3.29 is to write a Queue that uses a circular linked list, keeping only one Node instance variable (last).
All comments are welcome, but especially ones focusing on advanced C++ techniques as well as the algorithm itself.
#ifndef QUEUE_HH
#define QUEUE_HH
#include <cstddef>
#include <stdexcept>
template<class T>
class Queue {
public:
Queue()
: _last(nullptr)
{}
void enqueue(T value)
{
// Create a new node, not yet linked to anything
Node* node = new Node{value, nullptr};
if(is_empty()) {
// Only node in the list, link it to itself
node->next = node;
} else {
// Link the new node to the start of the list
node->next = _last->next;
// Add the new node to the end of the list
_last->next = node;
}
_last = node;
}
T dequeue()
{
if(is_empty()) {
throw std::out_of_range("Empty queue");
}
// Get the first node in the list
Node* node = _last->next;
// Unlink the node by pointing last to the next node
_last->next = node->next;
// If we're removing the only node in the list, set last node to nullptr
if(node == _last) {
_last = nullptr;
}
// Retrieve the value before deleting the node
int value = node->value;
delete node;
return value;
}
size_t size() const
{
if(is_empty()) {
return 0;
}
// Start at last node, count iterations until last node is reached again
size_t count = 0;
Node* current = _last;
do {
count++;
current = current->next;
} while(current != _last);
return count;
} | {
"domain": "codereview.stackexchange",
"id": 43815,
"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++, algorithm, c++11, linked-list",
"url": null
} |
c++, algorithm, c++11, linked-list
return count;
}
bool is_empty() const
{
return _last == nullptr;
}
private:
struct Node
{
T value;
Node* next;
};
Node* _last;
};
#endif // QUEUE_HH
Answer: There is a bug in the dequeue function:
// Retrieve the value before deleting the node
int value = node->value;
The Queue class is a template, therefore the value of the node is of type T. And instead of assigning it, moving the value (see std::move) is a better choice:
T value{std::move(node->value)};
Why move?
Imagine T is a string or an vector with millions of entries. A copy is expensive, move will only transfer the associated resources (e.g. simple pointer exchange). Don't forget, node will be destroyed, therefore the value in node too. That's why the assignment to the return value. Again, why create and destroy if we just simply could transfer (move) it.
As long as T is a primitive type (small type), there is no difference between copy and move assignment, but the more there is to copy ... | {
"domain": "codereview.stackexchange",
"id": 43815,
"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++, algorithm, c++11, linked-list",
"url": null
} |
c++, c++20, child-process, posix
Title: Executing a Bash script from C++
Question: I am trying to execute a Bash command, get the pid, read the (error) output and optionally pass input.
I am still quite new at C++ and I would like to know if this is a correct & safe implementation for use in real-world applications?
The target operating systems are MacOS 12.5 & Ubuntu (server) 20.04.
The target C++ version is C++20 (aka C++2a).
#include <iostream>
#include <unistd.h>
#include <array>
#include <string>
int main() {
// Vars.
const char* command = "echo Hello World!";
const char* input = "";
const int READ_END = 0;
const int WRITE_END = 1;
int infd[2] = {0, 0};
int outfd[2] = {0, 0};
int errfd[2] = {0, 0};
// Cleanup func.
auto cleanup = [&]() {
::close(infd[READ_END]);
::close(infd[WRITE_END]);
::close(outfd[READ_END]);
::close(outfd[WRITE_END]);
::close(errfd[READ_END]);
::close(errfd[WRITE_END]);
};
// Pipes.
auto rc = ::pipe(infd);
if(rc < 0) {
throw std::runtime_error(std::strerror(errno));
}
rc = ::pipe(outfd);
if(rc < 0) {
::close(infd[READ_END]);
::close(infd[WRITE_END]);
throw std::runtime_error(std::strerror(errno));
}
rc = ::pipe(errfd);
if(rc < 0) {
::close(infd[READ_END]);
::close(infd[WRITE_END]);
::close(outfd[READ_END]);
::close(outfd[WRITE_END]);
throw std::runtime_error(std::strerror(errno));
}
// Parent.
auto pid = fork();
if(pid > 0) {
::close(infd[READ_END]); // Parent does not read from stdin
::close(outfd[WRITE_END]); // Parent does not write to stdout
::close(errfd[WRITE_END]); // Parent does not write to stderr
if(::write(infd[WRITE_END], input, strlen(input)) < 0) {
throw std::runtime_error(std::strerror(errno));
}
::close(infd[WRITE_END]);
} | {
"domain": "codereview.stackexchange",
"id": 43816,
"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++20, child-process, posix",
"url": null
} |
c++, c++20, child-process, posix
// Child.
else if(pid == 0) {
::dup2(infd[READ_END], STDIN_FILENO);
::dup2(outfd[WRITE_END], STDOUT_FILENO);
::dup2(errfd[WRITE_END], STDERR_FILENO);
::close(infd[WRITE_END]); // Child does not write to stdin
::close(outfd[READ_END]); // Child does not read from stdout
::close(errfd[READ_END]); // Child does not read from stderr
::execl("/bin/bash", "bash", "-c", command, nullptr);
::exit(EXIT_SUCCESS);
}
// Error.
if(pid < 0) {
cleanup();
throw std::runtime_error("Failed to fork");
}
// Wait at pid.
int status = 0;
::waitpid(pid, &status, 0);
// Read output.
std::string output;
std::string error;
std::array<char, 256> buffer;
ssize_t bytes = 0;
while ((bytes = ::read(outfd[READ_END], buffer.data(), buffer.size())) > 0) {
output.append(buffer.data(), bytes);
}
while ((bytes = ::read(errfd[READ_END], buffer.data(), buffer.size())) > 0) {
error.append(buffer.data(), bytes);
}
// Get exit status.
if(WIFEXITED(status)) {
status = WEXITSTATUS(status);
}
// Cleanup.
cleanup();
std::cout << "PID: " << pid << "\n";
std::cout << "STATUS: " << status << "\n";
std::cout << "OUTPUT: " << output << "\n";
std::cout << "ERROR: " << error << "\n";
}
Answer: This is a reasonably good start.
You definitely want to use a function, rather than putting everything in main(). That will force you to think about how to return the output and error strings and the exit status (returning the PID seems pointless after the process has exited).
It might be better to pass a couple of std::ostream& as arguments (perhaps default to null streams), rather than returning strings. That could allow the calling program to handle output as it is produced, rather than waiting until the child has finished. | {
"domain": "codereview.stackexchange",
"id": 43816,
"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++20, child-process, posix",
"url": null
} |
c++, c++20, child-process, posix
The cleanup is scattered all over the function - seriously consider wrapping those pipe file-descriptors in RAII objects so that they clean up themselves whenever the function throws or returns.
The structure here is a bit strange:
auto pid = fork();
if(pid > 0) {
⋮
}
// Child.
else if(pid == 0) {
⋮
}
// Error.
if(pid < 0) {
⋮
cleanup();
throw std::runtime_error("Failed to fork");
}
That final if could be an else (and I'd probably test that first, to get the error handling out of the way). The only negative value that fork() is documented to return is -1, so we could even use a switch here.
It's odd that the exception thrown on fork failure discards the useful information in errno, that we keep in other failure paths.
This is definitely wrong:
::execl("/bin/bash", "bash", "-c", command, nullptr);
::exit(EXIT_SUCCESS);
If execl() returns, it means it failed, so we should be exiting with a failure status.
I'm not sure that leaving status = 0 when the program exited by signal is a good choice. And if the process hasn't terminated (remember that wait() returns when the child is stopped, for example), we probably want to loop.
We can have a deadlock with programs that produce more output, because we wait for the process to exit before we start reading its output - but the process may be blocked on its output pipe. We'll need to read output as it is produced (using select() to choose which stream to read from, and periodically wait() for it with the WNOHANG option set to see if it has terminated). | {
"domain": "codereview.stackexchange",
"id": 43816,
"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++20, child-process, posix",
"url": null
} |
php, laravel, wordpress
Title: Default to array when value is null or false
Question: I'm working with ACF in WP which provides a get_field() function. The function can return an array of values, null or false. When the result of the function doesn't contain an array of values I want to default to an empty array.
This is how I do it at the moment but would like to know if there's a neater way to accomplish the same thing.
// can these lines be combined into one without multiple function calls?
$field = get_field('mobile_menu', 'option');
$field = $field ? $field : [];
return collect($field); // other processing
Answer: Shake Rattle and Roll ?:
The ternary short cut ?: , A.K.A. "the Elvis operator" has been available since PHP 5.3.
It could be used to simplify that second line:
$field = $field ? $field : [];
to:
$field = $field ?: [];
That could be used on the line where get_field() is called:
$field = get_field('mobile_menu', 'option') ?: [];
which would allow for the elimination of the second line.
At that point $field is a single-use variable and can be eliminated:
return collect(get_field('mobile_menu', 'option') ?: []); | {
"domain": "codereview.stackexchange",
"id": 43817,
"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": "php, laravel, wordpress",
"url": null
} |
c#, .net, async-await
Title: Asynchronous tasks to subscribe to orders and fills
Question: Pretty straightforward question. The methods SubscribeToOrdersAsync and SubscribeToFillsAsync are pretty similar due to ConnectionLost and ConnectionRestored.
What would be the best approach to follow the DRY principle? I created the SubscribeToAsync method which is my point of view but I would like to know yours.
using CryptoExchange.Net.Objects;
using CryptoExchange.Net.Sockets;
using FTX.Net.Interfaces.Clients;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace InvEx.FtxExchange;
public class FtxProducer : IHostedService
{
private readonly ILogger<FtxProducer> _logger;
private readonly IFTXSocketClient _socketClient;
public FtxProducer(ILogger<FtxProducer> logger, IFTXSocketClient socketClient)
{
_logger = logger;
_socketClient = socketClient;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
var ordersSub = await SubscribeToOrdersAsync(cancellationToken);
var fillsSub = await SubscribeToFillsAsync(cancellationToken);
await SubscribeToAsync(() => _socketClient.Streams.SubscribeToOrderUpdatesAsync(data =>
{
_logger.LogInformation("Orders: {@Data}", data.Data);
}, cancellationToken));
}
public Task StopAsync(CancellationToken cancellationToken)
{
return _socketClient.UnsubscribeAllAsync();
}
private async Task<UpdateSubscription?> SubscribeToAsync(Func<Task<CallResult<UpdateSubscription>>> func)
{
var subscription = await func();
if (subscription.Success)
{
subscription.Data.ConnectionLost += () => _logger.LogError("Connection lost");
subscription.Data.ConnectionRestored += _ => _logger.LogInformation("Connection restored");
return subscription.Data;
}
return null;
} | {
"domain": "codereview.stackexchange",
"id": 43818,
"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#, .net, async-await",
"url": null
} |
c#, .net, async-await
return subscription.Data;
}
return null;
}
private async Task<UpdateSubscription?> SubscribeToOrdersAsync(CancellationToken cancellationToken = default)
{
var subscription = await _socketClient.Streams
.SubscribeToOrderUpdatesAsync(data =>
{
_logger.LogInformation("Orders: {@Data}", data.Data);
}, cancellationToken);
if (subscription.Success)
{
subscription.Data.ConnectionLost += () => _logger.LogError("Connection lost");
subscription.Data.ConnectionRestored += _ => _logger.LogInformation("Connection restored");
return subscription.Data;
}
return null;
}
private async Task<UpdateSubscription?> SubscribeToFillsAsync(CancellationToken cancellationToken = default)
{
var subscription = await _socketClient.Streams
.SubscribeToUserTradeUpdatesAsync(data =>
{
_logger.LogInformation("Fills: {@Data}", data.Data);
}, cancellationToken);
if (subscription.Success)
{
subscription.Data.ConnectionLost += () => _logger.LogError("Connection lost");
subscription.Data.ConnectionRestored += _ => _logger.LogInformation("Connection restored");
return subscription.Data;
}
return null;
}
}
Answer: Even though you have not explicitly mentioned it in your question but I assume you are using this library.
Your SubscribeToAsync is a good starting point. But your to be provided func parameters are still have much resemblance as you can see
await SubscribeToAsync(() => _socketClient.Streams.SubscribeToOrderUpdatesAsync(data =>
{
_logger.LogInformation("Orders: {@Data}", data.Data);
}, cancellationToken)); | {
"domain": "codereview.stackexchange",
"id": 43818,
"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#, .net, async-await",
"url": null
} |
c#, .net, async-await
await SubscribeToAsync(() => _socketClient.Streams.SubscribeToUserTradeUpdatesAsync(data =>
{
_logger.LogInformation("Fills: {@Data}", data.Data);
}, cancellationToken));
If you want to move as much logic as possible into your SubscribeToAsync then you have to assess the above method calls. What are the differences?
SubscribeToOrderUpdatesAsync vs SubscribeToUserTradeUpdatesAsync
"Orders: vs "Fills:
If you could provide these information to the SubscribeToAsync methods then you could get rid of the SubscribeToOrdersAsync and SubscribeToFillsAsync methods entirely.
Fortunately you can do that:
private async Task<UpdateSubscription?> SubscribeToAsync<T>(
Func<IFTXSocketClientStreams, Func<Action<DataEvent<T>>, CancellationToken, Task<CallResult<UpdateSubscription>>>> methodSelector,
string logPrefix, CancellationToken token)
{
var asyncMethod = methodSelector(_socketClient.Streams);
var subscription = await asyncMethod(data => _logger.LogInformation(logPrefix +": {@Data}", data.Data), token);
if (!subscription.Success)
return null;
subscription.Data.ConnectionLost += () => _logger.LogError("Connection lost");
subscription.Data.ConnectionRestored += _ => _logger.LogInformation("Connection restored");
return subscription.Data;
}
The methodSelector parameter: It select the to be called method from the IFTXSocketClientStreams inteface
Since FTXOrder and FTXUserTrade don't have a common base class that's why you have to make the SubscribeToAsync generic
The logPrefix parameter: The prefix of the logging message
The token parameter: The cancellation token
With this in your hand the entire class could be shortened like this:
public class FtxProducer : IHostedService
{
private readonly ILogger<FtxProducer> _logger;
private readonly IFTXSocketClient _socketClient;
public FtxProducer(ILogger<FtxProducer> logger, IFTXSocketClient socketClient)
=> (_logger, _socketClient) = (logger, socketClient); | {
"domain": "codereview.stackexchange",
"id": 43818,
"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#, .net, async-await",
"url": null
} |
c#, .net, async-await
public async Task StartAsync(CancellationToken cancellationToken)
{
await SubscribeToAsync<FTXOrder>(stream => stream.SubscribeToOrderUpdatesAsync, "Orders", cancellationToken);
await SubscribeToAsync<FTXUserTrade>(stream => stream.SubscribeToUserTradeUpdatesAsync, "Fills", cancellationToken);
}
public Task StopAsync(CancellationToken cancellationToken)
=> _socketClient.UnsubscribeAllAsync();
private async Task<UpdateSubscription?> SubscribeToAsync<T>(
Func<IFTXSocketClientStreams, Func<Action<DataEvent<T>>, CancellationToken, Task<CallResult<UpdateSubscription>>>> methodSelector,
string logPrefix, CancellationToken token)
{
var asyncMethod = methodSelector(_socketClient.Streams);
var subscription = await asyncMethod(data => _logger.LogInformation(logPrefix +": {@Data}", data.Data), token);
if (!subscription.Success) return null;
subscription.Data.ConnectionLost += () => _logger.LogError("Connection lost");
subscription.Data.ConnectionRestored += _ => _logger.LogInformation("Connection restored");
return subscription.Data;
}
}
UPDATE #1
May you just change _logger.LogInformation(logPrefix +": {@Data}", data.Data) to something more generic?
private async Task<UpdateSubscription?> SubscribeToWithLoggingAsync<T>(
Func<IFTXSocketClientStreams, Func<Action<DataEvent<T>>, CancellationToken, Task<CallResult<UpdateSubscription>>>> methodSelector,
string logPrefix, CancellationToken token)
=> await SubscribeToAsync(methodSelector, data => _logger.LogInformation(logPrefix +": {@Data}", data.Data), token); | {
"domain": "codereview.stackexchange",
"id": 43818,
"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#, .net, async-await",
"url": null
} |
c#, .net, async-await
private async Task<UpdateSubscription?> SubscribeToAsync<T>(
Func<IFTXSocketClientStreams, Func<Action<DataEvent<T>>, CancellationToken, Task<CallResult<UpdateSubscription>>>> methodSelector,
Action<DataEvent<T>> handler, CancellationToken token)
{
var asyncMethod = methodSelector(_socketClient.Streams);
var subscription = await asyncMethod(handler, token);
if (!subscription.Success) return null;
subscription.Data.ConnectionLost += () => _logger.LogError("Connection lost");
subscription.Data.ConnectionRestored += _ => _logger.LogInformation("Connection restored");
return subscription.Data;
}
The SubscribeToWithLoggingAsync is a specialized version of the more generic SubscribeToAsync
It specifies that the handler should perform some simple logging
The SubscribeToAsync method's signature looks a bit terrifying now, but it is generic enough to be reused in multiple ways
UPDATE #2
public abstract Task<CallResult<UpdateSubscription>> SubscribeToTickerUpdatesAsync(string symbol, Action<DataEvent<FTXStreamTicker>> handler, CancellationToken ct = default(CancellationToken)) I wasn't able to call this method.
If you look at the signature of the method then you can see there is an extra input parameter called symbol. The SubscribeToAsync's methodSelector is unaware of this.
In order to support the call of SubscribeToTickerUpdatesAsync or SubscribeToTradeUpdatesAsync like this:
await SubscribeWithSymbolToAsync<FTXStreamTicker>(stream => stream.SubscribeToTickerUpdatesAsync, "Ticker", cancellationToken);
await SubscribeWithSymbolToAsync<IEnumerable<FTXTrade>>(stream => stream.SubscribeToTradeUpdatesAsync, "Trade", cancellationToken); | {
"domain": "codereview.stackexchange",
"id": 43818,
"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#, .net, async-await",
"url": null
} |
c#, .net, async-await
we need the following trick:
private async Task<UpdateSubscription?> SubscribeWithSymbolToAsync<T>(
Func<IFTXSocketClientStreams, Func<string, Action<DataEvent<T>>, CancellationToken, Task<CallResult<UpdateSubscription>>>> methodSelector,
string symbol, CancellationToken token)
{
var asyncMethod = (Action<DataEvent<T>> handler, CancellationToken cToken) =>
methodSelector(_socketClient.Streams)(symbol, handler, cToken);
var subscription = await asyncMethod(data => _logger.LogInformation(symbol + ": {@Data}", data.Data), token);
return SubscribeToEvents(subscription);
}
private async Task<UpdateSubscription?> SubscribeToAsync<T>(
Func<IFTXSocketClientStreams, Func<Action<DataEvent<T>>, CancellationToken, Task<CallResult<UpdateSubscription>>>> methodSelector,
Action<DataEvent<T>> handler, CancellationToken token)
{
var asyncMethod = methodSelector(_socketClient.Streams);
var subscription = await asyncMethod(handler, token);
return SubscribeToEvents(subscription);
}
private UpdateSubscription SubscribeToEvents(CallResult<UpdateSubscription> subscription)
{
if (!subscription.Success) return null;
subscription.Data.ConnectionLost += () => _logger.LogError("Connection lost");
subscription.Data.ConnectionRestored += _ => _logger.LogInformation("Connection restored");
return subscription.Data;
}
The SubscribeWithSymbolToAsync binds the symbol formal parameter of the methodSelector to the provided symbol parameter
In other words, we convert a Func<T1, T2, T3> to a Func<T2, T3> by supplying T1
The SubscribeWithSymbolToAsync does not rely on SubscribeToAsync so I extract the common part
The SubscribeToEvents handles the event subscribtions | {
"domain": "codereview.stackexchange",
"id": 43818,
"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#, .net, async-await",
"url": null
} |
python, python-3.x, validation, integer, assertions
Title: Python function: user input to get positive integer using assert
Question: Is it a bad thing to use asserts to validate user inputs? Or should I keep using an if statement in case the number isnt positive?
Code with assert statement:
def get_posit_n() -> int:
from locale import atoi
while True:
try:
number = atoi(input('Enter a positive integer:\n-> ').strip())
assert (number > 0)
return number
except (ValueError, AssertionError):
print('Number must be an positive integer...\n')
Code with if statement:
def get_positive_integer(msg: str = "Enter a integer value: ") -> int:
from locale import atoi
while True:
try:
number: int = atoi(input(msg + '\n-> ').strip())
if number <= 0:
continue
return number
except ValueError:
print('Invalid value!\n')
Answer: The intended use of assert is in test code,
or to validate internal preconditions.
To validate user input, the common recommendation is to raise a ValueError.
There is no point in raising an error (with assert in the posted code) only to catch it right after.
Also, AssertionError is not meant to be caught,
it's meant to let it crash the program.
Taking the best parts of the examples:
from locale import atoi
def input_positive_integer() -> int:
while True:
try:
number: int = atoi(input('Enter a positive integer:\n-> ').strip())
if number <= 0:
print('Number must be a positive integer...\n')
continue
return number
except ValueError:
print('Invalid value!\n') | {
"domain": "codereview.stackexchange",
"id": 43819,
"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, validation, integer, assertions",
"url": null
} |
python, image
Title: Grepping for text in images
Question: I built a small wrapper script around pytesseract, that lets you
check if an image contains some text, or pattern
look for images, that contain some text, or pattern
High Level Approach
I get the image text with pytesseract.image_to_string(img), and then compare against the user supplied regex with pattern.search(text) (pattern being a normal re.Pattern object).
Usage
The usage is meant to mimick grep, but there's obviously a lot missing. Some things, like -a, -b and -v are planned for the future, but not included for now.
usage: imgrep [-h] [-i] [-r] [-f] [-0] pattern file
Grep for text in images.
positional arguments:
pattern A Python regex, to search for.
file Path of the image(s) to search through. (Or folder(s),
if `--recursive' is specified).
options:
-h, --help show this help message and exit
-i, --ignore-case Ignore case distinctions in patterns and input data.
-r, --recursive Grep through every file under a given directory.
-f, --filenames-only Only print the file names, not the contents. Makes no
sense without `--recursive', and will be ignored if
`--recursive' is not specified.
-0, --null Print the output seperated by null characters, this is
useful for badly named files. Makes no sense without
`--filenames-only', but will be done regardless, if
specified!
Be patient. It uses multiple cores, but this just takes a while. Searching for
a specific string in my ca. 2000 image strong memes folder took about 8
minutes and 30 seconds.
Code
import argparse
import re
from typing import List, Union
from pathlib import Path
from multiprocessing import Pool
from os import cpu_count
from functools import partial
import PIL
import pytesseract | {
"domain": "codereview.stackexchange",
"id": 43820,
"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, image",
"url": null
} |
python, image
import PIL
import pytesseract
def parse_args(argv=None):
parser = argparse.ArgumentParser(description='Grep for text in images.')
parser.add_argument('pattern', type=str, help='A Python regex, to search for.')
parser.add_argument('file', type=Path,
help='Path of the image(s) to search through. (Or folder(s), if `--recursive\' is specified).')
parser.add_argument('-i', '--ignore-case', action='store_true',
help='Ignore case distinctions in patterns and input data.')
parser.add_argument('-r', '--recursive', action='store_true',
help='Grep through every file under a given directory.')
parser.add_argument('-f', '--filenames-only', action='store_true',
help='Only print the file names, not the contents.\nMakes no sense without `--recursive\', '
'and will be ignored if `--recursive\' is not specified.')
parser.add_argument('-0', '--null', action='store_true',
help='Print the output seperated by null characters, this is useful for badly named files.\n'
'Makes no sense without `--filenames-only\', but will be done regardless, if specified!')
parser.epilog = f'Be patient. It uses multiple cores, but this just takes a while.\n' \
f'Searching for a specific string in my ca. 2000 image strong memes folder took about 8 minutes ' \
f'and 30 seconds.'
return parser.parse_args() if argv is None else parser.parse_args(argv)
def imgrep(image: Union[str, Path], needle: re.Pattern) -> List[str]:
try:
img = PIL.Image.open(image)
except PIL.UnidentifiedImageError:
# skip in case PIL cannot decode the file for any reason
# (e.g. it might not even be image data)
return [] | {
"domain": "codereview.stackexchange",
"id": 43820,
"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, image",
"url": null
} |
python, image
haystack: str = pytesseract.image_to_string(img)
return [line for line in haystack.splitlines() if needle.search(line)]
def recurse(directory: Union[str, Path], needle: re.Pattern, filenames_only: bool = False) -> List[str]:
output = []
dir = Path(directory)
files = [file for file in dir.glob('**/*') if file.is_file()]
with Pool() as pool:
f = partial(imgrep, needle=needle)
chunksize = len(files) // (cpu_count() * 4) if len(files) > (cpu_count() * 4) else 1
results = pool.map(f, files, chunksize=chunksize)
for hits, file in zip(results, files):
if hits:
if filenames_only:
output.append(str(file))
else:
output.append(f'{file}: ')
output.extend(hits)
return output
def main(argv=None):
args = parse_args() if argv is None else parse_args(argv)
recursive: bool = args.recursive
ignore_case: bool = args.ignore_case
filenames_only: bool = args.filenames_only
null: bool = args.null
pattern: re.Pattern = re.compile(args.pattern) if not ignore_case else re.compile(args.pattern, re.IGNORECASE)
file: Path = args.file
if not file.exists():
print(f'{file} does not exist, or is not readable.')
exit(1)
if not recursive:
if file.is_dir():
print(f'{file} is a directory. Try again with `--recursive\'')
exit(2)
else:
if not file.is_dir():
print(f'{file} is not a directory. Try again without `--recursive\'')
exit(3)
output = imgrep(file, pattern) if not recursive else recurse(file, pattern, filenames_only)
for line in output:
print(line, end='\0' if null else '\n')
exit(0)
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43820,
"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, image",
"url": null
} |
python, image
exit(0)
if __name__ == '__main__':
main()
Concerns
What I'm mostly concerned about is the way I handle the arguments, and where the logic resides. There are not so many right now, that it would be a problem, but since I'm thinking about adding some for various things in the future this seems problematic.
For example, while I do think, it makes sense to handle the -0, -r and -i options outside the actual functions (recurse and imgrep), it does not make sense for the -f option, or -a and -b options, that I want to add.
This and the argument validation seem a little ugly to me, but honestly, I don't know what I would do differently.
Comments regarding improvements of command line options, and general usage are also appreciated.
The whole project can be found at GitHub, if you want to comment on the packaging and/or CI/CD approach.
Answer: Overall I think this is pretty nice code.
Make the UX more friendly
It's an error when:
the specified path is a directory and --recursive is not used
the specified path is a file and --recursive is used
Although the usage message helpfully tells what to do (add or drop --recursive),
it would be simpler to decide the right action depending on whether the path is a directory or not.
Simpler for users and for the implementation too.
But you make a good point in a comment that recursive grep is a CPU intensive operation, and the --recursive flag serves as a safeguard.
That makes sense, and the UNIX grep utility does this too.
On the other hand, grep doesn't complain when --recursive is present and the path argument is a file.
Maybe that could be a good middle ground.
Separate concerns
The main function performs:
additional validation of command line arguments
call the right function to execute the main task
output results
It would be good to move the implemnentations to separate functions.
Where to keep the validation logic?
I think you raise a very important concern here: | {
"domain": "codereview.stackexchange",
"id": 43820,
"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, image",
"url": null
} |
python, image
What I'm mostly concerned about is the way I handle the arguments, and where the logic resides. There are not so many right now, that it would be a problem, but since I'm thinking about adding some for various things in the future this seems problematic.
To phrase it differently,
the arguments returned by argparse are sometimes not fully validated,
raw low level configuration values,
which need further transformations to be useful,
such as the processing of a raw string pattern into a compiled regex.
I think it's a good idea to create a dedicated abstract data type to capture higher level configuration values,
using vocubulary that makes sense to the implementation.
Consider for example:
@dataclass
class Params:
pattern: re.Pattern
path: Path
filenames_only: bool
use_null_terminator: bool
def validated_params(argv=None) -> Params:
if argv is None:
args = parse_args()
else:
args = parse_args(argv)
path = Path(args.file)
if not path.exists():
print(f'{path} does not exist, or is not readable.')
exit(1)
if args.ignore_case:
pattern = re.compile(args.pattern, re.IGNORECASE)
else:
pattern = re.compile(args.pattern)
return Params(
pattern=pattern,
path=path,
filenames_only=args.filenames_only,
use_null_terminator=args.null
)
def main(argv=None):
params = validated_params(argv)
# ...
Use better names
The names are pretty good, but I have some ideas:
dir shadows a built-in, basedir or path would be better
file can be a directory or a file, so path would work better
recurse doesn't describe itself well. How about imgrep_dirs or recursive_imgrep.
null as a variable name puts me off a little because it's a keyword in many other languages.
And it doesn't describe well its purpose, so I'd just spell it out as use_null_terminator.
Don't repeat yourself
It's not a big problem, but there is some duplication here: | {
"domain": "codereview.stackexchange",
"id": 43820,
"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, image",
"url": null
} |
python, image
Don't repeat yourself
It's not a big problem, but there is some duplication here:
chunksize = len(files) // (cpu_count() * 4) if len(files) > (cpu_count() * 4) else 1
A simpler way to the same effect:
chunksize = max(1, len(files) // (cpu_count() * 4))
Use stricter types
I don't see why imgrep and recurse both expect Union[str, Path] parameter.
It seems they are only called with Path,
so that would be a more appriate and at the same time simpler signature.
Streaming the output
Instead of collecting results in a list,
I think it would be better to yield them:
To save memory
To show results as the come in, rather than waiting until the end of processing all files | {
"domain": "codereview.stackexchange",
"id": 43820,
"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, image",
"url": null
} |
beginner, c, formatting, io
Title: K&R Exercise 3-3. Expands shorthand notations (e.g., a-z to abc..xyz, 0-9 to 012..789)
Question: I have been learning C with K&R Book 2nd Ed. So far I have completed quite a few exercises.
For the following exercise (Chapter 3, Ex-3.3):
Exercise 3-3. Write a function expand(s1, s2) that expands shorthand
notations like a-z in the string s1 into the equivalent complete list
abc...xyz in s2. Allow for letters of either case and digits, and be
prepared to handle cases like a-b-c and a-z0-9 and -a-z. Arrange that
a leading or trailing - is taken literally.
I have written this solution. I would like to know how to improve it.
#include <stdio.h>
#include <ctype.h>
#define MAXLINE 1024
int get_line(char line[], int maxline);
void expand(const char s1[], char s2[]);
int match(int start, int end);
int
main(void)
{
char s1[MAXLINE];
char s2[MAXLINE];
while (get_line(s1, MAXLINE) > 0) {
expand(s1, s2);
printf("%s", s2);
}
return (0);
}
/**
* Here I have tried to write a loop equivalent to the loop seen
* previously in chapter 1. (without using && and ||,
* as specified in chapter 2 of the book, exercise 2.2).
*
* for (i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i)
* ...
**/
int
get_line(char s[], int lim)
{
int c, i;
i = 0;
while (--lim > 0) {
c = getchar();
if (c == EOF)
break;
if (c == '\n')
break;
s[i++] = c;
}
if (c == '\n')
s[i++] = c;
s[i] = '\0';
return (i);
}
void
expand(const char s1[], char s2[])
{
int i, j, ch;
for (i = j = 0; (ch = s1[i++]) != '\0'; ) {
if (s1[i] == '-' && match(s1[i-1], s1[i+1])) {
for (i++; ch < s1[i]; ) {
s2[j++] = ch++;
}
} else
s2[j++] = ch;
}
s2[j] = '\0';
} | {
"domain": "codereview.stackexchange",
"id": 43821,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, formatting, io",
"url": null
} |
beginner, c, formatting, io
int
match(int start, int end)
{
return ((isdigit(start) && isdigit(end)) ||
(islower(start) && islower(end)) ||
(isupper(start) && isupper(end)));
}
these are a few of the tests that I did with the program that I've written.
a-z
abcdefghijklmnopqrstuvwxyz
a-b-c
abc
a-z0-9
abcdefghijklmnopqrstuvwxyz0123456789
-a-z
-abcdefghijklmnopqrstuvwxyz
A-Z
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0-9
0123456789
-A-D
-ABCD
0-7
01234567
a-h
abcdefgh | {
"domain": "codereview.stackexchange",
"id": 43821,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, formatting, io",
"url": null
} |
beginner, c, formatting, io
0-9
0123456789
-A-D
-ABCD
0-7
01234567
a-h
abcdefgh
Answer: General Observations
The code generally looks good.
An experienced C programmer would probably use pointers rather than indexing through the array.
When unit testing code such as the functions int match(int start, int end) and void expand(const char s1[], char s2[]) it is generally better to create the strings to be tested in the code rather than reading in the strings, you should also prepare strings that are the expected output of the functions. Automated tests are better because they are reproducible.
One of the problems with using the K&R book is that it predates the introduction of the bool type into standard C. If I was writing this code I would include stdbool.h and have match return a bool instead of an int.
On Windows 10 using Visual Studio 2022 there seems to be a bug, the program never terminates when a new line is entered without any text.
Prefer C Standard Library Functions
The code includes the function get_line(char s[], int lim), however there are standard C library functions that can perform this operation, one is char fgets(char str, int count, FILE *stream). Using library functions is generally preferred over writing your own function because it doesn't need debugging and it may perform better than the function you write.
Code Organization
Function prototypes are very useful in large programs that contain multiple source files, and that in case they will be in header files. In a single file program like this it is better to put the main() function at the bottom of the file and all the functions that get used in the proper order above main(). Keep in mind that every line of code written is another line of code where a bug can crawl into the code.
Variable Names
The variable names s and lim are not as descriptive as they could be, for instance I might rename lib to be buffer_size.
Alternate Implementation
#include <ctype.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h> | {
"domain": "codereview.stackexchange",
"id": 43821,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, formatting, io",
"url": null
} |
beginner, c, formatting, io
#define MAXLINE 1024
bool
match(int start, int end)
{
return ((isdigit(start) && isdigit(end)) ||
(islower(start) && islower(end)) ||
(isupper(start) && isupper(end)));
}
void
expand(const char s1[], char s2[])
{
int i, j, ch;
for (i = j = 0; (ch = s1[i++]) != '\0'; ) {
if (s1[i] == '-' && match(s1[i - 1], s1[i + 1])) {
for (i++; ch < s1[i]; ) {
s2[j++] = ch++;
}
}
else
s2[j++] = ch;
}
s2[j] = '\0';
}
int
main(void)
{
char s1[MAXLINE];
char s2[MAXLINE];
while (strlen(fgets(s1, MAXLINE, stdin)) > 0) {
expand(s1, s2);
printf("%s", s2);
}
return (0);
} | {
"domain": "codereview.stackexchange",
"id": 43821,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, formatting, io",
"url": null
} |
programming-challenge, typescript, generics
Title: Small typesafe assertion library, is()
Question: I need to write a function with the following requirements (Programming TypeScript book by B. Cherny, Chapter 4, exercise 5):
Implement a small typesafe assertion library, is. Start by sketching out your types. When you’re done, you should be able to use it like this:
// Compare a string and a string
is('string', 'otherstring') // false
// Compare a boolean and a boolean
is(true, false) // false
// Compare a number and a number
is(42, 42) // true
// Comparing two different types should give a compile-time error
is(10, 'foo') // Error TS2345: Argument of type '"foo"' is not assignable to parameter of type 'number'.
// [Hard] I should be able to pass any number of arguments
is([1], [1, 2], [1, 2, 3]) // false
This is the code that I have so far:
type AllowedTypes = string | boolean | number;
type Checker = {
<T extends AllowedTypes>(l: T, r: T): boolean;
};
let is: Checker = <T>(l: T, r: T): boolean => {
return l === r;
};
console.log(is('string', 'otherstring'));
console.log(is(true, false));
console.log(is(42, 42));
// console.log(is(10, 'foo')); // gives error
// console.log(is([1], [1])); // array not allowed
// console.log(is(1, [1])); // array not allowed
type MultiChecker = {
<T>(...args: T[]): boolean;
};
let multi_is: MultiChecker = <T>(...args: T[]): boolean => {
return args.every((v: T) => v === args[0]);
};
console.log(multi_is([1], [1, 2], [1, 2, 3]));
console.log(multi_is(1, 1, 1, 1, 1));
console.log(multi_is('abcd', 'str', 'str'));
Please review it/suggest improvements. | {
"domain": "codereview.stackexchange",
"id": 43822,
"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, typescript, generics",
"url": null
} |
programming-challenge, typescript, generics
Please review it/suggest improvements.
Answer: You haven’t implemented one function, you’ve implemented two.
Your multi_is() function can handle any number of arguments, including 2, so it seems to me you could ditch the is() method and rename multi_is() to is()
Except, multi_is() can accept any number of arguments, including 0 & 1, which is probably not what is expected.
If the function was written with this signature:
let is: Checker = <T>(l: T, r: T, ...args: T[]): boolean => {
...
};
less than 2 arguments would be a compile-time error. | {
"domain": "codereview.stackexchange",
"id": 43822,
"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, typescript, generics",
"url": null
} |
c++, game
Title: Text Based UNO with Colors and Bots
Question: This is the first big thing I have tried in c++. I would like to know any improvements that I can make on it. It uses 4 custom header files, 3 of which are general tools.
Also I am on linux and I have no idea how to check how this would work on windows. I know some colors might look different or it might not look as expected so if someone could help me on how to check that.
UNO.cpp
This is the file thats compiled to an executable
#include "Card.hpp"
#include "MagnTxt.hpp"
#include "GetSS.hpp"
using namespace std; | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
using namespace std;
void Rules();//Prints All Rules
void Begin(Cards arr[]);//Draws 6 Cards For Each Player
void Orderfrom(int si, vector<int>& v);//Orders Indexes from si - l and then 0 - si and stores it in v
void getCardSize();//Asks The Users For Card Length and Cards Width
vector<string> setPlayers(int p, int b);//Creates 2 Vectors using setName appends them and returns it
vector<string> setName(string ty, int n);//Asks The User for n of ty else names all ty 1, ty 2, ..., ty n
void GetStatus(vector<string> n, int si);//Gets Status of All Player starting from si'th Player
void PrintOrder(vector<int> oi, vector<string> pn, int si);//Prints Turn Order using Player Name from pn Starting from si
void PlusN(int n);//Prints + n using MagnTxt.hpp
void ReverseOrder(vector<int>& v, int& p);//Reverses Order And Changes p to New Index After Reverses Order
void SwitchWith(Cards& plt, Cards& plf);//Switches plt's Cards with plf's Cards
void SwitchAll(Cards arr[], vector<int> ord);//Switches All Cards Based On Turn Order Stored in ord
void SpCard(vector<int>& o, int& ind, int& m, string& c, string& ctdp, bool ib);//If A Card Is Special it Changes Accepted Values Based on The Special Card
int PlDraws(Cards& pl, string& c, string ctdp, int& m, int& ind, bool sm, bool ib);//It Makes pl Draw m Cards or Draws Until They Are Able To Play
int O7SpM(Cards arr[], vector<string> pl, vector<int> o, string c, int& i, bool o7, bool ib, int o7i);//Switches Cards if 0 or 7 is Played and o7mode is Enabled
void SafeCin(string msg, string err, int& i, int ll, int ul);//Shows msg accepts value for i, for invalid or out of bounds input it asks again with err shown
void UpdateLengths();//Sets New Card Length and Card Width Based on The Screen Size and lenf and widf
void Clear();//Clears Screen Using cls or clear based on os
void Stopper();//Asks For Any Input Before Clearing The Screen
void WinningMessage(string mssg);//Shows Winning Message Magnified And Colorful using MagnTxt.hpp | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
ScreenSize ss;
int lenf = 420, widf = 105, Div = 1000, cl, cw, space;//Stores Arbitary lenf, widf to set Card Length, Card Width and Spaces Before Displaying Singlar Card | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
int main()
{
bool isBot = false, o7cond = false;//isBot Stores If The Current Player is a Bot, o7cond stores if 07 Mode is Enabled or not
int nop = 0, nob = 0, mult = 0, ctp, i = 0, o7, acs, cind = 0;
/*nop stores number of players, nob stores number of bots, mult stores Number of Cards to Draw, ctp stores the index of card to play, i stores the index that loops through order, acs stores all cards size of the current player, cind stores the crrent players index*/
string lcard = "", ctdp = "";//lcard stores last card and ctdp stores the card to display which has the selected color stored immediately after playing
vector<int> order;//Stores Turn Order using indexes
Rules();
SafeCin("Enter Number of Players: ", "\nNumber of Players Cant be Less than or Equal to 1\n", nop, 1, numeric_limits<int>::max());//gets nop from 1 - max_int
SafeCin("Enter Number of Bots: ", "\nNumber of Players Cant be Less than or Equal to 0\n", nob, 0, numeric_limits<int>::max());//gets nop from 0 - max_int
SafeCin("\nActivate 0-7 Mode ?(1 for Yes, Anything Else for No): ", "\nNon-Numerical Values Not Allowed!", o7, numeric_limits<int>::min(), numeric_limits<int>::max());//Allows for any numerical integer value and stores it in o7
getCardSize();
vector<string> players = setPlayers(nop, nob);//Stores All Player Names And All Bots Name in players
Cards PlArr[nop + nob];//Creates Cards Objects for both Players and Bots
if(o7 == 1 && Cards::count > 1)//Activates o7cond if user entered 1 for o7 and there are more than 1 player
o7cond = true;
Orderfrom((rand() % Cards::count), order);//Orders Index from a random number between 0 to Cards::count(which is total number of objects)
Begin(PlArr);//Draws Cards for All Objects
Clear();
cout<<"This Game Will Start with: "<<players[order[0]];//Shows the Player That The Game Will Start With
while(true)//Infinite Loop
{ | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
while(true)//Infinite Loop
{
i -= (i >= Cards::count) ? Cards::count : 0;//Makes i safe, say skip is played at i = 2 and Cards::count = 3, i will become 4 when it needs to be 1, this will make i the desired num as i - Cards::count will be 1
cind = order[i];//Stores the actual index of the player getting it from order using i
Stopper();
UpdateLengths();
isBot = cind >= nop;//As bots are added after players all indexes greater than equal to nop will be of bots
PlArr[cind].Sort();//Sorts All Cards Color Wise
GetStatus(players, cind);
PrintOrder(order, players, i);
if(lcard != "")//Prints ctdp if lcard isn't empty i.e ctdp is displayed when a card has been played
{
cout<<"\n\nPreviously Played Card: \n";
Cards::Display(ctdp, cl, cw + 2, -1, space);
}
if(mult != 0)//If mult is not 0 i.e there are n cards to draw(i.e previosly draw 2 or draw 4 has been played)
{
cout<<Cards::SetTextColor(ctdp, -1);//Sets a new color based on the color of draw 2 or color choosen for draw 4
PlusN(mult);
cout<<Cards::SetTextColor("", 5);//Resets Color to Default
}
if(!(PlArr[cind].CanPlayAny(lcard)) && lcard != "" )//Checks if a player can play any cards and if the lcard has a value
{
cout<<"\n"<<players[cind]<<" Can't Play Any Card! "<<endl;
if(PlDraws(PlArr[cind], lcard, ctdp, mult, i, true, isBot) == 1)
continue;//Makes Player Draw Cards and goes to the next turn if Draw 4 or Draw 2 is causing the drawing
}
acs = PlArr[cind].AllCards.size();
if(!isBot)//If The Player isnt a bot
{
cout<<"\n\n"<<players[cind]<<"'s Cards:\n";
int scw = ss.getWidth();
PlArr[cind].Display(cl, cw, scw);//Displays All Cards of the Player with 1 based indexes(i.e 1, 2, 3,.., n) | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
SafeCin(("\n\nEnter the the Index of the Card to Play: \n1 Being the Leftmost Card and " + to_string(acs) + " Being the Rightmost Card\nEnter " + to_string(acs + 1) + " For Drawing\n"), "\nThis Option Doesn't Exist", ctp, 1, acs + 1);//Gets The Card to Play Based on Index
}
else
{
int nxtcl = PlArr[order[(i + 1 >= Cards::count ? i + 1 - Cards::count : i + 1)]].AllCards.size();//Gets Number of Cards of the Next Player in Order
ctdp = PlArr[cind].CardChoice(ctp, lcard, ctdp, nxtcl, o7);//Gets New Card To Display and selected card index 0 based and o7 index if 07 is Played
ctp++;//Makes ctp 1 based index
}
if(ctp == acs + 1)//If Player Chooses To Draw Cards instead of Playing
{
PlDraws(PlArr[cind], lcard, ctdp, mult, i, false, isBot);//Makes Player Draws till They are Able to Play
continue;//Goes to The next turn
}
if(!(Cards::CanPlay(PlArr[cind].AllCards[ctp - 1], lcard)) && lcard != "")//If The Selected Card Cant Be Played and lcard has value
{
cout<<"\nThis Card Can't be Played"<<endl;
continue;
}
lcard = PlArr[cind].AllCards[ctp - 1];//Sets new lcard based on selected card
if(!isBot)//if it isnt a bot ctdp is updated(as ctdp is by default updated when .CardChoice is called)
ctdp = lcard;
PlArr[cind].Remove(ctp - 1);//Removes The Played Card From Current Players Cards
cout<<"\n"<<players[cind]<<" Played: \n";
Cards::Display(ctdp, cl, cw + 2, ctp, space);//Displays The Played Card
if(Cards::AllStatus[cind] == "WON!!!")//If Current Player Has Won It Breaks From The Infinite Loop
break;
if(O7SpM(PlArr, players, order, lcard, i, o7cond, isBot, o7) == 1)
continue;
SpCard(order, i, mult, lcard, ctdp, isBot);
i++;//Goes To The next Index in Order
} | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
i++;//Goes To The next Index in Order
}
WinningMessage(players[cind] + " WON THE GAME!!!");
}
void Rules()
{
Clear();
UpdateLengths();
int scw = ss.getWidth();//Gets scw as cw = (scw * widf)/Div, therefore scw = (cw * Div) / widf
//int sp = (23 * scw) / 50;//stores sp that is the no. of spaces to print before displaying card
Fill f2('-'), f;//f2 objects fills empty space with -, f fills empty space with ' '
cout<<f2.fwcent("RULES", scw)<<endl;
cout<<"\n"<<f.fwcent("1) To Play A Card You Will Be Required To Enter Indexes Which Will Be Displayed On Top Of Card or Before The Card Based On Display Modes", scw)<<endl;//Centeres The String by filling remaining spaces before and after the string
cout<<f.fwcent("2) Some Of These Indexes Will Change After Every Round As They Are Automatically Sorted By Color", scw)<<endl;
cout<<f.fwcent("3) There Are 4 Colors: Pink, Green, Blue, Yellow", scw)<<endl;
cout<<f.fwcent("4) Any Wild Card Allows You To Change Color", scw)<<endl;
cout<<f.fwcent("5) DRAW 4 Stacks But Only On Other Draw 4s", scw)<<endl;
cout<<f.fwcent("6) DRAW 2 Stacks But Only On Other Draw 2s", scw)<<endl;
cout<<f.fwcent("7) If 7-0 Mode Is Enabled 7 Switches Your Hand With 1 Selected Player, And 0 Switches All Hands Based On Turn Order", scw)<<endl;
cout<<f.fwcent("8) You Can Draw Cards Instead Of Playing A Card On Your Turn, But This Will Lead To Drawing Until A Drawn Card Is Playable On The Previously Played Card And Will Skip Your Turn", scw)<<endl;
cout<<"\n\n"<<f.fwcent("****THERE ARE 2 DISPLAY MODE FOR CARDS:****", scw)<<endl;
cout<<"\n"<<f.fwcent("Mode 1) If There Are Less Then Or Equal To 3 Rows Of Cards", scw)<<endl;
cout<<"\n";
Cards::Display("Wild Draw 4", cl, cw + 2, 1, space);//Display Wild Draw 4 with cl and cw
cout<<"\n\n"<<f.fwcent("Mode 2) If There is More Then 3 Rows Of Cards", scw)<<endl;
cout<<"\n"<<f.fillwith("", (scw - 12) / 2); | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
cout<<"\n"<<f.fillwith("", (scw - 12) / 2);
Cards::Display("Wild Draw 4", 1, 1, 1, space);//Displays Wild Draw 4 as [ 1) Wild Draw 4 ]
cout<<"\n\n\n"<<f2.fwcent("RULES", scw)<<endl;
Stopper();
}
void Begin(Cards arr[])
{
for(int i = 0; i < Cards::count; i++)
arr[i].Draw(6);//Calls Draw n for each Cards Object to Start Every Player with n cards
}
void Orderfrom(int si, vector<int>& v)
{
int isi = si, i = 0;//stores si in isi to limit i as si is used to add index till Cards::count
while(si < Cards::count)
{ v.push_back(si); si++; }//adds si till si is less then Cards::count which is total number of objects
while(i < isi)//starts adding from 0 till the initial si(isi)
{ v.push_back(i); i++; }
}
void getCardSize()
{
int scl, scw;
ss.getScreenSize(scl, scw);
SafeCin("\nEnter Desired Card Length for Display Mode 1 (0 for Default): ", "\nNon-Numerical Values or Values Below 0 Not Allowed!", cl, 0, numeric_limits<int>::max());//gets desired card length or lets user to let it be the default by entering 0
SafeCin("\nEnter Desired Card Width for Display Mode 1 (0 for Default): ", "\nNon-Numerical Values or Values Below 0 Not Allowed!", cw, 0, numeric_limits<int>::max());//gets desired card width or lets user to let it be the default by entering 0
if(cl != 0)//if it isnt default
lenf = (cl * Div) / scl;//it finds the new factors to make the selected length change with screen size
if(cw != 0)
widf = (cw * Div) / scw;
}
vector<string> setPlayers(int p, int b)
{
vector<string> tore = setName("Player", p);//Gets Player names and stores it in tore
if(b != 0)//if there are bots
{
vector<string> ta = setName("Bot", b);//Gets Names for Bots
tore.insert(tore.end(), ta.begin(), ta.end());//Adds Bots Names to the end of Player Names
}
return tore;
}
vector<string> setName(string ty, int n)
{
Clear();
vector<string> v;
string name;
int c; | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
{
Clear();
vector<string> v;
string name;
int c;
SafeCin(("Do you Want to Enter " + ty + " Names: Yes(1)/ No(2) ?\nIf not (2) Entered " + ty + "s will be Named as " + ty + " n\n"), ("Invalid Choice!!\nEnter 1 for Entering Names and Enter 2 for Setting Names as " + ty + " n\n"), c, 1, 2);//Asks The User if the ty names should be set to default or user entered
cin.ignore();//To Make sure getline can be used
for(int i = 1; i <= n; i++)
{
Clear();
if(c == 1)//If User Entered
{
cout<<"Enter Name for "<<ty<<" "<<i<<": ";//Asks the user for i'th ty name
getline(cin, name);//stores the user entered name in string name
}
else//If default
name = ty + " " + to_string(i);//Stores name as ty i
v.push_back(name);//Adds ty name to vector v
}
return v;
}
void GetStatus(vector<string> n, int si)
{
cout<<"All Player Status: \n\n";
for(int i = 0; i < Cards::count; i++)//Loops through Cards::count times
{
if(si == Cards::count) si = 0;//if starting index hits Cards::count, it resets it to 0
string ta = (i != (Cards::count - 1)) ? ", " : "\n";//Sets Seperator to \n if the last status is being printed else it sets it to ", "
cout<<n[si]<<": "<<Cards::AllStatus[si]<<ta;//Displays The Player Name Followed by Players Status and Finally The Seperator
si++;//Goes To The Next Index
}
}
void PrintOrder(vector<int> oi, vector<string> pn, int si)
{
cout<<"\nTurn Order: \n\n";
int c = oi.size();//c is the count for the number of players
while(c != 0)
{
if(si == oi.size())//if si hits oi.size() it resets si to 0 tis to prit from si to oi.size and then from 0 to si
si = 0;
string ta = (c == 1) ? "\n" : " ----> ";//If Count is 1 i.e it is the last player is being printed the seperator is turned to \n
cout<<pn[oi[si]]<<ta;//Prints Player Names Based on Turn Order | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
cout<<pn[oi[si]]<<ta;//Prints Player Names Based on Turn Order
si++; c--;//Goes to the next si and reduces c
}
}
void PlusN(int n)
{
Fill f; MgTxt m;
cout<<endl;
m.PrintWTxt(f.fillwith("", space), "+" + to_string(n));//Prints +n Magnified with preceeding spaces
}
void ReverseOrder(vector<int>& v, int& p)
{
int cele = v[p];//stores the original index
reverse(v.begin(), v.end());//reverses the entire turn order
p = find(v.begin(), v.end(), cele) - v.begin();//gets the new position of original index
}
void SwitchWith(Cards& plt, Cards& plf)
{
vector<string> Temp = plt.AllCards;//Stores plt in Temp to later exchange
plt.AllCards = plf.AllCards;//Sets the value of plt to plf
plt.UpdateStatus();//Updates plt's status
plf.AllCards = Temp;//Sets plf as Temp
plf.UpdateStatus();//Updates plf's Status
}
void SwitchAll(Cards arr[], vector<int> ord)
{
/*This is Better Explained With an Example Say,
*ord = {4, 3, 2, 1, 0} and Cards = {"8 cards", "6 cards", "7 cards", "2 cards", "4 cards"}//Though it switches AllCards I am using Status for Simplicity
*say card is already sorted based on ord even though in reality it is accessed while switching
*therefore Cards = {"4 cards", "2 cards", "7 cards", "6 cards", "8 cards"}
*l will be 4 this prevents out of bounds within the loop
*c = "4 cards", c2 = "2 cards"
Within Loop condition i < (l viz 4)
*i = 1; Cards[1] = c = "4 cards"; c = "7 cards", c2 is same; new Cards = {"4 cards", "4 cards", "7 cards", "6 cards", "8 cards"}
*i = 2; Cards[2] = c2 = "2 cards"; c is same, c2 = "6 cards"; new Cards = {"4 cards", "4 cards", "2 cards", "6 cards", "8 cards"}
*i = 3; Cards[3] = c = "7 cards"; c = "8 cards", c2 is same; new Cards = {"4 cards", "4 cards", "2 cards", "7 cards", "8 cards"}
*i = 4; condition false; Last Values c = "8 cards", c2 = "6 cards"
Outside Loop | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
*i = 4; condition false; Last Values c = "8 cards", c2 = "6 cards"
Outside Loop
*Cards[4] = c2 = "6 cards"; new Cards = {"4 cards", "4 cards", "2 cards", "7 cards", "6 cards"}
*Cards[0] = c = "8 cards"; new Cards = {"8 cards", "4 cards", "2 cards", "7 cards", "6 cards"}
Therefore this uses two containers to alternatively store values and switch values*/
int l = ord.size() - 1;
vector<string> c = arr[ord[0]].AllCards, c2 = arr[ord[1]].AllCards;
for(int i = 1; i < l; i++)
{
arr[ord[i]].AllCards = (i % 2 == 1) ? c : c2;
arr[ord[i]].UpdateStatus();//update status is called to reflect the new changes after switching
if(i % 2 == 1)
c = arr[ord[i + 1]].AllCards;
else
c2 = arr[ord[i + 1]].AllCards;
}
arr[ord[l]].AllCards = (l % 2 == 1) ? c : c2;
arr[ord[0]].AllCards = (l % 2 == 0) ? c : c2;
arr[ord[l]].UpdateStatus(); arr[ord[0]].UpdateStatus();
}
void SpCard(vector<int>& o, int& ind, int& m, string& c, string& ctdp, bool ib)
{
string n = Cards::getNum(c);//Gets the number part of the card this is to check if the card is special
if(Cards::getColor(c) == "Wild" && !ib)//If te card is wild and it isnt a bot it asks the user for a new color
{
int ch;
SafeCin("\nChoose a New Color by Index: \n1) Pink, 2) Blue, 3) Green, 4) Yellow\n", "\nOnly Indexes 1 to 4 Allowed", ch, 1, 4);//gets color through index
string carr[4] = {"Pink ", "Blue ", "Green ", "Yellow "};//array used to directly access color
ctdp = carr[ch - 1] + n;//changes the card to display to the card with user selected color i.e for wild draw 4 and pink choosen it sets o pink draw 4
}
if(n == "Reverse")
ReverseOrder(o, ind);//Calls Reverse order if the card is reverse
else if(n == "Skip")
ind++;//increments the index as the index is incremented at the end of main loop therefore skipping the next index in order
else if(n == "Draw 2") | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
else if(n == "Draw 2")
m += 2;//increases m by 2 therefore increasing the to draw stack by 2
else if(n == "Draw 4")
m += 4;//increases m by 4 therefore increasing the to draw stack by 4
else if(n == "Color Changer")
c = ctdp;//it immediately changes last card to ctdp as wild color changer only changes color
}
int PlDraws(Cards& pl, string& c, string ctdp, int& m, int& ind, bool sm, bool ib)
{
cout<<"\nThey Will Draw ";
if(m != 0)//If There is an active to draw stack
{
cout<<m<<" Cards "<<endl;
pl.Draw(m);//Draws m Cards for the player
m = 0;//resets to draw stack
if(!ib)//If the player isnt a bot it display all cards with new Cards Drawn
pl.Display(cl, cw, (cw * Div) / widf);
if(c == "Wild Draw 4")//If The Card that caused the draw is draw 4 it makes it inactive by switching it ctdp which has the selected color
c = ctdp;
else if(Cards::getNum(c) == "Draw 2")
c = Cards::getColor(c) + " Draw2";//If it is draw 2 that caused the draw it makes it inactive by setting it to Draw2 to distinguish it from active Draw 2 which has space
ind++;//Sets the ind to next turn to not let the player play
return 1;//returns 1 to say to go to the next turn
}
else//If There is no stack that means player is forced to draw because they have no playable cards or they dont want to play a card
{
int ol = pl.AllCards.size(), nl;//Old Number of Cards is stored in ol and nl will be used to store new Number of Cards
if(sm)//Shows This Message if they were forced to draw
cout<<"Until They Are Able To Play!"<<endl;
else//If They choose to draw it skips their turn
ind++;
pl.DrawTCP(c);//It Draws Cards Until They Are Able To Play A Card on last card(c)
nl = pl.AllCards.size();
cout<<"\nThey Drew "<<(nl - ol)<<" Cards! \n";//Shows the number of cards drawn | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
cout<<"\nThey Drew "<<(nl - ol)<<" Cards! \n";//Shows the number of cards drawn
if(!ib)//If it isnt a bot it displays last displayed card
{
cout<<"\nLast Drawn Card: \n";
Cards::Display(pl.AllCards[nl - 1], cl, cw + 2, nl, space);
}
return 0;
}
}
int O7SpM(Cards arr[], vector<string> pl, vector<int> o, string c, int& i, bool o7, bool ib, int o7i)
{
string n = Cards::getNum(c);//Gets the number part of the card this is to check if the card is 0 or 7
if(!o7 || (n != "0" && n != "7"))//if the card neither 0 nor 7 or if 0-7 mode is disabled it does nothig and returns 0
return 0;
if(n == "7")
{
int ind = o7i;//o7i is the index that bot chooses it is entered as -1 for player
if(!ib)//If the player isnt a bot
{
string pwi = "\nEnter Index of the Player You Want to Switch With: \n";
for(int j = 0; j < Cards::AllStatus.size(); j++)
{
if(o[i] == j)
continue;
pwi += to_string(j + 1) + ") " + pl[j] + " : " + Cards::AllStatus[j] + "\n";
}
SafeCin(pwi, "\nIndex Out of Bounds!!", ind, 1, o.size());//Asks for index on the basis of index displayed above
ind--;
while(ind == o[i])
{
cout<<Cards::SetTextColor("Pink ", -1)<<"\nIndex Doesn't Exist"<<Cards::SetTextColor("", 5)<<endl;
SafeCin(pwi, "\nIndex Out of Bounds!!", ind, 1, o.size());
ind--;
}
}
SwitchWith(arr[o[i]], arr[ind]);//Switches Current Players Card with the Selected Index
cout<<"\n"<<pl[o[i]]<<" Exchanged Cards With "<<pl[ind]<<"\n";//Shows which player switched card with which player
}
else//If it is 0 it switches all cards using SwitchAll() function
{ cout<<"\n"<<pl[o[i]]<<" Exchanged All Cards \n"; SwitchAll(arr, o); } | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
{ cout<<"\n"<<pl[o[i]]<<" Exchanged All Cards \n"; SwitchAll(arr, o); }
if(!ib)//If The Player isnt a bot It shows them the new hand After Exchanging
{
cout<<"\nNew Hand: "<<endl;
arr[o[i]].Display(cl, cw, (cw * Div) / widf);
}
return 0;
}
void SafeCin(string msg, string err, int& i, int ll, int ul)
{
cout<<msg;//Displays the message to let user know what is expected
cin>>i;//Gets the input
bool cond = (i < ll) || (i > ul);//finds if input is outside limits
while(cin.fail() || cond)//loops while cin fails or cond is true
{
cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n');//Clears Buffer and ignores everything till \n
cout<<Cards::SetTextColor("Wild ", 1)<<err<<endl;//Displays Error Message With Pink Color
cout<<Cards::SetTextColor("", 5)<<msg;//Displays message Again with defalt colors
cin>>i; cond = (i < ll) || (i > ul);//Gets the input again and checks for cond again
}
}
void UpdateLengths()
{
int sl, sw;
ss.getScreenSize(sl, sw);//Gets Screen Height and Width and Stores it in sl and sw, respectively.
cl = (sl * lenf) / Div; cw = (sw * widf) / Div; space = (sw - cw) / 2;//Gets cl, cw and space using screen size, lenf, widf
}
void Clear()
{
#if defined(_WIN32)
system("cls");//If os is windows it executes "cls"
#else
system("clear");//else it executes "clear"
#endif
}
void Stopper()
{
string _;
cout<<"\nEnter Anything to Continue: ";
cin.ignore();//Makes sure /n doesnt bleed over from cin so that user can enter
getline(cin, _);
Clear();//Clears Screen
}
void WinningMessage(string mssg)
{
string stemp = "";//stores parts of the mssg, this is to display every word in new line
Fill f;
cout<<"\n\n\nRESULTS:\n\n";
int scw = ss.getWidth();
scw = scw / 2;//halfs scw to fill with ' '
for(int i = 0; i <= mssg.size(); i++)
{ | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
scw = scw / 2;//halfs scw to fill with ' '
for(int i = 0; i <= mssg.size(); i++)
{
if(mssg[i] == ' ' || i == mssg.size())//If it is a space or if it is the last character
{
MgTxt m;//Instance of MgTxt to magnify text
cout<<endl;//Starts with a new line
string* pt = m.getPrArr(stemp);//Gets Pointer To The Array That Stores 5 lines of Magnified Text
stemp = "";//empties stemp
for(int j = 0; j < MgTxt::Size; j++)//Goes Through the Array
{
cout<<f.fillwith("", (scw - (pt->size() / 2)))<<Cards::SetTextColor("Wild ", (j % 4) + 1)<<*pt;//Fills with total of (scw - pt.size() / 2) spaces followed by changing text color and then printing j + 1 th line of the text
pt++;//makes pt point to the next element
}
continue;//continues to next iteration to not include ' '
}
stemp += mssg[i];//adds characters to stemp
}
cout<<Cards::SetTextColor("", 5);//Sets Color to Default
} | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
Card.hpp
This is used to create a class with all functions of a card that is drawing cards, removing cards, displaying cards, etc.
#include "Fill.hpp"
#include <iostream>
#include <algorithm>
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif
using namespace std; | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
class Cards
{
private:
static string colors[5];//Stores All Possible Colors for UNO Cards
static string pcards[15];//Store All Possible Cards(excluding Color Combinations i.e it Stores 2 instead of Red 2)
int index;//Stores the index of an Card Object wrt All Created Card Objects(i.e 1st object will have index 0)
static bool SameNum(string a, string b)//Checks if 2 cards have Same Number
{
string sub1 = getNum(a), sub2 = getNum(b);//Gets Number of each card and stores it in sub1 and sub2
if(sub1 == pcards[10] && sub2 == "Draw2")
return true;//Card has num Draw2 if Draw 2 has Resulted in Someone Drawing Cards (i.e It Allows for Draw 2 on an Already Completed Draw 2)
return (sub1 == sub2);//returns true if Both have Same nums else return false
}
static bool SameColor(string a, string b)//Checks If Both Cards have Same Colors
{
string sub1 = getColor(a), sub2 = getColor(b);//Gets Colors for Both Cards
if(b == (colors[4] + " " + pcards[11]) && Cards::getNum(a) == pcards[12])
return false;//If Last Card(b) is Wild Draw 4 and a is Wild Color Changer it returns false
if(getNum(b) == pcards[10])
return false;//If Last Card(b) is Draw 2 it returns false Therefore Only Allowing other draw 2s
if(sub1 == colors[4])
return true;//If a's Color is Wild and Last Card(b) isnt a Draw 2(see previous condition), it returns true
return (sub1 == sub2);//returns true or false based on if the colors are same
}
static void Display(vector<string> ac, int si, int l, int w, int s)
{//Displays All Cards in ac, with length l, width w, after 's' spaces, Display Indexes Of the Cards Based on si
if(w < 13 || l < 5)//as the largest
return Display(ac, si);
cout<<endl; | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
return Display(ac, si);
cout<<endl;
int tb = w/12, ts = tb, coln, pcn, cent = (l - 1)/2;//tb and ts stores number of spaces in between cards, coln and pcn cycles through colors and pcards, cent stores the center line
Fill f('-'), f2;//Creates Fill Objects to Fill Space with '-' for f and ' ' for f2
string spacer = "", spacerb = "";
while(s != 0)//Loops through Based on s to Get the Number of spaces before Starting to Display Cards
{ spacerb += ' '; s--; }
while(ts != 0)//Loops through Based on ts to Get the spacer Between Cards
{ spacer += ' '; ts--; }
if(si > 0)//If si is Non Negative it Enters the Indexes to display
{
cout<<spacerb;
for(int i = 0; i < ac.size(); i++)//Limits number of indexes to Number of Cards(ac.size())
{
int totl = 1 + w + tb;//w + 1 is the width of the card and tb is space in between cards
cout<<f2.fwcent(si, totl);//Centers si and fills the rest of the space based on totl
si++;//Goes to the next index
}
}
cout<<endl;
for(int i = 0; i < l; i++)//Loops through all Lines Based on the length of the card
{
coln = 0; pcn = 0;
string beg = (i == 0 || i == (l- 1)) ? " " : "|";//starts with " " if its the first or last line else starts with "|"
cout<<spacerb<<SetTextColor(ac[0], 4)<<beg;//spaces each line based on spacerb
for(int j = 0; j < ac.size(); j++)//Loops through the Cards
{
if(i == 0 || i == (l - 1))//if its the first or last line
cout<<SetTextColor(ac[j], (i == 0 ? 1 : 2))<<f.fillwith("", w);//fills with '-' based on w
else if(i == 1 || i == (l - 2))//if its second or second last line | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
else if(i == 1 || i == (l - 2))//if its second or second last line
{
cout<<SetTextColor(ac[j], 5)<<f2.fwcent(getColor(ac[coln]), w);//prints and centers the card color based on w
coln++;//goes to the next cards color
}
else if(i == cent)//if its the center line
{
cout<<SetTextColor(ac[j], 5)<<f2.fwcent(getNum(ac[pcn]), w);//Centers Card's Number based on w
pcn++;//goes to the next cards pcards
}
else
cout<<f2.fillwith("", w);//Fills with ' ' based on w
cout<<SetTextColor(ac[j], 3)<<beg<<spacer;//Ends with beg and adds spacer in between cards
if(j == (ac.size() - 1))
cout<<endl;//if it is the last card it goes to the next line after printing that line
}
}
cout<<SetTextColor("", 5);//resets text color so that anything printing next is in the default color
}
static void Display(vector<string> ac, int si)//Displays AllCards in a simpler fashion i.e [n) Wild Draw 4, n + 1) Red 2, ...]
{
cout<<"[ ";
bool isNeg = si < 0;//If Starting Index(si) Is Negative It Does Not Display Indexes
for(int i = 0; i < ac.size(); i++)
{
string ce = (i != (ac.size() - 1)) ? ", " : " ]\n";//Sets ce with a seperator it becomes " ]\n" If Its The Last Card
string sind = isNeg ? "" : to_string(si) + ") ";//Stores Card Index or Keeps it Empty Based on isNeg
if(getColor(ac[i]) == colors[4])//Checks if the Card Is Wild
{
cout<<SetTextColor(ac[i], (rand() % 4) + 1)<<sind;//Displays The Index With 1 Random Color | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
for(int j = 0; j < ac[i].size(); j++)//Loops Through Characters of The Card
cout<<SetTextColor(ac[i], (j % 4 + 1))<<ac[i][j];//Displays Each Character With A Color In Order
cout<<SetTextColor("", 5)<<ce;//Displays Seperator with Default Color
}
else
cout<<SetTextColor(ac[i], 5)<<sind<<ac[i]<<SetTextColor("", 5)<<ce;//Displays The Index And Card With The Cards Color Followed By The Seperator With The Default Color
si++;
}
}
public:
static vector<string> AllStatus;//Stores Status(i.e number of Cards or uno or won) of All Card Objects
vector<string> AllCards;//Stores All Cards of a Cards Object
static int count;//Counts the number of Cards Objects
Cards()
{
srand(time(0));//To make random against time
count++;//Increases count every time object is created
AllStatus.push_back("");//creates empty status when an object is created
index = count - 1;//sets index of an object as (count at the moment at creation) - 1
}
static void Display(string card, int l, int w, int si, int sp)
{//Display card 'card' of length l, width w, index(to be displayed) si, and number of spaces based on sp
vector<string> st;
st.push_back(card);//pushes back 'card' to st
Display(st, si, l, w, sp);//passes st and other parameters to private static void Display(vector<string>, int, int, int, int)
}
void Display(int l, int w, int scw)//Displays cards in AllCards based on length l, width w, and screen width scw
{
int sp = w/12, noac = ((scw - sp - 1) / (w + sp + 1));//sp is the number of spaces between each card and, noac is Number Of Allowed Cards
/*sp is space between cards, sep is seperator between cards which is either '|' or ' ' and c represents cards | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
as cards are displayed as : sp sep c sp sep c ... sp sep, we know if in a row there are n cards there will be n + 1 sp and n + 1 sep, we also know that the sum of all cards width, sp and sep should be less than or equal to scw, we also know te size of sep will always be 1
Therefore, (n * w) + (n + 1)(sp) + (n + 1) <= scw, nw + nsp + sp + n + 1 <= scw, n(w + sp + 1) + sp + 1 <= scw,
n(w + sp + 1) <= (scw - sp - 1), n <= (scw - sp - 1) / (w + sp + 1)
As int drops all decimals and we want maximum value of n we can drop '<' and use the formula noac = (scw - sp - 1) / (w + sp + 1)*/
if(AllCards.size() > (noac * 3))//if number of cards cant be displayed in 3 rows or if card width is less than 13 it calls void Display()
return Display(AllCards, 1);
vector<string> subac;//Stores sub vectors from AllCards
int i = 1;
while(i <= AllCards.size())
{
string s = AllCards[i - 1];
subac.push_back(s);
if((i % noac) == 0)//If number of cards it has already added is a multiple of 8
{
cout<<endl;//goes to new line to make sure every 8 cards are one below the other
Display(subac, (i - (noac - 1)), l, w, sp);//Displays the current subac (with 8 cards)
subac.clear();//empties the vector
}
i++;
}
if(!subac.empty())//if subac still has cards within it, it Displays them
{ cout<<endl; Display(subac, (i - subac.size()), l, w, sp); }
}
void Draw()//Adds a card to AllCards
{
int coln = rand() % 4;//gets a random index from 0 to 3 to get a random color other then "Wild"
int pcn = rand() % 15;//gets a random index from 0 to 14 to get a random pcards | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
int pcn = rand() % 15;//gets a random index from 0 to 14 to get a random pcards
string colorpart = colors[coln], numpart = pcards[pcn];//gets the numpart and colorpart from colors and pcards based on coln and pcn
if(pcn == 11 || pcn == 12)//if pcn is the index of Color Changer or Draw 4 it sets colorpart as "Wild"
colorpart = colors[4];
AllCards.push_back((colorpart + " " + numpart));//Adds the colorpart and numpart with " " to AllCards hence generating a new card
UpdateStatus();
}
void Draw(int n)//Calls Draw() n times
{
for(int i = 0; i < n; i++)
Draw();
}
void DrawTCP(string lcard)//Calls Draw unless it finds a playable card based on lcard
{
bool cond = false;//set to false to draw at least once
while(!cond)
{
Draw();
cond = CanPlay(AllCards[AllCards.size() - 1], lcard);
}
}
void Remove(int ind)//Removes a card from AllCards at index ind
{
if(ind > AllCards.size() || ind < 0)//if index is out of bounds it does nothing
return;
AllCards.erase((AllCards.begin() + ind));//.erase removes an element using iterators .begin() points to index 0 adding ind makes it point to the element at index
UpdateStatus();//gets new status after removing card
}
void Sort()//Sorts AllCards based on color
{
int s = AllCards.size();//gets the size before adding anything
vector<string> r, g, b, y;//creating vectors for colors red, green, blue, yellow, respectfully
for(int i = 0; i < s; i++)//goes through the original cards of AllCards(i.e before s)
{
string col = getColor(AllCards[i]);//gets colors for card at i | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
{
string col = getColor(AllCards[i]);//gets colors for card at i
if(col == colors[0])//if color for the current card is Red it adds the card at i to r
r.push_back(AllCards[i]);
else if(col == colors[1])//if color for the current card is Green it adds the card at i to g
g.push_back(AllCards[i]);
else if(col == colors[2])//if color for the current card is Blue it adds the card at i to b
b.push_back(AllCards[i]);
else if(col == colors[3])//if color for the current card is Red it adds the card at i to y
y.push_back(AllCards[i]);
else//if it is Wild it adds it directly to AllCards to save space and time
AllCards.push_back(AllCards[i]);
}
AllCards.erase(AllCards.begin(), AllCards.begin() + s);//Erases the original cards
AllCards.reserve((AllCards.size() + r.size() + g.size() + b.size() + y.size()));//reserves sum of vectors and remaining AllCards
AllCards.insert(AllCards.end(), r.begin(), r.end());//inserts all red cards(stored in r) at the end of AllCards
AllCards.insert(AllCards.end(), g.begin(), g.end());//inserts all green cards(stored in g) at the end of AllCards
AllCards.insert(AllCards.end(), b.begin(), b.end());//inserts all blue cards(stored in b) at the end of AllCards
AllCards.insert(AllCards.end(), y.begin(), y.end());//inserts all yellow cards(stored in y) at the end of AllCards
}
static bool CanPlay(string selcard, string lcard)//Checks if selcard can be played on lcard
{ return (SameColor(selcard, lcard) || SameNum(selcard, lcard)); }
bool CanPlayAny(string lcard)//Checks if any of cards from AllCards can be played on lcard
{
for(string s : AllCards)//Loops through AllCards
{ | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
{
for(string s : AllCards)//Loops through AllCards
{
if(CanPlay(s, lcard))//checks if current card can be played on lcard
return true;
}
return false;
}
static string getNum(string card)//gets Number of a card(i.e pcards)
{
int nst = card.find(' ') + 1, size1 = card.length() - nst;
//' ' seperates color and num so index after num is the start of num which is stored in nst, the size of num is total size - size of color + 1 viz equal to nst
string sub = card.substr(nst, size1);//creates a substring starting from nst of size size1
return sub;
}
static string getColor(string card)
{
int size1 = card.find(' ');//as ' ' seperates color and num, the index of ' ' will be equal to size of color
string sub = card.substr(0, size1);//creates a substring starting from 0 (as color of a card is first) of size size1
return sub;
}
void UpdateStatus()
{
int s = AllCards.size();//gets the number of cards
if(s == 0 || s == 1)//if number of cards is 0 or 1
AllStatus[index] = s == 0 ? "WON!!!" : "UNO!!";//Updates Staus of the Current Object as WON if s is 0, or UNO if s is 1
else
AllStatus[index] = to_string(s) + " Cards";//Updates Staus of the Current Object
}
static string SetTextColor(string card, int l)
{
string o = "\x1B[", s = "Color 0";//o is for linux and it stores ansi sequence to set color, s is for windows and it uses System command to Set Color
if(getColor(card) == colors[0] || (getColor(card) == colors[4] && l == 1))//Pink or Wild and 1
{ o += "35m"; s += "C"; }//Pink
else if(getColor(card) == colors[1] || (getColor(card) == colors[4] && l == 2))//Green or Wild and 2 | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
{ o += "92m"; s += "A"; }//Green
else if(getColor(card) == colors[2] || (getColor(card) == colors[4] && l == 3))//Blue or Wild and 1
{ o += "94m"; s += "9"; }//Blue
else if(getColor(card) == colors[3] || (getColor(card) == colors[4] && l == 4))//Yellow or Wild and 1
{ o += "93m"; s += "E"; }//Yellow
else if(l == 5)//Anything Else and If l = 5
{ o += "0m"; s += "F"; }//Default
#if defined(_WIN32)
system(s.c_str());
return "";//Returns Nothing As Windows Command Switches Color as Soon As system is executed
#endif
return o;//Returns o as it switches color when o is printed
}
string CardChoice(int& ci, string lcard, string ctdp, int nxtc, int& o7ind)
{
vector<string> plcard;//Stores All Playable Cards
int diff = 3 + AllCards.size() - nxtc;//Incentive for Wild Based on The Number Of Cards Of The Current Player() and The Next Players Cards(nxtc)
int colinc[5] = {5, 5, 5, 5, (diff < 3 ? -10 : diff)};//Sets All Colors Incentive as 5 and sets wild to -10 if Current Player Has Less Cards or Diff
if(lcard != "")//Checks If Last Card is Empty
{
for(string s : AllCards)//Loops Through All Cards of the PLayer
if(CanPlay(s, lcard))//Checks If The Current Card Is Playable
plcard.push_back(s);//Adds The Card If It is PLayable
}
else//If Last Card Is Empty it Allows All Cards of The Player To Be Played
plcard = AllCards;
for(string s : AllCards)
colinc[find(colors, end(colors), getColor(s)) - colors] += 1;//Increases Color's Incentive Each Time A Color Appears, To Incentivise Playing Cards of A Color Which A Player Has More Of | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
int allinc[plcard.size()] = {0};//Makes An Array To Store Incentives For All Playable Cards and Sets It To 0
for(int i = 0; i < plcard.size(); i++)
{
allinc[i] += colinc[find(colors, end(colors), getColor(plcard[i])) - colors];//Adds colinc To Each Cards Incentive Based On The Cards Color
int pci = find(pcards, end(pcards), getNum(plcard[i])) - pcards;//Finds The Num(see pcards) of Each Card
allinc[i] += (pci == 0 || pci == 7 || pci > 9) ? 1 : 0;//Checks If The Card is a special Card i.e 0, 7, Skip, Draw 2, Reverse, etc. And Incentives it slightly
}
int cdin = (max_element(allinc, allinc + (sizeof(allinc) / sizeof(allinc[0]))) - allinc);//Gets The Index From allinc for the card with The Most Incentive
o7ind = -1;
ctdp = plcard[cdin];//Sets The Card To Play To The Selected Card Based on cdin
if(getColor(plcard[cdin]) == colors[4])
ctdp = colors[max_element(colinc, (end(colinc) - 1)) - colinc] + " " + getNum(plcard[cdin]);//If The Card Is Wild it Sets The Color To the Color Which Is Found The Most in AllCards
else if(getNum(plcard[cdin]) == pcards[7])//If The Num is 7
{
for(int i = 0; i < AllStatus.size(); i++)//Loops Through AllStatus Which Stores The Number of Cards or UNO!! or WON!!! In All Objects of Cards
{
if(i == index)//Makes Sure It Does Not Try To Exchange With Itself
continue;
if(AllStatus[i] == "UNO!!")//If It Finds A Player With UNO!! It selects that Player
{
o7ind = i;
break;
}
else if(o7ind == -1)//If it is -1 i.e No Index Has Been Stored It Stores The First Possible Index
o7ind = i; | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
o7ind = i;
else if( stoi(getColor(AllStatus[i])) < stoi(getColor(AllStatus[o7ind])) )
o7ind = i;
/*getColor Essentially Gets All Character Before ' ' which In AllStatus Will Be Number of Cards it Converts it To int to Compare if The
Previously Stored Index's Number of Cards is Less Then The Current Index's Number of Cards, If Thats True It Changes o7ind to i*/
}
}
ci = find(AllCards.begin(), AllCards.end(), plcard[cdin]) - AllCards.begin();//It Finds The Index of The Selected Card
return ctdp;//Returns Selected Card With Choosen Color if Wild
}
};
//Initializes static members
int Cards::count = 0;
string Cards::colors[5] = {"Pink", "Green", "Blue", "Yellow", "Wild"};
string Cards::pcards[15] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "Draw 2", "Draw 4", "Color Changer", "Skip", "Reverse"};
vector<string> Cards::AllStatus = {}; | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
Fill.hpp
This is used to fill a certain length with the given value and rest of the length with selected character, it can also center the value and fill its left and right side with a selected character.
#include <string>
#include <sstream>
#include <iomanip>
#include <vector>
#include <cmath>
using namespace std; | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
class Fill
{
private:
bool isNum(string st)
{
int count = 0;
for(int i = 0; i < st.length(); i++)
{
int asc = (int) st[i];
bool cond = (asc >= 48 && asc <= 57);//stores if this char is a digit
if(i == 0)
cond = (cond || (asc == 45));//allows for - at position 0(representing negative number)
if(i != (st.length() - 1) && i != 0)
{
bool cond2 = (asc == 46);
cond = (cond || cond2);//allows for . at any point other then the first or last character
count += cond2 ? 1 : 0;//keeps count of number of . character
}
if(!cond || count > 1)//if cond is false or if the number has more then 1 decimal place it is considered invalid
return false;
//as cond will only be false if the char is non numerical or negative sign appears in any position other then the starting position or if the number starts or ends with a decimal point
}
return true;
}
void RemUz(string& str)
{
size_t si = str.find(".");//finds the index of '.' to see if the num has decimal places
size_t lnfz = str.find_last_not_of("0");//gets the index of last non-zero before all zereos
if(lnfz != string::npos && si != string::npos)//If the num has decimals and useless zereos
str.erase(lnfz + 1);//removes all useless zereos
if(str[str.length() - 1] == '.')//if the last element is a decimal remove the decimal
str.pop_back();
}
template<typename T>
string PStringV(T d)//converts any data type to string using string stream to get accuarate precisions
{
stringstream stream;//creates a new string stream | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
{
stringstream stream;//creates a new string stream
stream<<fixed<<setprecision(prec)<<d;//adds d or a float types to string stream with precision set to prec
return stream.str();//converts stream to string
}
public:
char ta = ' ';//stores the char that will be used to fill remaining space(default: ' ')
int prec = 6;//stores precision for float and double types(default 6 decimal spaces)
int n = 10;
char trs = '+', brs = '+', rs = '|', trf = '-', brf = '-';
//Constructors
Fill(){ }
Fill(int p)//sets user prefferred precision
{ prec = p; }
Fill(char c)//sets user prefferred ta
{ ta = c; }
Fill(int p, char c)//sets user prefferred ta & precision
{ ta = c; prec = p;} | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
//Functions
template<typename T>
string fillwith(T val, int als)
{
string st = PStringV(val);
string s = "";//creates empty s with every call
if(isNum(st))//checks if s stores a number
RemUz(st);//Removes trailing zereos from decimals
int n = als - st.length();
for(int i = 0; i < n; i++)
s += ta;
s = st + s;//returns the string(i.e any input of any function) and the filled space
return s;//i.e for fillwith("ab", 9) ta = '+' it will return string "ab+++++++"
}
template<typename T>
string fillwith(T st, string alst)
{ return fillwith(st, alst.length()); }//takes string and calculates its length and passes the data to fillwith(string, int)
//Centered
template<typename T>
string fwcent(T val, int als)
{
string st = PStringV(val);
if(isNum(st))//Removes useless 0
RemUz(st);
string toret;//stores the string to return
int l = st.length(), size1 = l/2, size2 = ceil((float)l/2.0);//to divide the string into two halfs to center it
int si1 = 0, si2 = size1;//starting index for first half will be 0 and the second half will be size1
string ss1 = st.substr(si1, size1), ss2 = st.substr(si2, size2);//divides st based on above data
int tf1 = als/2 - ss1.length(), tf2 = ceil((float)als/2.0);
toret = fillwith("", tf1) + ss1 + fillwith(ss2, tf2);
return toret;
}
template<typename T>
string fwcent(T st, string alst)
{ return fwcent(st, alst.length()); }
};
MagnTxt.hpp
This is used to magnify almost all characters to 5 lines
#include <algorithm>
#include <string>
#include <iostream>
#include <sstream> | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
class MgTxt
{
private:
static std::string MagLett[59][5];
static char NormLett[59];
std::string sp = " ";
std::string sep = " ";
std::string Tp[5] = {"", "", "", "", ""};
void MagTxt(std::string s)
{
for(char c : s)
{
c = std::toupper(c);
if(c == ' ')
{
Tp[0] += sp; Tp[1] += sp;
Tp[2] += sp; Tp[3] += sp;
Tp[4] += sp;
}
else
{
char* cind = std::find(std::begin(NormLett), std::end(NormLett), c);
if(cind == std::end(NormLett))
continue;
int ind = cind - std::begin(NormLett);
for(int j = 0; j < Size; j++)
Tp[j] += MagLett[ind][j] + sep;
}
}
Tp[0] += "\n"; Tp[1] += "\n"; Tp[2] += "\n"; Tp[3] += "\n"; Tp[4] += "\n";
}
public:
static int Size;
MgTxt()
{ Tp[0] = ""; Tp[1] = ""; Tp[2] = ""; Tp[3] = ""; Tp[4] = ""; }
template<typename T>
std::string* getPrArr(T val)
{
std::stringstream stream; stream<<val;
std::string st = stream.str();
MagTxt(st);
return Tp;
}
template<typename T>
void PrintMT(T val, int up)
{
if(up == 1)
getPrArr(val);
for(int i = 0; i < Size; i++)
std::cout<<Tp[i];
std::cout<<"\n";
}
template<typename T>
void PrintMT(T val)
{ PrintMT(val, 1); }
template<typename T>
void PrintWTxt(std::string ta, T val, int up)
{
if(up == 1)
getPrArr(val);
for(int i = 0; i < Size; i++)
std::cout<<ta<<Tp[i];
std::cout<<"\n";
} | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
std::cout<<ta<<Tp[i];
std::cout<<"\n";
}
template<typename T>
void PrintWTxt(std::string ta, T val)
{ return PrintWTxt(ta, val, 1); }
};
int MgTxt::Size = 5;
char MgTxt::NormLett[59] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '+', '-', '@', '_', '/', '!', '#', '?', '|', '\\', '%', '^', '[', ']', ':', ';', '{', '}', '(', ')', '.', '\'', '"'};
std::string MgTxt::MagLett[59][5] = {//Note:To See How That Letter Would Look Just Press Enter After The Commas And Align The ""
{" ---- ", "| |", "| |", "| |", " ---- "},//0
{" /| ", " | ", " | ", " | ", " -----"},//1
{" ---- ", " |", " ---- ", "| ", " ---- "},//2
{" ---- ", " |", " ---- ", " |", " ---- "},//3
{"| ", "| ", " ---- ", " |", " |"},//4
{" ---- ", "| ", " ---- ", " |", " ---- "}, //5
{" ---- ", "| ", " ---- ", "| |", " ---- "},//6
{" ---- ", " | ", " ----", " | ", " | "}, //7
{" ---- ", "| |", " ---- ", "| |", " ---- "},//8
{" ---- ", "| |", " ---- ", " |", " ---- "}, //9
{" ", " /\\ ", " / \\ ", " /----\\ ", " / \\ "},//A
{" ____ ", "| \\", "|____/", "| \\", "|____/"},//B
{" ____ ", "/ ", "| ", "| ", "\\____ "},//C
{" ____ ", "| \\ ", "| \\", "| /", "|____/ "},//D
{" ---- ", "| ", " ---- ", "| ", " ---- "},//E
{" ---- ", "| ", " ---- ", "| ", "| "},//F
{" ---- ", "| ", "| -- ", "| | |", " -|-- "},//G
{"| |", "| |", "|----|", "| |", "| |"}, //H
{" ----- ", " | ", " | ", " | ", " ----- "},//I
{" ---- ", " | ", " | ", " | ", "--- "}, //J
{"| ", "| / ", "| / ", "| \\ ", "| \\ "},//K | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
{"| ", "| / ", "| / ", "| \\ ", "| \\ "},//K
{" ", "| ", "| ", "| ", "|____ "}, //L
{" _ _ ", "| \\ / |", "| \\/ |", "| |", "| |"},//M
{" _ ", "| \\ |", "| \\ |", "| \\ |", "| \\_|"}, //N
{" ---- ", "| |", "| oo |", "| |", " ---- "},//O
{" ---- ", "| |", "|---- ", "| ", "| "}, //P
{" ---- ", "| |", "| |", "| \\ |", " ---\\ "},//Q
{" ---- ", "| |", "| --- ", "| \\ ", "| \\ "}, //R
{" ____ ", "/ ", "\\____ ", " \\", " ____/"},//S
{"-------", " | ", " | ", " | ", " | "}, //T
{"| |", "| |", "| |", "| |", " ---- "},//U
{"\\ /", " \\ / ", " \\ / ", " \\ / ", " V "}, //V
{" ", "| |", "| |", "| /\\ |", "|_/ \\_|"},//W
{" \\ /", " \\ / ", " X ", " / \\ ", " / \\"}, //X
{" \\ /", " \\ / ", " Y ", " | ", " | "},//Y
{"_____ ", " / ", " / ", " / ", " /____"}, //Z
{" ", " | ", " -- --", " | ", " "},//+
{" ", " ", "------", " ", " "},//-
{" ---- ", "| __|", "| | |", "| -- ", " ---- "},//@
{" ", " ", " ", " ", "______"},// _
{" /", " / ", " / ", " / ", " / "},// /
{" | ", " | ", " | ", " | ", " O "}, //!
{" ", " / /", " -/---/-", "-/---/- ", "/ / "}, //#
{"____ ", " \\ ", " / ", " | ", " O "}, //?
{" | ", " | ", " | ", " | ", " | "}, //|
{" \\ ", " \\ ", " \\ ", " \\ ", " \\"}, /*\*/
{" _ / ", "|_| / ", " / _ ", " / |_|", " / "}, //%
{" /\\ ", " / \\ ", " ", " ", " "}, //^
{" __ ", "| ", "| ", "| ", "|__ "}, //[
{" __ ", " |", " |", " |", " __|"},//]
{" _ ", " |_|", " ", " _ ", " |_|"}, //:
{" _ ", "|_|", " _ ", "\\_\\", "/_/"}, //; | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
{" _ ", " |_|", " ", " _ ", " |_|"}, //:
{" _ ", "|_|", " _ ", "\\_\\", "/_/"}, //;
{" __", " / ", "_|_ ", " | ", " \\__"}, //{
{"__ ", " \\ ", " _|_", " | ", "__/ "}, //}
{" _ ", " / ", "| ", "| ", " \\_ "}, //(
{" _ ", " \\ ", " |", " |", " _/ "}, //)
{" ", " ", " ", " _ ", "|_|"}, //'.'
{" _ ", "\\_\\", "/_/", " ", " "}, //'
{" _ _ ", "\\_\\ \\_\\", "/_/ /_/", " ", " "}//"
}; | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
GetSS.hpp
This is used to get the screen size
#if defined(__unix__)
#include <sys/ioctl.h>
#include <cstdio>
#elif defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif
class ScreenSize
{
private:
int h, w;
public:
void getScreenSize(int& height, int& width)//No idea how it works got from Stackoverflow
{
#if defined(_WIN32)
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
width = (int) (csbi.srWindow.Right-csbi.srWindow.Left + 1);
height = (int) (csbi.srWindow.Bottom-csbi.srWindow.Top + 1);
#else
struct winsize w;
ioctl(fileno(stdout), TIOCGWINSZ, &w);
width = (int)(w.ws_col);
height = (int)(w.ws_row);
#endif
}
void UpdateSize()
{ getScreenSize(h, w); }
int getHeight()
{
UpdateSize();
return h;
}
int getWidth()
{
UpdateSize();
return w;
}
}; | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
Answer: Code readability
This code is very hard to read, since you have used almost no whitespace (like empty lines) to visually distinguish related code, and you have way too many comments. Ideally, code should be self-expanatory: by giving functions and variables proper names and by using the right organization, it should be mostly self-documenting. Comments should only be used to explain the remaining things that would still be unclear for another programmer reading your code.
Use a curses library
As you'll have noticed, nicely formatting the output is hard to do in plain C++. There isn't even a standard function to clear the screen. The latter, and printing in color, is also not easy to do portably, although printing ANSI escape codes are supported by many terminals and are indeed the best way to go. If you are using them anyway, also use them to clear the screen; this is much more efficient than calling system().
Instead of trying to do this from scratch, I strongly recommend you use a curses library. These provide a standard interface for writing full-screen text applications, and there are implementations for most major operating systems.
Sorting cards
I see you are using <algorithm> in your code, but then I was surprised that when sorting cards on color, you didn't use std::sort(). You can provide a custom function to determine what to sort on. For example:
void Sort()
{
std::sort(AllCards.begin(), AllCards.end(), [](auto& lhs, auto& rhs) {
return getColor(lhs) < getColor(rhs);
});
}
Or with C++20's ranges algorithms it becomes even simpler:
void Sort()
{
std::ranges::sort(AllCards, {}, getColor);
}
Avoid stringly types
Instead of having cards be represented by strings, create a struct Card that describes a card. For example:
struct Card {
enum class Color {
RED,
YELLOW,
BLUE,
GREEN,
} color; | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
c++, game
enum class Type {
NUMBER,
SKIP,
REVERSE,
DRAW,
WILDCARD,
WILDDRAW,
} type;
int value;
};
This avoids having to parse strings all the time. | {
"domain": "codereview.stackexchange",
"id": 43823,
"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++, game",
"url": null
} |
performance, android, kotlin, mvvm
Title: Observe LiveData to indicate whether or not to display TextViews in MVVM
Question: In the context of MVVM, is this an efficient way to communicate to the view that I should display some TextViews? Any advice on how I can improve it?
ViewModel code:
private var _shouldDisplayDischargeCurrent = MutableLiveData<Boolean>()
val shouldDisplayDischargeCurrent: LiveData<Boolean>
get() = _shouldDisplayDischargeCurrent
Activity code:
viewModel.shouldDisplayDischargeCurrent.observe(this, Observer { shouldDisplay ->
if (!shouldDisplay) {
binding.textviewDischargeCurrentTitle.visibility = GONE
binding.textviewDischargeCurrent.visibility = GONE
binding.textviewDischargeTimeTitle.visibility = GONE
binding.textviewDischargeTime.visibility = GONE
}
})
Answer: Will asume you are using ConstraintLayout and also want to show the views (currently your code only hides the views) so I think it can be improved in 2 ways.
The first way is to use View.isVisible extension from google's lib instead of setting GONE. So you code will become like this:
viewModel.shouldDisplayDischargeCurrent.observe(this, Observer { shouldDisplay ->
binding.textviewDischargeCurrentTitle.isVisible = !shouldDisplay
binding.textviewDischargeCurrent.isVisible = !shouldDisplay
binding.textviewDischargeTimeTitle.isVisible = !shouldDisplay
binding.textviewDischargeTime.isVisible = !shouldDisplay
})
and the second way is to use Constraint Group. Add a new element in XML with all the view's ids you want to hide:
<androidx.constraintlayout.widget.Group
android:id="@+id/textview_group"
app:constraint_referenced_ids="textviewDischargeCurrent, textviewDischargeCurrentTitle,textviewDischargeTime,textviewDischargeTimeTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/> | {
"domain": "codereview.stackexchange",
"id": 43824,
"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": "performance, android, kotlin, mvvm",
"url": null
} |
performance, android, kotlin, mvvm
and then in your code:
viewModel.shouldDisplayDischargeCurrent.observe(this, Observer { shouldDisplay ->
// those are no longer needed
// binding.textviewDischargeCurrentTitle.isVisible = !shouldDisplay
// binding.textviewDischargeCurrent.isVisible = !shouldDisplay
// binding.textviewDischargeTimeTitle.isVisible = !shouldDisplay
// binding.textviewDischargeTime.isVisible = !shouldDisplay
binding.textviewGroup.isVisible = !shouldDisplay
})
Also Observer { can be removed so the final result with Constraint Group will be:
viewModel.shouldDisplayDischargeCurrent.observe(this) { shouldDisplay ->
binding.textviewGroup.isVisible = !shouldDisplay
}
Regarding performance I could not find much about this. Maybe someone else can comment about it. Personaly I would go with Constraint Group and View.isVisible | {
"domain": "codereview.stackexchange",
"id": 43824,
"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": "performance, android, kotlin, mvvm",
"url": null
} |
python, beginner
Title: Run Script in SolarWinds Orion via Python
Question: I've been using Python for about two months now and I know that there is a lot of improvement to be made.
This script runs a command against a device within our SolarWinds Orion environment. The script works fine, I'd love to know how I could make improvements on the code quality and methods that are used.
I appreciate any help and suggestions that you can offer!
from orionsdk import SwisClient
import time
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
sw_server = ####
username = ####
password = ####
device_ip = "192.0.0.0"
swis = SwisClient(sw_server, username, password)
# Get the device's NodeID to be able to point the query at the specific device
data = swis.query(f"SELECT NodeID, ReverseDNS, Status, StatusText, DisplayName, LastBoot, AgentIP FROM Cirrus.Nodes WHERE AgentIP = '{device_ip}'")
list = [i['NodeID'] for i in data['results']]
nodeID = (''.join(list))
# Command that we'd like to run against the device
command = 'show version'
# Run command against the device
response = swis.invoke('Cirrus.ConfigArchive', 'ExecuteScript', [nodeID], command)
transfer_id = (''.join(response))
time.sleep(5)
# Check the status of the command:
# Status = 1: Incomplete
# Status = 2: Complete
# I'm guessing that there are more status codes, but I haven't yet discovered them nor their meaning
status = '1'
while status == '1':
response = swis.query(f"SELECT status, action, DeviceOutput, UserName,TransferID, NodeID, DateTime, ErrorMessage FROM NCM.TransferResults WHERE TransferID = '{transfer_id}'")
status_code = [i['status'] for i in response['results']]
status = ",".join(map(str, status_code))
time.sleep(5)
if status != '1':
DeviceOutput = [i['DeviceOutput'] for i in response['results']]
DeviceOutput = (''.join(DeviceOutput))
print(DeviceOutput)
break | {
"domain": "codereview.stackexchange",
"id": 43825,
"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",
"url": null
} |
python, beginner
Answer: Given the domain-specific nature of the code there's only a limited amount of review that I can provide, but:
Don't hard-code credentials in source. This is not secure, and is inconvenient for production operations. The credentials should be off-loaded to a permissions-controlled file or wallet system or environment variables that are themselves configured with security in mind.
(''.join(list)) does not need outer parens.
Do not make a variable called list since it shadows a built-in.
Since you only join on list, don't materialise that comprehension to a list []; instead leave it as a generator like
node_id = ''.join(i['NodeID'] for i in data['results'])
Further, it seems like you should expect only one result from your query, and you should terminate the script if that isn't the case, so unpack the query:
data = swis.query(f"SELECT NodeID, ReverseDNS, Status, StatusText, DisplayName, LastBoot, AgentIP FROM Cirrus.Nodes WHERE AgentIP = '{device_ip}'")
result, = data['results']
node_id = result['NodeID']
Another problem is injection vulnerability. If this source corresponds to the client library that you're using, then it has a params you need to prefer over string formatting.
You should delete your first sleep(). Since your second sleep is in a polling loop there's probably no avoiding it.
Rather than putting a placeholder value in status, convert to a forever-loop; tuple-unpack single query results; and don't unnecessarily degrade an integer to a string:
while True:
response = swis.query(f"SELECT status, action, DeviceOutput, UserName,TransferID, NodeID, DateTime, ErrorMessage FROM NCM.TransferResults WHERE TransferID = '{transfer_id}'")
result, = response['results']
if result['status'] != 1:
break
device_output = result['DeviceOutput']
print(device_output)
That isn't tested, of course, so YMMV. | {
"domain": "codereview.stackexchange",
"id": 43825,
"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",
"url": null
} |
php, laravel
Title: Laravel PostController
Question: I'm new at Laravel and I got an assessment task from company where they want me to create a mini-blog with Users and Posts.
I was using following methods:
index, create, show, store, edit and destroy in PostController. When I finished I sent it to them but they told me:
We still want you have a look at some parts of your code:
The index function of your PostController
Your delete function of your PostController
I am not sure what can I improve in index and delete methods. Here are how they looks like in controller:
public function index()
{
$post = Post::all();
return view('blog.index')
->with('posts', Post::orderBy('created_at', 'DESC')->get());
}
public function destroy($id)
{
$post = Post::where('id',$id);
$post->delete();
return redirect('/blog')
->with('message', 'Your post has been deleted!');
}
Here are the routes (web.php):
Route::get('/', [PagesController::class, 'index']);
Route::resource('/blog', PostsController::class);
Auth::routes();
Do you have any suggestions on what to improve, or maybe do we have any best practices related to mentioned methods?
Answer: Thanks for migrating this from Stackoverflow! Let's take a look at your code:
public function index() {
$post = Post::all();
return view('blog.index')->with('posts', Post::orderBy('created_at', 'DESC')->get());
}
This isn't bad, but the main issue is that $post is never used. You can remove that line completely. Also, ->with() works, but there are other syntaxes available, such as simply passing an array as the 2nd parameter of ->view(). Also, orderBy('created_at', 'DESC') can simply be replaced by ::latest():
public function index() {
return view('blog.index', [
'posts' => Post::latest()->get()
]);
} | {
"domain": "codereview.stackexchange",
"id": 43826,
"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": "php, laravel",
"url": null
} |
php, laravel
The destroy() method also isn't bad, but, since you're using a ResourceController, you shouldn't need to do Post::find(); that should be implied:
public function destroy(Post $post) {
$post->delete();
return redirect()->route('blogs.index')->with([
'message' => 'Your Post has been deleted'
]);
}
This should work, but your definition in routes/web.php seems a bit odd. I would recommend:
Route::resource('/posts', PostsController::class);
And anywhere you have blog, replace with post (or posts). You'll also need to move anything in resources/views/blogs to resources/views/posts. Resource Controllers ideally should reference the same name as the model they are representing. | {
"domain": "codereview.stackexchange",
"id": 43826,
"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": "php, laravel",
"url": null
} |
c++, abstract-factory, variant-type
Title: Helper functions for use with std::variant without an actual object
Question: Sometimes, you want to an type of a particular index in an std::variant, and do something with that type without having an actual object. An example use-case would be de-serialization. What do you think of the following approach?
/**
* @brief Used as placeholder to allow tag dispatching
*/
template<class T>
using empty = std::type_identity<T>;
/**
* @brief Find the index of the type that satisfies pred
*/
template<class Variant, class Predicate, size_t N = std::variant_size_v<Variant>>
constexpr size_t find_type(Predicate&& pred)
{
if constexpr(N != 0)
{
using current_type = std::variant_alternative_t<N - 1, Variant>;
if(pred(empty<current_type>{}))
{
return N - 1;
}
else
{
return find_type<Variant, N - 1, Predicate>(std::forward<Predicate>(pred));
}
}
else
{
return std::variant_npos;
}
}
template<class Callback, class ... Args>
using callback_wrapper = void (*)(Callback&&, Args&&...);
template<class Variant, size_t N, class Callback, class ... Args>
constexpr void assign_callback(
std::array<callback_wrapper<Callback, Args...>, std::variant_size_v<Variant>>& values)
{
if constexpr(N != 0)
{
using current_type = std::variant_alternative_t<N - 1, Variant>;
values[N - 1] = [](Callback&& cb, Args&&... args){
std::move(cb)(empty<current_type>{}, std::move(args)...);
};
assign_callback<Variant, N - 1>(values);
}
} | {
"domain": "codereview.stackexchange",
"id": 43827,
"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++, abstract-factory, variant-type",
"url": null
} |
c++, abstract-factory, variant-type
template<class Variant, class Callback, class ... Args>
constexpr auto create_vtable()
{
constexpr auto N = std::variant_size_v<Variant>;
std::array<callback_wrapper<Callback, Args ...>, N> ret{};
assign_callback<Variant, std::size(ret)>(ret);
return ret;
}
/**
* @brief Calls cb for an "empty" of type with index
*/
template<class Variant, class Callback, class ... Args>
decltype(auto) on_type_index(size_t index, Callback&& cb, Args&&... args)
{
static constexpr auto vtable = create_vtable<Variant, Callback, Args...>();
vtable[index](std::forward<Callback>(cb), std::forward<Args>(args)...);
}
Answer:
Sometimes, you want to an type of a particular index in an std::variant,
Yes, you can do that with std::variant_alternative_t, which you are already using in your code.
and do something with that type without having an actual object.
You can do lots of things with just types, but I think you mean you actually want to pass that type as a function parameter to another function. This is where you use std::type_identity; it provides you with an otherwise empty object but it has an associated type alias type.
I was thinking you might avoid having to use std::type_identity by allowing Predicate to be a template template parameter, then you can write:
template<class Variant, template<class> class Predicate, size_t N = std::variant_size_v<Variant>>
constexpr size_t find_type()
{
...
if(Predicate<current_type>)
...
}; | {
"domain": "codereview.stackexchange",
"id": 43827,
"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++, abstract-factory, variant-type",
"url": null
} |
c++, abstract-factory, variant-type
However, template template parameters can only be template classes, not template (constepxr) variables, and recursively calling find_type() with a template type is apparently impossible.
There are also some situations where std::declval() might be of use, although I don't think it would help you.
Iterating over variants
You are using recursive functions to iterate over the possible variants. That is one way to do it. Another way is to use std::apply() in some way. Consider creating a helper function that creates a std::tuple of empty types for each of the variant's types:
template<class Variant, size_t... Is>
auto empties(std::index_sequence<Is...> = std::make_index_sequence<std::variant_size_v<Variant>>()) {
return std::tuple<empty<std::variant_alternative_t<Is, Variant>>...>{};
}
Then you can pass it a lambda that iterates over each "empty" using a fold expression:
std::apply([](auto... types){
(some_func(types), ...);
}, empties<Variant>());
Although it doesn't look any better than your approach. However, one advantage is that it iterates over the variant's types forward, instead of your recursive functions that go backwards, which might be surprising.
Bug in find_type()
When you call find_type() recursively, you have the order of the template arguments wrong.
Don't std::move() the callback and its arguments
You should not use std::move() when calling the callback. Instead, std::forward() the arguments and the callback, and use std::invoke() to call it:
values[N - 1] = [](Callback&& cb, Args&&... args) {
std::invoke(std::forward<Callback>(cb), std::forward<Args>(args)...);
};
Let the callback itself std::move() if so desired. | {
"domain": "codereview.stackexchange",
"id": 43827,
"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++, abstract-factory, variant-type",
"url": null
} |
python, python-3.x, datetime, json
Title: Saving and reading the last successful execution as a json-file
Question: I've got some tools that run perdiodically like weekly or monthly that don't support any retry mechanism. In order to increase their chance to succeed in case a database wasn't reachable or some other problem occured, I simply schedule them to run several times per day or a couple of days in month.
Currently they do their job every time they run, regardles whether they succeeded the first time or not. I'd like to change this by saving a simple token with the timestamp of the last successful execution.
Implementation
This is where my Tick class comes into play. I designed it handle a json-token with only a single property. I know at this point it could be a plain text file, but this escalates pretty quickly so I'd like it to be future-proof.
{"created_on": "2022-09-01T15:36:08.434008"}
It allows me to save the current datetime and also takes care of reading it and checking whether the token is still valid or already expired. Its job is simple, but I wanted to have it as pretty and as smartass as it can be. This is how it looks like:
import json
import pathlib
import os
from functools import lru_cache
from datetime import datetime, date
from typing import Any, Callable, Dict, Union
class Tick:
def __init__(self, file_name: Union[str, bytes, os.PathLike], lifetime: float, calc_as: Callable[..., float]):
self.file_name = file_name
self.lifetime = lifetime
self.calc_as = calc_as
def check(self):
pathlib.Path(os.path.dirname(self.file_name)).mkdir(parents=True, exist_ok=True)
data = json.dumps({self.created_on.__name__: datetime.now()}, cls=_JsonDateTimeEncoder)
with open(self.file_name, "w") as f:
f.write(data)
self.created_on.cache_clear() | {
"domain": "codereview.stackexchange",
"id": 43828,
"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, datetime, json",
"url": null
} |
python, python-3.x, datetime, json
@lru_cache # avoid reading the file more than once until updated
def created_on(self) -> Union[datetime, None]:
if not os.path.isfile(self.file_name):
return None
with open(self.file_name, "r") as f:
return json.loads(f.read(), cls=_JsonDateTimeDecoder)[self.created_on.__name__]
def seconds(self) -> Union[float, None]:
return (datetime.now() - self.created_on()).total_seconds() if self.created_on() else None
def minutes(self) -> Union[float, None]:
return self.seconds() / 60 if self.seconds() else None
def hours(self) -> Union[float, None]:
return self.minutes() / 60 if self.minutes() else None
def days(self) -> Union[float, None]:
return self.hours() / 24 if self.hours() else None
def is_expired(self) -> bool:
return not self.calc_as(self) or self.calc_as(self) > self.lifetime
def is_valid(self) -> bool:
return not self.is_expired()
Since the json package cannot handle datetime by default, I created these two classes to handle that part.
class _JsonDateTimeEncoder(json.JSONEncoder):
def default(self, o: Any) -> Any:
if isinstance(o, (date, datetime)):
return o.isoformat()
class _JsonDateTimeDecoder(json.JSONDecoder):
def __init__(self):
super().__init__(object_hook=self.parse_datetime_or_default)
@staticmethod
def parse_datetime_or_default(d: Dict):
r = dict()
for k in d.keys():
r[k] = d[k]
if isinstance(d[k], str):
try:
r[k] = datetime.fromisoformat(d[k]) # try parse date-time
except ValueError:
pass # default value is already set
return r
Example
This is how I test it:
import json
from datetime import datetime
from src.tick_off import Tick
if __name__ == "__main__":
tick = Tick(r"c:\temp\token_test__.json", lifetime=5, calc_as=Tick.hours) | {
"domain": "codereview.stackexchange",
"id": 43828,
"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, datetime, json",
"url": null
} |
python, python-3.x, datetime, json
# tick.check()
print(tick.hours())
print("is_expired:", tick.is_expired())
print("is_valid:", tick.is_valid())
The one thing that bothers me the most is the repeated conditions in methods like minutes, hours & days that use virtually identical conditions:
return self.seconds() / 60 if self.seconds() else None
Unfortunatelly None / 60 doesn't produce None but an error, but maybe there is some smart way one can get rid of these conditions without turning it into a try/except that would be even more ugly?
Answer: First the positives: you've put some effort into typehints, caching, and encapsulation, all good things. You've started into pathlib support, which is good, and you target Python 3, which is good.
Union[datetime, None] is just Optional[datetime].
file_name is too broad in its type. Just force the caller to pass a Path. This is not an external-facing library: you don't need to, and should not, adopt the shotgun approach to argument types. After all of that effort, you still don't use Path properly - you're calling top-level open() and os.path.isfile when you should be using the Path equivalents.
When you write
pathlib.Path(self.file_name).mkdir(parents=True, exist_ok=True) | {
"domain": "codereview.stackexchange",
"id": 43828,
"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, datetime, json",
"url": null
} |
python, python-3.x, datetime, json
It seems to me like this should be getting .parent, not making a directory named the same as the target file.
calc_as is a fascinating, convoluted mistake. Don't do any of this. Just accept a timedelta for lifetime instead of a float. Delete all of your time unit conversion functions.
Don't dumps and loads string-based functions; call their file alternatives dump and load.
is_expired etc. are good candidates for being made @propertys.
If you want to support datetime parsing in JSON, fine. Your implementation, first, is more complicated than it needs to be: don't subclass JSONEncoder/JSONDecoder; just pass function references to object_hook and default at time of serialisation. Also, parse_datetime_or_default has been written to be too generic. Think: it attempts to convert any value in JSON to a datetime, regardless of whether that's appropriate. You have a fixed dictionary format; adhere to it.
self.created_on.__name__ is not necessary. You know the key name, so just... write it as a string.
Write unit tests.
check is a deceptive name. It doesn't check anything; it creates the file.
Don't lru_cache; just cache.
Suggested
import json
from functools import cache
from datetime import datetime, date, timedelta
from pathlib import Path
from tempfile import NamedTemporaryFile
from time import sleep
from typing import Any
def json_default(o: Any) -> Any:
if isinstance(o, (date, datetime)):
return o.isoformat()
def json_object_hook(d: dict[str, Any]) -> dict[str, Any]:
return {
**d,
'created_on': datetime.fromisoformat(d['created_on']),
}
class Tick:
def __init__(self, file_name: Path, lifetime: timedelta) -> None:
self.file_name = file_name
self.lifetime = lifetime | {
"domain": "codereview.stackexchange",
"id": 43828,
"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, datetime, json",
"url": null
} |
python, python-3.x, datetime, json
def create(self) -> None:
self.file_name.parent.mkdir(parents=True, exist_ok=True)
data = {'created_on': datetime.now()}
with self.file_name.open('w') as f:
json.dump(data, f, default=json_default)
self.get_created_on.cache_clear()
@property
def is_created(self) -> bool:
return self.file_name.is_file()
@cache # avoid reading the file more than once until updated
def get_created_on(self) -> datetime:
with self.file_name.open() as f:
return json.load(f, object_hook=json_object_hook)['created_on']
@property
def elapsed(self) -> timedelta:
return datetime.now() - self.get_created_on()
@property
def is_valid(self) -> bool:
return self.is_created and self.elapsed < self.lifetime
@property
def is_expired(self) -> bool:
return not self.is_valid
def test() -> None:
lifetime = timedelta(seconds=1)
tick = Tick(Path('noexist'), lifetime)
assert not tick.is_created
assert not tick.is_valid
assert tick.is_expired
with NamedTemporaryFile(suffix='_token_test.json') as temp:
tick = Tick(Path(temp.name), lifetime)
assert tick.is_created
tick.create()
assert tick.is_created
assert tick.is_valid
assert not tick.is_expired
sleep(1.5)
assert tick.is_created
assert not tick.is_valid
assert tick.is_expired
if __name__ == '__main__':
test() | {
"domain": "codereview.stackexchange",
"id": 43828,
"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, datetime, json",
"url": null
} |
programming-challenge, time-limit-exceeded, swift, trie, backtracking
Title: Leet Code 139 (Word Break) using a trie with recursion
Question: I was attempting to solve LeetCode 139 - Word Break
Given a string s and a dictionary of strings wordDict, return
true if s can be segmented into a space-separated sequence of one
or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false
Constraints:
1 <= s.length <= 300
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 20
s and wordDict[i] consist of only lowercase English letters.
All the strings of wordDict are unique.
I watched some videos saying implementing a trie would be an efficient approach to solve this so I implemented a Trie as follows:
fileprivate class TrieNode {
var data: Character?
var isWordEnd = false
var next = [Character: TrieNode]()
} | {
"domain": "codereview.stackexchange",
"id": 43829,
"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, time-limit-exceeded, swift, trie, backtracking",
"url": null
} |
programming-challenge, time-limit-exceeded, swift, trie, backtracking
fileprivate struct Trie {
var root = TrieNode()
func insert(_ word: String) {
var rootNode = root
for char in word {
rootNode = insertInternal(char, at: rootNode)
}
rootNode.isWordEnd = true
}
func insertInternal(_ char: Character, at node: TrieNode) -> TrieNode {
var nextNode = TrieNode()
if node.next[char] != nil {
nextNode = node.next[char]!
}
nextNode.data = char
node.next[char] = nextNode
return nextNode
}
func doesWordExist(_ word: String) -> Bool {
var rootNode = root
for char in word {
let nextNode = rootNode.next
if nextNode[char] == nil {
return false
}
rootNode = nextNode[char]!
}
return rootNode.isWordEnd
}
}
Then in order to solve the problem, I took the recursion / backtracking approach with the help of the Trie created above in the following way:
func wordBreak(_ s: String, _ wordDict: [String]) -> Bool {
let trie = Trie()
for word in wordDict {
trie.insert(word)
}
return wordBreakInternal(s, wordDict: trie)
}
fileprivate func wordBreakInternal(_ s: String, wordDict: Trie) -> Bool {
if s.isEmpty { return true }
let leftIndex = s.startIndex
var rightIndex = s.startIndex
while rightIndex < s.endIndex {
let word = String(s[leftIndex ... rightIndex])
if wordDict.doesWordExist(word) {
var nextStartIndex = rightIndex
s.formIndex(after: &nextStartIndex)
let nextWord = String(s[nextStartIndex ..< s.endIndex])
if wordBreakInternal(nextWord, wordDict: wordDict) {
return true
}
}
s.formIndex(after: &rightIndex)
}
return false
} | {
"domain": "codereview.stackexchange",
"id": 43829,
"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, time-limit-exceeded, swift, trie, backtracking",
"url": null
} |
programming-challenge, time-limit-exceeded, swift, trie, backtracking
I feel the solution works in terms of giving the desired output for these test cases:
print(wordBreak("leetcode", ["leet","code"])) // true
print(wordBreak("applepenapple", ["apple","pen"])) // true
print(wordBreak("catsandog", ["cats","dog","sand","and","cat"])) // false
print(wordBreak("aaaaaaa", ["aaaa","aaa"])) // true
However, when a large string is the input:
s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab"
wordDict = ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]
I get Time Limit Exceeded in my LeetCode submission.
Could someone advice if the optimization needs to be done in my trie implementation or in my backtracking / recursion with some ideas on how to make things more efficient ?
Answer: Summary: Your code is written clearly, and works correctly as far as I can see. It can be improved at a few points, and string slices can be used for a small performance improvement. In order to make it work with really large strings within the given time constraint, additional techniques like memoization must be used.
Simplify and improve the code
The var data: Character? of class TrieNode is assigned, but never used. It can be removed.
In func insertInternal() a
var nextNode = TrieNode()
is created but not used if node.next[char] already exists. Also the forced unwrapping can be avoided:
func insertInternal(_ char: Character, at node: TrieNode) -> TrieNode {
if let nextNode = node.next[char] {
return nextNode
} else {
let nextNode = TrieNode()
node.next[char] = nextNode
return nextNode
}
}
In func doesWordExist the variable name of
let nextNode = rootNode.next | {
"domain": "codereview.stackexchange",
"id": 43829,
"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, time-limit-exceeded, swift, trie, backtracking",
"url": null
} |
programming-challenge, time-limit-exceeded, swift, trie, backtracking
In func doesWordExist the variable name of
let nextNode = rootNode.next
is misleading: it is not a node but a dictionary. Again the forced unwrapping (and the comparison against nil) can be avoided:
func doesWordExist(_ word: Substring) -> Bool {
var rootNode = root
for char in word {
if let nextNode = rootNode.next[char] {
rootNode = nextNode
} else {
return false
}
}
return rootNode.isWordEnd
}
Use Substring
It is more efficient to pass Substrings to the recursively called wordBreakInternal() functions instead of Strings. Substring is a “string slice” and shares the storage with the original string. The helper function is then declared as
func wordBreakInternal(_ s: Substring, wordDict: Trie) -> Bool
and called as
return wordBreakInternal(s[...], wordDict: trie) | {
"domain": "codereview.stackexchange",
"id": 43829,
"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, time-limit-exceeded, swift, trie, backtracking",
"url": null
} |
programming-challenge, time-limit-exceeded, swift, trie, backtracking
and called as
return wordBreakInternal(s[...], wordDict: trie)
This makes the function a bit faster, but not fast enough to solve the programming challenge within the time limit.
Memoization
The function is too slow for long strings because of the heavy recursion. One approach to reduce the amount of recursive calls is memoization: For each substring which has been determined to be word-breakable or not, remember the result:
func wordBreak(_ s: String, _ wordDict: [String]) -> Bool {
let trie = Trie()
var memo = [Substring: Bool]()
for word in wordDict {
trie.insert(word)
}
func wordBreakInternal(_ s: Substring) -> Bool {
if let memoized = memo[s] {
return memoized
}
if s.isEmpty { return true }
let leftIndex = s.startIndex
var rightIndex = s.startIndex
while rightIndex < s.endIndex {
let word = (s[leftIndex ... rightIndex])
if trie.doesWordExist(word) {
var nextStartIndex = rightIndex
s.formIndex(after: &nextStartIndex)
let nextWord = (s[nextStartIndex ..< s.endIndex])
if wordBreakInternal(nextWord) {
memo[s] = true
return true
}
}
s.formIndex(after: &rightIndex)
}
memo[s] = false
return false
}
return wordBreakInternal(s[...])
}
I have also made the helper function a nested function in the main function, so that the memoization dictionary (and the trie) need not be passed around as function parameters.
This function computes
let s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" | {
"domain": "codereview.stackexchange",
"id": 43829,
"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, time-limit-exceeded, swift, trie, backtracking",
"url": null
} |
programming-challenge, time-limit-exceeded, swift, trie, backtracking
let wordDict = ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]
let result = wordBreak(s, wordDict)
in about 7 milliseconds (compiled in Release mode, running on a Macbook Air M2).
To trie or not to trie
You have used a Trie in order to determine quickly if the strings starts with one of the given words. As it turns out, using the built-in hasPrefix() method does this even better. Using string slices and memoization as before we get
func wordBreak(_ s: String, _ wordDict: [String]) -> Bool {
var memo = [Substring: Bool]()
func wordBreakInternal(_ s: Substring) -> Bool {
if let memoized = memo[s] {
return memoized
}
if s.isEmpty {
return true
}
for word in wordDict {
if s.hasPrefix(word) {
if wordBreakInternal(s.dropFirst(word.count)) {
memo[s] = true
return true
}
}
}
memo[s] = false
return false
}
return wordBreakInternal(s[...])
}
which computes the above test case in less than a millisecond. | {
"domain": "codereview.stackexchange",
"id": 43829,
"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, time-limit-exceeded, swift, trie, backtracking",
"url": null
} |
beginner, c, formatting, io
Title: K&R Exercise 4-6. Add commands for handling variables
Question: For the following exercise (Chapter 4, Ex-4.6) of the Book (K&R 2nd Edition):
Exercise 4-6. Add commands for handling variables. (It's easy to
provide twenty-six variables with single-letter names.) Add a variable
for the most recently printed value.
I have written this solution. I'd like to know how to "improve" or at least if what I have done could be considered "decent" in some way and can be improved. (The program is not only based on the solution of Exercise 4.6 but from exercises 4.3 to 4.6, which I modified and added as I completed the exercises.)
main.c
#include <stdio.h>
#include <stdlib.h> /* for atof() */
#include <math.h>
#include "calc.h"
#define MAXOP 100 /* max size of operand or operator */
#define MAXVAL 26
/* reverse Polish calculator */
int
main(void)
{
int type;
double op2;
char s[MAXOP];
double variable[MAXVAL] = {0.0}; | {
"domain": "codereview.stackexchange",
"id": 43830,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, formatting, io",
"url": null
} |
beginner, c, formatting, io
while ((type = getop(s)) != EOF) {
switch (type) {
case NUMBER:
push(atof(s));
break;
/**
* In exercise 4-5 of the book. I had to add "access" to library functions
* like sin, exp, pow, etc...
*
* For this I decided to implement a function called math_f_handling, to
* handle it. (see the file "math_f_handling.c", for a more detailed
* description of the following functions:)
*
* - math_f_handling()
* - match_math_libs()
*/
case ID:
math_f_handling(s);
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
if (op2 != 0.0)
push(pop() / op2);
else
printf("error: zero divisor\n");
break;
/**
* As specified in Exercise 4-3. of the book, I extended the calculator
* by adding the modulus (%) operator and provisions for negative numbers.
*/
case '%':
op2 = pop();
if (op2 != 0.0)
push(fmod(pop(), op2));
else
printf("error: zero divisor\n");
break;
/**
* In exercise 4-4 of the book. I was supposed to add commands to print the
* top element of the stack, duplicate it, swap the two top elements, and a
* command to clear the stack. (the implementations of the following functi-
* ons are in the file "stack.c")
*
* -peek()
* -duptop()
* -swap()
* -clear()
*/
case '?':
peek();
break;
case '#':
duptop();
break; | {
"domain": "codereview.stackexchange",
"id": 43830,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, formatting, io",
"url": null
} |
beginner, c, formatting, io
peek();
break;
case '#':
duptop();
break;
case '~':
swap();
break;
case 'C':
clear();
break;
case '\n':
printf("\t%.8g\n", pop());
break;
default:
/**
* And here is what I've added to handle the variables, as specified
* above (Exercise 4-6).
*/
if ((type >= 'A' && type <= 'Z') || type == '=') {
if (type != '=') {
push(variable[type - 'A']);
}
} else
printf("error: unknown command %s\n", s);
break;
}
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 43830,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, formatting, io",
"url": null
} |
beginner, c, formatting, io
calc.h
#ifndef CALC_H_HEADER
#define CALC_H_HEADER
#define NUMBER '0' /* signal that a number was found */
#define ID 'I' /* identifier */
extern int sp;
extern char buf[];
void push(double);
double pop(void);
void peek(void);
void duptop(void);
void swap(void);
void clear(void);
int getop(char []);
int getch(void);
void ungetch(int);
void math_f_handling(char []);
int match_math_libs(char []);
#endif /* CALC_H_HEADER */
getch.c
#include <stdio.h>
#define BUFSIZE 100
static char buf[BUFSIZE]; /* buffer for ungetch */
static int bufp = 0; /* next free position in buf */
/* getch: get a (possibly pushed back) character */
int
getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
/* ungetch: push character back on input */
void
ungetch(int c)
{
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
getop.c
#include <stdio.h>
#include <ctype.h>
#include "calc.h"
/* getop: get next operator or numeric operand */
int
getop(char s[])
{
int i, c;
while ((s[0] = c = getch()) == ' ' || c == '\t')
;
s[1] = '\0';
if (isalpha(c)) {
i = 0;
while (isalpha(s[++i] = c = getch()))
;
s[i] = '\0';
if (c != EOF)
ungetch(c);
return ID;
}
if (!isdigit(c) && c != '.')
return c; /* not a number */
i = 0;
if (isdigit(c)) /* collect integer part */
while (isdigit(s[++i] = c = getch()))
;
if (c == '.') /* collect fraction part */
while (isdigit(s[++i] = c = getch()))
;
s[i] = '\0';
if (c != EOF)
ungetch(c);
return NUMBER;
}
stack.c
#include <stdio.h>
#include "calc.h"
#define MAXVAL 100 /* maximun depth of val stack */
int sp = 0; /* next free stack position */
double val[MAXVAL]; /* value stack */ | {
"domain": "codereview.stackexchange",
"id": 43830,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, formatting, io",
"url": null
} |
beginner, c, formatting, io
int sp = 0; /* next free stack position */
double val[MAXVAL]; /* value stack */
/* push: push f onto value stack */
void
push(double f)
{
if (sp < MAXVAL)
val[sp++] = f;
else
printf("error: stack full, can't push %g\n", f);
}
/* pop: pop and return top value from stack */
double
pop(void)
{
if (sp > 0)
return val[--sp];
else {
printf("error: stack empty\n");
return 0.0;
}
}
/* peek: print the top element of the stack */
void
peek(void)
{
if (sp > 0)
printf("\t%.8g\n", val[sp - 1]);
}
/* duptop: duplicate top element of the stack */
void
duptop(void)
{
double item = pop();
push(item);
push(item);
}
/* swap: swap the two top elements */
void
swap(void)
{
double item1 = pop();
double item2 = pop();
push(item1);
push(item2);
}
/* clear: clear the stack */
void
clear(void)
{
sp = 0;
}
math_f_handling.c
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "calc.h"
#define DEF_LEN 8 /* default length */
/**
* I did not add all the functions found in the book
* (Appendix B, Section 4).
*
* Note: In the math_f_handling function, I had to comment out the line
* that is inside the default statement, because when the user tries to
* enter input like the following:
*
* 15 A = 20 B = A B +
*
* The user may receive this result:
*
* A is not a supported function.
* B is not a supported function.
* A is not a supported function.
* B is not a supported function.
* 35
*/
static const char *math_libs[] =
{
"sin", "cos",
"tan", "pow",
"exp", "sqrt",
"floor", "ceil"
}; | {
"domain": "codereview.stackexchange",
"id": 43830,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, formatting, io",
"url": null
} |
beginner, c, formatting, io
void
math_f_handling(char s[])
{
double op2;
int n = match_math_libs(s);
switch (n) {
case 1:
push(sin(pop()));
break;
case 2:
push(cos(pop()));
break;
case 3:
push(tan(pop()));
break;
case 4:
op2 = pop();
push(pow(pop(), op2));
break;
case 5:
push(exp(pop()));
break;
case 6:
push(sqrt(pop()));
break;
case 7:
push(floor(pop()));
break;
case 8:
push(ceil(pop()));
break;
default:
// printf("%s is not a supported function.\n", s);
break;
}
}
int
match_math_libs(char s[])
{
int loc, found;
found = -1;
for (loc = 0; loc < DEF_LEN; loc++) {
if (strcmp(s, math_libs[loc]) == 0) {
found = loc + 1;
return found;
}
}
return found;
}
I included my Makefile, just in case.
CC=gcc
CFLAGS=-Wall -g
LDFLAGS=
SRC=src
OBJ=obj
HDR=hdr
SRCS=$(wildcard $(SRC)/*.c)
OBJS=$(patsubst $(SRC)/%.c, $(OBJ)/%.o, $(SRCS))
HDRS=$(wildcard $(SRC)/*.h)
BINDER=bin
BIN=$(BINDER)/main
SUBMITNAME=project4-6.zip
all: $(BIN)
release: CFLAGS=-Wall -O2 -DNDEBUG
release: clean
release: $(BIN)
$(BIN): $(OBJ) $(OBJS) $(BINDER)
# $(CC) $(CFLAGS) $(OBJS) -o $@ -lreadline
$(CC) $(CFLAGS) $(OBJS) -o $@ -lm
$(OBJ)/%.o: $(SRC)/%.c
$(CC) $(CFLAGS) -c $< -o $@
$(OBJ):
mkdir -p $@
$(BINDER):
mkdir -p $@
clean:
$(RM) -r $(BINDER)/* $(OBJ)/*
$(RM) -r $(OBJ)
$(RM) -r $(BINDER)
$(RM) *.i
$(RM) *.zip
$(RM) *.s
$(RM) *.bc
$(RM) *.txt
$(RM) *.out
submit:
$(RM) $(SUBMITNAME)
zip $(SUBMITNAME) $(BIN)
these are a few of the tests that I did with the program that I've written.
1 2 - 4 5 + *
-9
15 A = 20 B = A B +
35
15 A = 20 B = A B + ?
35
35
15 A = 20 B = A B %
15
3 4 ? ~
4
3
5 2 sin
0.90929743
4 3 cos
-0.9899925
2 2 pow
4 | {
"domain": "codereview.stackexchange",
"id": 43830,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, formatting, io",
"url": null
} |
beginner, c, formatting, io
3 4 ? ~
4
3
5 2 sin
0.90929743
4 3 cos
-0.9899925
2 2 pow
4
Answer: Mod or remainder?
"by adding the modulus (%) operator" --> C does not have a mod operator. % is the remainder, as is fmod(). What's the difference between “mod” and “remainder”?.
Why range test?
type >= 'A' && type <= 'Z' is not as portable as isupper(type). C does not require consecutive letters. Example.
Namespace
calc.h declares functions all over the namespace. Consider a more localized naming conventions like calc_peek, calc_pop, .... This will reduced collisions with other code.
char vs. unsigned char
static char buf[BUFSIZE]; better as static unsigned char buf[BUFSIZE]; to avoid implementation defined behavior, UB on is...() functions and cope with rare non-2's complement encoding.
How much precision?
Code uses 8, yet more is needed to well distinguish doubles.
// printf("\t%.8g\n", val[sp - 1]);
printf("\t%.*g\n", DBL_DECIMAL_DIG, val[sp - 1]);
// or fold some nearby value together
printf("\t%.*g\n", DBL_DIG, val[sp - 1]);
Why only ' ', '\t'
c = getch()) == ' ' || c == '\t' compares only against 2 possible white-spaces. More common to use isspace(c).
Error messages
Consider printing errors on stderr.
// printf("ungetch: too many characters\n");
fprintf(stderr, "ungetch: too many characters\n");
Signed values
I'd expect getop() to accept input with a '-' or '+ sign.
Stack empty?
At the end of processing, the stack should be empty. I'd expect a test for that.
Max operand
As double ranges typically from 1.0e+/-300 or more and code does not support exponential input, to allow input of all double, use at least DBL_MAX_10_EXP, -DBL_MIN_10_EXP. To allow extended precision, leading zeros, spaces, etc., consider 2x DBL_MAX_10_EXP for the max operand size. | {
"domain": "codereview.stackexchange",
"id": 43830,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, formatting, io",
"url": null
} |
javascript
Title: Card generator with some calculations
Question: Basically, I am creating a random math generator.
the first line has a random number from 1 to 99
also, the second line has a random number from 1 to 99
and we also generate a random operator (*, +, -),
and the last line bold is the result of the calculation.
on click, we call a function that generates a div with all the logic,
and we used <template> to do something like react but with HTML only.
I see that there is some repetitive things, but not know how to improve, it will be helpful if you help!
class Card {
#CONTAINER = document.querySelector("#container");
#TEMPLATE = document
.querySelector("template#card")
.content.querySelector("div")
.cloneNode(true);
constructor() {
this.container = this.#CONTAINER;
this.template = this.#TEMPLATE;
this.container.appendChild(this.template);
}
get element() {
return this.template;
}
}
document.querySelector("#btn").addEventListener("click", () => {
generateCard();
});
for (let i = 0; i < 5; i++) {
generateCard()
}
function generateCard() {
let card = new Card().element;
let cardOutputs = {
first: card.querySelector(".first-number"),
second: card.querySelector(".second-number"),
result: card.querySelector(".result-number"),
};
let arrRandom = [];
let operationsArray = ["+", "-", "*"];
let randomOperation =
operationsArray[Math.round(Math.random() * (operationsArray.length - 1))];
Object.values(cardOutputs).forEach((output, index) => {
if (cardOutputs.result !== output) {
arrRandom.push(Math.round(Math.random() * 100));
output.textContent = addZeroPrefix(arrRandom[index]);
} else {
if (randomOperation === "+") {
addiction();
}
if (randomOperation === "-") {
if (arrRandom[0] > arrRandom[1]) {
subtraction();
} else {
addiction();
}
} | {
"domain": "codereview.stackexchange",
"id": 43831,
"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",
"url": null
} |
javascript
if (randomOperation === "*") {
multiplication();
}
card.scrollIntoView({
behavior: "smooth",
});
function addiction() {
card.querySelector(".operator").textContent = "+";
output.textContent = addZeroPrefix(arrRandom.reduce((a, b) => a + b));
}
function subtraction() {
card.querySelector(".operator").textContent = "-";
output.textContent = addZeroPrefix(arrRandom.reduce((a, b) => a - b));
}
function multiplication() {
card.querySelector(".operator").textContent = "*";
output.textContent = addZeroPrefix(arrRandom.reduce((a, b) => a * b));
}
}
});
function addZeroPrefix(num) {
if (num < 10) {
return `0${num}`;
}
return num;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-blue-200 h-screen grid grid-rows-[1fr_auto]">
<div id="container" class="container mx-auto py-10 px-4 flex flex-wrap justify-center gap-4 grid-cols-3 overflow-auto"></div>
<div class="grid place-items-center w-full px-4">
<button id="btn" class="py-4 w-full max-w-screen-md shadow-sm text-2xl bg-white hover:scale-95 hover:shadow-2xl transition rounded-lg mb-4">generate</button>
</div>
<template id="card">
<div class="h-min p-6 rounded-xl bg-white hover:-translate-y-2 hover:shadow-lg hover: shadow hover:rotate-2 hover:scale-105 transition text-2xl">
<div>
<div class="flex gap-4">
<div class="first-number flex-grow">errpr</div>
<div class="operator">error</div>
</div>
<div class="flex gap-4 border-b-2">
<div class="second-number flex-grow">error</div>
<div>=</div>
</div> | {
"domain": "codereview.stackexchange",
"id": 43831,
"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",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.