text stringlengths 1 2.12k | source dict |
|---|---|
c++, c++17, template-meta-programming
template <typename T>
struct lref_iff_lref<T&&> {using type = remove_reference_t<T>;};
/**
* ElementsView<I, TC>
*
* View over Ith elements of each tuple contained by container TC.
*
* C++17. Only operator[] and size() supported. Kind of like
* std::ranges::elements_view (C++20), but works with custom "zip"
* pseudo-container (not shown) as std::ranges::zip_view not available
* until C++23. */
template <size_t I, typename TC>
class ElementsView {
static constexpr size_t index = I;
public:
using value_type = fwd_cont_val_t<I, TC>;
explicit ElementsView(TC c) : data_{c} {}
value_type& operator[](size_t pos) { return std::get<index>(data_[pos]);}
value_type& operator[](size_t pos) const { return std::get<index>(data_[pos]);}
auto size() const { return data_.size();}
private:
lref_iff_lref_t<TC> data_;
};
template<size_t I, class U>
auto elements(U&& u) { return ElementsView<I, decltype(u)>{std::forward<U>(u)};}
} // namespace animal::util::eview
namespace animal::util { using eview::elements; }
// eview-tests.hpp
#include "catch2/catch_test_macros.hpp"
#include <array>
namespace util = animal::util;
TEST_CASE("basic util::elements") {
std::array<std::pair<int, char>, 3> ap{{{1, 'a'}, {2, 'b'}, {3, 'c'}}};
auto ev1 = util::elements<1>(ap);
ev1[1] = 'z';
auto ev0 = util::elements<0>(ap);
ev0[1] = 42;
const auto& cap = ap;
REQUIRE(cap[1].first == 42);
REQUIRE(cap[1].second == 'z');
auto cev0 = util::elements<0>(cap);
// TD<decltype(cev0)::value_type> mistery;
// ev3[2] = 26; // ERROR, GOOD: cap is const, so ev3 has const value_type
auto cev1 = util::elements<1>(cap);
REQUIRE(cev0[1] == 42);
REQUIRE(cev1[1] == 'z');
}
TEST_CASE("more util::elements") {
using TOP = std::tuple<std::pair<int, std::pair<int, int>>, char, std::string>;
std::vector<TOP> vtop { {{1, {11, 111}}, 'A', "a"}, {{2, {22, 222}}, 'B', "b"} }; | {
"domain": "codereview.stackexchange",
"id": 43364,
"lm_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++17, template-meta-programming",
"url": null
} |
c++, c++17, template-meta-programming
auto ev0 = util::elements<0>(vtop);
REQUIRE(ev0[1].first == 2);
util::elements<0>(vtop)[1].first = 3;
REQUIRE(util::elements<0>(vtop)[1].first == 3);
REQUIRE(std::get<0>(vtop[1]).first == 3);
auto composed{util::elements<0>(util::elements<0>(vtop))};
REQUIRE(composed[1] == 3);
composed[1] = 4;
REQUIRE(util::elements<0>(vtop)[1].first == 4);
REQUIRE(std::get<0>(vtop[1]).first == 4);
const auto& cvtop = vtop;
auto intermediate = util::elements<0>(cvtop);
auto composed2{util::elements<0>(util::elements<0>(cvtop))};
REQUIRE(composed2[1] == 4);
// composed2[1] = 777; // ERROR, GOOD: source owning container is const
auto composed3{util::elements<1>(util::elements<1>(util::elements<0>(cvtop)))};
REQUIRE(composed3[1] == 222);
// composed3[1] = 777;
}
Answer: Missing iterators
As it is now, I would say it is cute, but not very useful. In most of your test code, you can see that using std::get<>() requires less typing than using util::elements<>(). However, your class would really shine if it implemented iterators, such that you can do:
for (auto& e0: util::elements<0>(vtop)) {
std::cout << e0.first << '\n';
}
But also so that you can use many of the STL algorithms on your view.
There is no need for the helper templates
You can make your code deduce the right type for data_ without needing lref_iff_lref_t. In:
template<size_t I, class U>
auto elements(U&& u) {
return ElementsView<I, decltype(u)>{std::forward<U>(u)};
}
If u is an lvalue-reference, U is deduced as U&. However, if u is an rvalue-reference, U is deduced as U. However, decltype(u) will deduce the rvalue-reference that you don't want. The solution is to simply remove the decltype() here:
return ElementsView<I, U>{std::forward<U>(u)}; | {
"domain": "codereview.stackexchange",
"id": 43364,
"lm_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++17, template-meta-programming",
"url": null
} |
c++, c++17, template-meta-programming
There will be some compile errors then due to the fwd_* templates deducing the wrong thing. However, a much simpler solution is to let the compiler deduce the type for you from the std::get<>() expression you are using:
using value_type = decltype(std::get<index>(data_[0]));
However, both your original value_type and the one using decltype() have an issue:
What about const views?
There is a problem when making a const view.The const-qualified operator[] will still return a mutable reference to data_, if the latter is an lvalue reference to a non-const container. Slapping a const in front of it doesn't work though, because that will make it a const reference instead of a reference to const data. You have to remove the reference from value_type first, then add the const & back to it:
const std::remove_reference_t<value_type>& operator[](size_t pos) const {
return std::get<index>(data_[pos]);
}
Or better, don't let value_type lie, and make sure it is a value type and not a reference to begin with:
using value_type = std::remove_reference_t<...>;
Note that you could also have avoided the issue by using auto return type deduction:
const auto& operator[](size_t pos) const {
return std::get<index>(data_[pos]);
} | {
"domain": "codereview.stackexchange",
"id": 43364,
"lm_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++17, template-meta-programming",
"url": null
} |
python, php, image, laravel
Title: PHP / Laravel - Using Python to image manipulation
Question: I have a simple job class in Laravel, that will do the following:
Get all the images in a folder /original
Perform some image manipulation on each image
Save each image in a new folder /preprocessed
All of these steps are added to a queue.
However, I have taken an alternative approach and it is using python to do the actual image manipulation.
This is my code:
$images = Storage::allFiles($this->document->path('original'));
foreach ($images as $key => $image) {
$file = storage_path() . '/app/' . $image; //token/unique_id/original/1.jpg
$savePath = storage_path() . '/app/' . $this->document->path('preprocessed');
$filename = $key . '.jpg';
//Scale and save the image in "/preprocessed"
$process = new Process("python3 /Python/ScaleImage.py {$file} {$savePath} {$filename}");
$process->run();
// executes after the command finishes
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
return false;
}
}
In my python file ScaleImage.py, it simply performs some image manipulation and saves the image to the /preprocessed folder.
def set_image_dpi(file)
//Image manipulation - removed from example
//save image in /preprocessed
im.save(SAVE_PATH + FILE_NAME, dpi=(300, 300))
return SAVE_PATH + FILE_NAME
print(set_image_dpi(FILE_PATH))
The above code works.
In the future, I might need to do even more image manipulation such as noise removal, skew correction, etc.
My final goal is to use Tesseract OCR on the preprocessed image to grab the text content of the image.
Now I am sure I could achieve similar results, for example using ImageMagick in PHP.
However, I've read that for image processing and OCR, Python's performance is a lot better.
Is the above approach a good idea? Is there anything that can be improved?
Answer:
Anything that can be improved? | {
"domain": "codereview.stackexchange",
"id": 43365,
"lm_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, php, image, laravel",
"url": null
} |
python, php, image, laravel
Answer:
Anything that can be improved?
This line uses interpolation with complex (curly) syntax:
$process = new Process("python3 /Python/ScaleImage.py {$file} {$savePath} {$filename}");
The simple syntax can be used - i.e. curly braces can be removed
$process = new Process("python3 /Python/ScaleImage.py $file $savePath $filename");
Though there is an argument to maintain the habit of including curly braces for the times when it is required and also for clarity.
Now I am sure I could achieve similar stuff with for example ImageMagick in PHP.
Yes the PHP Image Processing and GD library has functions like imageresolution() to set the resolution of an image. It can be used with functions like imagecreatefromjpeg() to create the image object and imagejpeq() to output the image to a file. And yes there is an ImageMagick function Imagick::setImageResolution() which could be used instead. | {
"domain": "codereview.stackexchange",
"id": 43365,
"lm_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, php, image, laravel",
"url": null
} |
c++, beginner, object-oriented, game, playing-cards
Title: Blackjack game in C++
Question: I developed a blackjack game. I am relatively new to c++ and OOP, so I am asking for feedback on what could be improved. This game features betting, taking a card, standing, and splitting a hand. Besides, it also has a dealer that takes when his hand is under 17 and stands when it is over.
#include <bits/stdc++.h>
using namespace std;
class Card {
private:
int cardNum;
int cardType;
int value;
string name;
public:
Card(int ct, int cn);
~Card() {}
int getType() {return cardType;}
int getNum() {return cardNum;}
int getVal() {return value;}
string getName() {return name;}
};
Card::Card(int ct, int cn) : cardNum(cn), cardType(ct) {
if(cardNum == 1) {
value = 11;
} else if(cardNum >= 10) {
value = 10;
} else value = cardNum;
switch(cardNum) {
case 1 :
name = "ace";
break;
case 11 :
name = "jack";
break;
case 12 :
name = "queen";
break;
case 13 :
name = "king";
break;
default:
name = to_string(cardNum);
break;
}
switch(cardType) {
case 1 :
name.append(" of clubs");
break;
case 2 :
name.append(" of diamonds");
break;
case 3 :
name.append(" of hearts");
break;
case 4 :
name.append(" of spades");
break;
}
}
class Deck {
private:
const int deckSize = 52;
vector<Card*> deck;
int pos;
public:
Deck();
~Deck();
void shuffle(); //{random_shuffle(deck.begin(), deck.end());}
Card* getCard();
}; | {
"domain": "codereview.stackexchange",
"id": 43366,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, object-oriented, game, playing-cards",
"url": null
} |
c++, beginner, object-oriented, game, playing-cards
Deck::Deck() : pos(0) {
deck.reserve(deckSize);
for(int i = 1; i <= 4; i++) {
for(int j = 1; j <= 13; j++) {
deck.push_back(new Card(i, j));
}
}
}
Deck::~Deck() {
for(auto i : deck) {
delete i;
}
}
void Deck::shuffle() {
for(long long unsigned i = 0; i < deck.size(); i++) {
swap(deck[i], deck[rand()%deck.size()]);
}
}
Card* Deck::getCard() {
if(pos >= deckSize) {
shuffle();
pos = 0;
}
return deck[pos++];
}
class Hand {
private:
Deck* deck;
vector<Card*> cards;
int points;
unordered_set<Card*> aces;
public:
Hand(Deck* d) : deck(d), points(0) {}
~Hand() {}
void clearHand();
void addCard();
void addSpecificCard(Card* c);
int getPoints() {return points;}
Card* removeCard();
vector<Card*> getCards() {return cards;}
};
void Hand::clearHand() {
points = 0;
aces = unordered_set<Card*>();
cards = vector<Card*>();
}
void Hand::addCard() {
cards.push_back(deck->getCard());
if(cards.back()->getNum() == 1) aces.insert(cards.back());
points += cards.back()->getVal();
if(points > 21) {
while(!aces.empty() && points > 21) {
points -= 10;
aces.erase(aces.begin());
}
}
}
void Hand::addSpecificCard(Card* c) {
cards.push_back(c);
if(c->getNum() == 1) aces.insert(c);
points+=c->getVal();
}
Card* Hand::removeCard() {
Card* lastCard = cards.back();
points -= lastCard->getVal();
if(lastCard->getNum() == 1) aces.erase(lastCard);
cards.pop_back();
return lastCard;
} | {
"domain": "codereview.stackexchange",
"id": 43366,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, object-oriented, game, playing-cards",
"url": null
} |
c++, beginner, object-oriented, game, playing-cards
class Dealer{
private:
Hand* hand;
public:
Dealer(Deck* d) : hand(new Hand(d)) {}
~Dealer() {delete hand;}
void getNewHand() {hand->clearHand();}
void addCard() {return hand->addCard();}
string makeTurn();
int getScore() {return hand->getPoints();}
Hand* getHand() {return hand;}
};
string Dealer::makeTurn() {
if(hand->getPoints() < 17) {
hand->addCard();
return "hit";
}
return "stand";
}
class House {
private:
Deck* deck;
vector<Hand*> hands;
Dealer* dealer;
private:
float playNewGame();
public:
House() : deck(new Deck()), dealer(new Dealer(deck)) {}
~House() {delete deck; delete dealer;}
void playBlackJack();
};
float House::playNewGame() {
deck->shuffle();
Hand* curHand = new Hand(deck);
hands.push_back(curHand);
hands[0]->addCard();
hands[0]->addCard();
dealer->addCard();
cout << "DEALERS first card: ";
cout << dealer->getHand()->getCards().back()->getName() << endl;
dealer->addCard();
if(hands[0]->getPoints() == 21) {
if(dealer->getScore() == 21) {
cout << "YOU and the DEALER have TIED ";
for(auto i : hands[0]->getCards()) cout << i->getName() << "; ";
cout << endl;
for(auto i : hands) {
delete i;
}
hands.clear();
dealer->getNewHand();
return 1;
} else {
cout << "YOU have WON with hand: ";
for(auto i : hands[0]->getCards()) cout << i->getName() << "; ";
cout << endl;
for(auto i : hands) {
delete i;
}
hands.clear();
dealer->getNewHand();
return 1.5;
}
}
unordered_set<Hand*> validHands;
validHands.insert(curHand);
float multiplier = 0;
string answer = "placeholder"; | {
"domain": "codereview.stackexchange",
"id": 43366,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, object-oriented, game, playing-cards",
"url": null
} |
c++, beginner, object-oriented, game, playing-cards
validHands.insert(curHand);
float multiplier = 0;
string answer = "placeholder";
long long unsigned iter = 0;
while((answer != "no") && (iter < hands.size())) {
if((hands[iter]->getCards()[0]->getNum() != 1) &&
(hands[iter]->getCards()[1]->getNum() != 1) &&
(hands[iter]->getCards()[0]->getNum() == hands[iter]->getCards()[1]->getNum())) {
cout << "YOUR HAND: ";
for(auto i : hands[iter]->getCards()) cout << i->getName() << "; ";
cout << "SCORE = " << hands[0]->getPoints() << endl;
answer = "placeholder";
while(answer != "yes" && answer != "no") {
cout << "split? yes/no" << endl;
cin >> answer;
}
if(answer == "yes") {
Hand* newHand = new Hand(deck);
newHand->addSpecificCard(curHand->removeCard());
newHand->addCard();
curHand->addCard();
hands.push_back(newHand);
curHand = newHand;
validHands.insert(curHand);
}
}
iter++;
}
answer = "hit";
bool isUnder = false; | {
"domain": "codereview.stackexchange",
"id": 43366,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, object-oriented, game, playing-cards",
"url": null
} |
c++, beginner, object-oriented, game, playing-cards
answer = "hit";
bool isUnder = false;
while(answer == "hit" || answer != "stand") {
auto hand = validHands.cbegin();
while(hand != validHands.end()) {
cout << " YOUR HAND: ";
for(auto i : (*hand)->getCards()) cout << i->getName() << "; ";
cout << "with SCORE = " << (*hand)->getPoints() << endl;
cout << "hit? hit/stand" << endl;
cin >> answer;
if(answer == "hit") {
(*hand)->addCard();
if((*hand)->getPoints() > 21) {
cout << "YOU have LOST with hand: ";
for(auto i : (*hand)->getCards()) cout << i->getName() << "; ";
cout << "with SCORE = " << (*hand)->getPoints() << endl;
hands.erase(find(hands.begin(), hands.end(), *hand));
multiplier -= 2;
hand = validHands.erase(hand);
if(hand == validHands.end()) answer = "stand";
} else if((*hand)->getPoints() == 21) {
cout << "YOU have hand: ";
for(auto i : (*hand)->getCards()) cout << i->getName() << "; ";
cout << "with SCORE = " << (*hand)->getPoints() << endl;
hand = validHands.erase(hand);
isUnder = true;
if(hand == validHands.end()) answer = "stand";
}
} else hand++;
}
}
if(validHands.empty() && !isUnder) return multiplier;
answer = "hit";
while(answer != "stand")
answer = dealer->makeTurn(); | {
"domain": "codereview.stackexchange",
"id": 43366,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, object-oriented, game, playing-cards",
"url": null
} |
c++, beginner, object-oriented, game, playing-cards
answer = "hit";
while(answer != "stand")
answer = dealer->makeTurn();
if(dealer->getScore() > 21) {
cout << "DEALER has LOST with hand: ";
for(auto i : dealer->getHand()->getCards()) cout << i->getName() << "; ";
cout << "with SCORE: " << dealer->getScore() << endl;
for(auto i : hands) {
delete i;
}
multiplier += 2* hands.size();
hands.clear();
dealer->getNewHand();
return multiplier;
}
for(auto hand : hands) {
cout << "your hand with hand SCORE = " << hand->getPoints() << " has ";
if(dealer->getScore() == hand->getPoints()) {
cout << "TIED with dealers hand: ";
for(auto i : dealer->getHand()->getCards()) cout << i->getName() << "; ";
cout << "with SCORE: " << dealer->getScore() << endl;
} else {
if(hand->getPoints() > dealer->getScore()) {
cout << "WON";
multiplier += 2;
} else {
cout << "LOST";
multiplier -= 2;
}
cout << " against the dealers hand: ";
for(auto i : dealer->getHand()->getCards()) cout << i->getName() << "; ";
cout << "with SCORE: " << dealer->getScore() << endl;
}
}
for(auto i : hands) {
delete i;
}
hands.clear();
dealer->getNewHand();
return multiplier;
} | {
"domain": "codereview.stackexchange",
"id": 43366,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, object-oriented, game, playing-cards",
"url": null
} |
c++, beginner, object-oriented, game, playing-cards
void House::playBlackJack() {
float totalMoney = 1000;
cout << "your total money = " << totalMoney << endl;
string cashOut = "no";
while((totalMoney > 0) && (cashOut == "no" || cashOut != "yes")) {
int bet = INT_MAX;
while(bet > totalMoney) {
cout << "bet number?" << endl;
cin >> bet;
}
totalMoney += bet*playNewGame()/2;
cout << "your total money = " << totalMoney << endl;
if(totalMoney > 0) {
cout << "cash out? yes/no" << endl;
cin >> cashOut;
}
}
}
int main()
{
srand((time(0)));
House h;
h.playBlackJack();
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 43366,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, object-oriented, game, playing-cards",
"url": null
} |
c++, beginner, object-oriented, game, playing-cards
int main()
{
srand((time(0)));
House h;
h.playBlackJack();
return 0;
}
Answer: General Observations
Playing is fun. There one upgrade could be allowing the player to double down their bet. The program could use some error handling, when the program prompted me with "cash out? yes/no" I entered y for yes, and it took me into another hand, it should either report an error or accept y for yes. Some other interesting options might be to allow the player to play 2 hands against the dealer. The blackjack tables in Las Vegas allow 5 or 6 players at a time, you could allow for other players at the table.
Have a minimum bet, I bet zero once and it was allowed.
Real casinos very rarely have one deck blackjack games, the shoe used at most Las Vegas casinos contains 6 decks. This prevents card counting, which is one way to cheat at blackjack. The dealing machines use more decks than 6.
General Code Observations
The classes are broken up in good manner.
Code Observations
Avoid using namespace std;
If you are coding professionally you probably should get out of the habit of using the using namespace std; statement. The code will more clearly define where cout and other identifiers are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifiercout you may override within your own classes, and you may override the operator << in your own classes as well. This stack overflow question discusses this in more detail.
Include Files
I generally only see #include <bits/stdc++.h> on programming challenge sites, where they want to allow the users to use any standard template library include, professionals will only include what they need to include. I was able to get the program to compile with the following:
#include <iostream>
#include <string>
#include <vector>
#include <unordered_set> | {
"domain": "codereview.stackexchange",
"id": 43366,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, object-oriented, game, playing-cards",
"url": null
} |
c++, beginner, object-oriented, game, playing-cards
One of the reasons for including only what is necessary is that it allows others who have to maintain the code to know what they are dealing with. A second reason is that #include means exactly that it is including a file into the current file, the more that gets including, the longer the compile time is. To keep build times down only include what is necessary.
Code and File Organization
It seems that all of the code is currently in one file, while this works in C++, multiple classes in a single file doesn't work in some other object oriented languages. A better reason to break the code into multiple files, one header and one source for each class is that it is easier to maintain the code. Header files provide the interface and should rarely change, C++ source files may change often for bug fixes or for additional functionality. There is no reason to recompile the house class when you make changes in card.cpp, you just need to re-link. Having one class per header file and source file allows whoever needs to maintain the code to immediately find the code they need to update.
Complexity
The function House::playNewGame() is too complex (does too much). It is 158 lines of code, that is almost 3 screens. A general rule in programming is that no function should be larger than a single screen (usually about 55 lines of code). Anything larger than one screen is very difficult to maintain because you can't see what is going on in the rest of the function. It is also important to limit the scope of the variables. There are several logical blocks of code in playNewGame() that could become their own functions.
There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:
that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function. | {
"domain": "codereview.stackexchange",
"id": 43366,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, object-oriented, game, playing-cards",
"url": null
} |
c++, beginner, object-oriented, game, playing-cards
Due to the complexity of the function House::playNewGame() it is very hard to review, I may have missed some things.
Object Oriented Programming Principles
SOLID is 5 object oriented design principles. SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. This will help you design your objects and classes better.
The Single Responsibility Principle - A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class.
The Open–closed Principle - states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
The Liskov Substitution Principle - Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.
The Interface segregation principle - states that no client should be forced to depend on methods it does not use.
The Dependency Inversion Principle - is a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details. | {
"domain": "codereview.stackexchange",
"id": 43366,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, object-oriented, game, playing-cards",
"url": null
} |
c#, strings
Title: Split large strings into parts by last index of character and by max length
Question: This is my method to split strings into parts by last index of character and by max length, the rationale for this method is because I have to send, in a payload via POST, a list of strings that cannot have more than 40 characters each, suffice to say that I can't cut words in half otherwise it would be much easier.
public IEnumerable<string> SplitStringByLastIndexOfAndMaxLength(string stringToSplit, int splitMaxLength, char delimiter)
{
while (!string.IsNullOrEmpty(stringToSplit))
{
if (stringToSplit.Length <= splitMaxLength)
{
yield return stringToSplit;
break;
}
var splitIndex = stringToSplit.LastIndexOf(delimiter, splitMaxLength);
var removeSpace = 1;
if (splitIndex < 0)
{
// if a word is larger than splitMaxLength we still split it
splitIndex = splitMaxLength;
// taking care to not remove a non space character
removeSpace = 0;
}
var partialString = stringToSplit[..splitIndex];
stringToSplit = stringToSplit[(splitIndex + removeSpace)..];
yield return partialString;
}
}
Usage, example with 40 characters max and split by space:
var address = "...Are included in two of the substrings. " +
"If you want to exclude the characters, you can " +
"add the periods... ...Are included in of the substrings. " +
"If you want to exclude the period characters, you can " +
"add the period... Some more text";
var addresses = SplitStringByLastIndexOfAndMaxLength(address, 40, ' ');
foreach (var address in addresses)
{
Console.WriteLine(address + " -> " + address.Length);
} | {
"domain": "codereview.stackexchange",
"id": 43367,
"lm_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#, strings",
"url": null
} |
c#, strings
foreach (var address in addresses)
{
Console.WriteLine(address + " -> " + address.Length);
}
Output:
...Are included in two of the -> 29
substrings. If you want to exclude the -> 38
characters, you can add the periods... -> 38
...Are included in of the substrings. If -> 40
you want to exclude the period -> 30
characters, you can add the period... -> 37
Some more text -> 14
Can you think of improvements to be made?
(This could be made into an extension method but for the time being it's enough.) | {
"domain": "codereview.stackexchange",
"id": 43367,
"lm_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#, strings",
"url": null
} |
c#, strings
Answer: since your method is for requests payloads, you need to use memory-friendly approaches. I don't know how often the method would be called, and how much requests at average your application would handle in daily bases. In all cases, it would be a good decision to assume the worst case scenarios, so handling them from the start would prevent from future high memory allocations.
Also, I encourage you to use VS profiler or you could use BenchmarkDotNet in which would help give you a first-glance overview on your code diagnostic measurements. Use test samples to mimic the actual requests payloads, and also try to give at least three real test scenarios, (one with least , one with average, and one with high API consumptions) just to diagnose and measure the overall performance (with memory allocation) of this addition.
With this, you would know which approach would be better for your case.
This is much better in logic and memory handling. The only missing part is a handling for splitMaxLength where it might be <= 0 or >= stringToSplit.Length.
For readability part, SplitStringByLastIndexOfAndMaxLength I think if we use SplitByLastIndexOf it would be enough, since the method arguments would tell what type of input it's taking, and what it does returns. The only part is hidden, is the use of LastIndexOf.
I have modified your version to improve readability and code follow-up. and added some comments to explain the changes that I've made.
public static IEnumerable<string> SplitByLastIndexOf(string source, int blockSize, char delimiter)
{
if (string.IsNullOrWhiteSpace(source)) yield break; | {
"domain": "codereview.stackexchange",
"id": 43367,
"lm_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#, strings",
"url": null
} |
c#, strings
// in case of invalid block size.
if (blockSize <= 0 || blockSize >= source.Length)
{
blockSize = source.Length;
}
// reuse it rather than initializing it on each iteration
var removeSpace = 1;
// reuse it rather than initializing it on each iteration
var delimiterIndex = -1;
while (source.Length > blockSize)
{
delimiterIndex = source.LastIndexOf(delimiter, blockSize);
if(delimiterIndex == -1)
{
// if a word is larger than blockSize we still split it
delimiterIndex = blockSize;
// taking care to not remove a non space character
removeSpace = 0;
}
yield return source[..delimiterIndex];
source = source[(delimiterIndex + removeSpace)..];
// reset
delimiterIndex = -1;
removeSpace = 1;
}
// return any remaining text.
if (source.Length > 0)
{
yield return source;
}
} | {
"domain": "codereview.stackexchange",
"id": 43367,
"lm_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#, strings",
"url": null
} |
python, performance, datetime, pandas
Title: Generate date_range for string intervals like 09:00-10:00/11:00-14:00/15:00-18:00 and calculate the working minutes
Question: I'm a bit new in python and I'm trying to achieve what I can't with VBA, get things faster.
I have large datasets like this in the source(just a sample):
This is done also by python and it's a CSV file.
What my code has to do with this is:
Get the column "Planned" And "Department Planned".
Convert the schedules in "Planned" column to 30 min intervals between starting and ending. Some schedules can be weird like 09:37-15:42 (so they need to be handled, normalizing the intervals from 9:30 to 15:30)
With that list, calculate the minutes worked in another column refering to the original schedule, so in the example 09:37 will have an interval starting from 9:30 but there will be only 23 mins working there.
explode the columns from points 2 and 3 to rows repeating the column Department Planned and Location NAme.
Group by: Location Name, Date Time (from point 3), Department Planned. Adding the minutes worked. | {
"domain": "codereview.stackexchange",
"id": 43368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
This is the code:
#calcula_Presentes_Contratados
import pandas as pd
from itertools import groupby
from datetime import datetime, timedelta
def configuraDataFrame(df, horario, modo):
#drop unwanted columns and filter empty rows
df = df[df.columns.intersection([
'CentroPlanificacion',
'Fecha',
horario,
modo
])]
df = df[df[horario].notna()]
if df.empty:
return df
return df[df[horario].str.contains(":")]
def fechaYHora(horario, fecha, posicion):
#calculate time and date for each start and ending time if the ending time < starting time, add one day to the ending.
hora = datetime.strptime(horario.split('-')[posicion], '%H:%M')
fecha = datetime.strptime(fecha, '%Y-%m-%d')
if posicion == 1:
horaI = datetime.strptime(horario.split('-')[0], '%H:%M')
horaI = datetime(fecha.year, fecha.month, fecha.day, horaI.hour, 0)
if hora.minute >= 30:
hora = datetime(fecha.year, fecha.month, fecha.day, hora.hour, 30)
else:
hora = datetime(fecha.year, fecha.month, fecha.day, hora.hour, 0)
if posicion == 1 and hora < horaI: hora += timedelta(days=1)
return hora
def extraeRangos(horario, fecha, aplicaSeparador):
try:
#get all match schedules if there are any
partido = horario.split('/')
listahorarios = []
#loop through al the schedules and add the range with the split separator "Separa aquí"
for horarios in partido:
rangoactual = pd.date_range(start=fechaYHora(horarios, fecha, 0), end=fechaYHora(horarios, fecha, 1), freq="30min").strftime('%Y-%m-%d, %H:%M').to_list()
listahorarios += rangoactual
if aplicaSeparador: listahorarios.append('Separa aquí')
return listahorarios
except: | {
"domain": "codereview.stackexchange",
"id": 43368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
return listahorarios
except:
return
def calculaMinutosInicio(horaInicio, tramoInicial):
#function to calculate starting minutes
horaInicio = datetime.strptime(horaInicio,'%H:%M')
tramoFin = datetime.strptime(tramoInicial.split(", ")[1], '%H:%M') + timedelta(minutes=30)
if tramoFin < horaInicio: horaFin += timedelta(days=1)
return tramoFin - horaInicio
def calculaMinutosFin(horaFin, tramoFin):
#function to calculate ending minutes
horaFin = datetime.strptime(horaFin,'%H:%M')
if horaFin.minute == 0 or horaFin.minute == 30: return timedelta(seconds=0)
tramoFin = datetime.strptime(tramoFin.split(", ")[1], '%H:%M')
return horaFin - tramoFin
def generaListasPorPartido(lista_tramos):
lista_final = []
listaTemp = []
#loop through the list looking for "Separa aquí"
for tramo in lista_tramos:
#if found, all the items stored before in the list will go in a single list
if tramo == 'Separa aquí':
lista_final.append(listaTemp)
listaTemp = []
#store all items in between "Separa aquí"
else:
listaTemp.append(tramo)
#return a list of lists for each matching schedule
return lista_final
def generaListaTramos(lista_tramos, horario):
listatramos = []
#calculate starting minutes from starting time to starting interval
minutosInicio = int(calculaMinutosInicio(horario.split("-")[0], lista_tramos[0]).seconds / 60)
#calculate ending minutes from ending time to ending interval
minutosFin = int(calculaMinutosFin(horario.split("-")[1], lista_tramos[-1]).seconds / 60)
for tramo in lista_tramos:
#the first index will have the starting minutes
if lista_tramos.index(tramo) == 0:
listatramos.append(minutosInicio)
#the last index will have the ending minutes
elif tramo == lista_tramos[-1]:
listatramos.append(minutosFin) | {
"domain": "codereview.stackexchange",
"id": 43368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
elif tramo == lista_tramos[-1]:
listatramos.append(minutosFin)
#every interval in between will always have 30 minutes
else:
listatramos.append(30)
return listatramos
def calculaConexion(lista_tramos, horario):
#if the list is not empty
if len(lista_tramos) > 0:
listatramos = []
#gnerate a list for each match schedule
lista_tramos = generaListasPorPartido(lista_tramos)
horario: horario = horario.split("/")
#add the working minutes to each interval
for i in range(len(lista_tramos)):
listatramos.extend(generaListaTramos(lista_tramos[i], horario[i]))
return listatramos
def eliminaSeparadores(lista):
return list(filter(('Separa aquí').__ne__, lista))
def generaRangoHoras(df, campo, nuevo_campo):
#generate range of times column
df[nuevo_campo] = df.apply(lambda row: extraeRangos(row[campo], row['Fecha'], True), axis=1)
#generate working minutes column
df['Conexión_' + nuevo_campo] = df.apply(lambda row: calculaConexion(row[nuevo_campo], row[campo]), axis=1)
#get rid of the manual separator for match schedules
df[nuevo_campo] = df.apply(lambda row: eliminaSeparadores(row[nuevo_campo]), axis=1)
return df
def explotaHoras(df, listaSinExplotar):
df = df.set_index(listaSinExplotar).apply(pd.Series.explode).fillna('').reset_index()
return df
def main(rutaficheros):
#read soruce file
rutaExcel = rutaficheros + 'BaseACC.csv'
dfOrigen = pd.read_csv(rutaExcel, converters={i: str for i in range(100)})
#create lists to loop
listaCamposHorario = ['Programado', 'Programado 2']
listaCamposModo = ['Modo Planificado', 'Modo Planificado 2']
#for each item in list, create the time range, working minutes and export the file
for horario, modo in zip(listaCamposHorario, listaCamposModo):
df = configuraDataFrame(dfOrigen, horario, modo)
if not df.empty: | {
"domain": "codereview.stackexchange",
"id": 43368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
df = configuraDataFrame(dfOrigen, horario, modo)
if not df.empty:
df = generaRangoHoras(df, horario, 'Franjas_Programado')
df = explotaHoras(df, ['CentroPlanificacion', 'Fecha', horario, modo])
#drop unwanted columns for the final result
df = df.drop([horario, 'Fecha'], axis=1)
#drop unwanted rows for the final result
df = df[df['Conexión_Franjas_Programado'] > 0]
#group all the working minutes by location, planned/planned2 and department/department2
df = df.groupby(['CentroPlanificacion', modo, 'Franjas_Programado']).agg({'Conexión_Franjas_Programado' : 'sum'}).reset_index()
df.to_csv(rutaficheros + horario + '.csv', index=False)
return | {
"domain": "codereview.stackexchange",
"id": 43368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
And this should be the output:
The output file: | {
"domain": "codereview.stackexchange",
"id": 43368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
This takes around 35 seconds when I have a 100k rows source file and I think it could be better but I'm still very new in python to know more efficient ways to code.
Sample data
Dirección,Territorio,DNI,Agente,CentroPlanificacion,Campaña Origen,Fecha,Presentes,Contratados,ModoPlanificacion,Habilidades Agente,Programado,Modo Planificado,Programado 2,Modo Planificado 2
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-01,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-02,09:00-15:00,09:00-15:00,Department1,Department1,09:00-13:00,Department1,13:00-15:00,Department2
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-03,09:00-15:00,09:00-15:00,Department1,Department1,09:00-10:00/11:00-14:00/15:00-18:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-04,09:00-15:00,09:00-15:00,Department1,Department1,22:00-06:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-05,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-06,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-07,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-08,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-09,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-10,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,, | {
"domain": "codereview.stackexchange",
"id": 43368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-11,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-12,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-13,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-14,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-15,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-16,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-17,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-18,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-19,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-20,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-21,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-22,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-23,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,, | {
"domain": "codereview.stackexchange",
"id": 43368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-24,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-25,VAC,09:00-15:00,Department1,Department1,VAC,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-26,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-27,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-28,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-29,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-30,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-31,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,, | {
"domain": "codereview.stackexchange",
"id": 43368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
Answer: Consider revamping your current setup to work mostly in Pandas methods that operates on whole DataFrames and Series objects as opposed to mostly built-in Python methods on scalar values that loop and append to lists.
Beginners should know Pandas/Numpy programming is markedly different than general purpose Python programming. Below is working solution for one shift column on sample data. Of course, adjust and expand as needed to meet actual, larger data.
Input
For demonstration, I changed the shift start of very first record to 9:37 and shift end of very last record to 13:37.
from io import StringIO
import pandas as pd | {
"domain": "codereview.stackexchange",
"id": 43368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
txt = '''Dirección,Territorio,DNI,Agente,CentroPlanificacion,Campaña Origen,Fecha,Presentes,Contratados,ModoPlanificacion,Habilidades Agente,Programado,Modo Planificado,Programado 2,Modo Planificado 2
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-01,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-02,09:00-15:00,09:00-15:00,Department1,Department1,09:37-13:00,Department1,13:00-15:00,Department2
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-03,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-04,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-05,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-06,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-07,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-08,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-09,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-10,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-11,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,, | {
"domain": "codereview.stackexchange",
"id": 43368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-12,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-13,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-14,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-15,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-16,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-17,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-18,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-19,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-20,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-21,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-22,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-23,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-24,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,, | {
"domain": "codereview.stackexchange",
"id": 43368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-25,VAC,09:00-15:00,Department1,Department1,VAC,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-26,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-27,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-28,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-29,LIBRE,LIBRE,Department1,Department1,LIBRE,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-30,09:00-15:00,09:00-15:00,Department1,Department1,09:00-15:00,Department1,,
BussinessName,TerritoryNAme,WorkerID1,WorkerName1,Location1,Department1,2022-05-31,09:00-15:00,09:00-15:00,Department1,Department1,09:00-13:37,Department1,,''' | {
"domain": "codereview.stackexchange",
"id": 43368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
with StringIO(txt) as f:
raw_df = pd.read_csv(f)
Cleaning
See Series.replace, Series.split, Series.str.cat, pandas.to_datetime, and pandas.notnull.
# SUBSET COLUMNS
raw_df = raw_df[
["Territorio", "Campaña Origen", "Fecha", "Programado", "Modo Planificado"]
]
# SPLIT SHIFT RANGE
raw_df[["Shift_Start", "Shift_End"]] = (
raw_df["Programado"].replace({"LIBRE": None, "VAC": None})
.str.split("-", 1, expand=True)
)
# CONCATENATE DAY AND TIME, THEN CONVERT TO DATETIME
raw_df["Shift_Start"], raw_df["Shift_End"] = (
pd.to_datetime(raw_df["Fecha"].str.cat(raw_df["Shift_Start"], sep= " ")),
pd.to_datetime(raw_df["Fecha"].str.cat(raw_df["Shift_End"], sep=" "))
)
# REMOVE FREE DAYS
raw_df = raw_df[
pd.notnull(raw_df["Shift_Start"]) & pd.notnull(raw_df["Shift_End"])
]
Expanding Rows
See pandas.date_range, pandas.Timestamp.floor, pandas.Timedelta, DataFrame.loc, DataFrame.iterrows, and pandas.concat.
def expand_row_by_dates(row):
# BUILD RANGE FROM START TO END IN 30 MIN INTERVALS
shift_range = pd.date_range(
row["Shift_Start"].floor('30min'),
row["Shift_End"].floor('30min'),
freq='30min'
)
# BUILD NEW LONGER DATA FRAME, BINDING ROW VALUES AND DATE RANGE
df = pd.DataFrame({
"Territorio": row["Territorio"],
"Campaña Origen": row["Campaña Origen"],
"Fecha": row["Fecha"],
"Shift_Date": shift_range,
"Minutes_Worked": 30
})
# RE-CALCULATE FIRST 30 MIN INTERVAL TO ACTUAL
diff = (
(row["Shift_Start"] - df["Shift_Date"].min()) /
pd.Timedelta(minutes=1)
)
df.loc[df.index[0], "Minutes_Worked"] = (30-diff) if diff != 0 else 30)
# RE-CALCULATE LAST 30 MIN INTERVAL TO ACTUAL
diff = (
(row["Shift_End"] - df["Shift_Date"].max()) /
pd.Timedelta(minutes=1)
)
df.loc[df.index[-1], "Minutes_Worked"] = (diff if diff != 0 else 30)
return df | {
"domain": "codereview.stackexchange",
"id": 43368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
# ITERATE THROUGH ROWS AND COMPILE EXPANDED DATA FRAMES
shifts_df = pd.concat(
[expand_row_by_dates(row) for i, row in raw_df.iterrows()],
ignore_index=True
)
Output
shifts_df
Territorio Campaña Origen Fecha Shift_Date Minutes_Worked
0 TerritoryNAme Department1 2022-05-02 2022-05-02 09:30:00 23
1 TerritoryNAme Department1 2022-05-02 2022-05-02 10:00:00 30
2 TerritoryNAme Department1 2022-05-02 2022-05-02 10:30:00 30
3 TerritoryNAme Department1 2022-05-02 2022-05-02 11:00:00 30
4 TerritoryNAme Department1 2022-05-02 2022-05-02 11:30:00 30
.. ... ... ... ... ...
260 TerritoryNAme Department1 2022-05-31 2022-05-31 11:30:00 30
261 TerritoryNAme Department1 2022-05-31 2022-05-31 12:00:00 30
262 TerritoryNAme Department1 2022-05-31 2022-05-31 12:30:00 30
263 TerritoryNAme Department1 2022-05-31 2022-05-31 13:00:00 30
264 TerritoryNAme Department1 2022-05-31 2022-05-31 13:30:00 7 | {
"domain": "codereview.stackexchange",
"id": 43368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, datetime, pandas",
"url": null
} |
python, python-3.x, numpy
Title: Python function that shears image by n degrees while keeping the relationship between height and width
Question: I am trying to find a method to shear/skew an image horizontally or vertically by n degrees (n ranges from -90 to 90 excluding the terminals) so that the result would meet the following conditions:
The result would keep the size of the dimension that is not sheared, it means if you shear the image horizontally, the result would have the same height as the input and vice-versa.
The result would keep the relationship between the width and height of the original image.
The above means, if you name the width and height of the original image w and h, and shear the image horizontally by n degrees, the result would have be h tall, and the width w1 would be:
w1 = w / math.cos(math.radians(n)) + h * math.tan(math.radians(n))
So that the skewed width w2 and skewed height h2 would satisfy the following:
h2 = h / math.cos(math.radians(n))
w2 = w1 - h * math.tan(math.radians(n))
assert h2/w2 == h/w
I have written a custom function that does exactly this, except that it is inefficient and inelegant
Code
import math
import numpy as np
from itertools import product
from PIL import Image | {
"domain": "codereview.stackexchange",
"id": 43369,
"lm_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, numpy",
"url": null
} |
python, python-3.x, numpy
Code
import math
import numpy as np
from itertools import product
from PIL import Image
def rhombize(arr, angle, dimension='vertical', reverse=False):
assert 0 < angle < 90
assert dimension in ('horizontal', 'vertical')
height, width, dimensions = arr.shape
ratio1 = math.cos(math.radians(angle))
ratio2 = math.tan(math.radians(angle))
if reverse:
arr = np.flipud(arr) if dimension == 'vertical' else np.fliplr(arr)
h, w = height, width
if dimension == 'vertical':
h = round(height / ratio1 + width * ratio2 )
else:
w = round(width / ratio1 + height * ratio2 )
rhomb = np.zeros((h, w, dimensions), dtype=np.uint8)
for y in range(height):
for x in range(width):
a, b = x, y
a1, b1 = a+1, b+1
if dimension == 'vertical':
b = round(y / ratio1 + x * ratio2)
b1 = round((y + 1) / ratio1 + (x + 1) * ratio2)
else:
a = round(x / ratio1 + y * ratio2)
a1 = round((x + 1) / ratio1 + (y + 1) * ratio2)
rhomb[b:b1, a:a1] = arr[y, x]
if reverse:
rhomb = np.flipud(rhomb) if dimension == 'vertical' else np.fliplr(rhomb)
return rhomb
if __name__ == '__main__':
arr = np.zeros((1024, 768, 3), dtype=np.uint8)
for y, x in product(range(256), repeat=2):
arr[y*4:y*4+4, x*3:x*3+3] = (x, 0, y)
img1 = Image.fromarray(arr)
img1.show()
img1.save('D:/img1.jpg')
rhombized = rhombize(arr, 30)
img2 = Image.fromarray(rhombized)
img2.show()
img2.save('D:/img2.jpg')
First image:
Second image:
I am wondering what is the proper way to do this, I know about affine transformations and that seems indeed to be the right way to do this, but my math is not that good and none of the online tutorials I can find covers it.
So how can I properly implement the exactly same logic using affine transformations? | {
"domain": "codereview.stackexchange",
"id": 43369,
"lm_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, numpy",
"url": null
} |
python, python-3.x, numpy
Edit
Maybe my description does not succinctly describe what I am really trying to achieve here, so here are some pictures that explains what I am really trying to do better:
Then I am trying to upscale that rectangle, so that the dimension that is not skewed equals to its original value.
My code did exactly that, shearing while keeping aspect ratio, I only wanted the shearing to happen in one dimension, either horizontal or vertical, but not both.
I have already discovered that for vertical shearing, the relationship between the new y coordinate y1 and the original y0 coordinate should satisfy the following in order to achieve intended result:
y1 = y0 / cos(a) + x0 * tan(a)
x1 = x0
For horizontal shearing:
x1 = x0 / cos(a) + y0 * tan(a)
y1 = y0
And the above is exactly what my code implements, and I have measured the results and they do indeed keep the aspect ratio.
I just can't write my idea into a transformation matrix. None of the online tutorials I can find covered how to convert math formulas into transformation matrixes, Google search is useless as usual. | {
"domain": "codereview.stackexchange",
"id": 43369,
"lm_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, numpy",
"url": null
} |
python, python-3.x, numpy
Answer: It's actually more work to accept a dimension and a reverse. Just accept simultaneous horizontal and vertical angles, and if they're negative, assume reverse.
You don't need a cos; you only need tan in both dimensions. You also don't need flipud and fliplr.
Since you're interested in affine transformations, consider expressing your new h and w as a combined multiplication with a 2x2 transformation matrix.
In no case (sample image generation, transformation) should you be pixel-wise iterating.
You should not operate on the image as a Numpy array during transformation; you should use the pillow built-in affine transformation support.
Add PEP484 type hints.
Move your __main__ symbols into a function, since where they are now they still have global scope.
You've transposed your sample image from what you expected, in all likelihood. Numpy has height first, PIL has width first.
Suggested
This works for positive or negative horizontal or vertical shear. For simultaneous shear, the image is correct but the bounding box is not; I leave this edge case for you to figure out.
import numpy as np
from PIL import Image
def rhombize(
img: Image,
h_angle: float = 0,
v_angle: float = 0,
):
tans = np.tan(np.radians((v_angle, h_angle)))
# Transform the old image size to the new image size
size_transform = np.eye(2)
size_transform[
(0, 1),
(1, 0),
] = np.abs(tans)
new_size = img.size @ size_transform
'''
[ a b c ][ x ] [ x']
[ d e f ][ y ] = [ y']
[ 0 0 1 ][ 1 ] [ 1 ]
'''
shear = np.eye(2, 3)
# Shift the x position based on the y position and vice versa
shear[
(1, 0),
(0, 1),
] = tans
# Shift the x and y positions everywhere;
# we need to be piecewise via clip() because in half of the cases
# our origin needs to shift
shear[(1, 0), 2] = np.clip(-tans * img.size, a_max=0, a_min=None) | {
"domain": "codereview.stackexchange",
"id": 43369,
"lm_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, numpy",
"url": null
} |
python, python-3.x, numpy
rhombised = img.transform(
size=tuple(new_size.astype(int)),
method=Image.AFFINE,
data=shear.flatten(),
# resample omitted - we don't really care about quality
)
return rhombised
def test() -> None:
arr = np.zeros((768, 1024, 3), dtype=np.uint8)
arr[:, :, 0] = np.linspace(0, 255, 1024, dtype=np.uint8)[np.newaxis, :] # red ramp, horz
arr[:, :, 2] = np.linspace(0, 255, 768, dtype=np.uint8)[:, np.newaxis] # blue ramp, vert
img1 = Image.fromarray(arr)
# img1.show()
img2 = rhombize(img1, h_angle=0, v_angle=-15)
img2.show()
if __name__ == '__main__':
test()
Strict equivalence
I still don't pretend to understand the geometric interpretation of what you're doing, but mathematically it's pretty easy to make an affine transformation to represent it. Note that due to a quirk in Pillow, the final affine transformation needs to be an inverse of the size transform. You still need to clip for the negative cases.
import numpy as np
from numpy.linalg import inv
from PIL import Image
def rhombize(
img: Image,
x_angle: float = 0,
y_angle: float = 0,
):
w0, h0 = img.size
angles = np.radians((x_angle, y_angle))
tanx, tany = np.tan(angles)
cosx, cosy = np.cos(angles)
'''
Transform the old image coordinates to the new image coordinates
[ a b c ][ x ] [ x']
[ d e f ][ y ] = [ y']
[ 0 0 1 ][ 1 ] [ 1 ]
'''
shear = np.array((
# x col y col global col
(1/cosx, tanx, max(0, -h0*tanx)), # -> x' row
( tany, 1/cosy, max(0, -w0*tany)), # -> y' row
( 0, 0, 1), # -> 1 row
))
size_transform = np.abs(shear[:2, :2])
w1, h1 = (size_transform @ img.size).astype(int)
print(shear)
'''
The original implementation was assigning old coordinates to new
coordinates on the left-hand side, so this needs to be inverted
'''
shear = inv(shear)
print(shear) | {
"domain": "codereview.stackexchange",
"id": 43369,
"lm_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, numpy",
"url": null
} |
python, python-3.x, numpy
rhombised = img.transform(
size=(w1, h1),
method=Image.AFFINE,
data=shear[:2, :].flatten(),
# resample omitted - we don't really care about quality
)
return rhombised
def test() -> None:
arr = np.zeros((768, 1024, 3), dtype=np.uint8)
arr[:, :, 0] = np.linspace(0, 255, 1024, dtype=np.uint8)[np.newaxis, :] # red ramp, horz
arr[:, :, 2] = np.linspace(0, 255, 768, dtype=np.uint8)[:, np.newaxis] # blue ramp, vert
img1 = Image.fromarray(arr)
img2 = rhombize(img1, y_angle=25, x_angle=-35)
img2.show()
if __name__ == '__main__':
test()
Simultaneous shear works:
though it appears that you don't want to allow that. The one-dimensional cases simplify your inverse and make it so that the special cases can be solved analytically, instead of numerically through linalg.inv().
import numpy as np
from PIL import Image
def rhombize(
img: Image,
x_angle: float = 0,
y_angle: float = 0,
) -> Image:
epsilon = 1e-12
has_x, has_y = np.abs((x_angle, y_angle)) > epsilon
if has_x and has_y:
raise ValueError('Two-axis shear is not supported')
if not (has_x or has_y):
return img # no-op
w0, h0 = img.size
angles = np.radians((x_angle, y_angle))
sinx, siny = np.sin(angles)
cosx, cosy = np.cos(angles)
tanx, tany = np.tan(angles) | {
"domain": "codereview.stackexchange",
"id": 43369,
"lm_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, numpy",
"url": null
} |
python, python-3.x, numpy
'''
Transform the old image coordinates to the new image coordinates
[ a b c ][ x ] [ x']
[ d e f ][ y ] = [ y']
[ 0 0 1 ][ 1 ] [ 1 ]
In the forward case (used for size transformation), the last row and last column are irrelevant.
In the inverse case (used for image transformation), the last row is implied.
'''
shear_forward = np.array((
(1/cosx, tanx),
( tany, 1/cosy),
))
shear_inverse = np.array((
( cosx, -sinx, min(0, h0*tanx)*cosx),
(-siny, cosy, min(0, w0*tany)*cosy),
))
size_transform = np.abs(shear_forward)
w1, h1 = (size_transform @ img.size).astype(int)
rhombised = img.transform(
size=(w1, h1),
method=Image.AFFINE,
data=shear_inverse.flatten(),
# resample omitted - we don't really care about quality
)
return rhombised
def test() -> None:
arr = np.zeros((768, 1024, 3), dtype=np.uint8)
arr[:, :, 0] = np.linspace(0, 255, 1024, dtype=np.uint8)[np.newaxis, :] # red ramp, horz
arr[:, :, 2] = np.linspace(0, 255, 768, dtype=np.uint8)[:, np.newaxis] # blue ramp, vert
img1 = Image.fromarray(arr)
img2 = rhombize(img1, y_angle=30)
img2.show()
if __name__ == '__main__':
test() | {
"domain": "codereview.stackexchange",
"id": 43369,
"lm_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, numpy",
"url": null
} |
c++, object-oriented, design-patterns
Title: Adapter pattern in C++ via Inheritance and Composition
Question: Any suggestions on how the implementation of the C++ Adapter pattern could be improved here? Implemented via:
Composition
Inheritance
What needed to be adapted was the OptionLegacy class which returns implied volatility of the option but the client needs the dollar price so a simple conversion was included.
#include <iostream>
#include <cmath>
// Return price of option by volatility
// Adaptee - old legacy type option objects
class OptionLegacy
{
protected:
float volatilityPrc;
double spotPrice;
int expiryDays;
public:
OptionLegacy(float v, double s, int t) :
volatilityPrc(v), spotPrice(s), expiryDays(t) {}
float GetVol() const {
return volatilityPrc;
}
double GetSpot() const {
return spotPrice;
}
int GetTau() const {
return expiryDays;
}
};
// Return price of option in dollars. Current interface that client uses
class OptionPriceDollars
{
protected:
float vol;
double spot;
double tau;
public:
OptionPriceDollars() = default;
OptionPriceDollars(float v, double s, double t) :
vol(v), spot(s), tau(t) {}
virtual float GetPrice() {
return 0.4 * spot * vol * sqrt(tau);
}
};
// via composition
class Adapter
{
OptionLegacy adaptee;
public:
Adapter(const OptionLegacy & o): adaptee(o) {}
float GetPrice() {
return 0.4 * adaptee.GetSpot() * adaptee.GetVol() / 100 * sqrt(adaptee.GetTau()/365);
}
};
// via inheritance
class AdapterInheritance : public OptionPriceDollars, private OptionLegacy
{
public:
AdapterInheritance(const OptionLegacy & o) : OptionLegacy(o.GetVol(), o.GetSpot(), o.GetTau()) {};
float GetPrice() override {
return 0.4 * spotPrice * volatilityPrc / 100 * expiryDays / 365;
}
};
int main()
{
OptionPriceDollars od(0.14, 100, 1);
std::cout << "The price of the option is " << od.GetPrice() << std::endl; | {
"domain": "codereview.stackexchange",
"id": 43370,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns",
"url": null
} |
c++, object-oriented, design-patterns
OptionLegacy op(14, 100, 365);
Adapter a(op);
std::cout << "The price of the old style option is (composition) " << a.GetPrice() << std::endl;
AdapterInheritance b(op);
std::cout << "The price of the old style option is (inheritance) " << b.GetPrice() << std::endl;
int x;
std::cin >> x;
}
Answer: Incorrect use of inheritance
There is a problem with class AdapterInheritance. It contains both the member variables of OptionLegacy and of OptionPriceDollars. But only one set of variables is desired; those of OptionLegacy. You should not inherit from the concrete OptionPriceDollars class. If anything, you should only inherit from an "interface", however C++ does not have interface classes like some other programming languages. You could use pure virtual functions to create an abstract base class, but that's not exactly the same. So I recommend you just write:
class AdapterInheritance : private OptionLegacy
{
public:
AdapterInheritance(const OptionLegacy & o) : OptionLegacy(o.GetVol(), o.GetSpot(), o.GetTau()) {};
float GetPrice() {
return 0.4 * spotPrice * volatilityPrc / 100 * expiryDays / 365;
}
};
Or if you need to use a base class, create an abstract one:
class OptionPrice {
public:
virtual float GetPrice() = 0;
};
And have both AdapterInheritance and OptionPriceDollars publicly inherit from that.
Other ways to create adaptable interfaces
C++ is a multi-paradigm language. You don't have to put everything into classes. You could create a freestanding function GetPrice() that takes a reference to any object, and calls the member function GetPrice():
template<typename T>
float GetPrice(T& o) {
return o.GetPrice();
}
That would then work on OptionPriceDollars as well as your adapters. To make it also work with OptionLegacy, you can provide an overload of GetPrice():
float GetPrice(OptionLegacy& adaptee) {
return 0.4 * adaptee.GetSpot() * adaptee.GetVol() / 100 * sqrt(adaptee.GetTau()/365);
} | {
"domain": "codereview.stackexchange",
"id": 43370,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns",
"url": null
} |
c++, object-oriented, design-patterns
That way, in main() you can write:
std::cout << "The price of the option is " << GetPrice(od) << '\n';
std::cout << "The price of the old style option is " << GetPrice(op) << '\n';
Be consistent
I see different variable names for exactly the same thing, like volatilityPrc, vol and v. I see both float and double being used, if the result of GetPrice() is going to be a float, why use doubles? Why does OptionPriceDollars have a default constructor but the other classes don't?
Prefer \n over std::endl
Prefer using '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually not necessary and might impact performance.
Improve the constructor of AdapterInheritance
You can make use of the fact that OptionLegacy has an implicit copy constructor, and simplify the constructor of AdapterInheritance like so:
AdapterInheritance(const OptionLegacy & o) : OptionLegacy(o) {}
That's actually very much what you did in Adapter. Another way to implement the constructor is to have it accept any set of arguments, and pass them on to the constructor of OptionLegacy:
template<typename... Args>
AdapterInheritance(Args&&... args): OptionLegacy(std::forward<Args>(args)...) {}
Which might look weird if you have never used templates parameter packs and perfect forwarding before, but this is a standard way to do this. The advantage is that you only have to write this one constructor, and it will cover all the possible constructors OptionLegacy has, including the implicit copy and move constructors. Another advantage of this is that you no longer have to create an OptionLegacy first, you can now just write:
AdapterInheritance b(14, 100, 365); | {
"domain": "codereview.stackexchange",
"id": 43370,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, design-patterns",
"url": null
} |
c#, comparative-review
Title: Returning the other value of boolean enum
Question: I have a class with a "mode" state. There are currently two modes and we are not likely to add more in the future.
The class has a CurrentMode property, and a function to swap to the other mode.
I have implemented this using another property called ModeNotInUse which returns the opposite value of CurrentMode.
However, I am in two minds about how to implement this ModeNotInUse
public enum PlayerMode
{
Puzzle,
Action
}
public class ModeController
{
public PlayerMode CurrentMode { get; private set; }
private PlayerMode ModeNotInUse => ...
public void SwitchMode()
{
CurrentMode = ModeNotInUse
}
}
My two implimentations of this are:
private PlayerMode ModeNotInUse
=> CurrentMode switch
{
PlayerMode.Puzzle => PlayerMode.Action,
_ => PlayerMode.Puzzle
};
Or
private PlayerMode ModeNotInUse
=> CurrentMode == PlayerMode.Puzzle
? PlayerMode.Action
: PlayerMode.Puzzle;
Which better captures my intent here? The first is my preference but I worry it's difficult to read.
(edit)
I could of course do this with a backing boolean field but that feels even less clean
private bool inPuzzleMode;
public PlayerMode CurrentMode
{
get => inPuzzleMode switch
{
true => PlayerMode.Puzzle,
false => PlayerMode.Action
};
private set => inPuzzleMode = value == PlayerMode.Puzzle;
}
private PlayerMode ModeNotInUse
=> inPuzzleMode switch
{
true => PlayerMode.Action,
false => PlayerMode.Puzzle
};
Which do you think is best?
Answer: I think a method would be better than a property in this case. However, I would do it this way :
public class ModeController
{
public PlayerMode CurrentMode { get; private set; }
public void SwitchMode()
=> CurrentMode == PlayerMode.Puzzle ? PlayerMode.Action : PlayerMode.Puzzle;
} | {
"domain": "codereview.stackexchange",
"id": 43371,
"lm_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#, comparative-review",
"url": null
} |
c#, comparative-review
if the PlayerMode is used in different classes, and you want to get the opposite mode, then you can move SwitchMode() into an extension :
public static class Extension {
public static PlayerMode SwitchMode(this PlayerMode current)
=> current == PlayerMode.Puzzle ? PlayerMode.Action : PlayerMode.Puzzle;
}
public class ModeController
{
public PlayerMode CurrentMode { get; private set; }
public void SwitchMode() => CurrentMode = CurrentMode.SwitchMode();
}
if there is a requirement where you want to know the old mode, then you could store the old mode before switching it, and add another method to get the old mode. | {
"domain": "codereview.stackexchange",
"id": 43371,
"lm_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#, comparative-review",
"url": null
} |
c++, performance, radix-sort
Title: Asking for C++ advice based on a radix sort function | {
"domain": "codereview.stackexchange",
"id": 43372,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, radix-sort",
"url": null
} |
c++, performance, radix-sort
Question: Can someone point out what possible edge cases/leaks/inefficiencies my code has and how they could be avoided/fixed. Basically, I want to know what mistakes I make so I can avoid making them in the future.
I chose an LSD radix sort function as a sample for no particular reason.
The function:
//arrPtr - pointer to the array being sorted; count - its count
//scoreFunction - function that assigns scores to elements based on which they will be sorted in ascending order
//args - pointer to an array of pointers used to pass data to the scoreFunction
template<class T>
void rsort(T *arrPtr, size_t count, int scoreFunction(T val, void **args) = [](T val, void **args) {return val; }, void **args = nullptr) {
struct elem { //Pairing indices with their scores
size_t idx;
int scr;
};
struct elemPtr { //Pointer struct to avoid memory leaks in case of an exception
elem *ptr;
~elemPtr() { delete[] ptr; }
void swap(elemPtr &aux) {
elemPtr t{ ptr };
ptr = aux.ptr;
aux.ptr = t.ptr;
t.ptr = nullptr;
}
};
elemPtr srt{ new elem[count] }, srtAux{ new elem[count] };
for (size_t i = 0; i < count; ++i) { //Assigning indices and scores that are converted to unsigned representation + 2^31
srt.ptr[i].idx = i;
srt.ptr[i].scr = scoreFunction(arrPtr[i], args) ^ 0x80000000;
}
for (unsigned char bShft = 0; bShft < 32; bShft += 8) { // Base 256 LSD radix sort based on the scores
size_t dCnt[256]{};
for (size_t i = 0; i < count; ++i)
++dCnt[srt.ptr[i].scr >> bShft & 255];
for (unsigned char i = 0; i < 255; ++i)
dCnt[i + 1] += dCnt[i];
for (size_t i = count; i > 0; --i) {
--dCnt[srt.ptr[i - 1].scr >> bShft & 255];
srtAux.ptr[dCnt[srt.ptr[i - 1].scr >> bShft & 255]] = srt.ptr[i - 1];
}
srt.swap(srtAux);
} | {
"domain": "codereview.stackexchange",
"id": 43372,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, radix-sort",
"url": null
} |
c++, performance, radix-sort
}
srt.swap(srtAux);
}
for (size_t i = 0; i < count; ++i) //Filling with 0s to reuse as an array of bools that represent if the element is in the right place
srtAux.ptr[i].idx = 0;
for (size_t i = 0; i < count; ++i) { //Rearranging the original array by dividing the elements into enclosed loops
if (srtAux.ptr[i].idx)
continue;
T temp = arrPtr[i];
size_t curIdx = i;
while (srt.ptr[curIdx].idx != i) {
srtAux.ptr[curIdx].idx = 1;
arrPtr[curIdx] = arrPtr[srt.ptr[curIdx].idx];
curIdx = srt.ptr[curIdx].idx;
}
srtAux.ptr[curIdx].idx = 1;
arrPtr[curIdx] = temp;
}
} | {
"domain": "codereview.stackexchange",
"id": 43372,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, radix-sort",
"url": null
} |
c++, performance, radix-sort
I didn't use any libraries to make the function independent-- if that makes sense.
Answer: Use the standard library, or emulate it
I didn't use any libraries to make the function independent-- if that makes sense.
It can indeed be a burden for developers if a library they want to use has lots of dependencies, as they need to incorporate those into their build system, have to deal with licensing issues, and so on. However, on almost any platform you will have a standard library that you can rely on without doing anything special.
Consider your elemPtr, this is basically the same as std::unique_ptr.
So I would strongly recommend using the latter instead. And in case this isn't available on the platform you want to run it on, you could create a drop-in replacement for std::unique_ptr. You should avoid adding things to the std namespace yourself, so a way to do this properly would be:
#if HAVE_UNIQUE_PTR
#include <memory>
using std::unique_ptr;
#else
class unique_ptr {
// ...
};
#endif
Passing the score function
You are passing the score function as a regular function pointer, and you want to be able to have a variable number of arguments passed to it. Using void** is not very safe. Again, if you can I would recommend using the standard library here, and use std::function<int(T)> to pass the function. It will allow you to pass lambdas with captures, so you don't have to worry about any extra arguments.
Another solution is to make the template itself variadic, allowing you to really pass an arbitrary number of arguments without resorting to void**, like so:
template<typename T, typename... Args>
void rsort(T *arrPtr, size_t count, int scoreFunction(T val, Args...) = [](T val, Args...) {return val;}, Args... args) {
// ...
srt.ptr[i].scr = scoreFunction(arrPtr[i], args...) ^ 0x80000000;
// ...
} | {
"domain": "codereview.stackexchange",
"id": 43372,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, radix-sort",
"url": null
} |
c++, performance, radix-sort
Pass by const reference where appropriate
Passing val and args by value to scoreFunction() can be inefficient, depending on their types. Prefer to pass them by const reference instead:
int scoreFunction(const T& val, const Args&...)
Use of a score function might be problematic
You are not radix sorting T, you are radix sorting the 32-bit score associated with each element of the array pointed to by arrPtr. However, it might not always be easy to create a score function. Consider having an array of std::strings. It would be easy to radix-sort strings, using char as the radix. However, given an set of arbitrary strings that I want to sort alphabetically, it's very hard to create a scoreFunction() that would map every string to a 32-bit value and still keep them in the same order. | {
"domain": "codereview.stackexchange",
"id": 43372,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, radix-sort",
"url": null
} |
c#, .net
Title: Managing websocket subscriptions
Question: The following code is pulling data off an exchange. It keeps the subscriptions to the channels because when the websocket client reconnects, all subscriptions are gone and we basically need to resubscribe. When a message is received, it parses it directly from ReadOnlyMemory<T> to avoid string allocations and if it's recognized as a subscription, it calls its callback. I would like to get a review on this code because managing websocket subscriptions is something common and this code going to be reused into other exchanges' implementation.
public class Subscription
{
public Subscription(SubscriptionRequest request, Action<Notification> action)
{
Id = Guid.NewGuid();
Request = request;
Action = action;
}
public Guid Id { get; }
public SubscriptionRequest Request { get; }
public Action<Notification> Action { get; }
}
public class SubscriptionManager
{
private readonly ILogger<SubscriptionManager> _logger;
private readonly IList<Subscription> _subscriptions = new List<Subscription>();
public SubscriptionManager(ILoggerFactory? loggerFactory = default)
{
_logger = (loggerFactory ?? NullLoggerFactory.Instance).CreateLogger<SubscriptionManager>();
}
public void AddSubscription(Subscription subscription)
{
lock (_subscriptions)
{
if (!_subscriptions.Contains(subscription))
{
_subscriptions.Add(subscription);
}
}
}
public void RemoveSubscription(Subscription subscription)
{
lock (_subscriptions)
{
if (_subscriptions.Contains(subscription))
{
_subscriptions.Remove(subscription);
}
}
}
public Subscription? GetSubscription(Guid id)
{
lock (_subscriptions)
{
return _subscriptions.FirstOrDefault(x => x.Id == id);
}
} | {
"domain": "codereview.stackexchange",
"id": 43373,
"lm_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",
"url": null
} |
c#, .net
public IList<Subscription> GetSubscriptions()
{
lock (_subscriptions)
{
return _subscriptions;
}
}
public IEnumerable<Action<Notification>> GetCallbacks(string channel)
{
lock (_subscriptions)
{
foreach (var subscription in _subscriptions)
{
if (subscription.Request.Channels.Contains(channel))
{
yield return subscription.Action;
}
}
}
}
public void Reset()
{
lock (_subscriptions)
{
_subscriptions.Clear();
}
}
}
public sealed class BitClient : IDisposable
{
private readonly ILogger<BitClient> _logger;
private readonly string _accessKey;
private readonly string _secretKey;
private readonly RestClient _restClient;
private readonly StsWebSocketClient _socketClient;
private readonly SubscriptionManager _subscriptionManager;
public BitClient(BitEndpointType endpointType, string accessKey, string secretKey, ILoggerFactory? loggerFactory = default)
{
_logger = (loggerFactory ?? NullLoggerFactory.Instance).CreateLogger<BitClient>();
_restClient = endpointType switch
{
BitEndpointType.Production => new RestClient("https://api.bit.com"),
BitEndpointType.Testnet => new RestClient("https://betaapi.bitexch.dev"),
_ => throw new NotSupportedException()
};
_socketClient = endpointType switch
{
BitEndpointType.Production => new StsWebSocketClient("wss://spot-ws.bit.com", loggerFactory),
BitEndpointType.Testnet => new StsWebSocketClient("wss://betaspot-ws.bitexch.dev", loggerFactory),
_ => throw new NotSupportedException()
};
_socketClient.Connected += OnConnected;
_socketClient.Disconnected += OnDisconnected;
_socketClient.MessageReceived += OnMessageReceived; | {
"domain": "codereview.stackexchange",
"id": 43373,
"lm_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",
"url": null
} |
c#, .net
_accessKey = accessKey;
_secretKey = secretKey;
_subscriptionManager = new SubscriptionManager(loggerFactory);
}
public void Dispose()
{
_restClient.Dispose();
_socketClient.Connected -= OnConnected;
_socketClient.Disconnected -= OnDisconnected;
_socketClient.MessageReceived -= OnMessageReceived;
_socketClient.Dispose();
}
public Task StartAsync()
{
return _socketClient.StartAsync();
}
public Task StopAsync()
{
_subscriptionManager.Reset();
return _socketClient.StopAsync();
}
public async Task SendAsync(SubscriptionRequest request, Action<Notification> callback)
{
var json = JsonSerializer.Serialize(request);
var message = new Message(Encoding.UTF8.GetBytes(json));
await _socketClient.SendAsync(message).ConfigureAwait(false);
_subscriptionManager.AddSubscription(new Subscription(request, callback));
}
public Task SubscribeToTickerAsync(string[] pairs, Action<Ticker> callback)
{
var request = new SubscriptionRequest(SubscriptionType.Subscribe, pairs, new[] { "ticker" }, IntervalType.Raw, null);
return SendAsync(request, n => callback(n.Data.Deserialize<Ticker>()!));
}
public Task SubscribeToDepthAsync(string[] pairs, Action<Depth> callback)
{
var request = new SubscriptionRequest(SubscriptionType.Subscribe, pairs, new[] { "depth" }, IntervalType.Raw, null);
return SendAsync(request, n => callback(n.Data.Deserialize<Depth>()!));
}
public async Task SubscribeToUserTradesAsync(Action<IEnumerable<UserTrade>> callback)
{
var token = await GetAuthenticationTokenAsync().ConfigureAwait(false); | {
"domain": "codereview.stackexchange",
"id": 43373,
"lm_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",
"url": null
} |
c#, .net
var request = new SubscriptionRequest(SubscriptionType.Subscribe, null, new[] { "user_trade" }, IntervalType.Raw, token);
await SendAsync(request, n => callback(n.Data.Deserialize<IEnumerable<UserTrade>>()!)).ConfigureAwait(false);
}
private void OnConnected(object? sender, EventArgs e)
{
foreach (var subscription in _subscriptionManager.GetSubscriptions())
{
Task.Run(async () =>
{
await SendAsync(subscription.Request, subscription.Action).ConfigureAwait(false);
});
}
}
private void OnDisconnected(object? sender, EventArgs e)
{
}
private void OnNotification(Notification notification)
{
var callbacks = _subscriptionManager.GetCallbacks(notification.Channel);
foreach (var callback in callbacks)
{
try
{
Task.Run(() => callback(notification));
}
catch (Exception ex)
{
_logger.LogError(ex, "OnNotification: Error during event callback call");
}
}
}
private void OnMessageReceived(object? sender, MessageReceivedEventArgs e)
{
using var document = JsonDocument.Parse(e.Message.Buffer);
if (document.RootElement.TryGetProperty("channel", out var channelElement))
{
var channel = channelElement.GetString();
Debug.Assert(channel != null);
if (channel == "subscription")
{
var response = document.RootElement.Deserialize<BaseResponse<SubscriptionResponse>>();
Debug.Assert(response != null);
//Console.WriteLine($"SUBSCRIPTION | Code: {response.Data.Code} | Message: {response.Data.Message} | Subscription: {response.Data.Subscription}");
}
else
{
var notification = document.RootElement.Deserialize<Notification>(); | {
"domain": "codereview.stackexchange",
"id": 43373,
"lm_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",
"url": null
} |
c#, .net
Debug.Assert(notification != null);
OnNotification(notification);
}
}
}
}
```
Answer: If you would replace the List<Subscription> + lock combo inside your SubscriptionManager to ConcurrentDictionary<Guid, Subscription> then the class implementation can be greatly simplified and would be more concise.
public class SubscriptionManager
{
private readonly ILogger<SubscriptionManager> _logger;
private readonly ConcurrentDictionary<Guid,Subscription> _subscriptions = new ();
public SubscriptionManager(ILoggerFactory? loggerFactory = default)
=> _logger = (loggerFactory ?? NullLoggerFactory.Instance)
.CreateLogger<SubscriptionManager>();
public void AddSubscription(Subscription subscription)
=> _subscriptions.TryAdd(subscription.Id, subscription);
public void RemoveSubscription(Subscription subscription)
=> _subscriptions.TryRemove(subscription.Id, out _);
public Subscription? GetSubscription(Guid id)
=> _subscriptions.TryGetValue(id, out var sub) ? sub : null;
public IList<Subscription> GetSubscriptions()
=> _subscriptions.Values.ToList();
public IEnumerable<Action<Notification>> GetCallbacks(string channel)
=> _subscriptions.Values
.Where(sub => sub.Request.Channels.Contains(channel))
.Select(sub => sub.Action)
.ToList();
public void Reset()
=> _subscriptions.Clear();
} | {
"domain": "codereview.stackexchange",
"id": 43373,
"lm_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",
"url": null
} |
java, performance, random, queue
Title: Randomized Queue with ArrayList from Princeton's Algorithm Book
Question: In the book they recommend to utilize an Array, but I think that it's easier to use an ArrayList instead, is there any problem with that? Is this code well designed?
package com.company;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.Random;
public class RandomQueue<Item>{
private ArrayList<Item> a;
private int size;
Random r;
public RandomQueue(){
a = new ArrayList<Item>();
size = 0;
}
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
public void enqueue(Item item){
a.add(item);
size++;
}
public Item dequeue(){
if(isEmpty()){
throw new NoSuchElementException("Queue is empty");
}else {
r = new Random();
int randomIndex = r.nextInt(size);
Item item = a.get(randomIndex);
a.remove(randomIndex);
size--;
return item;
}
}
public Item sample(){
r = new Random();
if(isEmpty()){
throw new IndexOutOfBoundsException();
}
int index = r.nextInt(size);
return a.get(index);
}
} | {
"domain": "codereview.stackexchange",
"id": 43374,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, random, queue",
"url": null
} |
java, performance, random, queue
}
Answer: You should document the reason why Random r is package private. At the moment the reason is not clear, but if you fix the "perpetual reinstantiation" by initializing the r variable in the constructor, then you can take advantage of the package private visibility in unit tests by replacing the random number generator with a non-random Random implementation (because unit testing random behaviour is pretty much impossible).
If you go with the static Random as suggested by @mdfst13, then you should use ThreadLocalRandom so that different threads that use the class do not interfere with each other.
It is customary in Java that generic types are defined using single capital letters. Using a name that resembles a class name (<Item>) can be confusing as in a cursory glance it suggests that a specific Item class should be used. This increases cognitive load, which makes following the code more difficult.
Beyond generic types, single letter names should be avoided. Use names that describe the purpose of the field. Non-descriptive field names again increase the cognitive load on the reader.
The two instances of generating a random index should be refactored to an internal method.
public class RandomQueue<T> {
private final List<T> data = new ArrayList<>();
/**
* Package private so that it can be overridden in unit tests.
*/
Random rand = new Random();
private int randomIndex() {
return rand.nextInt(data.size());
}
....
}
Because this is Java and the class implements a collection of objects, you should see if it would make sense to implement the Collection interface. This might make the class more versatile. | {
"domain": "codereview.stackexchange",
"id": 43374,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, performance, random, queue",
"url": null
} |
c++, array, circular-list
Title: std::array based push-only circular buffer
Question: Minimal implementation of a circular buffer based on std::array, where elements can only be pushed and iterated. I'm interested on potential failures and very trivial optimizations, as I'd like to keep it as simple as possible.
#ifndef CIRCULAR_BUFFER_H
#define CIRCULAR_BUFFER_H
#include <array>
// Array-based push-only circular buffer.
// Sample usage:
//
// CircularBuffer<int, 3> buff;
// buff.push( 1 ); // 1
// buff.push( 2 ); // 1 2
// buff.push( 3 ); // 1 2 3
// buff.push( 4 ); // 2 3 4
// buff.push( 5 ); // 3 4 5
//for( int i : buff )
// std::cout << i << std::endl;
template <class T, std::size_t SIZE>
class CircularBuffer
{
public:
static_assert( SIZE > 0 );
void push( const T & value )
{
if( ( ++mCurrentIndex ) == mCapacity )
mCurrentIndex = 0;
mBuffer[ mCurrentIndex ] = value;
if( mSize != mCapacity )
++mSize;
}
void push( T && value )
{
if( ( ++mCurrentIndex ) == mCapacity )
mCurrentIndex = 0;
mBuffer[ mCurrentIndex ] = std::move( value );
if( mSize != mCapacity )
++mSize;
}
void reset()
{
mCurrentIndex = -1;
mSize = 0;
}
class iterator
{
public:
using iterator_category = std::output_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = T*;
using reference = T&;
explicit iterator( pointer bufferPtr, unsigned int index, unsigned int visited ) :
mBufferPtr( bufferPtr ),
mIndex( index ),
mVisited( visited )
{}
iterator& operator++()
{
if( ++mIndex == mCapacity )
mIndex = 0;
++mVisited;
return *this;
}
iterator operator++( int )
{
iterator retval = *this;
++( *this );
return retval;
} | {
"domain": "codereview.stackexchange",
"id": 43375,
"lm_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++, array, circular-list",
"url": null
} |
c++, array, circular-list
bool operator==( iterator other ) const
{
return ( ( mBufferPtr + mIndex ) == ( other.mBufferPtr + other.mIndex ) ) &&
( mVisited == other.mVisited );
}
bool operator!=( iterator other ) const
{
return !( *this == other );
}
reference operator*() const
{
if( mIndex == -1 )
throw std::runtime_error( "Circular buffer is empty" );
return mBufferPtr[ mIndex ];
}
private:
pointer mBufferPtr;
unsigned int mIndex;
unsigned int mVisited;
};
iterator begin()
{
const unsigned int beginIndex = ( mSize < mCapacity ) ? 0 : ( mCurrentIndex + 1 ) % mCapacity;
return iterator( mBuffer.data(), beginIndex, 1 );
}
iterator end()
{
const unsigned int endIndex = ( mSize < mCapacity ) ? ( mCurrentIndex + 1 ) : ( mCurrentIndex + 1 ) % mCapacity;
return iterator( mBuffer.data(), endIndex, mSize + 1 );
}
private:
enum { mCapacity = SIZE };
std::array<T, mCapacity> mBuffer;
unsigned int mCurrentIndex = -1;
unsigned int mSize = 0;
};
#endif // CIRCULAR_BUFFER_H | {
"domain": "codereview.stackexchange",
"id": 43375,
"lm_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++, array, circular-list",
"url": null
} |
c++, array, circular-list
#endif // CIRCULAR_BUFFER_H
Answer: Missing Includes
It doesn't compile for me without the #include <stdexcept>.
Other stuff is luckily included by other includes. I'm personally a fan of explicit includes though. (std::size_t, std::move, std::output_iterator_tag, std::ptrdiff_t)
Size & Capacity
As already mentioned in another answer use one type only for one thing, namely your size and current index values. (It could lead to bugs btw if mSize can never reach mCapacity.)
And while doing that think about "fixing" mCapacity. Maybe I'm missing something but what's up with that enum wrapper? Why not just simply make it a static and/or constexpr member? Or why not just omit it altogether and just use the template parameter directly?
Also note that the template parameter says "size" while the member says "capacity" and the mSize member has actually nothing to do with the SIZE template parameter.
Bug: Deref begin() on an Empty Buffer
That should probably lead to an exception if I understand the intention of the check in the operator*. But it doesn't. And if I see correctly it actually can only throw if you reach the maximum possible size given by the type of the variable, i.e. std::numeric_limits<unsigned>::max() (or whatever common size type you settle on - and given that it will be an unsigned one).
(As already mentioned in another answer it is questionable though if you want to throw there, anyway, because standard containers don't. But it can be a nice safety feature of course.)
Circular Iterator
The iterator is circular for fully filled buffers only. It should be if(++mIndex == mSize) in operator++() - if it is intended to be a circular iterator after all.
About reset
Note that this does not what clear for standard containers does. I.e. it does not erase and therefore does not destruct anything.
That could of course be intended and be the reason why it is not called clear after all. | {
"domain": "codereview.stackexchange",
"id": 43375,
"lm_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++, array, circular-list",
"url": null
} |
c++, tree, binary-search-tree
Title: Binary Search Tree implementation in C++ with templates
Question: Im implementing a BST using templates and dynamic memory, here is my attempt:
This is the BSTNode.hh
#ifndef BSTNODE_HH
#define BSTNODE_HH
#include <list>
#include <algorithm>
using namespace std;
template <class K, class V>
class BSTNode
{
public:
BSTNode(const K &key) {
this->key = key;
this->values = {};
}
BSTNode(const K &key, const list<V>& values) {
this->key = key;
this->values = values;
}
BSTNode(const BSTNode<K, V> &orig)
{
this->key = orig.key;
this->values = orig.values;
if (orig.left != nullptr)
{
this->left = new BSTNode<K, V>(*orig.left);
//this->left->setValues()
left->setParent(this); // Goes back to the new child to set the parent as this
}
if (orig.right != nullptr)
{
this->right = new BSTNode<K, V>(*orig.right);
right->setParent(this); // Goes back to the new child to set the parent as this
}
};
virtual ~BSTNode() { }
/* Modificadors */
// Declareu-hi aquí els modificadors (setters) dels atributs que manquen
/* Consultors */
void setParent(BSTNode<K, V> *parent) { this->parent = parent; }
void setRight(BSTNode<K,V> *right){this->right = right;}
void setLeft(BSTNode<K,V>*left){this->left= left;}
void setValues(const list<V>& v) {this->values = v;}
// Declareu-hi aquí els consultors (getters) dels atributs que manquen
const K &getKey() const { return key; }
const list<V> &getValues() const { return this->values; }
BSTNode<K, V>* getLeft() const {return this->left;}
BSTNode<K, V>* getRight() const {return this->right;}
BSTNode<K, V>* getParent() const {return this->parent;} | {
"domain": "codereview.stackexchange",
"id": 43376,
"lm_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++, tree, binary-search-tree",
"url": null
} |
c++, tree, binary-search-tree
/* Operacions */
bool isRoot() const { return this->parent == nullptr; }
bool hasLeft() const { return left != nullptr; }
bool hasRight() const { return right != nullptr; }
bool isExternal() const { return !hasLeft() and !hasRight(); }
void insertValue(const V &v) { values.push_back(v); }
int depth() const
{
if (this->isRoot())
return 0;
else
return 1 + parent->depth();
}
int height() const
{
if (isExternal())
return 1;
else
return 1 + max(left->height(), right->height());
}
bool operator==(const BSTNode<K, V> &node) const
{
if (key != node.key)
return false;
auto it1 = values.begin();
auto it2 = node.values.begin();
for (; it1 != values.end() && it2 != node.values.end(); it1++, it2++)
{
if (*it1 != *it2)
return false;
}
return it1 == values.end() && it2 == node.values.end();
}
private:
K key;
list<V> values;
// Afegiu-hi aquí els atributs que manquen
BSTNode<K, V> *left{nullptr};
BSTNode<K, V> *right{nullptr};
BSTNode<K, V> *parent{nullptr};
};
#endif
BSTArbre.hh
#ifndef BSTARBRE_HH
#define BSTARBRE_HH
#include "BSTNode.hh"
#include <iostream>
#include <exception>
using namespace std;
template <class K, class V>
class BSTArbre
{
public:
BSTArbre() : root(nullptr), _size(0){};
BSTArbre(const BSTArbre<K, V> &orig)
{
this->_size = orig._size;
// TODO: revisar que este bien
this->root = new BSTNode<K, V>(orig.root);
};
BSTArbre(const BSTNode<K, V>& r)
{
// TODO: revisar que este bien
this->_size = 0;
this->root = new BSTNode<K, V>(r);
};
virtual ~BSTArbre()
{
destroyRec(root);
}; | {
"domain": "codereview.stackexchange",
"id": 43376,
"lm_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++, tree, binary-search-tree",
"url": null
} |
c++, tree, binary-search-tree
virtual ~BSTArbre()
{
destroyRec(root);
};
void destroyRec(BSTNode<K, V> *n)
{
if (n != nullptr)
{
destroyRec(n->getLeft());
destroyRec(n->getRight());
delete n;
}
}
bool empty() const { return root == nullptr; }
int size() const { return _size; };
int height() const
{
if (empty())
return 0;
return root->height();
};
BSTNode<K, V> *insert(const K &k, const V &value) {
return _insert(this->root, nullptr, k, value, false);
// el padre de root es nullptr
}
BSTNode<K,V>* _insert(BSTNode<K, V> *r, BSTNode<K, V> *parent,
const K &k, const V &value, bool left) {
if (r == nullptr) {
r = new BSTNode<K, V>(k);
r->insertValue(value);
r->setParent(parent);
if (!left and parent != nullptr) {
parent->setRight(r);
}
else if (left and parent != nullptr) parent->setLeft(r);
return r;
}
else {
if (k > r->getKey()) {
return _insert(r->getRight(), r, k, value, false);
}
else return _insert(r->getLeft(), r, k, value, true);
}
}
const list<V> &valuesOf(const K &k) const
{
BSTNode<K, V> *n = search(k);
if (n == nullptr)
throw invalid_argument("Key not found!");
else
return n->getValues();
}
void printValues(const list<V> &values) const
{
for (auto it = values.begin(); it != values.end(); it++)
{
cout << *it << " ";
}
cout << endl;
} | {
"domain": "codereview.stackexchange",
"id": 43376,
"lm_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++, tree, binary-search-tree",
"url": null
} |
c++, tree, binary-search-tree
void printPreorder(const BSTNode<K, V> *n = nullptr) const
{
if (n != nullptr)
{
cout << n->getKey() << endl;
printValues(n->getValues());
printPreorder(n->getLeft());
printPreorder(n->getRight());
}
}
void printInorder(const BSTNode<K, V> *n = nullptr) const
{
if (n != nullptr)
{
printInorder(n->getLeft());
cout << n->getKey() << endl;
printValues(n->getValues());
printInorder(n->getRight());
}
}
void printPostorder(const BSTNode<K, V> *n = nullptr) const
{
if (n != nullptr)
{
printPostorder(n->getLeft());
printPostorder(n->getRight());
cout << n->getKey() << endl;
printValues(n->getValues());
}
}
BSTNode<K, V>* getRoot() {
return this->root;
}
const list<BSTNode<K, V> *> &getLeafNodes() const;
void printSecondLargestKey() const {
if (empty())
throw invalid_argument("Empty tree!");
else
printSecondLargestKey(root);
};
void printSecondLargestKey(BSTNode<K, V>* root) {
if (root->getRight() == nullptr) {
cout << root->getKey() << endl;
}
else {
printSecondLargestKey(root->getRight());
}
}
void mirrorTree() {
if (empty())
throw invalid_argument("Empty tree!");
else
mirrorTree(root);
};
void mirrorTree(BSTNode<K, V>* root) {
if (root->getLeft() != nullptr) {
mirrorTree(root->getLeft());
}
if (root->getRight() != nullptr) {
mirrorTree(root->getRight());
}
BSTNode<K, V>* temp = root->getLeft();
root->setLeft(root->getRight());
root->setRight(temp);
} | {
"domain": "codereview.stackexchange",
"id": 43376,
"lm_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++, tree, binary-search-tree",
"url": null
} |
c++, tree, binary-search-tree
protected:
BSTNode<K, V> *root;
BSTNode<K, V> *search(const K &k) const
{
BSTNode<K, V> *act = root;
while (act != nullptr)
{
if (act->getKey() < k)
{
act = act->getLeft();
}
else if (act->getKey() > k)
{
act = act->getRight();
}
else
return act;
}
return nullptr;
}
private:
int _size;
/* Mètodes auxiliars definiu aquí els que necessiteu */
};
#endif
Answer: Stick with a single language
I see you have some Catalan comments, and instead of BSTTree you write BSTArbre, but all other types, variables and member functions are named in English. I recommend you be consistent and write everything in English then; it's already required for someone to understand most of your code, and this way people who don't read Catalan can read your code without issues.
Don't make the destructors virtual
I see you made the destructors virtual. That is only necessary if you are writing a base class, however it doesn't look like your classes are meant to be inherited from, so remove the virtual keyword. Or in the case of BSTNode, remove the destructor entirely, since it's empty anyway.
You could make BSTNode part of BSTArbre
You can nest classes in C++. This allows you to write:
class BSTArbre {
public:
class Node {
...
};
...
BSTArbre(const BSTArbre &orig)
{
_size = orig._size;
root = new Node(orig.root);
};
...
protected:
Node *root;
...
}; | {
"domain": "codereview.stackexchange",
"id": 43376,
"lm_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++, tree, binary-search-tree",
"url": null
} |
c++, tree, binary-search-tree
Note how you no longer need to append <K, V> to the node type, as the inner class is part of the template as well. Note that you can also write BSTArbre without <K, V> inside the template, you don't have to repeat the template parameters for types that are within the template.
Unnecessary use of this->
It is almost never necessary to use this-> in C++. I would remove it everywhere. The exceptions might be functions like setParent(), but you could avoid it even there by renaming the function parameter in some way.
Prefer '\n' over std::endl
Prefer using '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually not necessary and might impact performance.
Make helper function private
There are several helper functions, like destroyRec() and _insert() that should only be called by other member functions of BSTArbre. Make them private, so they cannot be accidentily called. Keep the public API tidy. If you don't, you risk other code starting to call the helper functions, and that means it will be much harder to change your class later without breaking users.
Handle corner cases where possible
Why throw an exception when trying to mirror an empty tree? It seems natural that the result of mirroring an empty tree is just another empty tree, so I would return without any error instead.
size() always returns zero
You are never updating _size, so size() will always return zero. Either make sure you properly update _size whenever nodes get added or removed, or remove the member variable _size and let size() calculate it every time it is called.
Consider adding iterators | {
"domain": "codereview.stackexchange",
"id": 43376,
"lm_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++, tree, binary-search-tree",
"url": null
} |
c++, tree, binary-search-tree
Consider adding iterators
Your class has functions to print the contents to std::cout in pre/in/post-order. But what if I want to print to a file? What if I want to do something else with the values I've stored in the tree? Instead of adding more and more member functions, it would be much nicer if BSTArbre would just provide the means to iterate over the elements in the desired order, and let the caller decide what to do with it. Imagine being able to write:
for (auto& node: tree.preorder()) {
std::cout << node->getKey() << '\n';
} | {
"domain": "codereview.stackexchange",
"id": 43376,
"lm_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++, tree, binary-search-tree",
"url": null
} |
c++, tree, binary-search-tree
This will require some work; you would have to create a preorder() functions that returns a class that has begin() and end() member functions, those member functions should return iterators that iterate over the tree in the desired order.
I would start with just adding iterators to BSTArbre directly, such that you can write:
for (auto& node: tree) {
...
}
And just have that do an in-order iteration over the nodes. Find some tutorial about writing your own iterators.
This might seem a lot of work, but if you do this, then apart from range-for working with your class, many STL algorithms might also be able to work directly with your class.
Only store a single value in a node
Each BSTNode has a single key and a std::list of values. Maybe that's what you needed, but now you've had to add functions to manipulate that list, adding complexity to your classes. Instead, I would just store a single value:
V value;
And if you want to have a binary search tree that stores a list of values, you can simply have the caller make that explicit. For example, like so:
BSTArbre<int, std::list<int>> tree; | {
"domain": "codereview.stackexchange",
"id": 43376,
"lm_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++, tree, binary-search-tree",
"url": null
} |
python, performance, python-3.x
Title: Generate readable English words from given letters
Question: I was redirected from StackOverflow to your community in hope to get some help and improve my script.
The script receives letters as input and generates possible words, then extracts readable words from comparing my list items with file containing English words.
For example when I enter as input : eys
this will generate a list like:
["esy", "eys", "sey", "sye", "yes", "yse"]
and return the correct readable word "yes" as a final result.
The problem is when the length of input is greater than 8 characters it takes much time and I want to use Threading or Multiprocessing to reduce the latency.
My script
'''Create script that generate readable english words from given letters'''
from math import factorial
from itertools import permutations
from time import time, ctime
from threading import Thread
import multiprocessing as mp
class GetReadableWords:
def __init__(self, letters):
self.letters = letters
def prob_words(self):
self.comb = factorial(len(self.letters))
print('Nomber of combinitions that we have is : ', self.comb)
self.prob = [''.join(ltr) for ltr in permutations(self.letters)]
return self.prob
def chek_word(self):
result = []
for word in set(self.prob_words()):
with open('corncob_lowercase.txt', 'r') as f:
for line in f.readlines():
line = line.rstrip()
if word == line:
result.append(word)
else:
continue
f.close()
return result
'''def run(self):
with mp.Pool() as pool:
pool.map(self.chek_word(), self.prob, chunksize=1)'''
if __name__ == "__main__":
user_input = input('Enter your random characters : ')
sart_time = time()
print("starting time at : ", ctime(sart_time).split(' ')[3]) | {
"domain": "codereview.stackexchange",
"id": 43377,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x",
"url": null
} |
python, performance, python-3.x
c = GetReadableWords(user_input)
'''
threads = []
for word in c.prob_words():
p = mp.Process(target=c.chek_word(), args=(word,))
threads.append(p)
p.start()
for job in jobs:
job.join()
'''
#print(c.run())
print(c.chek_word())
end_time = time()
print("ending time at : ", ctime(end_time).split(' ')[3])
elaps_t = (end_time - sart_time)
print("time taken is : %.2f sec" % elaps_t)
Answer: Algorithm
The problem here is that your algorithm isn't scalable. For any given n-letter word, prob_words() generates n! candidate words. That's 40320 candidates for an 8-letter input.
To compound your performance problem, check_word() opens and scans the word list file once for each candidate word. Since the entire word list should fit quite comfortably memory on any general-purpose computer these days, you should read the word list just once.
So, forget about multithreading or multiprocessing. Work smarter, not harder! If you want to determine whether two words are anagrams of each other, all you need is to count or sort the letters. You don't need to generate a combinatoric explosion.
Design
GetReadableWords is not a well designed class. A good hint that the design is wrong is that classses (and objects) should be named like a noun, not a verb phrase. A second hint that you've gone wrong is that letters is really an input for just prob_words(), and not so much for chek_words().
In addition, neither prob_words() nor chek_words() is a good method name. Those names make no sense to me.
There is way too much code under if __name__ == "__main__". If you have that much code, then you should put it in a main() function and call it.
Suggested solution
'''Generate English words from given letters''' | {
"domain": "codereview.stackexchange",
"id": 43377,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x",
"url": null
} |
python, performance, python-3.x
class AnagramWordFinder:
def __init__(self, word_list_filename='corncob_lowercase.txt'):
self.vocab = {}
with open(word_list_filename) as f:
for line in f:
word = line.rstrip()
self.vocab.setdefault(''.join(sorted(word)), []).append(word)
def words_from_letters(self, letters):
return self.vocab.get(''.join(sorted(letters)), [])
def main():
word_finder = AnagramWordFinder()
print(word_finder.words_from_letters(input('Enter your characters: ')))
if __name__ == '__main__':
main()
Arguably, you don't even need a class, especially if you only need to ask for input only once.
def unscramble_letters(letters, word_list_filename='corncob_lowercase.txt'):
letters = ''.join(sorted(letters))
with open(word_list_filename) as f:
for line in f:
if ''.join(sorted(line.rstrip())) == letters:
yield line.rstrip()
if __name__ == '__main__':
print(list(unscramble_letters(input('Enter your characters: ')))) | {
"domain": "codereview.stackexchange",
"id": 43377,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x",
"url": null
} |
c, linked-list, stack
Title: Basic Stack Operations using Linked List in C
Question: I have made a few functions for some basic stack operations using linked lists. Please review my code and suggest some ways to increase its readability. I would also love to hear ideas on how to make my code more compact and simple.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void Traversal(struct node *ptr)
{
do
{
printf("The element is : %d\n", ptr->data);
ptr = ptr->next;
} while (ptr->next != NULL);
}
int isEmpty(struct node *top)
{
if (top == NULL)
{
return 1;
}
else
{
return 0;
}
}
int isFull(struct node *top)
{
struct node *n = malloc(sizeof(struct node *));
if (n == NULL)
{
return 1;
}
else
{
return 0;
}
free(n);
}
struct node *push(struct node *top, int x)
{
if (isFull(top))
{
printf("Stack Overflow\n");
}
else
{
struct node *n = malloc(sizeof(struct node));
n->data = x;
n->next = top;
top = n;
}
return top;
}
struct node *pop(struct node *top)
{
if (isEmpty(top))
{
printf("Stack Underflow\n");
}
else
{
struct node *n = top;
top = top->next;
free(n);
}
return top;
}
struct node *peek(struct node *top, int atPosition) // To view the value stored at a specific postion
{
struct node *ptr = top;
if (atPosition < 0)
{
printf("Invalid Index\n");
}
else
{
for (int i = 1; i < atPosition && ptr->next != NULL; i++)
{
ptr = ptr->next;
}
printf("The data at index %d is %d\n", atPosition, ptr->data);
}
free(ptr);
return top;
}
struct node *stackTop(struct node *top)
{
printf("The data stored in stack top is %d\n", top->data);
return top;
} | {
"domain": "codereview.stackexchange",
"id": 43378,
"lm_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, linked-list, stack",
"url": null
} |
c, linked-list, stack
struct node *stackBottom(struct node *top)
{
struct node *ptr = top;
while (ptr->next != NULL)
{
ptr = ptr->next;
}
printf("The data stored in stack bottom is %d\n", ptr->data);
free(ptr);
return top;
}
Answer: push() has undefined behaviour any time its malloc() returns a null pointer.
isFull() leaks memory (because the matching free() call is unreachable). Also, whether or not an allocation is successful tells us nothing about future allocations.
Instead of the broken and unreliable isFull(), work on the principle of attempting the action and taking appropriate recovery steps when it fails (sometimes described as easier to ask for forgiveness than permission, or EAFP):
struct node *push(struct node *top, int x)
{
struct node *n = malloc(sizeof *n);
if (!n) { return n; } /* failure */
n->data = x;
n->next = top;
top = n;
return top;
}
It's usually a bad idea for low-level library functions to generate output (especially to stdout) - you might want to use the code in a GUI program, and report errors via a status bar or pop-up window, for example. I would make it the caller's responsibility to examine the result and report it appropriately:
if (!push(top, x) {
fputs("Out of memory\n", stderr); /* Not "stack overflow" - that's misleading! */
} | {
"domain": "codereview.stackexchange",
"id": 43378,
"lm_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, linked-list, stack",
"url": null
} |
javascript, node.js, child-process
Title: Spawning a child process that is accessible in global scope through use of eval()
Question: So basically my question is what would be a better way to achieve my goal? The code below works fine but looks like it is extremely inefficient and could be achieved in a better way. The code essentially spawns several child processes with a dynamic name and because the eval() function is in the global scope, the child processes are also available in global scope. I need to have the processes available in a global scope since I want to be able to kill each process individually through use of commands. I hope I have explained everything as clear as needed. If there are any questions, feel free to ask.
Thanks.
processName = "child";
for (let a = 0; a < deviceAmount; a++) {
eval(
`
var ${processName + a} = child_process.spawn("node", ["slave.js", ${a + 1}]);
${processName + a}.stdout.setEncoding("utf8");
${processName + a}.stdout.on("data", function (data) {
process.stdout.write(data);
});
${processName + a}.stderr.setEncoding("utf8");
${processName + a}.stderr.on("data", function (data) {
process.stderr.write("ERROR: " + data);
});
${processName + a}.on("close", function (code) {
process.stdout.write("Exited with code: " + code);
});
`
);
}
Answer: Unless there's some reason the child processes need to have their own names in the global scope, the easier and safer solution would seem to be having a global array which the child processes are kept in. Something kind of like this:
// At the top level
var children = [];
// Possibly elsewhere
for (let a = 0; a < deviceAmount; a++) {
let child = child_process.spawn("node", ["slave.js", a + 1]); | {
"domain": "codereview.stackexchange",
"id": 43379,
"lm_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, node.js, child-process",
"url": null
} |
javascript, node.js, child-process
child.stdout.setEncoding("utf8");
child.stdout.on("data", function (data) {
process.stdout.write(data);
});
child.stderr.setEncoding("utf8");
child.stderr.on("data", function (data) {
process.stderr.write("ERROR: " + data);
});
child.on("close", function (code) {
process.stdout.write("Exited with code: " + code);
});
children.push(child);
} | {
"domain": "codereview.stackexchange",
"id": 43379,
"lm_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, node.js, child-process",
"url": null
} |
python, array, matrix
Title: Returning all divisors of a number as a matrix with N X 2 dimensions
Question: I have developed a class structure with methods to return a matrix from a single input array. The objective is to insert the middle value of the array so 2n remains in terms of array length. So there should be an even number always. The minimum length is provided by a prime number, which is not a product of two smaller numbers. Therefore, 5 should only have [1,5] as a list.
For example, if I want all divisors of the number 10 these are 1, 2, 5, 10, this is fine as its 2n in length. However, for an array with divisors of 16 I get 1, 2, 4, 8, 16 which is odd. The objective is to find all the divisors, then reduce the matrix when each divisor is found. The reduction is based on the outer 2 values, so [1, 16], [2,8], [4] but 4 on its own cannot make 16, so we insert 4 again to get [1, 2, 4, 4, 8, 16] which is 2(3) in length.
It's a little messy and so I wanted to receive a review on my code. It's my first time implementing a class with methods - I was thrilled to get this to work! I aim to implement logarithmic transformation and more in the future, so this was just the first step. It's very slow with numbers larger than 1,000,000
A few examples of the print output:
data = data_structure()
print(data.reshape_array(16),data.divisor(16),data.mid_value(16))
[[ 1 16] ,[ 1 2 4 8 16] ,[ 1 2 4 4 8 16]
[ 2 8]
[ 4 4]]
Here's what I have tried:
import numpy as np
"""
This should from any input create a numpy array and return a matrix that splits the array
into 2n parts. For odd array lengths, the mid-value is inserted to get an even value.
"""
class data_structure: | {
"domain": "codereview.stackexchange",
"id": 43380,
"lm_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, array, matrix",
"url": null
} |
python, array, matrix
class data_structure:
def divisor(self,number):
i = 0
divisors=[]
while i < number:
i+=1
for mult in range(0, number+1, i):
if number == mult:
divisors.append(i)
return np.asarray(divisors) #return the divisors as a numpy list
#ADD A MID VALUE:
def mid_value(self, number, no_array = False):
self._mid_value = self.divisor(number) #set _mid_value as the divisor list
if no_array == False:
if len(self._mid_value) %2 != 0:
mid_value = int((len(self._mid_value) - 1)/2)
for ind, middle in enumerate(self._mid_value):
if middle == self._mid_value[mid_value]:
test=np.insert(self._mid_value, ind, middle)
return test
else:
return self._mid_value
else:
pass | {
"domain": "codereview.stackexchange",
"id": 43380,
"lm_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, array, matrix",
"url": null
} |
python, array, matrix
def reshape_array(self,number):
_array_ = self.mid_value(number, no_array = False).copy()
array_ = self.mid_value(number, no_array = False)
len_arr_ = len(array_)
n = 0
reduced_arrays = []
if len_arr_ > 2:
while n < len_arr_: # less than total length of list
n += 2
if len_arr_ > n: #if the length of the array is greater than 2 do conditional
splice = len_arr_-(n-1) #we want to splice the outer two values and delete then reduce
reduced_arrays.append(array_[::splice])
search_reduce = np.searchsorted(array_, array_[::splice])
reduce_array = np.delete(array_, search_reduce)
array_ = reduce_array #this is to return to the spliced value when reduced
if len(array_) == 2:
reduced_arrays.append(array_) #we do not get the reduced values above so get the value two values
else:
continue
else:
return _array_
return np.column_stack(reduced_arrays).T #this should stack them and return a matrix with maximum 2 columns and n+=1 rows
``` | {
"domain": "codereview.stackexchange",
"id": 43380,
"lm_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, array, matrix",
"url": null
} |
python, array, matrix
Answer:
PEP8 specifies CapWords for class names. But you should figure out a better class name than DataStructure, since that's not very descriptive.
Your docstring starts out "from any input". You really mean "for a positive number". The docstring should come immediately after the class definition, so that DataStructure.doc (and other Python stuff) can find it.
To my math-inclined mind, if you say something is "2n", I assume that "n" is related to something, which in this case must be the input. So I would change "2n" to "even length"
I'm not too concerned with long lines if they're unavoidable. But if it's just a comment that makes the line too long, then split that up a bit.
i=0;while i<number:i+=1 is a really complicated way of writing for i in range(1,number+1).
Add a __name__=='__main__' guard, so that you can incorporate the unit test you showed us. You should also test when number is prime (so you have a 2x1 output), and a non-repeated value non-prime number (which is the most common case).
Your approach for finding divisors is really strange. It looks like you're trying to avoid using the % operator. We can just check if number%i==0. The method is now short enough that we can put that into a list expression: divisors = [ i for i in range(1,number+1) if number%i==0 ].
else:pass is useless.
You want to use booleans without explicitly comparing them to True or False. if no_array == False should just be if not no_array. But now we have a double negative, so lets change no_array into want_array. But:
mid_value by default modifies the array and then returns it. If I toggle the flag the other way, it creates a private variable that nothing else accesses. That's pointless, so lets just remove that possibility.
In a similar idea of removing ==False, you could consider changing if len(_mid_value) %2 != 0 to if len(_mid_value) %2.
Since nothing else needs to access _mid_value, lets not add it to the class. | {
"domain": "codereview.stackexchange",
"id": 43380,
"lm_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, array, matrix",
"url": null
} |
python, array, matrix
Since nothing else needs to access _mid_value, lets not add it to the class.
Instead of int((len(_mid_value) - 1)/2), we can just use len(_mid_value)//2, since we know the length is odd.
You're going through enumerate(_mid_value) to find a specific value at a specific index. You already know the index (and hence the value), so you don't need the for loop. (This is the second time you've used a for loop just to do an action for a single entry. Try to avoid that.)
The function mid_value has a variable mid_value. I'm going to rename the latter to mid_index.
If len_arr_<2, then _array_ and array_ are the same thing. We can return array_ and remove _array_. But in that case, you get a 1-d list, whereas with longer lists you get a 2-d list. We should change that so that you always get a 2-d list.
np.column_stack().T is the same as np.row_stack()
Don't add a comment if it's repeating what the code is doing. At best this is redundant and distracting (your first three comments). At worst, it's different than what the code says, leaving you wondering if the comment is out of date or actually useful ("if the length of the array is greater than 2 do conditional").
If mid_value overwrites _mid_value instead of assigning to test, then you can always return _mid_value and don't need to worry about the else.
Your function names are strange. divisor and mid_value sound like a single number, not a list of them. reshape_array sounds like it takes an array and reshapes it, not takes a number and returns the reshaped array. Instead, I'm going to rename divisor to get_divisors, mid_value_ to get_divisors_with_mid_value, and reshape_array to get_divisors_as_matrix.
divisor doesn't need self, so lets mark it as a @staticmethod. The only point of self in the other two is to be able to call another method of the class. So they can also become @staticmethod. But: | {
"domain": "codereview.stackexchange",
"id": 43380,
"lm_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, array, matrix",
"url": null
} |
python, array, matrix
You're not really using anything as a class. It's just three related functions. Personally, I'd skip the class and just make them functions (especially if you're only ever really using the 2xn matrix form). But let's leave them as a class for instructional sake. In that case, it makes more sense to pass the number to the constructor and make the arrays as part of the initialization (this means the functions aren't static after all). We'll move all the functions into the initialization (they're not that long anymore), and create properties with getters.
search_reduce is the indices 0 and len-1. It should be better named, and you shouldn't use np.searchsorted when you know what the outcome will be. But that whole section is really convoluted. Since you know it's going to be the outer two values, you can just use array_[0] and array_[-1] and delete those (and because its numpy, we can take and delete in one command each). It's now generic enough that you don't need the if len_arr_ > 2 anymore: while array_.size: reduced_arrays.append(array_[[0,-1]]); array_ = np.delete(array_,[0,-1]).
Even better: we know that the first column will be the first half of the array, and the second column will be the last half of the array, but in the other order. Let's just do that.
Even better: if number is big, then you don't want to take too much time checking all the intermediate values for divisors. You can use a shortcut: when you find a divisor, you know that number/divisor is also a divisor. And if you've been looking from 1 onward, then number/divisor is already decreasing. (If number is really big, it will be better to find the divisors using the prime factorization of number, but that's a much more complicated topic.)
The middle value gets repeated when number is a perfect square. This doesn't really factor into my code, but it should be stated. | {
"domain": "codereview.stackexchange",
"id": 43380,
"lm_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, array, matrix",
"url": null
} |
python, array, matrix
The result:
import numpy as np
class DataStructure:
"""
For a positive number, this should create a numpy array of all divisors and
return a matrix that splits the array into 2 parts. For odd array lengths,
the mid-value is repeated to get an even length.
"""
def __init__(self,number):
_small_divisors = np.asarray([ i for i in range(1,int(number**.5)+1) if number%i==0 ])
_large_divisors = number//_small_divisors
self.divisors_with_mid_value = np.concatenate([_small_divisors,[*reversed(_large_divisors)]])
self.divisors_as_matrix = np.column_stack([_small_divisors,_large_divisors])
if ( _small_divisors[-1] == _large_divisors[-1] ):
self.divisors = np.concatenate([_small_divisors[:-1],[*reversed(_large_divisors)]])
else:
self.divisors = self.divisors_with_mid_value
if __name__=='__main__':
for number in (7,16,30):
data = DataStructure(number)
print(data.divisors_as_matrix,data.divisors,data.divisors_with_mid_value)
'''
[[1 7]] [1 7] [1 7]
[[ 1 16]
[ 2 8]
[ 4 4]] [ 1 2 4 8 16] [ 1 2 4 4 8 16]
[[ 1 30]
[ 2 15]
[ 3 10]
[ 5 6]] [ 1 2 3 5 6 10 15 30] [ 1 2 3 5 6 10 15 30]
''' | {
"domain": "codereview.stackexchange",
"id": 43380,
"lm_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, array, matrix",
"url": null
} |
c++, object-oriented
Title: Minesweeper implementation in C++
Question: I have implemented minesweeper in C++. You can get a box by entering the coordinates -row number, then column; starting from 0- of said box (eg: "0 0"); you can mark a box as a bomb by adding the prefix "mark" (eg: "mark 0 0"); you can unflag a box by adding the prefix "unmark" (eg: "unmark 0 0"). The game ends when all non-bomb boxes have been checked & all bombs have been marked. Any feedback/ideas on how to improve my code would be very much appreciated.
main.cpp
#include "Game.h"
int main()
{
Game* g = new Game(16, 40);
g->playGame();
return 0;
}
Game.h
#ifndef GAME_H
#define GAME_H
#include "Grid.h"
#include <string>
class Game
{
private:
Grid* grid;
int** closedSet;
int len;
int foundNum, closedSetSize;
public:
Game(int n, int b);
~Game();
void printClosedSet();
void playGame();
private:
void clearSpace(int n, int m);
};
#endif // GAME_H
Game.cpp
#include "Game.h"
#include <queue>
#include <cstddef>
#include <iomanip>
#include <cstring>
#include <iostream>
Game::Game(int n, int b) : foundNum(0), closedSetSize(0) {
grid = new Grid(n, b);
len = grid->getSize();
closedSet = new int*[len];
for(int i = 0; i < len; i++) {
closedSet[i] = new int[len];
std::memset(closedSet[i], 0, len * sizeof(int));
}
}
Game::~Game() {
delete grid;
for(int i = 0; i < len; i++)
delete[] closedSet[i];
delete[] closedSet;
} | {
"domain": "codereview.stackexchange",
"id": 43381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
void Game::printClosedSet() {
std::cout << " ";
for(int i = 0; i < len; i++) {
std::cout << std::setw(3) << i;
}
std::cout << std::endl;
std::cout << " ";
for(int i = 0; i < len; i++) {
std::cout << "---";
}
std::cout << std::endl;
for(int i = 0; i < len; i++) {
std::cout << std::setw(3) << i << "|";
for(int j = 0; j < len; j++) {
if(closedSet[i][j] == 1) {
std::cout << std::setw(3) << grid->getNum(i, j);
} else if(closedSet[i][j] == 0) {
std::cout << std::setw(3) << "-";
} else std::cout << std::setw(3) << "*";
}
std::cout << std::endl;
}
} | {
"domain": "codereview.stackexchange",
"id": 43381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
void Game::playGame() {
std::string s;
int n, m;
while(true) {
printClosedSet();
std::cin >> s;
if((s.find_first_not_of("0123456789") == std::string::npos) && ((std::stoi(s) <= len-1) && (std::stoi(s) >= 0))) {
n = std::stoi(s);
s = "placeholder";
while(s.find_first_not_of("0123456789") != std::string::npos) {
std::cin >> s;
if((s.find_first_not_of("0123456789") == std::string::npos) &&
((std::stoi(s) > len-1) || (std::stoi(s) < 0))) s = "placeholder";
}
m = std::stoi(s);
if(closedSet[n][m] == 0) {
if(grid->getNum(n, m) < 0) {
grid->printBombs(closedSet);
std::cout << "YOU HAVE LOST" << std::endl;
break;
}
clearSpace(n, m);
}
} else if (s == "mark" || s == "unmark"){
std::string temp = "placeholder";
while(temp.find_first_not_of("0123456789") != std::string::npos) {
std::cin >> temp;
if((temp.find_first_not_of("0123456789") == std::string::npos) &&
(std::stoi(temp) > len-1)) temp = "placeholder";
}
n = std::stoi(temp);
temp = "placeholder";
while(temp.find_first_not_of("0123456789") != std::string::npos) {
std::cin >> temp;
if((temp.find_first_not_of("0123456789") == std::string::npos) &&
(std::stoi(temp) > len-1)) temp = "placeholder";
}
m = std::stoi(temp);
if((s == "mark") && (closedSet[n][m] == 0)) {
closedSet[n][m] = 3;
if(grid->getNum(n, m) < 0) ++foundNum;
} else if((s == "unmark") && (closedSet[n][m] == 3)) {
closedSet[n][m] = 0;
if(grid->getNum(n, m) < 0) --foundNum;
} | {
"domain": "codereview.stackexchange",
"id": 43381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
if(grid->getNum(n, m) < 0) --foundNum;
}
} else continue;
if((grid->getBombNum() == foundNum) && (closedSetSize == len*len - grid->getBombNum())) {
printClosedSet();
std::cout << "YOU HAVE WON" << std::endl;
break;
}
}
grid->clearGrid();
grid->generateGrid();
for(int i = 0; i < len; i++)
std::memset(closedSet[i], 0, len * sizeof(int));
foundNum = 0;
closedSetSize = 0;
} | {
"domain": "codereview.stackexchange",
"id": 43381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
void Game::clearSpace(int n, int m) {
std::queue<std::pair<int, int>> q;
if(closedSet[n][m] == 0) ++closedSetSize;
closedSet[n][m] = 1;
if(grid->getNum(n, m) == 0) q.push(std::make_pair(n, m));
while(!q.empty()) {
n = q.front().first;
m = q.front().second;
closedSet[n][m] = 1;
if((n < len-1) && (closedSet[n+1][m] == 0)) {
if(grid->getNum(n+1, m) == 0)
q.push(std::make_pair(n+1, m));
closedSet[n+1][m] = 1;
++closedSetSize;
}
if((n < len-1) && (m < len-1) && (closedSet[n+1][m+1] == 0)) {
if(grid->getNum(n+1, m+1) == 0)
q.push(std::make_pair(n+1, m+1));
closedSet[n+1][m+1] = 1;
++closedSetSize;
}
if((n < len-1) && (m > 0) && (closedSet[n+1][m-1] == 0)) {
if(grid->getNum(n+1, m-1) == 0)
q.push(std::make_pair(n+1, m-1));
closedSet[n+1][m-1] = 1;
++closedSetSize;
}
if((m < len-1) && (closedSet[n][m+1] == 0)) {
if(grid->getNum(n, m+1) == 0)
q.push(std::make_pair(n, m+1));
closedSet[n][m+1] = 1;
++closedSetSize;
}
if((n > 0) && (closedSet[n-1][m] == 0)) {
if(grid->getNum(n-1, m) == 0)
q.push(std::make_pair(n-1, m));
closedSet[n-1][m] = 1;
++closedSetSize;
}
if((n > 0) && (m < len-1) && (closedSet[n-1][m+1] == 0)) {
if(grid->getNum(n-1, m+1) == 0)
q.push(std::make_pair(n-1, m+1));
closedSet[n-1][m+1] = 1;
++closedSetSize;
}
if((n > 0) && (m > 0) && (closedSet[n-1][m-1] == 0)) {
if(grid->getNum(n-1, m-1) == 0)
q.push(std::make_pair(n-1, m-1));
closedSet[n-1][m-1] = 1;
++closedSetSize;
} | {
"domain": "codereview.stackexchange",
"id": 43381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
if((m > 0) && (closedSet[n][m-1] == 0)) {
if(grid->getNum(n, m-1) == 0)
q.push(std::make_pair(n, m-1));
closedSet[n][m-1] = 1;
++closedSetSize;
}
q.pop();
}
}
Grid.h
#ifndef GRID_H
#define GRID_H
#include <vector>
class Grid
{
private:
int** grid;
int len;
int bombNum;
std::vector<std::pair<int, int>> s;
public:
Grid(int n, int b);
~Grid();
void printBombs(int** closedSet);
void generateGrid();
void clearGrid();
int getNum(int n, int m) {return grid[n][m];}
int getSize() {return len;}
int getBombNum() {return bombNum;}
};
#endif // GRID_H
Grid.cpp
#include "Grid.h"
#include <iostream>
#include <cstring>
#include <algorithm>
#include <chrono>
#include <random>
#include <iomanip>
Grid::Grid(int n, int b) : len(n), bombNum(b) {
grid = new int*[len];
s.reserve(len);
for(int i = 0; i < len; i++) {
for(int j = 0; j < len; j++)
s.push_back(std::make_pair(i, j));
grid[i] = new int[len];
std::memset(grid[i], 0, len * sizeof(int));
}
generateGrid();
}
Grid::~Grid() {
for(int i = 0; i < len; i++)
delete[] grid[i];
delete[] grid;
} | {
"domain": "codereview.stackexchange",
"id": 43381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
Grid::~Grid() {
for(int i = 0; i < len; i++)
delete[] grid[i];
delete[] grid;
}
void Grid::printBombs(int** closedSet) {
std::cout << " ";
for(int i = 0; i < len; i++) {
std::cout << std::setw(3) << i;
}
std::cout << std::endl;
std::cout << " ";
for(int i = 0; i < len; i++) {
std::cout << "---";
}
std::cout << std::endl;
for(int i = 0; i < len; i++) {
std::cout << std::setw(3) << i << "|";
for(int j = 0; j < len; j++) {
if(grid[i][j] < 0) {
std::cout << std::setw(3) << "X";
} else if(closedSet[i][j] == 1) {
std::cout << std::setw(3) << grid[i][j];
} else std::cout << std::setw(3) << "-";
}
std::cout << std::endl;
}
}
void Grid::generateGrid() {
shuffle(s.begin(),
s.end(),
std::default_random_engine(std::chrono::system_clock::now().time_since_epoch().count()));
for(int i = 0; i < bombNum; i++) {
int randRow = s[i].first;
int randCol = s[i].second;
grid[randRow][randCol] = -1;
if(randRow > 0) {
if(grid[randRow-1][randCol] >= 0)
++grid[randRow-1][randCol];
if((randCol > 0) && (grid[randRow-1][randCol-1] >= 0))
++grid[randRow-1][randCol-1];
if((randCol < len-1) && (grid[randRow-1][randCol+1] >= 0))
++grid[randRow-1][randCol+1];
}
if(randRow < len-1) {
if(grid[randRow+1][randCol] >= 0)
++grid[randRow+1][randCol];
if((randCol > 0) && (grid[randRow+1][randCol-1] >= 0))
++grid[randRow+1][randCol-1];
if((randCol < len-1) && (grid[randRow+1][randCol+1] >= 0))
++grid[randRow+1][randCol+1];
}
if((randCol > 0) && (grid[randRow][randCol-1] >= 0))
++grid[randRow][randCol-1]; | {
"domain": "codereview.stackexchange",
"id": 43381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
if((randCol < len-1) && (grid[randRow][randCol+1] >= 0))
++grid[randRow][randCol+1];
}
}
void Grid::clearGrid() {
for(int i = 0; i < len; i++) {
for(int j = 0; j < len; j++)
grid[i][j] = 0;
}
}
Answer: Unnecessary memory allocations
You are using new and delete in many places where it is not necessary to do any memory allocations. Starting in main(), you can just write:
Game g(16, 40);
g.playGame();
Apart from slightly less typing, this also prevents the inevitable memory leak when you forget to delete what you just allocated.
The same goes for Game::grid, this doesn't have to be a pointer, it can be a regular member variable of Game.
Let STL containers manage memory for you
In those cases where you do need to allocate memory, try to avoid using manual new and delete. In particular, for arrays of which you don't know the size up front, you can use std::vector. It will automatically allocate and deallocate memory for you. If you have a two-dimensional array, you could make a vector of vectors, like so:
class Grid
{
std::vector<std::vector<int>> grid;
...
};
Grid::Grid(int n, int b): grid(n, std::vector<int>(n)), ... {
...
}
However, that brings me to the following:
Allocate a single array/vector for all elements of a 2D grid
Vectors of vectors, or dynamically allocated arrays of dynamically allocated arrays as you did in your code, are not efficient. To get to a certain element, the CPU would have to follow two pointers, which is inefficient. However, CPUs nowadays are great at multiplications and additions, so it is actually faster to allocate a 1D vector, and calculate yourself how to position 2D elements in it. For example:
class Grid
{
std::vector<int> grid;
};
...
Grid::Grid(int n, int b): grid(n * n), ... {
...
}
...
void Grid::printBombs(...) {
...
if (grid[i * len + j] < 0)
...
} | {
"domain": "codereview.stackexchange",
"id": 43381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
To avoid having to write that formula all the time, consider making a member function that takes the row and column position, and returns a reference to the desired grid element:
int& Grid::gridAt(int row, int col) {
return grid[row * len + col];
}
Then you can just write:
if (gridAt(i, j) < 0)
...
Once you have a one-dimensional vector, some other things become easier as well. For example,
Make use of STL algorithms
If you use STL containers, STL algorithms can now be used as well. For example, to clear the grid you can use [std::fill()][3]:
void Grid::clearGrid() {
std::fill(grid.begin(), grid.end(), 0);
}
Think of std::fill() and std::fill_n() as C++'s version of C's memset(), and there's std::copy() and std::copy_n to replace memcpy(), but the algorithms can do much more than that, saving you the trouble of having to implement them yourself. To get more familiar with them, I recommend you read or watch The World Map of C++ STL Algorithms.
Simplify parsing the input
Parsing the input is a bit complicated in your code, mainly because you either allow coordinates without any prefix, or coordinates with a prefix to be entered. Because you can't be sure if the first thing you read is going to be a number or a prefix, you have to read it as a std::string, check what it is, then use std::stoi() to convert it to a number if necessary. If you would change the way you read the input such that you always have to prefix the coordinates, and use the prefix "reveal" or "get" to reveal what is on a given grid position, you can greatly simplify parsing the input:
while (true) {
printClosedSet();
std::string command;
int row;
int col;
std::cin >> command >> row >> col;
if (command == "reveal") {
...
}
...
} | {
"domain": "codereview.stackexchange",
"id": 43381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
c++, object-oriented
std::cin >> command >> row >> col;
if (command == "reveal") {
...
}
...
}
Consider using emplace() instead of push() where possible
Many containers have both push() and emplace() functions. The latter is sometimes more efficient and convenient. In particular, it reserves room for the new element and constructs it in place, and the arguments to emplace() are passed to the constructor of the value type of the container. This allows you to write:
std::queue<std::pair<int, int>> q;
...
q.emplace(n, m);
Note how you no longer need to use std::make_pair().
Create a struct Cell
You are actually keeping track of the state of each location on the board using two grids; one is grid and the other closedSet. It's also not so nice to overload ints to mean different things. Consider creating a struct Cell that holds all information of a grid cell:
struct Cell {
int adjacentBombs;
bool bomb;
bool revealed;
bool marked;
};
The you just need one datastructure to hold all information about the board:
std::vector<Cell> grid;
Prefer '\n' instead of std::endl
Prefer using '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually not necessary and has performance implications. | {
"domain": "codereview.stackexchange",
"id": 43381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented",
"url": null
} |
python, hash-map, immutability
Title: Implement a Python frozenmap
Question: There are frozenset in Python, but no frozendict or frozenmap. I tried to implement it (Don't care too much about class naming, because I want to try to imitate the standard library) with frozenset, which implement O(1) time to find elements, and only calculates hash values according to all keys. The effect is almost perfect:
from typing import Any, NamedTuple
from collections.abc import Hashable, Mapping, Iterable, Iterator
from operator import itemgetter
from itertools import starmap, repeat, chain
_value = None
class kv_pair(NamedTuple):
key: Hashable
value: Any
def __eq__(self, other):
if isinstance(other, tuple):
return self.key == other[0]
elif isinstance(other, Hashable):
global _value
_value = self.value
return self.key == other
else:
return NotImplemented
def __hash__(self):
return hash(self.key)
def __str__(self):
return tuple.__repr__(self)
def __repr__(self):
return tuple.__repr__(self)
class frozenmap(Mapping):
__slots__ = '_frozen'
def __init__(self, iterable: Iterable = ()):
self._frozen = frozenset(starmap(kv_pair, iterable))
def keys(self) -> Iterable[Hashable]:
return frozenmap_keys(self._frozen)
def values(self) -> Iterable:
return frozenmap_values(self._frozen)
def items(self) -> Iterable[tuple[Hashable, Any]]:
return frozenmap_items(self._frozen)
def to_dict(self) -> dict:
return dict(self._frozen)
def get(self, key: Hashable, default=None) -> Any:
if key in self._frozen:
return _value
else:
return default
def copy(self) -> 'frozenmap':
return self.__class__(self._frozen)
@classmethod
def fromkeys(cls, keys, val=None) -> 'frozenmap':
return cls(zip(keys, repeat(val))) | {
"domain": "codereview.stackexchange",
"id": 43382,
"lm_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, hash-map, immutability",
"url": null
} |
python, hash-map, immutability
@classmethod
def from_dict(cls, dct: dict) -> 'frozenmap':
return cls(dct.items())
def __copy__(self) -> 'frozenmap':
return self.__class__(self._frozen)
def __bool__(self) -> bool:
return bool(self._frozen)
def __iter__(self) -> Iterator[tuple[Hashable, Any]]:
return map(itemgetter(0), self._frozen)
def __len__(self) -> int:
return len(self._frozen)
def __str__(self) -> str:
return self.__class__.__name__ + '({' + ', '.join(f'{repr(k)}: {repr(v)}'for k, v in self._frozen) + '})'
def __repr__(self) -> str:
return self.__class__.__name__ + '({' + ', '.join(f'{repr(k)}: {repr(v)}'for k, v in self._frozen) + '})'
def __eq__(self, other) -> bool:
if isinstance(other, Mapping):
try:
return all(other[k] == v for k, v in self._frozen)
except KeyError:
return False
else:
return False
def __hash__(self) -> int:
return hash(self._frozen)
def __contains__(self, item: Hashable) -> bool:
return item in self._frozen
def __getitem__(self, key: Hashable) -> Any:
if key in self._frozen:
return _value
else:
raise KeyError(key)
def __or__(self, other) -> 'frozenmap':
if isinstance(other, frozenmap):
return self.__class__(chain(self._frozen, other._frozen))
elif isinstance(other, dict):
return self.__class__(chain(self._frozen, other.items()))
else:
return NotImplemented
def __ror__(self, other) -> dict:
if isinstance(other, dict):
return dict(chain(self._frozen, other.items()))
else:
return NotImplemented
class frozenmap_keys:
__slots__ = '_frozen'
def __init__(self, frozen: frozenset[kv_pair]):
self._frozen = frozen | {
"domain": "codereview.stackexchange",
"id": 43382,
"lm_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, hash-map, immutability",
"url": null
} |
python, hash-map, immutability
def __init__(self, frozen: frozenset[kv_pair]):
self._frozen = frozen
def __str__(self) -> str:
return self.__class__.__name__ + '([' + ', '.join(repr(item.key) for item in self._frozen) + '])'
def __repr__(self) -> str:
return self.__class__.__name__ + '([' + ', '.join(repr(item.key) for item in self._frozen) + '])'
def __iter__(self) -> Iterator[Hashable]:
return map(itemgetter(0), self._frozen)
class frozenmap_values:
__slots__ = '_frozen'
def __init__(self, frozen: frozenset[kv_pair]):
self._frozen = frozen
def __str__(self) -> str:
return self.__class__.__name__ + '([' + ', '.join(repr(item.value) for item in self._frozen) + '])'
def __repr__(self) -> str:
return self.__class__.__name__ + '([' + ', '.join(repr(item.value) for item in self._frozen) + '])'
def __iter__(self) -> Iterator:
return map(itemgetter(1), self._frozen)
class frozenmap_items:
__slots__ = '_frozen'
def __init__(self, frozen: frozenset[kv_pair]):
self._frozen = frozen
def __str__(self) -> str:
return self.__class__.__name__ + '([' + ', '.join(map(repr, self._frozen)) + '])'
def __repr__(self) -> str:
return self.__class__.__name__ + '([' + ', '.join(map(repr, self._frozen)) + '])'
def __iter__(self) -> Iterator[tuple[Hashable, Any]]:
return map(tuple, self._frozen) | {
"domain": "codereview.stackexchange",
"id": 43382,
"lm_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, hash-map, immutability",
"url": null
} |
python, hash-map, immutability
def __iter__(self) -> Iterator[tuple[Hashable, Any]]:
return map(tuple, self._frozen)
Some test:
>>> a = {'123': '456', '789': 123}
>>> b = {'123': 456, 789: '123'}
>>> fa = frozenmap.from_dict(a)
>>> fb = frozenmap.from_dict(b)
>>> fa
frozenmap({'123': '456', '789': 123})
>>> fb
frozenmap({789: '123', '123': 456})
>>> fa.items()
frozenmap_items([('123', '456'), ('789', 123)])
>>> fa.keys()
frozenmap_keys(['123', '789'])
>>> fa.values()
frozenmap_values(['456', 123])
>>> a | b
{'123': 456, '789': 123, 789: '123'}
>>> fa | b
frozenmap({'789': 123, '123': '456', 789: '123'})
>>> fa | fb
frozenmap({'123': '456', 789: '123', '789': 123})
>>> a | fb
{'123': '456', 789: '123', '789': 123}
>>> a == fa
True
>>> a | fb == fa | fb
True
>>> fa['789']
123
>>> fb['123']
456
>>> ddict = {fa: a, fb: b}
>>> ddict
{frozenmap({'789': 123, '123': '456'}): {'123': '456', '789': 123}, frozenmap({789: '123', '123': 456}): {'123': 456, 789: '123'}}
>>> ddict[fa]
{'123': '456', '789': 123}
The implementation of the whole class relies on storing the key value pairs into the frozenset, and only judging the equality of the two key value pairs through the key.
But the implementation of __getitem__ method is not good, the key to implementing is to save the value of kv_pair in a global variable when a key is compared with it, and then retrieve it from the global variable:
class kv_pair:
...
def __eq__(self, other):
if isinstance(other, tuple):
return self.key == other[0]
elif isinstance(other, Hashable):
global _value
_value = self.value
return self.key == other
else:
return NotImplemented
...
class frozenmap(Mapping):
...
def __getitem__(self, key: Hashable) -> Any:
if key in self._frozen:
return _value
else:
raise KeyError(key)
... | {
"domain": "codereview.stackexchange",
"id": 43382,
"lm_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, hash-map, immutability",
"url": null
} |
python, hash-map, immutability
Although this should not be a problem in single threaded programs, this implementation makes me very uncomfortable. The root of the problem is that I can't get the reference of the element in the frozenset according to the key from frozenset. I haven't found a way to get it. Is it possible to get it? Or, is there a better way to implement frozenmap? I found people always replace it with sorted tuple from Stack Overflow, but this will lose the advantage of dictionary O(1) time looking up elements. | {
"domain": "codereview.stackexchange",
"id": 43382,
"lm_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, hash-map, immutability",
"url": null
} |
python, hash-map, immutability
Answer: Library code cannot resort to global variable hacks. You are attempting to
implement a data structure. That's a bedrock kind of library code. As such, it
cannot resort to crazy mechanisms like setting a global variable as a sneaky
workaround for a situation where you need to recover a key-value linkage that
was severed during class instantiation.
When you find yourself tempted to do something crazy, stop and do some
research. Python doesn't have a frozenmap, but it's not a new idea. PEP
416 explored the idea as a formal proposal.
ActiveState has a code recipe
for a frozendict. There are third-party frozendict
implementations. Those links
are fairly easy to read, understand, and learn from. In particular, the PEP
contains links to a variety of other implementations worth looking at. While I
explored the topic briefly, I also came across an idea for an immutable
dict
based on Python's new-ish MappingProxyType.
Unhelpful type proliferation: kv_pair, frozenmap_keys, frozenmap_values,
frozenmap_items. None of these types seem to help very much. Remember: a
frozenmap is immutable. Given that, a tuple would be a perfectly acceptable way
to represent its keys. Ditto for its values. And its items could just be a
tuple of tuples. As for kv_pair, it's not doing anything useful other than
supporting the global variable hack via its unusual implementation of
__eq__().
You don't need to destroy the underlying key-value mappings. You can
receive the inputs, build a dict, tuck that dict away as a quasi-private
attribute, and then implement the rest of the needed behavior: hashing,
iteration, lookup, raising on attempts to mutate, and so forth. Some of the
implementations noted above achieve such things by inheriting from dict,
disabling methods that mutate, and implementing a hashing approach. Others do
it by building a class from the ground up with the desired dict API. Either
way, you can still use a Python dict behind the scenes for underlying data | {
"domain": "codereview.stackexchange",
"id": 43382,
"lm_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, hash-map, immutability",
"url": null
} |
python, hash-map, immutability
way, you can still use a Python dict behind the scenes for underlying data
storage. Alternatively, if you really want to go hardcore, implement your own
hashmap for storage. Either way, you'll be using something dict-like (rather
than destroying the relationships and then hacking your way back to
recover lost linkages). | {
"domain": "codereview.stackexchange",
"id": 43382,
"lm_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, hash-map, immutability",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.