text stringlengths 1 2.12k | source dict |
|---|---|
c, mathematics, bitwise
Handle the first / last even in range more elegantly.
Inline the entire function.
Answer: The first implementation mixes integer and floating-point arithmetic. I definitely would avoid that.
The other two versions both use >> on a signed type (int), which is implementation-defined behaviour, so not a good choice for a portable program. Consider % 2 and / 2 instead of using bitwise operations, but remember which direction signed division rounds towards.
I think that testing bottom > top before applying the adjustment to make both numbers even is a mistake, and I think it causes erroneous results when bottom and top are the same odd value (which should return 0 as result).
In all cases, I would recommend adding a set of unit tests to ensure the correct results are returned. Make sure the tests include at least the following:
an empty range
a single even number
a single odd number
a range beginning with a positive even number
a range beginning with a positive odd number
a range beginning with a negative even number
a range beginning with a negative odd number
a range ending with a positive even number
a range ending with a positive odd number
a range ending with a negative even number
a range ending with a negative odd number
a range that includes 0
To answer your specific questions:
I don't think it can be much more elegant. You might choose to simply adjust the parameter values (with += or -=) rather than declaring new variables.
Any decent optimising compiler will inline such functions whenever the benefit is worth the cost. The whole point of high-level languages is to let the machine take such decisions rather than requiring the programmer to do so. | {
"domain": "codereview.stackexchange",
"id": 44583,
"lm_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, mathematics, bitwise",
"url": null
} |
c++, game-of-life, sfml
Title: An implementation of Conway's Game of Life using C++ and SFML
Question: I recently started learning C++ again, and I wrote a simple version of Conway's Game of Life. This version doesn't use 2 buffers to transfer changes over to the main view. Instead, it uses a stack of changes that are applied then drawn.
I'd like some feedback on how to improve my code.
Controls are:
Space - Start/Stop the simulation
E - Clear the board when simulation is stopped
R - Randomize the board when simulation is stopped
Left Click - Toggle cells when simulation is stopped
What it should look like:
The Code:
main.cpp
#include "gol.hpp"
#include <SFML/Graphics.hpp>
int main() {
const int boardWidth = 80;
const int boardHeight = 60;
const int cellWidth = 10;
const int cellHeight = 10;
bool doUpdate = false;
sf::RenderWindow window(sf::VideoMode(boardWidth*cellWidth, boardHeight*cellHeight), "Game Of Life");
window.setFramerateLimit(30);
GameOfLife game(boardWidth,boardHeight,cellWidth,cellHeight); | {
"domain": "codereview.stackexchange",
"id": 44584,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game-of-life, sfml",
"url": null
} |
c++, game-of-life, sfml
GameOfLife game(boardWidth,boardHeight,cellWidth,cellHeight);
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyReleased:
if (event.key.code == sf::Keyboard::Space) {
doUpdate = !doUpdate;
}
else if (event.key.code == sf::Keyboard::E) {
game.m_clearCells();
}
else if (event.key.code == sf::Keyboard::R) {
game.m_randomizeCells();
}
break;
case sf::Event::MouseButtonPressed:
if (!doUpdate && event.mouseButton.button == sf::Mouse::Left) {
int x = (double)event.mouseButton.x / cellWidth;
int y = (double)event.mouseButton.y / cellHeight;
if (x >= 0 && x <= boardWidth && y >= 0 && y <= boardHeight) {
game.m_flipCell(x, y);
}
}
break;
default:
break;
}
}
window.clear();
if (doUpdate) {
game.m_updateCells();
game.m_drawCellChanges(window);
}
else {
game.m_drawCells(window);
}
window.display();
}
return 0;
}
gol.hpp
#ifndef GOL_HPP_
#define GOL_HPP_
#include <stack>
#include <utility>
#include <SFML/Graphics.hpp>
typedef struct {
int live;
sf::RectangleShape shape;
} Cell;
typedef std::pair<int, int> CellChange;
typedef std::stack<CellChange> CellChanges;
class GameOfLife {
Cell* cells;
CellChanges changes;
int width, height, size; | {
"domain": "codereview.stackexchange",
"id": 44584,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game-of-life, sfml",
"url": null
} |
c++, game-of-life, sfml
class GameOfLife {
Cell* cells;
CellChanges changes;
int width, height, size;
int n_getIndex(int x, int y);
int n_countNeighbors(int x, int y);
int n_wrapValue(int v, int max);
public:
GameOfLife(int width_, int height_, int cellWidth, int cellHeight);
~GameOfLife();
void m_drawCells(sf::RenderWindow& window);
void m_drawCellChanges(sf::RenderWindow& window);
void m_updateCells();
void m_flipCell(int x, int y);
void m_randomizeCells();
void m_clearCells();
};
#endif
gol.cpp
#include <cstdlib>
#include <ctime>
#include "gol.hpp"
int GameOfLife::n_wrapValue(int v, int max) {
if (v == -1) return max - 1;
return v % max;
}
int GameOfLife::n_getIndex(int x, int y) {
return y * width + x;
}
int GameOfLife::n_countNeighbors(int x, int y) {
int neighbors = 0;
// Don't count the current cell
neighbors -= cells[n_getIndex(x, y)].live;
for (int oy = -1; oy < 2; oy++) {
for (int ox = -1; ox < 2; ox++) {
// Wrap the coordinates around the board
int cx = n_wrapValue(x + ox, width);
int cy = n_wrapValue(y + oy, height);
neighbors += cells[n_getIndex(cx, cy)].live;
}
}
return neighbors;
}
void GameOfLife::m_flipCell(int x, int y) {
cells[n_getIndex(x, y)].live = !cells[n_getIndex(x, y)].live;
}
void GameOfLife::m_randomizeCells() {
// Randomize the contents of the cells
// Generate a random number(1-10), if the number is even, the cell is alive, else the cell is dead.
srand(time(nullptr));
for (int i = 0; i < size; i++) {
cells[i].live = (rand() % 10) % 2 == 0;
}
}
void GameOfLife::m_clearCells() {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int i = n_getIndex(x, y);
cells[i].live = false;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44584,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game-of-life, sfml",
"url": null
} |
c++, game-of-life, sfml
GameOfLife::GameOfLife(int width_, int height_, int cellWidth, int cellHeight) {
size = width_ * height_;
width = width_;
height = height_;
cells = new Cell[size];
// Set the positions of the cells in the grid to screen position.
// Set the parameters of the cells for drawing
m_randomizeCells();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int i = n_getIndex(x, y);
cells[i].shape.setPosition(sf::Vector2f(x*cellWidth, y*cellHeight));
cells[i].shape.setSize(sf::Vector2f(cellWidth, cellHeight));
cells[i].shape.setFillColor(cells[i].live ? sf::Color::White : sf::Color::Black);
}
}
}
GameOfLife::~GameOfLife() {
delete[] cells;
}
void GameOfLife::m_drawCells(sf::RenderWindow& window) {
for (int i = 0; i < size; i++) {
// Correct the color of the cell
cells[i].shape.setFillColor(cells[i].live ? sf::Color::White : sf::Color::Black);
window.draw(cells[i].shape);
}
}
void GameOfLife::m_drawCellChanges(sf::RenderWindow& window) {
// m_drawCells must be called at least once before this so we can properly see the board
// Apply changes to the cells and draw those changes
while (!changes.empty()) {
CellChange change = changes.top();
changes.pop();
Cell& cell = cells[change.first];
cell.live = change.second;
cell.shape.setFillColor(cell.live ? sf::Color::White : sf::Color::Black);
window.draw(cell.shape);
}
} | {
"domain": "codereview.stackexchange",
"id": 44584,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game-of-life, sfml",
"url": null
} |
c++, game-of-life, sfml
void GameOfLife::m_updateCells() {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int i = n_getIndex(x, y);
int n = n_countNeighbors(x, y);
int isLive = cells[i].live;
int state = isLive;
if (isLive && (n < 2 || n > 3)) state = false;
else if (n == 3) state = true;
// Count the cells that changed and cells that stay alive.
// The ones that stayed alive are drawn so we can see the patterns that never die
if (state != isLive || (state && isLive)) {
changes.push(std::make_pair(i, state));
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44584,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game-of-life, sfml",
"url": null
} |
c++, game-of-life, sfml
Answer: General Observations
The code is generally pretty good, the design of the game can be improved.
There are 2 ways to improve the design of the game, first separate the display of the game from the logic of the game. This has already been done to some extent, but it can be improved using either the Model View Viewmodel (MVVM) design pattern or the Model View Controller (MVC) design pattern. There should be a class that is independent of the actual implementation of the display that hides the details of the display. This allows you to use different display software to display the game with the logic of the game remaining intact. You could have a class called MyInoutOutoutClass that handles the actual input and output and communicate with it either to a controller or through the view model modelview relationship.
This would mean that the include for SFML does not need to be included in main().
The other design improvement would be to move the while loop in main() into a function in the GameOfLife class in a function possibly called run() or rungame(). In the main() function itself, just init the display system and the game of life.
It is interesting to note that there is no use of std::size_t as an index or or size value.
Order of Private Versus Public
It is generally considered a best practice to put the public interfaces first, then the protected interfaces and the the private data and interfaces. This is true in both the header file and the source file. The reason for this is that when you are working with others on a team the consumers (users) of the public interfaces can quickly find the public interfaces to put it in their code. This allows rapid parallel development in a software team environment.
Keep Private Data Private | {
"domain": "codereview.stackexchange",
"id": 44584,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game-of-life, sfml",
"url": null
} |
c++, game-of-life, sfml
Keep Private Data Private
There is no reason that Cell typedef, the CellChange typedef and the CellChanges typedef are declared in public space, these are all private to the game of life. There are 2 ways to deal with this, the typedefs can be within the GameOfLife class, or there could be forward declarations in the header file and the actual definitions of the struct could be in the gol.cpp file.
class GameOfLife {
public:
GameOfLife(int width_, int height_, int cellWidth, int cellHeight);
~GameOfLife(); | {
"domain": "codereview.stackexchange",
"id": 44584,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game-of-life, sfml",
"url": null
} |
c++, game-of-life, sfml
void m_drawCells(sf::RenderWindow& window);
void m_drawCellChanges(sf::RenderWindow& window);
void m_updateCells();
void m_flipCell(int x, int y);
void m_randomizeCells();
void m_clearCells();
private:
typedef struct {
bool live;
sf::RectangleShape shape;
} Cell;
typedef std::pair<int, int> CellChange;
typedef std::stack<CellChange> CellChanges;
Cell* cells;
CellChanges changes;
int width, height, size;
int n_getIndex(int x, int y);
int n_countNeighbors(int x, int y);
int n_wrapValue(int v, int max);
};
Choice of int Versus bool
It isn't clear why the live field in the Cell struct is an int rather than a bool, the code clearly treats it as a boolean value and assignments to it are true and false. I changed it in my version and it removes a couple of warning messages.
Memory Allocation of Cells Versus Using an STL Container Class
It isn't clear why the code allocates a C style array of cells rather than using std::vector to contain a variable array of cells. Using STL containers lets C++ do the work rather than your code, and iterators can sometimes improve the performance. This might also reduce the need for a destructor (a default one could be used instead).
Random Number Generators
In the current implementation the function srand() should be called in main() and rand() should continue to be called in m_randomizeCells(). The srand() function should only be called once per execution of the program. As pointed out by J_H generating a number between 1 and 10 is an interesting limitation, you could generat and number between 1 and size.
In general in C++ there are better random number generators than the rand() function. The srand() and rand() functions are part of the standard C library and there have been improvements since they were written. The following example is from a discussion of C++ random number generators on stack overflow.
#include <random>
#include <iostream> | {
"domain": "codereview.stackexchange",
"id": 44584,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game-of-life, sfml",
"url": null
} |
c++, game-of-life, sfml
int main()
{
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist6(1,6); // distribution in range [1, 6]
std::cout << dist6(rng) << std::endl;
} | {
"domain": "codereview.stackexchange",
"id": 44584,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, game-of-life, sfml",
"url": null
} |
python-3.x, error-handling
Title: Function to return a file name from lists/dictionary constants | {
"domain": "codereview.stackexchange",
"id": 44585,
"lm_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-3.x, error-handling",
"url": null
} |
python-3.x, error-handling
Question: I'm reworking a set of two functions that return a text file name, constructed from a string argument and string variables from a module called inventory. It seems the inventory module served as a sort of constants module, so I've changed it to constants.py and capitalized the variables. The old functions suffer from a large swath of if/elifs on the order of 600 or so lines with too many elifs to count. The original intent of the code was to not only put together the text file name but to also raise value errors if incorrect strings were passed into the function or constants were changed. I figured I could rewrite this into a try except block, but the only way I could get it to work was nest a second try inside the second except clause. Instead of using single string constants, I've stored the constants in a dictionary to validate the string values before assembling the file name. I'm sure this is silly and there's probably a better way to do it, which is why I'm here.
The function was originally written to accept two arguments, a recipe (e.g.; 'Cake', 'Jam', 'Pie') and an optional argument for an add in ingredient called add_in (e.g.;'ChoclateChip', 'Maple', 'Honey'), with the default set to None. Throughout the remainder of the program, two parameters are never passed, only one, with the idea being that if the parameter passed is an add_in, the recipe retrieved would be for 'Cookies'. This doesn't mean that two parameters will never be passed but as long as I am working on this project they won't, or I will switch it to to require both with keywords. For now, I'm using an arbitrary argument just to keep it flexible. If this is a bad idea, I have no problems changing it. Is this something I should be doing? Or should I just punt this and use just a handful of if/elifs and not do any validating/error checking?
Anyhow. Here's my code:
In constants.py
RECIPES = ['Pie', 'Jam', 'Cookies', 'Doughnuts', 'Cake', 'Marmalade'] | {
"domain": "codereview.stackexchange",
"id": 44585,
"lm_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-3.x, error-handling",
"url": null
} |
python-3.x, error-handling
In constants.py
RECIPES = ['Pie', 'Jam', 'Cookies', 'Doughnuts', 'Cake', 'Marmalade']
ADD_INS = ['ChocolateChip', 'Maple', 'Honey', 'Pecan', 'Walnut', 'BrownSugar'] | {
"domain": "codereview.stackexchange",
"id": 44585,
"lm_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-3.x, error-handling",
"url": null
} |
python-3.x, error-handling
BAKERY_DICT = {'Apple': {'Recipes': RECIPES, 'Add-ins': ADD_INS},
'Orange': {'Recipes': RECIPES, 'Add-ins': ADD_INS}}
FRUIT = 'Apple'
The get_file_name function:
def get_file_name(*recipe_or_addin): # formerly get_file_name(recipe, addin=None)
try:
# validate the fruit by dictionary key and recipe by index in the dictionary
constants.BAKERY_DICT[constants.FRUIT]['Recipes'].index(recipe_or_addin[0])
return 'cook_book/recipe_' + "_".join([constants.FRUIT, recipe_or_addin[0]]) + '.txt'
except KeyError:
return 'No ' + constants.FRUIT + ' recipes in the bakery'
except ValueError:
try: #<--------#####I'm not so sure I should do it this way#####
# validate the add_in in the dictionary
constants.BAKERY_DICT[constants.FRUIT]['Add-ins'].index(recipe_or_addin[0])
return 'cook_book/recipe' + "_".join([constants.FRUIT, recipe_or_addin[0]]) + 'Cookies.txt'
except ValueError:
return 'No ' + recipe_or_addin[0] + ' in the inventory'
Answer: At the moment, you're using "_".join(...) to join fruit and ingredient/recipe, but it is a constant sized list. It would be more obvious to me to use an f-string, which would look like:
return f'cook_book/recipe_{constants.FRUIT}_{recipe_or_addin[0]}.txt'
This also would make what I suspect is a typo in your "add_in" -> "cookies" code more obvious (i.e. you return cook_book/recipeApple_WalnutCookies.txt for "Walnut" rather than cook_book/recipe*_*Apple_WalnutCookies.txt)
You use a slurped list (*recipe_or_addin) which takes any number of arguments and packs them into a list, and then you only ever check the first element of that list? Is what you want instead a default value?
def get_file_name(recipe_or_addin="Cookies") | {
"domain": "codereview.stackexchange",
"id": 44585,
"lm_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-3.x, error-handling",
"url": null
} |
python-3.x, error-handling
Try not to use error handling where you really want an if statement. I believe what you intend is:
def get_file_name(recipe_or_addin): # formerly get_file_name(recipe, addin=None)
if recipe_or_addin in constants.RECIPES:
...
elif recipe_or_addin in constants.ADD_INS:
...
else:
...
I'm not 100% sure what your ultimate goal is, but this does seem like something where you actually want to pass in fruit, recipe and add_in with defaults, e.g.
def get_file_name(fruit="apple", recipe="cookies", *add_in):
return f'cook_book/recipe_{fruit}_{recipe}{("_"+"_".join(add_in)) if add_in else ""}.txt'
Possibly with other checks of whether the combinations are valid, or you could use pathlib or the more beginner friendly, but ultimately more verbose os.path to check whether that file exists (and also join paths so your code is system independent, i.e Windows uses \ and *nix use / as path separators) and if it is found return it or otherwise raise an error or print the appropriate warning message. | {
"domain": "codereview.stackexchange",
"id": 44585,
"lm_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-3.x, error-handling",
"url": null
} |
python
Title: Get list of dates that are the last day each month in a date range
Question: What is a good way to get rid of these if/elif/else inside the for loop? How you would improve readability of it?
from datetime import datetime
from calendar import monthrange
def iter_completed_months(initial_date, today):
delta_months_years = (today.year - initial_date.year)*12
delta_months_current_year = today.month - initial_date.month
return delta_months_years + delta_months_current_year
initial_date = datetime(2021, 11, 30)
today = datetime.now()
# populate a list that goes from initial_date until today with all the dates
# representing the very end of each month
year = initial_date.year
month = initial_date.month
end_month_dates = []
for _iter_month in range(iter_completed_months(initial_date, today)):
if month <= 12:
day = monthrange(year, month)[1]
elif month > 12:
year = year + 1
month = 1
day = monthrange(year, month)[1]
else:
day = monthrange(year, month)[1]
end_month_dates.append(datetime(year, month, day))
month = month + 1
print(end_month_dates)
this code populates a list end_month_dates with all "end of months" from initial_date to today.
Answer: Put your code in functions. The benefits are numerous. Even
if you don't appreciate them fully yet, you should do it anyway. Stand
on the shoulders of the computing giants, who knew that functions
were the way to go.
You are using datetimes, but dates seem more appropriate. Based on the
information you have given us, the function should reason with dates.
A simpler approach. Compute the month start and end dates. Yield the latter
if it's still within the desired bounds. Then advance to the next month by
adding 31 days to the month start. [See the comment from RootTwo
for a further simplification, allowing one to drop month_start.]
from calendar import monthrange
from datetime import date, timedelta | {
"domain": "codereview.stackexchange",
"id": 44586,
"lm_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",
"url": null
} |
python
def last_dates_of_months(start_date, end_date):
d = start_date
while True:
# Compute first and last dates of the month.
month_start = d.replace(day = 1)
n_days = monthrange(d.year, d.month)[1]
month_end = d.replace(day = n_days)
# Yield or break.
if month_end <= end_date:
yield month_end
else:
break
# Advance to a date in the next month.
d = month_start + timedelta(days = 31) | {
"domain": "codereview.stackexchange",
"id": 44586,
"lm_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",
"url": null
} |
java, performance, programming-challenge, recursion, palindrome
Title: Recursive palindrome check
Question: I'm trying to solve this which basically calls for a recursive palindrome check with some minor extra steps (Special characters and whitespace can be ignored). The test inputs' length can be 100000 characters.
I don't have access to the inputs but between 5 datasets my code fails in one of them to answer in under one second and throws a runtime error because it takes more than a second.
The rules of the challenge are to solve under one second with less than 128 MB of memory usage and it should be solved using a recursive algorithm.
So my question is how to increase the performance of this code/algorithm to make it faster.
public class Palindrome_308 {
public static void main(String[] args) {
var scanner = new Scanner(System.in);
var isPalindrome = isPalindrome(scanner.nextLine().replaceAll("\\W", "").toLowerCase());
if (isPalindrome) System.out.println("YES");
else System.out.println("NO");
}
public static boolean isPalindrome(String input) {
var length = input.length();
if (length == 1) return true;
if (length == 2) return input.charAt(0) == input.charAt(1);
if (length == 3) return input.charAt(0) == input.charAt(2);
if (input.charAt(0) != input.charAt(length - 1)) return false;
return input.charAt(0) == input.charAt(length - 1) && isPalindrome(input.substring(1, length - 1));
}
}
Answer: Your handling of base cases is somewhat redundant.
/** @return <code>input</code> is a palindrome. */
public static boolean isPalindrome(CharSequence input) {
var length = input.length();
if (length <= 1)
return true;
return input.charAt(0) == input.charAt(length - 1)
&& isPalindrome(input.subSequence(1, length - 1));
} | {
"domain": "codereview.stackexchange",
"id": 44587,
"lm_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, programming-challenge, recursion, palindrome",
"url": null
} |
java, performance, programming-challenge, recursion, palindrome
Short of passing indices in a recursive function, there seems to be only so much you can do to improve performance for longer sequences when reducing the string length by a constant in each call.
An attempt to limit object creation yielded moderate speed-up for intermediate lengths, but for longer strings latency of higher levels of the memory hierarchy seems to dominate:
/** memory conscious view into another CharSequence than can
* be shortened by one char on both ends simultaneously. */
static class SequenceView implements CharSequence, Cloneable {
final CharSequence viewed;
int start = 0, length;
public SequenceView(CharSequence viewed) {
this.viewed = viewed;
length = viewed.length();
}
@Override
public int length() { return length; }
@Override
public char charAt(int index) {
if (index < 0 || length <= index)
throw new IllegalArgumentException();
return viewed.charAt(index + start);
} | {
"domain": "codereview.stackexchange",
"id": 44587,
"lm_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, programming-challenge, recursion, palindrome",
"url": null
} |
java, performance, programming-challenge, recursion, palindrome
@Override
public CharSequence subSequence(int start, int end) {
if (start < 0 || end < start || this.start + length < end)
throw new IllegalArgumentException();
SequenceView sv = new SequenceView(viewed);
sv.start = this.start + start;
sv.length = end - start;
return sv;
}
/** @return a <code>CharSequence</code> containing
* the former contents of <code>this</code> without
* the first and last character.
* To this end, <code>this</code> is returned (and
* modified, obviously). Consider yourself warned! */
CharSequence mid() {
if (length < 2)
throw new IllegalStateException();
start += 1;
length -= 2;
return this;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
/** @return <code>input</code> is a palindrome. */
public static boolean isPalindrome(CharSequence input) {
SequenceView sv = input instanceof SequenceView
? (SequenceView) input : new SequenceView(input);
return sv.length() <= 1 ||
sv.charAt(0) == sv.charAt(sv.length() - 1)
&& isPalindrome(sv.mid());
}
Well, the key in in getting complexity of a superlinear algorithm down in divide&conquer is to reduce problem size by a factor not too small. | {
"domain": "codereview.stackexchange",
"id": 44587,
"lm_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, programming-challenge, recursion, palindrome",
"url": null
} |
java, performance, programming-challenge, recursion, palindrome
Trying with sequences half the size: /** @return input is a palindrome. */
public static boolean isPalindrome(CharSequence input) {
int length = input.length();
if (length <= 3)
return length <= 1 || input.charAt(0) == input.charAt(length - 1);
int l4 = length / 4;
// palindrome if inner half is and concatenation of outer quarters
return isPalindrome(input.subSequence(l4, length - l4))
&& isPalindrome(new StringBuilder(input.subSequence(0, l4))
.append(input.subSequence(length - l4, length)));
}
There should never be sequences on the stack with more than twice the input characters all told. | {
"domain": "codereview.stackexchange",
"id": 44587,
"lm_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, programming-challenge, recursion, palindrome",
"url": null
} |
performance, vba, unicode, utf-8
Title: Transcoding UTF-8 to UTF-16-LE in VBA | {
"domain": "codereview.stackexchange",
"id": 44588,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, unicode, utf-8",
"url": null
} |
performance, vba, unicode, utf-8
Question: VBA is a language that's lacking a lot of basic functionality. (Pun intended)
Most libraries, if they exist in the first place, are OS-specific, and even some of the inbuilt functions don't work on MacOS or have bugs in any environment.
Recently I've found that the StrConv(s, vbUnicode) function transcoding a string to the VBA-internal UTF-16-LE encoding doesn't properly work in all environments and for all Unicode codepoints. Therefore, I simply implemented my own function for this task. (SO)
Since this is a fairly low-level task, I was trying to be efficient and to make the code as performant as possible by working on a single byte-array buffer and avoiding things like string concatenation which may be tempting here.
I ended up with this code which pretty much fits my needs. I'm sure though, there are still opportunities for improvement, and I have been asked to post it here for review so here you go.
Function DecodeUTF8(ByVal utf8str As String) As String
Dim utf8() As Byte, utf16() As Byte, i As Long, j As Long
Dim codePoint As Long, cpIndex As Long, numBytesOfCodePoint As Long
utf8 = utf8str
ReDim utf16(0 To (UBound(utf8) - LBound(utf8) + 1) * 2)
i = LBound(utf8): cpIndex = 0
Do While i <= UBound(utf8)
'Determine the number of bytes in the current UTF-8 codepoint
numBytesOfCodePoint = 1
If utf8(i) And &H80 Then
If utf8(i) And &H20 Then
If utf8(i) And &H10 Then
numBytesOfCodePoint = 4
Else: numBytesOfCodePoint = 3: End If
Else: numBytesOfCodePoint = 2: End If
End If
'Check if the UTF-8 codepoint is incomplete at the end of the string
If i + numBytesOfCodePoint - 1 > UBound(utf8) Then Err.Raise 5, _
"DecodeUtf8", _
"Incomplete UTF-8 codepoint at the end of the input string."
'Calculate the Unicode codepoint value from the UTF-8 bytes | {
"domain": "codereview.stackexchange",
"id": 44588,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, unicode, utf-8",
"url": null
} |
performance, vba, unicode, utf-8
'Calculate the Unicode codepoint value from the UTF-8 bytes
If numBytesOfCodePoint = 1 Then
codePoint = utf8(i)
Else
codePoint = utf8(i) And (2 ^ (7 - numBytesOfCodePoint) - 1)
For j = 1 To numBytesOfCodePoint - 1
codePoint = (codePoint * 64) + (utf8(i + j) And &H3F)
Next j
End If
'Convert the Unicode codepoint to UTF-16LE bytes
If codePoint < &H10000 Then
utf16(cpIndex) = CByte(codePoint And &HFF&)
utf16(cpIndex + 1) = CByte(codePoint \ &H100&)
cpIndex = cpIndex + 2
Else 'Calculate surrogate pair
Dim m As Long, lowSurrogate As Long, highSurrogate As Long
m = codePoint - &H10000
'(m \ &H400&) = most significant 10 bits of m
highSurrogate = &HD800& + (m \ &H400&)
'(m And &H3FF) = least significant 10 bits of m
lowSurrogate = &HDC00& + (m And &H3FF)
'Concatenate highSurrogate and lowSurrogate as UTF-16LE bytes
utf16(cpIndex) = CByte(highSurrogate And &HFF&)
utf16(cpIndex + 1) = CByte(highSurrogate \ &H100&)
utf16(cpIndex + 2) = CByte(lowSurrogate And &HFF&)
utf16(cpIndex + 3) = CByte(lowSurrogate \ &H100&)
cpIndex = cpIndex + 4
End If
i = i + numBytesOfCodePoint 'Move to the next UTF-8 codepoint
Loop
ReDim Preserve utf16(cpIndex - 1)
DecodeUTF8 = utf16
End Function | {
"domain": "codereview.stackexchange",
"id": 44588,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, unicode, utf-8",
"url": null
} |
performance, vba, unicode, utf-8
Answer: Great work, as usual, definitely needed for Mac compatibility and nice as a learning exercise.
Buffer
I don't think there is a way to improve on the Byte buffer approach. After all, the maximum number of bytes would be twice as many if all the codepoints are less than 128 i.e. one byte per codepoint.
An idea would be to replace these 2 lines:
ReDim Preserve utf16(cpIndex - 1)
DecodeUTF8 = utf16
with:
DecodeUTF8 = MidB$(utf16, 1, cpIndex)
but with no performance gain as there is already a conversion going on when passing the array argument as string. We're just saving a line of code.
However, a good improvement would be to have the buffer as an Integer array instead of Byte because then all codepoints and surrogates would be simply assigned to the array with no need to mask with codePoint And &HFF& or bit shift with codePoint \ &H100&. However, this will require some CopyMemory API calls. No time to do that now but I might return with a later edit.
Performance
Raising to power as in (2 ^ (7 - numBytesOfCodePoint) - 1) is a costly operation. We could use a static array of pre-calculated powers of 2 which can be used as a lookup.
We could also use a static array to store the number of bytes needed per codepoint and remove the need to have many If statements.
Somethig like:
Static byteCount(0 To 255) As Byte
Dim i As Long
If byteCount(0) = 0 Then
For i = &H0 To &H7F '0xxxxxxx
byteCount(i) = 1
Next i
For i = &HC0 To &HDF '110xxxxx
byteCount(i) = 2
Next i
For i = &HE0 To &HEF '1110xxxx
byteCount(i) = 3
Next i
For i = &HF0 To &HF7 '11110xxx
byteCount(i) = 4
Next i
End If | {
"domain": "codereview.stackexchange",
"id": 44588,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, unicode, utf-8",
"url": null
} |
performance, vba, unicode, utf-8
and now every first byte of each codepoint can be looked up in the array with something like:
bytesPerCode = byteCount(firstCPByte). A result of 0 would raise an invalid byte error.
Invalid sequence
You already have error handling in place in case the sequence is incomplete. However there are other issues that need to be addressed. This Wikipedia article lists a few:
invalid bytes
an unexpected continuation byte
a non-continuation byte before the end of the character
the string ending before the end of the character (which can happen in simple string truncation)
an overlong encoding
a sequence that decodes to an invalid code point
For example a byte value of 128 (&H80) should be flagged as invalid but in the current approach this passes as valid on the Else: numBytesOfCodePoint = 2: End If branch.
Another example: a byte value of 11000010 (&HC2) denotes a 2-byte codepoint and the second byte should be of the form 10xxxxxx but in the current approach something like 11000000 passes as a valid continuation byte.
The static byteCount array presented in the Performance section already covers nicely for invalid first bytes.
For 2 bytes per codepoint we can avoid overlong encoding by marking C0 and C1 as invalid directly in the static array i.e replace For i = &HC0 To &HDF with For i = &HC2 To &HDF because we know that 110xxxxx 10xxxxxx must already exclude anything below value 128.
For 3 and 4 bytes we can check for overlong encoding after codepoint has been calculated with something like:
If bytesPerCode = 3 And codePoint < &H800& Then
Err.Raise 5, methodName, "Overlong encoding"
ElseIf bytesPerCode = 4 And codePoint < &H10000 Then
Err.Raise 5, methodName, "Overlong encoding"
End If
Or, we could just have another static array with the accepted limits and call it like this:
If codePoint < minCodePoint(bytesPerCode) Then
Err.Raise 5, methodName, "Overlong encoding"
End If | {
"domain": "codereview.stackexchange",
"id": 44588,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, unicode, utf-8",
"url": null
} |
performance, vba, unicode, utf-8
Of course, we could cover 2 bytes per code point directly from the static array without needing to exclude C0 and C1 from the byteCount static array as mentioned above.
Solution
The solution presented below performs about 35% faster than the original solution presented in the question and this is thanks to the lookups using the static arrays. I've renamed the function name as a personal preference although DecodeUTF8 is perfectly fine.
Public Function UTF8ToUTF16LE(ByRef utf8Text As String) As String
Const methodName As String = "UTF8ToUTF16LE"
Dim bytesCount As Long: bytesCount = LenB(utf8Text)
If bytesCount = 0 Then Exit Function
'
Dim utf8() As Byte: utf8 = utf8Text
Dim utf16() As Byte: ReDim utf16(0 To bytesCount * 2 - 1)
'
Static byteCount(0 To 255) As Long
Static mask(3 To 5) As Long
Static minCodePoint(2 To 4) As Long
Dim i As Long
'
If byteCount(0) = 0 Then
For i = &H0& To &H7F& '0xxxxxxx
byteCount(i) = 1
Next i
For i = &HC2& To &HDF& '110xxxxx - C0 and C1 are invalid (overlong encoding)
byteCount(i) = 2
Next i
For i = &HE0& To &HEF& '1110xxxx
byteCount(i) = 3
Next i
For i = &HF0& To &HF3& '11110xxx - 111101xx is not valid according to RFC 3629 to match UTF-16 limits
byteCount(i) = 4
Next i
For i = 3 To 5
mask(i) = 2 ^ i - 1
Next i
minCodePoint(2) = &H80&
minCodePoint(3) = &H800&
minCodePoint(4) = &H10000
End If
'
Dim codePoint As Long
Dim bytesPerCode As Long
Dim j As Long
Dim loByte As Byte
Dim bufferIndex As Long: bufferIndex = 0
'
i = 0
Do
codePoint = utf8(i)
bytesPerCode = byteCount(codePoint)
'
If bytesPerCode = 0 Then
Err.Raise 5, methodName, "Invalid byte"
ElseIf bytesPerCode = 1 Then
utf16(bufferIndex) = codePoint | {
"domain": "codereview.stackexchange",
"id": 44588,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, unicode, utf-8",
"url": null
} |
performance, vba, unicode, utf-8
ElseIf bytesPerCode = 1 Then
utf16(bufferIndex) = codePoint
bufferIndex = bufferIndex + 2
ElseIf i + bytesPerCode > bytesCount Then
Err.Raise 5, methodName, "Incomplete character"
Else
codePoint = codePoint And mask(7 - bytesPerCode)
For j = 1 To bytesPerCode - 1
loByte = utf8(i + j)
If (loByte And &HC0&) <> &H80& Then '10xxxxxx
Err.Raise 5, methodName, "Invalid continuation byte"
End If
codePoint = codePoint * &H40& + (loByte And &H3F&)
Next j
If codePoint < minCodePoint(bytesPerCode) Then
Err.Raise 5, methodName, "Overlong encoding"
End If
'
'Convert from Unicode codepoint to UTF-16LE bytes
If bytesPerCode < 4 Then
utf16(bufferIndex) = CByte(codePoint And &HFF&)
utf16(bufferIndex + 1) = CByte(codePoint \ &H100&)
bufferIndex = bufferIndex + 2
Else
Dim m As Long: m = codePoint - &H10000
Dim lowSurrogate As Long: lowSurrogate = &HDC00& + (m And &H3FF&)
Dim highSurrogate As Long: highSurrogate = &HD800& + (m \ &H400&)
'
utf16(bufferIndex) = CByte(highSurrogate And &HFF&)
utf16(bufferIndex + 1) = CByte(highSurrogate \ &H100&)
utf16(bufferIndex + 2) = CByte(lowSurrogate And &HFF&)
utf16(bufferIndex + 3) = CByte(lowSurrogate \ &H100&)
bufferIndex = bufferIndex + 4
End If
End If
i = i + bytesPerCode
Loop Until i >= bytesCount
UTF8ToUTF16LE = MidB$(utf16, 1, bufferIndex)
End Function | {
"domain": "codereview.stackexchange",
"id": 44588,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, unicode, utf-8",
"url": null
} |
c++, c++20, variant-type
Title: A parse function for text line with fields separated by a comma with the known number and their type, simplified version
Question: simplifying this question, taking most of the comment into considerations, I ended up with this version, looking for some feedback
#include <iostream>
#include <tuple>
#include <cassert>
#include <type_traits>
std::tuple<std::string_view, std::string_view> split(std::string_view str, char delimiter)
{
auto pos = str.find(delimiter);
if (pos == std::string_view::npos)
{
return {str, {}};
}
return {str.substr(0, pos), str.substr(pos + 1)};
}
template <typename T>
auto parse(std::string_view str)
{
using T2 = std::unwrap_ref_decay_t<T>;
T2 res;
if constexpr (std::is_same_v<T2, std::string>) { return res = std::string(str);}
if (std::is_floating_point_v<T2>){ return res = std::stod(std::string(str));return res;}
if (std::is_integral_v<T2>) { return res = std::stol(std::string(str));}
throw std::invalid_argument("Invalid type");
}
template <typename T>
constexpr bool is_tuple = false;
template <typename T>
constexpr bool has_content = false;
template <typename T>
constexpr bool is_constructible = false;
template <typename... Ts>
constexpr bool is_tuple<std::tuple<Ts...>> = true;
template <typename... Ts>
constexpr bool has_content<std::tuple<Ts...>> = sizeof...(Ts) > 0;
template <typename... Ts>
constexpr bool is_constructible <std::tuple<Ts...>> = std::conjunction_v<std::is_default_constructible<Ts>...>;
template <typename TupleType>
requires is_tuple<TupleType> &&
has_content<TupleType> &&
is_constructible<TupleType>
auto handle(std::string_view str)
{
TupleType result;
auto parse_one = [&](auto &arg)
{
auto [ field, rest ] = split(str, ',');
arg = parse<decltype(arg)>(field);
str = rest;
};
std::apply([&](auto &...args)
{ (parse_one(args), ...); },
result);
return result;
} | {
"domain": "codereview.stackexchange",
"id": 44589,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, variant-type",
"url": null
} |
c++, c++20, variant-type
int main()
{
using LineData = std::tuple<std::string, double, int64_t>;
std::string_view input_str = "first_cut,55.3,177";
LineData result = handle<LineData>(input_str);
std::cout << "Parsed values:" << '\n';
std::cout << "String value: " << std::get<0>(result) << '\n';
std::cout << "Double value: " << std::get<1>(result) << '\n';
std::cout << "Int value: " << std::get<2>(result) << '\n';
return 0;
}
Answer: Simplify the constraints
You defined three type trait checkers: is_tuple, has_content and is_constructible. Note that has_content is also only ever true if the type passed is a std::tuple, so is_tuple is redundant.
The names are also wrong: has_content doesn't say anything about it checking for tuples, and one would say that a non-empty std::vector also "has content". Maybe is_nonempty_tuple is better? One could also argue that while an empty tuple is a corner case, the code you've written will actually handle that correctly, so there is no need to prevent it.
is_constructible is also misnamed: again despite the name not saying it, it only is ever true for std::tuples. But also note that "constructible" is not the same as "default constructible". So it should have been named is_default_constructible_tuple. However, there is no need to make such a check; std::is_default_constructible_v<TupleType> already checks that the whole tuple can be default constructed.
While you check that TupleType is a default-constructible, non-empty tuple, you didn't check whether the types stored in the tuple can actually be parsed. You could write a concept that checks whether you provide a default-constructible, non-empty, parsable std::tuple, but it would just duplicate the whole body of handle() inside a requires expression, which defeats the point.
I'd rather keep it simple:
template <typename TupleType>
requires is_tuple<TupleType> &&
std::is_default_constructible_v<TupleType>
auto handle(std::string_view str) … | {
"domain": "codereview.stackexchange",
"id": 44589,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, variant-type",
"url": null
} |
c++, c++20, variant-type
Avoid needing the tuple type to be default-constructible
You can avoid default-constructing a TupleType by making use of the fact that you can return a value from std::apply(), and that you can already refer to a variable's name when constructing it:
auto handle(std::string_view str)
{
auto parse_one = [&](auto &arg)
{
auto [ field, rest ] = split(str, ',');
str = rest;
return parse<decltype(arg)>(field);
};
TupleType result = std::apply([&](auto &...args)
{ return TupleType{parse_one(args)...}; },
result);
return result;
}
Simplify returning values from parse()
I think your parse() is unnecessarily complex because you forgot to add constexpr to the second and third if-statement. I think you can completely avoid the temporary variable res:
template <typename T>
auto parse(std::string_view str)
{
using T2 = std::unwrap_ref_decay_t<T>;
if constexpr (std::is_same_v<T2, std::string>) { return str; }
if constexpr (std::is_floating_point_v<T2>) { return std::stod(std::string(str)); }
if constexpr (std::is_integral_v<T2>) { return std::stol(std::string(str)); }
throw std::invalid_argument("Invalid type");
}
Prefer using std::from_chars() to parse numeric values
Unfortunately, std::stod() and std::stoi() don't take std::string_views as arguments, as you have discovered. I recommend you use std::from_chars() instead. It also doesn't take std::string_views, but it takes pointers to the start and end of the string, which you can easily create from a std::string_view. It also avoids having to deal with integers and floating point values separately:
if constexpr (std::is_arithmetic_v<T2>) {
if (T2 value; std::from_chars(str.begin(), str.end(), value) == std::errc{})
return value;
else
throw std::runtime_error("Parse error");
} | {
"domain": "codereview.stackexchange",
"id": 44589,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, variant-type",
"url": null
} |
java, beginner, object-oriented, calculator
Title: Calculator (Java/Beginner)
Question: I finished my first calculator using Java!
I try to apply Object-Oriented Programming!
I'll add my gitHub link if you're suited to viewing code on gitHub.
Here is a link to my GitHub Calculator Project
dvdev04-github-calculator
I enabled the calculator to calculate data type of Double, so it can get result containing decimals.
When reviewing, can you focus on whether my code
follows clean code
classes are divided reasonably
handled exceptions well (such when doing calculation)
has no redundant or repeated codes
Main Class
enter code hereimport java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// take in option chose in the menu & instantiate all the objects
Menu menu = new Menu();
Calculator calculate = new Calculator();
Database database = new Database();
EquationConverter equationConverter = new EquationConverter();
EquationFormatChecker equationFormatChecker = new EquationFormatChecker();
// Starting Calculator
System.out.println("Calculator Initializing...");
// Main Loop of Options
while(true) {
// Checking Input if it's 1 or 2 or 3
while(true) {
System.out.println("-------------------");
System.out.println("1. History\n2. Calculation\n3. Terminate");
try {
menu.setMenuChoice(Integer.parseInt(br.readLine()));
if (menu.getMenuChoice() >= 1 && menu.getMenuChoice() <= 3) {
break;
}
} catch (NumberFormatException e) {
System.out.println(">>> Wrong Input, please try again.");
}
} | {
"domain": "codereview.stackexchange",
"id": 44590,
"lm_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, beginner, object-oriented, calculator",
"url": null
} |
java, beginner, object-oriented, calculator
// using if else to figure out whether to view history/perform calculation/exit program
switch (menu.getMenuChoice()) {
// view history
case 1 -> {
if (database.checkEmpty()) {
System.out.println("Retrieving History...\n");
System.out.println(database.getHistory());
} else {
System.out.println(">>> History's Empty");
}
}
// do calculation
case 2 -> {
boolean continueCalculation = true;
while (continueCalculation) {
try {
System.out.println("-------------------");
System.out.print("Enter equation (Example: 1 + 4 * 5 / 2)\n=> ");
// take in the equation as String and pass it on to equation convertor
String equation = br.readLine();
equationConverter.setEverything(equation);
// checking validity of equation
boolean validityCheck = equationFormatChecker.checkValidity(equationConverter.getNumbersList(), equationConverter.getOperatorsList());
if (validityCheck) {
// code is in this order because of possible ArithmeticException in calculate
// find the answer
Double answer = calculate.calculateEquation(equationConverter.getNumbersList(), equationConverter.getOperatorsList()); | {
"domain": "codereview.stackexchange",
"id": 44590,
"lm_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, beginner, object-oriented, calculator",
"url": null
} |
java, beginner, object-oriented, calculator
// add equation to history (only equation, not answer)
database.addHistory(equation);
System.out.println("Answer: " + answer);
//and add answer to the database
database.addAnswerToEquation(answer);
continueCalculation = false;
}
} catch (NumberFormatException e1) {
System.out.println("Wrong format, try again.");
} catch (ArithmeticException e2) {
if (e2.getMessage().equals("Infinite"))
System.out.println("Can't divide by zero. Try again.");
if (e2.getMessage().equals("NaN")) System.out.println("Not a Number. Try Again");
}
}
}
// exit program
case 3 -> {
System.out.println("Terminating calculator...");
System.exit(0);
}
}
}
}
}
Menu Class
public class Menu {
private int menuChoice;
public void setMenuChoice(int menuChoice) {
this.menuChoice = menuChoice;
}
public int getMenuChoice() {
return menuChoice;
}
}
EquationConverter Class
import java.util.ArrayList;
import java.util.List;
public class EquationConverter {
private ArrayList<String> equationList;
private ArrayList<Double> numbersList;
private ArrayList<String> operatorsList;
// initialize equationList
EquationConverter() {
equationList = new ArrayList<>();
numbersList = new ArrayList<>();
operatorsList = new ArrayList<>();
}
// set the Equation
public void setEverything(String equationString) {
equationList.clear();
equationList.addAll(List.of(equationString.split(" ")));
setNumbersList();
setOperatorsList();
}
// get equationList
public ArrayList<String> getEquationList() {
return equationList;
} | {
"domain": "codereview.stackexchange",
"id": 44590,
"lm_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, beginner, object-oriented, calculator",
"url": null
} |
java, beginner, object-oriented, calculator
// get equationList
public ArrayList<String> getEquationList() {
return equationList;
}
// set list of numbers
public void setNumbersList() {
numbersList = new ArrayList<>();
for (int i = 0; i < equationList.size(); i += 2) {
numbersList.add(Double.parseDouble(equationList.get(i)));
}
}
// set list of operators
public void setOperatorsList() {
operatorsList = new ArrayList<>();
for (int i = 1; i < equationList.size(); i += 2) {
operatorsList.add(equationList.get(i));
}
}
public ArrayList<Double> getNumbersList() {
return numbersList;
}
public ArrayList<String> getOperatorsList() {
return operatorsList;
}
}
EquationFormatChecker Class
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class EquationFormatChecker {
private final List<String> operatorSet = new ArrayList<>(Arrays.asList("+", "-", "*", "/"));
// 0 for valid equation, 1 for invalid equation, 2 for division by zero
public boolean checkValidity(ArrayList<Double> numbers, ArrayList<String> operators) {
int length = numbers.size() + operators.size();
// checking if either List is empty or length is valid
if (numbers.isEmpty() || operators.isEmpty() || length < 3 || length % 2 == 0) {
return false;
}
// check if operatorsList contains + - * /
for (String operator : operators) {
if (!operatorSet.contains(operator)) {
return false;
}
}
return true;
}
}
Calculator Class
import java.util.ArrayList;
public class Calculator {
private ArrayList<Double> numberList;
private ArrayList<String> operatorList;
public double calculateEquation(ArrayList<Double> numbersList, ArrayList<String> operatorList) throws ArithmeticException {
this.numberList = numbersList;
this.operatorList = operatorList; | {
"domain": "codereview.stackexchange",
"id": 44590,
"lm_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, beginner, object-oriented, calculator",
"url": null
} |
java, beginner, object-oriented, calculator
this.numberList = numbersList;
this.operatorList = operatorList;
for (int i = 0; i < operatorList.size(); i++) {
if (operatorList.get(i).equals("*")) {
numbersList.set(i + 1, numbersList.get(i) * numbersList.get(i + 1));
operatorList.set(i, "+");
numbersList.set(i, 0D);
}
if (operatorList.get(i).equals("/")) {
double result = numbersList.get(i) / numbersList.get(i + 1);
if (Double.isInfinite(result)) throw new ArithmeticException("Infinite");
if (Double.isNaN(result)) throw new ArithmeticException("NaN");
numbersList.set(i + 1, numbersList.get(i) / numbersList.get(i + 1));
operatorList.set(i, "+");
numbersList.set(i, 0D);
}
}
Double accumulator = numbersList.get(0);
for (int i = 1; i < numberList.size(); i++) {
if (operatorList.get(i - 1).equals("+")) {
accumulator += numbersList.get(i);
}
if (operatorList.get(i - 1).equals("-")) {
accumulator -= numbersList.get(i);
}
}
return accumulator;
}
public ArrayList<Double> getNumberList() {
return numberList;
}
public ArrayList<String> getOperatorList() {
return operatorList;
}
}
Database Class
import javax.xml.crypto.Data;
import java.util.ArrayList;
public class Database {
private ArrayList<String> historyList;
private String historyString;
Database() {
this.historyList = new ArrayList<>();
}
public boolean checkEmpty() {
if (historyList.isEmpty()) {
return false;
} return true;
}
// add a line of equation to the String
public void addHistory(String equation) {
this.historyList.add(equation);
}
// return historyString
public String getHistory() {
ArrayListToString();
return historyString;
} | {
"domain": "codereview.stackexchange",
"id": 44590,
"lm_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, beginner, object-oriented, calculator",
"url": null
} |
java, beginner, object-oriented, calculator
// convert historyList to String
private void ArrayListToString() {
StringBuilder sb = new StringBuilder();
for (String oneEquation : historyList) {
sb.append(oneEquation.concat("\n"));
}
historyString = sb.toString();
}
// add answer to complete your equation
public void addAnswerToEquation(Double answer) {
String stringAnswer = String.valueOf(answer);
historyList.set(historyList.size() - 1, historyList.get(historyList.size() - 1).concat(" = " + stringAnswer));
}
public ArrayList<String> getHistoryList() {
return historyList;
}
public String getHistoryString() {
return historyString;
}
}
Answer: For a beginner this isn't terrible, but unfortunatly from a OOP point of view it's structured quite badly.
First i'm going to concentrate on the Database class. (Aside: a better name would be History or HistoryDatabase. To be honest most class and method names are badly chosen and inconsistant, but I'll ignore that for now).
One big point of OOP is to provide a self-contained object with a clear and sensible way to use it. Image that you wrote the class, but someone else will use it in their programm. It should be impossible for the user of the class to "break" it (or your class to break their programm). The class should preferably not allow to do "wrong" things at compile time, or at the very least notify the user (for example, through exceptions or some other error message/state) that what they are trying is wrong.
For example:
Database history = new Database();
// If the user would do the following, is it clear from what happens, what the problem is?
// history.addAnswerToEquation(3.0);
history.addHistory("1 + 2");
// Does this do what you or the user may expect?
System.out.println(history.getHistoryString());
history.addAnswerToEquation(3.0);
history.addAnswerToEquation(3.0);
// Is the history object now in a "good" state?
System.out.println(history.getHistory()); | {
"domain": "codereview.stackexchange",
"id": 44590,
"lm_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, beginner, object-oriented, calculator",
"url": null
} |
java, beginner, object-oriented, calculator
So the main problem here is addAnswerToEquation. It should at the very least the method should make sure the class is in a state to accept an answer. For example:
public void addAnswerToEquation(Double answer) {
if (historyList.isEmpty()) {
throw IllegalStateException("At least one expression needs to be added before adding an answer.");
}
String lastEntry = historyList.get(historyList.size() - 1);
if (lastEntry.contains("=")) {
throw IllegalStateException("The last expression allready has an answer added.");
}
String stringAnswer = String.valueOf(answer);
historyList.set(historyList.size() - 1, lastEntry.concat(" = " + stringAnswer));
}
However, is it really necessary to add the equation and the answer separately? It would probably be better to drop addAnswerToEquation and instead have addHistory take both the equation and the answer.
The three classes EquationConverter, EquationFormatChecker and Calculator have basically the same problem. Additionally the main functionality of the programm ist just arbitrary distributed over these three classes without any concrete connection between them. I don't have the time to go into details, but I'd suggest to first integrate the functionality of all three into a single Equation class. If more separation is needed, then this can be considered later. | {
"domain": "codereview.stackexchange",
"id": 44590,
"lm_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, beginner, object-oriented, calculator",
"url": null
} |
c#, linq, entity-framework
Title: Joining to in memory List
Question: I have an in memory list that I am joining to results from a query using entity framework. My list will most likely never be greater than 2500 records. The results from the database can fluctuate, depending on the filters used and it will grow in size. I've been able to join the results successfully but it feels a bit sluggish and I worry as the database grows that it could get worse. Is there anything I can do to make this more efficient? Please let me know if you need any additional information. Thanks!
var query = from e in _context.Employees
where (...filters...)
select e;
var employees = query.AsEnumerable();
var offices = _officeService.GetAllOffices();
var employeeData = from e in employees
join o in offices on e.Office equals o.Code
select new EmployeeData
{
EmployeeId = e.EmployeeId,
FullName = e.FullName,
Office = e.Office,
Area = o.Area,
Region = o.Region,
OfficeName = o.Name,
Position = e.Position,
Languages = e.Languages
};
return employeeData;
Answer: The dilemmas here:
query is an IQueryable. If you join it with offices, i.e. without AsEnumerable(), Entity Framework will throw an exception about primitive values, which is an obscure way of telling you that it can't translate offices into SQL.
So join in memory, i.e. with query.AsEnumerable(). But now all data from query will be pulled into memory, which has two adverse effects: neither the reduction in numbers of records by joining with offices nor the reduction in width of the result set by selecting only a restricted number of properties can be translated back to the SQL query. | {
"domain": "codereview.stackexchange",
"id": 44591,
"lm_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#, linq, entity-framework",
"url": null
} |
c#, linq, entity-framework
You obviously want to benefit from both strands of data reduction.
As for the reduction in number of rows, there's no way to make Entity Framework join with local data other than lists of primitive values. Even then, joining is rather inefficient because EF has to convert the local list into a temporary SQL table (sort of), which requires a considerable amount of code. It's more efficient to use Contains, which translates into an IN statement:
var officesCodes = offices.Select(o => o.Code).ToList();
var employeeInfo = from e in employees
where officesCodes.Contains(e.Office)
select ...
Now employeeInfo is an IQueryable, so it's possible to reduce the width of the result set by projection:
var employeeInfo = from e in employees
where officesCodes.Contains(e.Office)
select new
{
EmployeeId = e.EmployeeId,
FullName = e.FullName,
Office = e.Office,
Position = e.Position,
Languages = e.Languages
};
This achieves the desired data reduction. But now you haven't got EmployeeData objects yet. Can't be done by this query, because they also contain data from offices. This final step can only be achieved by joining the result in memory with offices:
var employeeData = from e in employeeInfo.AsEnumerable()
join o in offices on e.Office equals o.Code
select new EmployeeData
{
EmployeeId = e.EmployeeId,
FullName = e.FullName,
Office = e.Office,
Area = o.Area,
Region = o.Region,
OfficeName = o.Name,
Position = e.Position,
Languages = e.Languages
}; | {
"domain": "codereview.stackexchange",
"id": 44591,
"lm_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#, linq, entity-framework",
"url": null
} |
php, mysql, datetime, wordpress
Title: Search between dates in a WP Query
Question: In the posts I have a date field and a start and end date range. I need to query if it matches date or if it matches between the dates in the range. This Query works, but how can I optimize?
$args = array(
'post_type' => array('post'),
'post_status' => array( 'publish' ),
'posts_per_page' => 20,
'paged' => 1,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'this_day',
'value' => $startday,
'compare' => 'LIKE',
),
array(
'relation' => 'AND',
array(
'key' => 'date_start',
'value' => $endday,
'compare' => '<=',
'type' => 'DATE',
),
array(
'key' => 'date_end',
'value' => $startday,
'compare' => '>=',
'type' => 'DATE',
),
)
)
);
MySql sentence:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id )
INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id )
WHERE 1=1
AND
(
(
(
wp_postmeta.meta_key = 'this_day'
AND wp_postmeta.meta_value = '20220701'
)
OR
(
(
mt1.meta_key = 'date_start'
AND CAST(mt1.meta_value AS DATE) <= '20220701'
)
AND
(
mt2.meta_key = 'date_end'
AND CAST(mt2.meta_value AS DATE) >= '20220701'
)
)
)
)
AND wp_posts.post_type = 'post'
AND ((wp_posts.post_status = 'publish'))
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_date DESC
LIMIT 0, 20 | {
"domain": "codereview.stackexchange",
"id": 44592,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, mysql, datetime, wordpress",
"url": null
} |
php, mysql, datetime, wordpress
Answer: Thank you for your answers :)
In the end I have solved it by performing a first query where I perform the first filtering and on that array, I perform the second query between the selected dates.
if( $_POST['date_ini']!='' && $_POST['date_end']!='' ){
$date_ini = $_POST['date_ini']; // aaaa-mm-dd
$date_end = $_POST['date_end'];
$startday = str_replace('-','',$date_ini);
$endday = str_replace('-','',$date_end);
$date_result = date_i18n('j F Y', strtotime($startday));
} else {
$startday = date('Ymd');
$endday = date('Ymt', strtotime("+11 month")); // lastDayYear
$date_result = date_i18n('j F Y', strtotime($startday)).' > '.date_i18n('j F Y', strtotime($endday));
}
$parameters = array();
for($i=$startday;$i<=$endday;$i = date("Ymd", strtotime($i ."+ 1 days"))){
$parameters[] = array(
'key' => 'alternate_days',
'value' => '.*' . $i . '.*',
'compare' => 'REGEXP',
'type' => 'CHAR'
);
}
$args_ = array(
'post_type' => array('post'),
'post_status' => array( 'publish' ),
'cat' => 6, // if u need filter by cat
'showposts' => -1,
'meta_query' => array_merge( array(
'relation' => 'OR',
),
$parameters ) // parameters form filter
);
$args_2 = array(
'post_type' => array('post'),
'post_status' => array( 'publish' ),
'cat' => 6, // if u need filter by cat
'showposts' => -1,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'date_ini',
'value' => $endday,
'compare' => '<=',
'type' => 'DATE'
),
array(
'key' => 'date_end',
'value' => $startday,
'compare' => '>=',
'type' => 'DATE'
)
)
);
$query = new \WP_Query( $args_ );
$query2 = new \WP_Query( $args_2 ); | {
"domain": "codereview.stackexchange",
"id": 44592,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, mysql, datetime, wordpress",
"url": null
} |
php, mysql, datetime, wordpress
$query = new \WP_Query( $args_ );
$query2 = new \WP_Query( $args_2 );
$filter_posts_by_id = array_column( array_merge( $query->posts , $query2->posts ), 'ID' );
$end_query = new WP_Query( array( 'post__in' => $filter_posts_by_id ) ); | {
"domain": "codereview.stackexchange",
"id": 44592,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, mysql, datetime, wordpress",
"url": null
} |
c, file-system, tail-recursion
Title: Tar implementation
Question: I am writing a tar implementation for education purposes and I started with reading from a tar file and printing the file content.
I use recursion for getting the next tar header and googled "When to use recursion?" Landed on this post where Peter Burns said:
There is a technique that language implementers can use called tail call optimization which can eliminate some classes of stack overflow. Put succinctly: if a function's return expression is simply the result of a function call, then you don't need to add a new level onto the stack, you can reuse the current one for the function being called. Regrettably, few imperative language-implementations have tail-call optimization built in.
Did he explicitly mean language implementers or can this be used by me too then?
As I was told to add the complete code so I will add what I got for now. It's not much because this is my first time working with a standardized format and I first want to be a able to read every header and get the offsets right, as tar pads content to next bigger blocksize.
It only works for tar file containing files only. I will implement all other kind of types if I understand more.
For now as already asked. Is the tar_getNextHeader() function badly designed regarding tail recursion and the quote above?
And I would like to improve my naming skills for structures, definitions because I think some structure and definitions are not nicely named.
Also if you see something I can do better or should not do/use, let me know.
tar.h:
#ifndef _TAR_H // BEGIN INCLUDE GUARD
#define _TAR_H
/*********************************************************************************************************/
/* DEPENDANICIES */
/*********************************************************************************************************/
#include <stdio.h> | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
c, file-system, tail-recursion
#include <stdio.h>
/*********************************************************************************************************/
/* DEFINITIONS */
/*********************************************************************************************************/
typedef struct tar tar;
/*********************************************************************************************************/
/* FUNCTION DEFINITIONS */
/*********************************************************************************************************/
tar* tar_load(const char *filename);
void tar_print(tar *tar);
#endif
tar.c:
/*********************************************************************************************************/
/* DEPENDANICIES */
/*********************************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "tar.h"
#include "tar_internal.h"
/*********************************************************************************************************/
/* DEFINITIONS */
/*********************************************************************************************************/
/*********************************************************************************************************/
/* FUNCTION DEFINITIONS */
/*********************************************************************************************************/ | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
c, file-system, tail-recursion
/**
* @brief Loads a tar file and parses/allocates included headers
* NOTE: check for errno after calling
*
* @param path path to tar file
* @retval tar* on success
* @retval NULL on failure
*/
tar* tar_load(const char *path)
{
struct stat fi;
if(stat(path, &fi) != 0) {
return NULL;
}
tar *tar = malloc(sizeof *tar);
if(tar == NULL) {
return NULL;
}
tar->size = fi.st_size;
tar->filename = path;
tar->fd = open(path, O_RDONLY);
if(tar->fd == -1) {
free(tar);
return NULL;
}
tar->files = tar_getNextHeader(tar);
return tar;
}
/**
* @brief Prints file content (for testing purposes)
*
* @param tar
*/
void tar_print(tar *tar)
{
lseek(tar->fd, 0, SEEK_SET);
tar_entry *current = tar->files;
while(current) {
lseek(tar->fd, current->offset, SEEK_SET);
char buffer[512];
if(read(tar->fd, buffer, current->size) == 0) {
printf("EOF\n");
return;
}
printf("File: %s\n", current->header.filename);
printf("Content:\n%s\n\n", buffer);
current = current->next;
}
}
tar_internal.h:
#ifndef _TAR_INTERNAL_H // BEGIN INCLUDE GUARD
#define _TAR_INTERNAL_H
/*********************************************************************************************************/
/* DEPENDANICIES */
/*********************************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h> | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
c, file-system, tail-recursion
/*********************************************************************************************************/
/* DEFINITIONS */
/*********************************************************************************************************/
#define NORMAL_FILE '0'
#define HARD_LINK '1'
#define SYMBOLIC_LINK '2'
#define CHARACTER_SPECIAL '3'
#define BLOCK_SPECIAL '4'
#define DIRECTORY '5'
#define FIFO '6'
#define CONTIGUOUS_FILE '7'
#define GLOBAL_EXTENDET_HEADER 'g'
#define EXTENDED_HEADER 'x'
/*
*/
#define TAR_BLOCKSIZE 512
#define USTAR "ustar"
typedef struct tar_header {
union {
struct {
char filename[100];
char mode[8];
char uid[8];
char gid[8];
char size[12];
char mtime[12];
char chksum[8];
char type;
char link_filename[100];
char magic[6];
char version[2];
char owner[32];
char group[32];
char devicemajor[8];
char deviceminor[8];
char prefix[155];
};
char padding[TAR_BLOCKSIZE];
};
} tar_header;
typedef struct tar_entry {
struct tar_entry *next;
const char *filename;
off_t offset;
size_t size;
tar_header header;
} tar_entry;
typedef struct tar {
const char *filename; // tar filename
size_t size; // tar file size
tar_entry *files; // linked list
size_t fd;
} tar;
/*********************************************************************************************************/
/* FUNCTION DEFINITIONS */
/*********************************************************************************************************/
size_t RoundUpBlock(size_t size, size_t blksz); | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
c, file-system, tail-recursion
size_t RoundUpBlock(size_t size, size_t blksz);
/*********************************************************************************************************/
/* TAR HEADER INTERFACE */
/*********************************************************************************************************/
bool tar_header_isUstar(tar_header *header);
void tar_header_setEmpty(tar_header *header);
bool tar_header_isDirectory(tar_header *header);
bool tar_header_isRegFile(tar_header *header);
bool tar_header_isLongName(tar_header *header);
bool tar_header_isLongLink(tar_header *header);
size_t tar_header_getSize(tar_header *header);
void tar_header_getPath(tar_header *header, char *path_buf, size_t len);
/*********************************************************************************************************/
/* TAR FILE INTERFACE */
/*********************************************************************************************************/
tar_entry* tar_getNextHeader(tar *tar);
int tar_skipFileContent(tar *tar, size_t filesz);
#endif
tar_internal.c:
/*********************************************************************************************************/
/* DEPENDANICIES */
/*********************************************************************************************************/
#include "tar.h"
#include "tar_internal.h"
/*********************************************************************************************************/
/* DEFINITIONS */
/*********************************************************************************************************/ | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
c, file-system, tail-recursion
/*********************************************************************************************************/
/* FUNCTION DEFINITIONS */
/*********************************************************************************************************/
bool tar_header_isUstar(tar_header *header)
{
return ( strncmp(header->magic, USTAR, sizeof(USTAR)-1) == 0 );
}
size_t RoundUpBlock(size_t size, size_t blksz)
{
size_t result = size % blksz;
if( result == size ) {
return blksz;
}
else if( result == 0 ) {
return result;
}
return (size / blksz + 1) * blksz;
}
void tar_header_setEmpty(tar_header *head)
{
memset(head->padding, 0, TAR_BLOCKSIZE);
}
bool tar_header_isDirectory(tar_header *head)
{
return head->type == DIRECTORY;
}
bool tar_header_isRegFile(tar_header *head)
{
return head->type == NORMAL_FILE;
}
/*
always check errno for error after this call
*/
size_t tar_header_getSize(tar_header *head)
{
return strtoul(head->size, NULL, 8);
}
/**
* @brief skips the file content inside file and jumps to the next header
*
* @param tar tar*
* @param filesz size of file of the current header
* @retval -1 on failure
* @retval current offset in file in bytes
*/
int tar_skipFileContent(tar *tar, size_t filesz)
{
off_t curpos = lseek(tar->fd, 0, SEEK_CUR);
size_t roundup = RoundUpBlock(filesz, TAR_BLOCKSIZE);
if(curpos == -1) {
return -1;
}
if(curpos + roundup > tar->size) {
printf("DEBUG: TAR OVERREAD!!!\n");
return -1;
}
if(lseek(tar->fd, roundup, SEEK_CUR) == -1) {
return -1;
}
return curpos;
} | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
c, file-system, tail-recursion
if(lseek(tar->fd, roundup, SEEK_CUR) == -1) {
return -1;
}
return curpos;
}
/**
* @brief Recusive call to fill the linked list of entries
* NOTE: alway check errno for this call. if errno == 0, and NULL is returned then EOF is reached, otherwise an error occured
* NOTE: this function checks for ustar magic string to skip 0-byte sequences at the end of file, it does not work for tar files using the old standard
* @param tar
* @retval NULL on failure (EOF or error while read)
* @retval tar_entry *
*/
tar_entry* tar_getNextHeader(tar *tar)
{
tar_entry *entry = malloc(sizeof *entry);
if(entry == NULL) {
return NULL;
}
size_t ret = read(tar->fd, &entry->header, TAR_BLOCKSIZE);
if(ret == 0 || ret == -1) {
goto CLEANUP;
}
if(!tar_header_isUstar(&entry->header)) {
goto CLEANUP;
}
entry->size = tar_header_getSize(&entry->header);
if(errno) {
perror("tar_getNextHeader()->tar_header_getSize()");
goto CLEANUP;
}
entry->offset = tar_skipFileContent(tar, entry->size);
if(entry->offset == -1) {
goto CLEANUP;
}
entry->next = tar_getNextHeader(tar);
if(errno) {
perror("tar_getNextHeader()->tar_getNextHeader()");
return NULL;
}
return entry;
CLEANUP:
free(entry);
return NULL;
} | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
c, file-system, tail-recursion
Answer: What’s the Deal Here
Tail recursion is an extremely useful pattern. You’d normally use it to transform a loop into an equivalent function that calls itself. All the state that carries over from one invocation of the loop to the next becaomes arguments to the function. It can also decompose a larger function into smaller ones that return calls to each other. It’s especially useful to implement state machines.
The code that gets generated—if this optimization is enabled—is just as optimized as a loop. In fact, most functional languages don’t allow you to write loops at all, and replace them entirely with this technique.
Tail-call optimization works for all tail calls, not only tail calls to the same function, but it’s especially efficient to make a tail call to the same function, because then you can re-use the exact same stack frame. On a machine-code level, you can replace a call instruction and all the other overhead of a function call with a jump instruction.
I personally use this method a lot because I’ve done a lot of functional programming, and because it greatly facilitates a style of coding that protects you from certain kinds of bugs. Specifically, all your state that carries over gets fed into your function as const parameters, and all exit points are either the final value or a tail call. The entire state of the next trip through the function can only be updated all at once, at the same time. You can’t forget to set any of it, and you can’t set any of it twice on the same iteration. (Or actually, you can shoot yourself in the foot that way, because this is C, but you have to really be explicit about it. It won’t happen by accident.)
It does have some disadvantages: if there’s a lot of state (and you can’t refactor into smaller pieces that need less of it), the tail calls can get cumbersome. And some of it might be tramp data, which most of the functions it passes through don’t even use, just pass to the next function in the chain. | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
c, file-system, tail-recursion
All modern C compilers can do the necessary optimization, but some need to be told to do it. GCC needs one of the optimization flags -O2, -O3, -Os or -foptimize-sibling-calls.
Clang and ICX have an extension, __attribute__((musttail)), that tells the compiler that a call must get this optimization. I therefore often write, for compatibility:
#if __clang__ || __INTEL_LLVM_COMPILER
# define MUSTTAIL __attribute((musttail))
#else
# define MUSTTAIL /**/
#endif | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
c, file-system, tail-recursion
This lets me write my tail-recursive calls as MUSTTAIL return, which expands to use this extension on the compilers that support it, or just return on those that don’t. (Annoyingly, I can only use it here if I return a function call from a void function, which is technically not legal. This doesn’t become an issue in functional programming, because functions with only side effects do not exist.)
Refactoring
So, let’s take as an example tar-print, which contains a while loop, and could therefore be refactored to use tail recursion:
/**
* @brief Prints file content (for testing purposes)
*
* @param tar
*/
void tar_print(tar *tar)
{
lseek(tar->fd, 0, SEEK_SET);
tar_entry *current = tar->files;
while(current) {
lseek(tar->fd, current->offset, SEEK_SET);
char buffer[512];
if(read(tar->fd, buffer, current->size) == 0) {
printf("EOF\n");
return;
}
printf("File: %s\n", current->header.filename);
printf("Content:\n%s\n\n", buffer);
current = current->next;
}
}
But First
Okay, before we go any further, stop and think about this:
char buffer[512];
if(read(tar->fd, buffer, current->size) == 0) { | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
c, file-system, tail-recursion
This looks like a buffer overrun to me. Always, always, always check for buffer overruns in C. And I mean it.
Are you absolutely, positively certain that current->size can never be greater than the size of buffer? No, because buffer is initialized with a literal that is not in sync with the code that manages these data structures! There is a #define TAR_BLOCKSIZE that looks like it might be relevant, but it isn’t used here. if you had a good reason to believe this was safe when you wrote it—and I don’t see any comment or explanation why that would be—this code has no way to tell what changes there might have been to the other module, nor does anyone maintaining it have anything warning them to come back here and update the size of this buffer, too.
So if you really, truly, are sure that this code will never overrun the buffer and break everything—if you know for a fact that it is perfectly safe—put your money where your mouth is and write
assert(current->size <= sizeof(buffer));
What reason is there not to? Your code is safe, right? There’s no bug here. So that assertion will always pass. Right?
Setting Things up
All right, with that out of the way, let’s take a look at the program. This code needs "tar_internal.h". Since you’re using the POSIX API, it’s a good idea to request a specific version of it before you include any headers, with
#define _POSIX_C_SOURCE 200809L
#define _XOPEN_SOURCE 700 | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
c, file-system, tail-recursion
Technically, setting both is redundant, but it protects you from anyone else setting either to a value you didn’t expect.
You don’t check any of your system calls for errors. That C even lets people away with this was a terrible idea. I’ll throw in the boilerplate I often use for all system calls that set errno:
void fatal_system_error_handler( const char* const msg,
const int err,
const char* sourcefile,
const int line )
{
fflush(stdout); // Don't cross the streams!
fprintf( stderr,
"%s (%s:%d): %s\n",
msg,
sourcefile,
line,
strerror(err) );
exit(EXIT_FAILURE);
}
#define fatal_system_error(msg) \
fatal_system_error_handler( (msg), errno, __FILE__, __LINE__ )
I also change the type of fd, apparently an open file descriptor, from size_t to int, because that’s how you’re using it.
Finally, I include all the headers needed for this to work.
Refactoring the Function Itself
There’s a bit of initialization, followed by the while loop. In another language, we’d put the initialization in a wrapper function and turn the loop into a nested helper function. In C, we don’t have nested functions, so the helper becomes a static function in the same file.
The while loop itself has three pieces of state it uses: a local buffer, a file descriptor tar->fd, and a pointer to current. The buffer doesn’t need to persist between invocations, so it can stay as a local. The other two become function parameters. Since they never need to be modified in the middle of an iteration, they can become const.
So the signature of the helper function replacing the while loop could be:
static void tar_print_helper( const int fd,
const tar_entry* const current ); | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
c, file-system, tail-recursion
The initialization does two things: lseek to an offset of 0, and intialize current. Since we’re only keeping a copy of the fd field of tar around, we initialize both of these pieces of state by calling tar_print_helper from our refactored function, creatively called tar_print2:
void tar_print2(const tar* const archive)
{
lseek(archive->fd, 0, SEEK_SET);
tar_print_helper(archive->fd, archive->files);
}
You’ll notice that the final line is a tail call, which is to say, the last thing the function does before it returns. It’s not tail-recursive, because it’s not calling itself (or a function with the same type of arguments as itself). Compilers often can inline function calls like that and optimize them the same way as tail-recursive calls. In practice, compilers sometimes do and sometimes don’t.
What does the helper, which replaces the loop, look like? Recall, the loop looks like this:
while(current) {
lseek(tar->fd, current->offset, SEEK_SET);
char buffer[512];
if(read(tar->fd, buffer, current->size) == 0) {
printf("EOF\n");
return;
}
printf("File: %s\n", current->header.filename);
printf("Content:\n%s\n\n", buffer);
current = current->next;
}
The refactored version looks like this:
static void tar_print_helper( const int fd,
const tar_entry* const current )
{
if (!current) {
return;
}
if ( (off_t)-1 == lseek(fd, current->offset, SEEK_SET) ) {
fatal_system_error("Error seeking to offset");
}
char buffer[512];
assert(current->size <= sizeof(buffer));
const ssize_t read_result = read(fd, buffer, current->size);
if (read_result < 0) {
fatal_system_error("Error reading from file descriptor in tar_entry");
}
if (read_result == 0) {
printf("EOF\n");
return;
}
printf("File: %s\n", current->header.filename);
printf("Content:\n%s\n\n", buffer); | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
c, file-system, tail-recursion
printf("File: %s\n", current->header.filename);
printf("Content:\n%s\n\n", buffer);
MUSTTAIL return tar_print_helper(fd, current->next);
}
Aside from one significant change to the code inside—actually checking for errors—only two things change. The loop condition becomes a test at the start of the function. (A do ... while loop would have it at the end instead.) And the update of current becomes a new call to the helper, with the new value of current as the second parameter. Because fd never changes, we can call it with the same value every time, and the compiler should notice that it never changes and optimize away any code to set it again.
What Does This Compile to?
This varies greatly. Clang 16.0.0 does not realize it can perform the tail-call optimization unless I specifically give it the MUSTTAIL directive although, once I do, it also recognizes that the non-tail-recursive call to it can be optimized away to a jump too. So this extension can sometimes improve the code considerably, even for functions that don’t make tail-recursive calls themselves.
ICX 2022 is based on a slightly-older version of the Clang backend, and has the same bug. GCC cannot do tail-call optimization on this code at all. Changing the function to return an int makes no difference here.
The problem here turns out to be declaring buffer as a local variable inside the helper. If I declare the buffer once, in the wrapper, and pass around a pointer to it, all three compilers become able to optimize it.
static void tar_print_helper( const int fd,
const tar_entry* const current,
char buffer[TAR_BLOCKSIZE] )
{
if (!current) {
return;
}
if ( (off_t)-1 == lseek(fd, current->offset, SEEK_SET) ) {
fatal_system_error("Error seeking to offset");
}
assert(current->size <= TAR_BLOCKSIZE);
const ssize_t read_result = read(fd, buffer, current->size); | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
c, file-system, tail-recursion
if (read_result < 0) {
fatal_system_error("Error reading from file descriptor in tar_entry");
}
if (read_result == 0) {
printf("EOF\n");
return;
}
printf("File: %s\n", current->header.filename);
printf("Content:\n%s\n\n", buffer);
return tar_print_helper(fd, current->next, buffer);
}
void tar_print2(const tar* const archive)
{
char buffer[TAR_BLOCKSIZE];
lseek(archive->fd, 0, SEEK_SET);
return tar_print_helper(archive->fd, archive->files, buffer);
} | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
c, file-system, tail-recursion
Another Example
I’ve written several solutions here that use tail recursion. Here’s one you might like.
Update: Error Handling
I’ll answer your question from the comments here.
I plugged in a piece of existing code I had, as a quick way to handle error codes (from library calls that set errno only!) You make a valid point that you don’t want a library to crash the program. You’ve thought about how this code should handle errors and what its requirements are, which is great! (Although, then, should it be sending messages to standard output, behind the application’s back?)
Indeed, some C coding standards forbid ignoring any return value, unless you explicitly write void. Some other languages, such as Rust, enforce this explicitly through its type system. Functions that might fail return a type that represents either an error or a valid result, and to use it for anything, you must unwrap it, and handle every case somehow (even if it’s just a runtime panic).
But your functions don’t report any errors, either, or return any information. They just return void. So, if there should be code elsewhere to recover or shut down more gracefully, how is any other code supposed to find out about them?
One classic approach is to return an error code. If you do this, be careful that the code for error is not also a valid return value! You might need to use a wider type for this; in this example, read() (in modern versions of POSIX) returns a ssize_t, or signed size type, rather that an unsigned size_t. This is so positive values can indicate success and negative values an error. Negative int values for error are the most common convention, because that’s how Dennis Ritchie and Ken Thompson did it. If you take this approach, all the if blocks that call fatal_system_error() would instead return -errno; (POSIX error values are positive) or maybe something like return (errno > 0) ? -errno : UNKNOWN_ERROR; to be sure. | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
c, file-system, tail-recursion
A variation on this is to define your own enum type that lists every possible error code. This has the advantage that the compiler, and your debugger, remember the name. Otherwise, you might have to look through a header file to see that -2 is -ENOENT, and means file-not-found (“No such directory entry”). It also means that if you handle errors in a switch block with no default: block, and someone later adds a new kind of error, the compiler will alert you that you are no longer handling every possible condition.
Another possible solution that I’ve implicitly referred to would be to keep an error code in a global variable. And the standard library still, for historical reasons, is stuck doing something that isn’t actually that any more but is mostly backwards-compatible with it. But that’s something that’s been abandoned. There are many problems with it, one of which is that it’s not thread-safe.
There’s another great option in C++ and many other languages: you can throw an exception. Whatever handler is currently active will catch it, and any resources allocated through RIIA will be properly released. The downside is that exceptions aren’t appropriate for a critical path, because catching one is slow. They’re designed for exceptional events that mean the program has to stop what it was doing anyway.
A final approach that’s often used in C is to return a success/error code and take a pointer to a destination buffer as an output parameter. This is not something you would frequently see used with tail recursion, though, since recursive solutions usually want to chain and compose their functions. | {
"domain": "codereview.stackexchange",
"id": 44593,
"lm_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, file-system, tail-recursion",
"url": null
} |
mathematics, template, generics, ada
Title: Using Ada's access type and generics to solve an ODE
Question: This post is linked to Ada: Convert float to decimal
I have produced Ada codes which uses the Euler algorithm Euler method to solve an ordinary differential equation. The codes given below are working fine. These codes were initially based on Ben Ari's Ada book: Ada for Software Engineers 2nd ed. 2009 Edition Section 13.6 in which Ada codes are given using the access type and generics to solve an ordinary differential equation with the Euler method. I've modified the codes so as to mimic hand (and calculator) computations so that what I get on paper matches the results I get with the Ada codes. An accuracy of six decimal places after the decimal was used.
The codes comprise of three parts: the main file diff.adb, the Euler procedure specification euler.ads and its body euler.adb. Sample results are given afterwards. Ada is robust in defining data in that which data type is more appropriate and since it's my first time with the access type and generics, I would like to know how the codes can be made better for example with the naming conventions and the data types used.
The main file diff.adb
with Ada.Numerics.Generic_Elementary_Functions; use Ada.Numerics;
with Ada.Text_IO; use Ada.Text_IO;
with Euler;
procedure Diff is
type Real is digits 7;
type Vector is array (Positive range <>) of Real;
type Ptr is access function (X : Real; Y : Real) return Real;
type Round_Ptr is access function (V : Real) return Real;
procedure Solve is new Euler (Float_Type => Real, Vector => Vector, Function_Ptr => Ptr, Function_Round_Ptr => Round_Ptr);
package Real_Functions is new Generic_Elementary_Functions (Real);
use Real_Functions;
package Real_IO is new Ada.Text_IO.Float_IO (Real);
use Real_IO; | {
"domain": "codereview.stackexchange",
"id": 44594,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "mathematics, template, generics, ada",
"url": null
} |
mathematics, template, generics, ada
function DFDX (X, Y : Real) return Real is (2.0 * X * Y);
function F (X : Real) return Real is (Exp (X**2.0 - 1.0));
function Round (V : in Real) return Real is (Real'Rounding (1.0E6 * V) / 1.0E6);
XI : constant Real := 1.0;
YI : constant Real := 1.0;
Step : constant Real := 0.1;
Result : Vector (Positive'First .. 6); --11 if step = 0.05
X_Value : Real;
begin
Solve (DFDX'Access, Round'Access, XI, YI, Step, Result);
Put_line(" x calc exact delta");
for N in Result'Range loop
X_Value := 1.0 + Step * Real (N - 1);
Put (X_Value, Exp => 0);
Put (" ");
Put (Result (N), Exp => 0);
Put (" ");
Put (F (X_Value), Exp => 0);
Put (" ");
Put (Result (N) - F (X_Value), Exp => 0);
Ada.Text_IO.New_Line;
end loop;
end Diff;
The file euler.ads
generic
type Float_Type is digits <>;
type Vector is array (Positive range <>) of Float_Type;
type Function_Ptr is access function (X, Y : Float_Type) return Float_Type;
type Function_Round_Ptr is access function (V : Float_Type) return Float_Type;
procedure Euler
(DFDX : in Function_Ptr; Round : Function_Round_Ptr; XI, YI, Step : in Float_Type; Result : out Vector);
The file euler.adb
procedure Euler
(DFDX : in Function_Ptr; Round : Function_Round_Ptr; XI, YI, Step : in Float_Type; Result : out Vector)
is
H : constant Float_Type := Step;
X : Float_Type := XI;
begin
Result (Result'First) := YI;
for N in Result'First + 1 .. Result'Last loop
Result (N) := Round(Result (N - 1)) + Round(H * DFDX (X, Result (N - 1)));
X := X + Step;
end loop;
end Euler;
The output with step h = 0.1 is
x
calc (Ada)
exact
delta
1.1
1.200000
1.233678
1.233678
1.2
1.464000
1.552707
-0.033678
1.3
1.815360
1.993716
-0.088707
1.4
2.287354
2.611696
-0.178356
1.5
2.927813
3.490343
-0.562530
The calc (Ada) results agree with hand (and calculator) computations (not shown here). | {
"domain": "codereview.stackexchange",
"id": 44594,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "mathematics, template, generics, ada",
"url": null
} |
mathematics, template, generics, ada
The calc (Ada) results agree with hand (and calculator) computations (not shown here).
Answer: Several elements merit comment:
Precision: Numerical methods using floating point math generally benefit from higher precision. There's no reason to round results during iteration. Instead, use the available precision, and format the displayed result as warranted:
type Real is digits System.Max_Digits;
Aft : constant := 6;
Put (F (X_Value), Aft => Aft, Exp => 0);
While this is a good general approach, a particular requested decimal precision may be able to rely on the Default_Aft, which is one less than the specified precision.
Initialization: For consistency, consider initializing YI with F(XI) and X_Value with XI.
Array indexing: While Ada conveniently permits indexing by any discrete type, the iterative nature of the algorithm may be more clear with a zero-based approach:
type Vector is array (Natural range <>) of Real;
Iteration: As the result Vector returns only ordinates, use the same iteration scheme to create and examine the results. Alternatively; consider passing two instances of Real_Vector or a Real_Matrix.
The compete example shown here produces the following result.
x calc exact delta
1.000000 1.000000 1.000000 0.000000
1.100000 1.200000 1.233678 0.033678
1.200000 1.464000 1.552707 0.088707
1.300000 1.815360 1.993716 0.178356
1.400000 2.287354 2.611696 0.324343
1.500000 2.927813 3.490343 0.562530
1.600000 3.806156 4.758821 0.952665
1.700000 5.024126 6.619369 1.595242
1.800000 6.732329 9.393331 2.661002
1.900000 9.155968 13.599051 4.443083
2.000000 12.635236 20.085537 7.450301 | {
"domain": "codereview.stackexchange",
"id": 44594,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "mathematics, template, generics, ada",
"url": null
} |
python, sqlalchemy, ddd
Title: DDD architecture pattern
Question: I'm trying to understand the DDD architecture pattern. I wrote a simple project in which I tried to use DDD arch. Here are my doubts after implementing it:
Does it make sense to use an ORM for a DDD project? Maybe I should drop the use of Base class from declarative_base?
Where should I define validators - in domain objects or in repository objects?
Should SimpleService(session) take a session in the initializer or specific repositories that I will create in the main function? Now I create it here:
class SimpleService:
"""Creates simple service."""
def __init__(self, session):
self.session = session
self.post_repository = PostRepository(session)
self.comment_repository = CommentRepository(session)
What should I change or improve in whole project? Please give me a quick review.
Short summary of project
Project structure:
.
│ main.py
│ README.rst
│ requirements.txt
│
├───blog
│ │ __init__.py
│ │
│ ├───domain
│ │ comment.py
│ │ post.py
│ │ __init__.py
│ │
│ ├───repository
│ │ │ __init__.py
│ │ │
│ │ ├───crud
│ │ │ base.py
│ │ │ comment.py
│ │ │ post.py
│ │ │ __init__.py
│ │ │
│ │ └───models
│ │ base.py
│ │ comment.py
│ │ post.py
│ │ __init__.py
│ │
│ └───service
│ simple.py
│ __init__.py
Business model in domain/post.py:
from dataclasses import dataclass
# from .comment import Comment
@dataclass
class Post:
id: str
title: str
content: str
# Should I implement it? If yes how to implement it here and in crud?
# comments: list[Comment]
#
# def __post_init__(self):
# if self.comments is None:
# self.comments = []
Orm model in repository/models/post.py:
from sqlalchemy import Column, String
from sqlalchemy.orm import relationship
from .base import Base | {
"domain": "codereview.stackexchange",
"id": 44595,
"lm_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, sqlalchemy, ddd",
"url": null
} |
python, sqlalchemy, ddd
class Post(Base):
__tablename__ = 'posts'
id = Column(String, primary_key=True)
title = Column(String)
content = Column(String)
executions = relationship('Comment', backref='post')
def __repr__(self):
return f'Post(id={self.id}, title={self.title}, content={self.content})'
CRUD class to manage orm model repository/crud/post.py:
from blog.repository.crud.base import BaseRepository
from blog.repository.models.post import Post as PostModel
from blog.domain.post import Post as PostEntity
class PostRepository(BaseRepository):
"""Creates object to manage post in data in database."""
def __init__(self, session):
self.session = session
def create(self, post):
"""Creates post."""
post_model = PostModel(id=post.id, title=post.title, content=post.content)
self.session.add(post_model)
self.session.commit()
def get_by_id(self, id_):
"""Gets post by id."""
post_model = self.session.query(PostModel).get(id_)
if post_model is not None:
return PostEntity(id=post_model.id, title=post_model.title, content=post_model.content)
Main business logic in service/simple.py:
import time
import uuid
from blog.repository.crud.comment import CommentRepository
from blog.repository.crud.post import PostRepository
from blog.domain.post import Post
from blog.domain.comment import Comment
class SimpleService:
"""Creates simple service."""
def __init__(self, session):
self.session = session
self.post_repository = PostRepository(session)
self.comment_repository = CommentRepository(session)
def run(self):
"""Performs fake operation (main app logic)."""
print('Fake action in simple service...') | {
"domain": "codereview.stackexchange",
"id": 44595,
"lm_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, sqlalchemy, ddd",
"url": null
} |
python, sqlalchemy, ddd
print('Creating posts...')
time.sleep(1)
post_id = str(uuid.uuid4())
post = Post(id=post_id,
title='Post 1',
content='Lorem Ipsum is simply dummy text of the printing and typesetting industry.')
self.post_repository.create(post)
print('Creating comment...')
time.sleep(1)
comment_id = str(uuid.uuid4())
comment_1 = Comment(id=comment_id,
content='Lorem Ipsum has been the industry\'s standard dummy text',
post=post)
self.comment_repository.create(comment_1)
print('Getting post from db...')
time.sleep(1)
print(self.post_repository.get_by_id(post_id))
print('Getting comment from db...')
time.sleep(1)
print(self.comment_repository.get_by_id(comment_id))
Entrypoint of app in main.py:
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from blog.repository.models.base import Base
from blog.service.simple import SimpleService
def main():
"""Entrypoint of app."""
database_uri = os.getenv('DATABASE_URI') # set DATABASE_URI=sqlite:///data.db
if database_uri is None:
database_uri = 'sqlite:///:memory:'
engine = create_engine(database_uri)
Base.metadata.create_all(engine)
with Session(engine) as session:
simple_service = SimpleService(session)
simple_service.run()
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 44595,
"lm_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, sqlalchemy, ddd",
"url": null
} |
python, sqlalchemy, ddd
if __name__ == '__main__':
main()
Answer: To expand a bit more on the other answer:
Does it make sense to use an ORM for a DDD project?
Yes, it's pretty common to use an ORM in a DDD project (pretty common = I am sharing my personal experience based on the projects that I have seen/worked on ). The key (IMO) is to ensure that the ORM does not leak into the domain layer. The repository layer (usually) acts as an interface between the domain layer and the persistence layer, so the domain layer should not be aware of the ORM implementation details. One way to achieve this is to define an abstraction layer on top of the ORM implementation, which is used by the repository layer. In your implementation, the ORM implementation details are in the repository/models directory, which is separated from the domain layer.
Regarding the use of the Base class from declarative_base, it depends on your project's requirements. If you don't need the functionality provided by the Base class, you can drop it.
Where should I define validators - in domain objects or in repository objects?
Validators should be defined in the domain objects because they are responsible for enforcing business rules. The repository layer's responsibility is to persist and retrieve domain objects, so it should not be concerned with enforcing business rules.
Should SimpleService(session) take a session in the initializer or specific repositories that I will create in the main function?
It's better to pass specific repositories to the SimpleService class's initializer because it helps to decouple the service layer from the persistence layer. In your implementation, you are passing the session to the SimpleService class's initializer and creating repositories inside the initializer. It's better to create the repositories in the main function and pass them to the SimpleService class's initializer. | {
"domain": "codereview.stackexchange",
"id": 44595,
"lm_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, sqlalchemy, ddd",
"url": null
} |
python, sqlalchemy, ddd
Regarding the overall implementation, it's a good start, and you have separated the domain layer from the persistence layer. Here are some suggestions for improvements:
Define interfaces for the repository layer and have concrete repository implementations that implement these interfaces. This way, you can swap out repository implementations without affecting the service layer or the domain layer.
Consider using a dependency injection framework to manage dependencies between layers.
Use a logger to log events and errors in your application.
Implement exception handling and error reporting to help with debugging and error recovery.
Consider implementing more functionality in your domain objects, such as validation and behaviour, instead of relying on data classes. | {
"domain": "codereview.stackexchange",
"id": 44595,
"lm_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, sqlalchemy, ddd",
"url": null
} |
performance, rust, mathematics
Title: Fast approximate sin/cos function in Rust
Question: Over the past month or so, I’ve been trying to create an extremely fast, platform agnostic, auto-vectorizing sin/cos function for fun. I initially started with sleef-rs’s fast sin function, and decoupled it from the library, made it more extensible, and optimized it further.
During my optimization process, I’ve been closely watching the generated assembly and llvm-mca on multiple platforms to make sure progressions on some platforms didn’t result in regressions on others. Right now, this is faster than SLEEF and Intel SVML, however, those are typically used for more accurate results.
Here’s the code currently:
#![feature(core_intrinsics)]
#![no_std]
use core::intrinsics::*;
/// Inputs valid between [-2^23, 2^23].
/// Precision can set between 0 and 3, with 0 being the fastest and least
/// precise, and 3 being the slowest and most precise.
/// If COS is set to true, the period is offset by PI/2.
///
/// As the inputs get further from 0, the accuracy gets continuously worse
/// due to nature of the fast range reduction.
///
/// This function should auto vectorize under LLVM with opt-level=3.
///
/// The coefficient constants were derived from the constants defined here:
/// https://publik-void.github.io/sin-cos-approximations/#_cos_abs_error_minimized_degree_6
#[inline]
pub unsafe fn sin_fast_approx<const PRECISION: usize, const COS: bool>(x: f32) -> f32 {
let pi_multiples = fadd_fast(
fmul_fast(x, core::f32::consts::FRAC_1_PI),
if COS { 0.0_f32 } else { -0.5_f32 },
);
let rounded_multiples = nearbyintf32(pi_multiples);
let pi_fraction = pi_multiples - rounded_multiples;
let fraction_squared = pi_fraction * pi_fraction; | {
"domain": "codereview.stackexchange",
"id": 44596,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, rust, mathematics",
"url": null
} |
performance, rust, mathematics
let coeffs = {
const COEFF_TABLE: [f32; 14] = [
-4.0_f32,
0.9719952_f32,
3.5838444_f32,
-4.8911867_f32,
0.99940324_f32,
-1.2221271_f32,
4.0412836_f32,
-4.933938_f32,
0.9999933_f32,
0.2196968_f32,
-1.3318802_f32,
4.058412_f32,
-4.934793_f32,
0.99999994_f32,
];
let shifted_degree = PRECISION + 1;
let slice_start = (((shifted_degree * shifted_degree) + shifted_degree) / 2) - 1;
let slice_end = slice_start + PRECISION + 2;
&COEFF_TABLE[slice_start..slice_end]
};
let mut output = coeffs[0];
for i in 1..coeffs.len() {
output = fadd_fast(fmul_fast(fraction_squared, output), coeffs[i]);
}
let parity_sign = (rounded_multiples.to_int_unchecked::<i32>() as u32) << 31_u32;
f32::from_bits(output.to_bits() ^ parity_sign)
} | {
"domain": "codereview.stackexchange",
"id": 44596,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, rust, mathematics",
"url": null
} |
performance, rust, mathematics
Code and built-in benchmarks on Compiler Explorer (Keep in mind that the hardware used to run the benchmarks is not consistent between tests. I would advise looking at llvm-mca to check the current architecture to interpret results.)
The main thing I’ve been watching is the separate truncation and rounding, attempting to combine them if possible. I’ve tried adding and subtracting 2^23, shifting the parity bit in between, but that was only faster on intel processors. I tried bit-shifting things around to combine parts of the operations, but that was slower across the board.
What I was able to do was, using platform-specific instructions, merge the round and int conversion into a single vcvtps2pd, and converting it back with a vcvtpd2ps, but I can’t seem to get LLVM to generate it for any situations. If I were able to get this to generate, it would be a pretty large performance gain for Intel CPUs that have a vroundps instruction with a 6-8 cycle latency.
Are there any ways to make this faster, more accurate (without sacrificing performance), or cleaner? | {
"domain": "codereview.stackexchange",
"id": 44596,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, rust, mathematics",
"url": null
} |
performance, rust, mathematics
Answer: I’ll defer to some of the greats and do this old-school. The Apollo 11 Guidance Computer approximation of sine (whose authors included Margaret Hamilton), calculated a three-term polynomial, .7853134·x - .3216147·x³ + 0.036551·x⁵ (close but not identical to a Taylor series approximation), This ran on a computer less powerful than your USB port, and was accurate enough to get a spaceship to the moon.
But that was well before my time. And at least she had a FPU! In the ’80s, it was commen to keep a table of one-eighth the unit circle, and rotate or reflect a lookup into that table to the actual sin or cos value requested using subrraction and/or reversing the sign.
For kicks, I went ahead and implemented a solution like that, which keeps a const table of the sin values in the first octant, maps all other values to the first octant using trigonometric identities, and rounds to the nearest discrete entry in the table.
I doubt this will actually be faster, since it has unpredictable branches, and a larger table with acceptable accuracy would incur a lot of cache misses. Also, Rust does not support floating-point math in const or static computations, so you would either need to generate a very large array expression in the source, or use lazy_static. Like I said, for kicks.
In theory, though, since the 8:1 mapping takes out the sine bit and two bits of precision, you could cover any f32 to the limit of its 24 bits of mantissa with “only” 4 Mi entries, using “only” 16 MiB of memory. Wonder what Margaret Hamilton would say about that.
And what programmers on computers without FPUs actually did back then was compute a fixed-precision table that used only integer math. If you could do that, you could actually turn this into aconst fn.
use std::f64::consts::TAU; | {
"domain": "codereview.stackexchange",
"id": 44596,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, rust, mathematics",
"url": null
} |
performance, rust, mathematics
const SIN_TABLE_ENTRIES : usize = 32;
const SIN_OCTANT : [f64; SIN_TABLE_ENTRIES + 1] = [
0.0, 0.024541228522912288, 0.049067674327418015, 0.07356456359966743,
0.0980171403295606, 0.1224106751992162, 0.14673047445536175, 0.17096188876030122,
0.19509032201612825, 0.2191012401568698, 0.24298017990326387, 0.26671275747489837,
0.29028467725446233, 0.3136817403988915, 0.33688985339222005, 0.3598950365349881,
0.3826834323650898, 0.40524131400498986, 0.4275550934302821, 0.44961132965460654,
0.47139673682599764, 0.49289819222978404, 0.5141027441932217, 0.5349976198870972,
0.5555702330196022, 0.5758081914178453, 0.5956993044924334, 0.6152315905806268,
0.6343932841636455, 0.6531728429537768, 0.6715589548470183, 0.6895405447370668,
0.0 // THis entry is a workaround for calculating a modulus of SIN_TABLE_ENTRIES instead of 0,
];
pub fn sin_approx(theta : f64) -> f64 {
let approx_gradient = (theta*8.0*SIN_TABLE_ENTRIES as f64/TAU).round() as i64 % (SIN_TABLE_ENTRIES*8) as i64;
let normalized = if approx_gradient < 0 {
(approx_gradient + 8*SIN_TABLE_ENTRIES as i64) as usize
} else {
approx_gradient as usize
}; | {
"domain": "codereview.stackexchange",
"id": 44596,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, rust, mathematics",
"url": null
} |
performance, rust, mathematics
if normalized < SIN_TABLE_ENTRIES {
SIN_OCTANT[normalized]
} else if normalized < 2*SIN_TABLE_ENTRIES {
let complement = SIN_OCTANT[2*SIN_TABLE_ENTRIES - normalized];
(1.0 - complement*complement).sqrt()
} else if normalized < 3*SIN_TABLE_ENTRIES {
let complement = SIN_OCTANT[normalized-2*SIN_TABLE_ENTRIES];
(1.0 - complement*complement).sqrt()
} else if normalized < 4*SIN_TABLE_ENTRIES {
SIN_OCTANT[4*SIN_TABLE_ENTRIES - normalized]
} else if normalized < 5*SIN_TABLE_ENTRIES {
-SIN_OCTANT[normalized - 4*SIN_TABLE_ENTRIES]
} else if normalized < 6*SIN_TABLE_ENTRIES {
let complement = SIN_OCTANT[6*SIN_TABLE_ENTRIES-normalized];
-(1.0 - complement*complement).sqrt()
} else if normalized < 7*SIN_TABLE_ENTRIES {
let complement = SIN_OCTANT[normalized-6*SIN_TABLE_ENTRIES];
-(1.0 - complement*complement).sqrt()
} else if normalized < 8*SIN_TABLE_ENTRIES {
-SIN_OCTANT[8*SIN_TABLE_ENTRIES-normalized]
} else {
panic!("The normalized index was not normalized!")
}
}
And a quick test:
pub fn main() {
(-24 as i32..=24).map(move|n|{n as f64 * TAU/12.0})
.map(move|x|{ ( x, x.sin(), sin_approx(x) ) })
.for_each(move|(theta, x1, x2)| {
println!("sin {} ≈ {} ≈ {}", theta, x1, x2); } )
} | {
"domain": "codereview.stackexchange",
"id": 44596,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, rust, mathematics",
"url": null
} |
performance, rust, mathematics
Update
This answer was more a different solution than an actual code review, so which I hope you don’t think is typical of this site. I’d wanted to investigate a few things about your answer, did not originally have time to finish, and what I found was, LGTM, ship it.
The one thing I might recommend is that it would be cleaner, in my opinion, if you wrote the calculation of the coefficent arrays as something like a match PRECISION block ending in _ => !unreachable(). That makes a bug where someone sets PRECISION to 5 fail fast, with a clear reason in the code why it failed. However, there is already a comment not far above explaining what the allowed values of PRECISION are. It would also be good to make the coefficients const, and const arrays of floating-point numbers are possible, just not const expressions that use floating-point operations. but as you know, Rust stops you from using the outer function’s const attribute. | {
"domain": "codereview.stackexchange",
"id": 44596,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, rust, mathematics",
"url": null
} |
c++, library, embedded, arduino
Title: Arduino library to simplify differential drive robots
Question: I've written code for an Arduino library to abstract away some of the underlying logic in a particular way of moving robots. Code is posted after explanations.
I'm not assuming a high degree of familiarity here so, I'll include abstracts from the README that will allow you to understand what the code is trying to do, and how its structured. If needed, I've taken the following code from its public repository at commit 5e25311 and you can view a more detailed README there.
This library provides an interface to easily control a differential wheeled robot using an Arduino-compatible microcontroller.
The expectation is that you have an even number of motors, with one half on either side of a structure that looks like a rover or a car. You then control the direction the robot moves in by controlling which motors turn on and in which direction. For example, if the left motors spin forward and the right motors spin backwards, the robot will rotate clockwise.
Types of robots offered by the library
There are classes for two kinds of robots included in this library.
Standard Differential Drive Robot
This is a normal differential drive robot, with motors on each side. It is what we described above: the direction is controlled by controlling which motors turn on and in which direction.
The class for this is DDBot.
Forward-biased Differential Drive Robot
The physical robot for this can be the same as a standard differential drive robot, but the control is different. In this case, the robot's motor's are always set to move forward. The direction is controlled by varying the speeds of the motors. In certain cases (like line followers), it is expected that this library leads to more less jerky motion of the robot.
The class for this is ForwardDDBot.
Different files
File name and location
Purpose
DDBot.h
Header file for declaring classes and inheritance.
DDBot.cpp
Source for function definitions. | {
"domain": "codereview.stackexchange",
"id": 44597,
"lm_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++, library, embedded, arduino",
"url": null
} |
c++, library, embedded, arduino
DDBot.cpp
Source for function definitions.
examples/Square/Square.ino
Example 1 of using the library.
examples/SpeedTuner/SpeedTuner.ino
Example 2 of using the library.
DDBot.h
#include <Arduino.h>
#ifndef DDBot_h
#define DDBot_h
/* Differential Drive Bot
This is a conventional **differential wheeled robot**, and direction is set by varying which motors spin
and in which direction.
Here, speed control of a motor simply controls how fast the robot moves. The expected use of this library
just involves the user calling the method of the appropriate direction and/or speed in their main loop.
*/
class DDBot {
private:
public:
// the sequence of pins is important, and is used throughout the library
// the first two pins are for the left motor, and the second two are for the right motor
// the first pin in each pair is for the forward direction, and the second is for the backward direction
uint8_t directionPins[4];
// when each motor has a dedicated PWM pin, it's possible to control the speed of each motor independently
// in other cases, the speed of each motor is controlled by the same PWM pin
// two declarations exist to accommodate both cases, and this pattern is used throughout the library
uint8_t PWMPins[2] = {0, 0};
uint8_t PWMPin = 0;
// the constructors are responsible for setting the pin numbers from the arguments to the class properties
DDBot(); // allow the user to directly set the arrays
DDBot(uint8_t directionPins[4]);
DDBot(uint8_t directionPins[4], uint8_t PWMPins[2]);
DDBot(uint8_t directionPins[4], uint8_t PWMPin);
void setPinModes();
void setSpeed(uint8_t speed);
void setSpeed(uint8_t leftSpeed, uint8_t rightSpeed); | {
"domain": "codereview.stackexchange",
"id": 44597,
"lm_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++, library, embedded, arduino",
"url": null
} |
c++, library, embedded, arduino
void setSpeed(uint8_t speed);
void setSpeed(uint8_t leftSpeed, uint8_t rightSpeed);
void writeDirections(bool leftForward, bool leftBackward, bool rightForward, bool rightBackward);
void writeDirections(bool leftForward, bool leftBackward, bool rightForward, bool rightBackward, uint8_t speed);
void writeDirections(bool leftForward, bool leftBackward, bool rightForward, bool rightBackward, uint8_t leftSpeed, uint8_t rightSpeed);
void forward();
void forward(uint8_t speed);
void forward(uint8_t leftSpeed, uint8_t rightSpeed);
void backward();
void backward(uint8_t speed);
void backward(uint8_t leftSpeed, uint8_t rightSpeed);
void left();
void left(uint8_t speed);
void left(uint8_t leftSpeed, uint8_t rightSpeed);
void right();
void right(uint8_t speed);
void right(uint8_t leftSpeed, uint8_t rightSpeed);
void clockwise();
void clockwise(uint8_t speed);
void clockwise(uint8_t leftSpeed, uint8_t rightSpeed);
void counterClockwise();
void counterClockwise(uint8_t speed);
void counterClockwise(uint8_t leftSpeed, uint8_t rightSpeed);
// it doesn't make sense to specify a PWM variant of a stop command
void stop();
~DDBot();
};
/* Forward Differential Drive Bot
This is a **differential wheeled robot** with a forward bias, and direction is set by varying just the
speed of each motor. So while the classic differential drive bot can use the same physical structure,
the functionality is different. For example, a forward differential drive bot can't turn in place or
move backwards.
This class was built for line following robots, where the robot is biased towards moving forward, and
just incrementally varying the speed provides smoother control than the classic differential drive bot.
This is important to ensure that the robot doesn't overshoot and lose track of the line. | {
"domain": "codereview.stackexchange",
"id": 44597,
"lm_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++, library, embedded, arduino",
"url": null
} |
c++, library, embedded, arduino
Conventionally, the direction of a differential wheeled robot is set by turning motors on
or off in a specific direction. In this setup, they are set to move forward perpetually, and
direction control is achieved by varying the speed of each motor instead. This allows for
smoother turns and will (hopefully) help the robot to stay on its line more reliably.
The main loop should be structured to use feedback control. To use this library, the user should call
the method of the appropriate direction when they want, and call the `write()` method once per loop.
This will update the speed of each motor to come closer to the target speed. This is done to avoid
sudden changes in speed. A delay might have to be added to the main loop to allow the changes to
propagate.
*/
class ForwardDDBot : public DDBot {
private:
// this is the value used to "slow down" a motor
// it is used when we want to turn, but don't want to set the speed of the other motor to 0
// this will be calculated in the init() method by multiplying the maxPWM by the adjustment factor
uint8_t _adjustedPWM;
// "actual" values are written to a motor during a given call of the write() method
// "target" values are the values that the user wants to write to a motor
// in each call of the write() method, the actual values are adjusted to come closer to the target values
uint8_t leftActualPWM, leftTargetPWM, rightActualPWM, rightTargetPWM;
public:
uint8_t maxPWM; // maximum "speed" for each motor
float adjustment; // scaling factor used when slowing down a given motor | {
"domain": "codereview.stackexchange",
"id": 44597,
"lm_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++, library, embedded, arduino",
"url": null
} |
c++, library, embedded, arduino
// the constructors are responsible for setting the pin numbers from the arguments to the class properties
ForwardDDBot(); // allow the user to directly set the arrays or the default PWM values
ForwardDDBot(uint8_t maxPWM, float adjustment);
ForwardDDBot(uint8_t directionPins[4], uint8_t PWMPins[2]);
ForwardDDBot(uint8_t directionPins[4], uint8_t PWMPins[2], uint8_t maxPWM, float adjustment);
void init();
void calculateAdjustedPWM();
void left();
void centre();
void right();
void stop();
// recall that rotations and moving backwards are not possible with this type of robot
// so these methods are not implemented
void write();
~ForwardDDBot();
};
#endif // DDBot_h
DDBot.cpp
#include "DDBot.h"
#include <Arduino.h>
#ifndef DDBot_cpp
#define DDBot_cpp
DDBot::DDBot() {}
DDBot::~DDBot() {}
DDBot::DDBot(uint8_t directionPins[4]) {
for (size_t i = 0; i < 4; i++) {
this->directionPins[i] = directionPins[i];
}
}
DDBot::DDBot(uint8_t directionPins[4], uint8_t PWMPins[2]) {
for (size_t i = 0; i < 4; i++) {
this->directionPins[i] = directionPins[i];
}
for (size_t i = 0; i < 2; i++) {
this->PWMPins[i] = PWMPins[i];
}
}
DDBot::DDBot(uint8_t directionPins[4], uint8_t PWMPin) {
for (size_t i = 0; i < 4; i++) {
this->directionPins[i] = directionPins[i];
}
this->PWMPin = PWMPin;
}
void DDBot::setPinModes() {
for (size_t i = 0; i < 4; i++) {
pinMode(directionPins[i], OUTPUT);
}
// do not set pinMode(s) for PWM pin(s) if they are not set (i.e. if they are 0)
if (PWMPins[0] != 0 && PWMPins[1] != 0) {
for (size_t i = 0; i < 2; i++) {
pinMode(PWMPins[i], OUTPUT);
}
}
if (PWMPin != 0) {
pinMode(PWMPin, OUTPUT);
}
} | {
"domain": "codereview.stackexchange",
"id": 44597,
"lm_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++, library, embedded, arduino",
"url": null
} |
c++, library, embedded, arduino
if (PWMPin != 0) {
pinMode(PWMPin, OUTPUT);
}
}
void DDBot::setSpeed(uint8_t speed) {
// do not set speed for PWM pin(s) if they are not set (i.e. if they are 0)
if (PWMPins[0] != 0 && PWMPins[1] != 0) {
analogWrite(PWMPins[0], speed);
analogWrite(PWMPins[1], speed);
}
if (PWMPin != 0) {
analogWrite(PWMPin, speed);
}
}
void DDBot::setSpeed(uint8_t leftSpeed, uint8_t rightSpeed) {
analogWrite(PWMPins[0], leftSpeed);
analogWrite(PWMPins[1], rightSpeed);
}
void DDBot::writeDirections(bool leftForward, bool leftBackward, bool rightForward, bool rightBackward) {
digitalWrite(directionPins[0], leftForward);
digitalWrite(directionPins[1], leftBackward);
digitalWrite(directionPins[2], rightForward);
digitalWrite(directionPins[3], rightBackward);
}
void DDBot::writeDirections(bool leftForward, bool leftBackward, bool rightForward, bool rightBackward, uint8_t speed) {
digitalWrite(directionPins[0], leftForward);
digitalWrite(directionPins[1], leftBackward);
digitalWrite(directionPins[2], rightForward);
digitalWrite(directionPins[3], rightBackward);
setSpeed(speed);
}
void DDBot::writeDirections(bool leftForward, bool leftBackward, bool rightForward, bool rightBackward, uint8_t leftSpeed, uint8_t rightSpeed) {
digitalWrite(directionPins[0], leftForward);
digitalWrite(directionPins[1], leftBackward);
digitalWrite(directionPins[2], rightForward);
digitalWrite(directionPins[3], rightBackward);
setSpeed(leftSpeed, rightSpeed);
}
// the following methods set the direction of the robot by controlling which
// direction motors are going to turn and in which direction
// you can figure out these methods by trying to imagine the robot, maybe
// using a model or a drawing
void DDBot::forward() {
writeDirections(HIGH, LOW, HIGH, LOW);
}
void DDBot::forward(uint8_t speed) {
writeDirections(HIGH, LOW, HIGH, LOW, speed);
} | {
"domain": "codereview.stackexchange",
"id": 44597,
"lm_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++, library, embedded, arduino",
"url": null
} |
c++, library, embedded, arduino
void DDBot::forward(uint8_t speed) {
writeDirections(HIGH, LOW, HIGH, LOW, speed);
}
void DDBot::forward(uint8_t leftSpeed, uint8_t rightSpeed) {
writeDirections(HIGH, LOW, HIGH, LOW, leftSpeed, rightSpeed);
}
void DDBot::backward() {
writeDirections(LOW, HIGH, LOW, HIGH);
}
void DDBot::backward(uint8_t speed) {
writeDirections(LOW, HIGH, LOW, HIGH, speed);
}
void DDBot::backward(uint8_t leftSpeed, uint8_t rightSpeed) {
writeDirections(LOW, HIGH, LOW, HIGH, leftSpeed, rightSpeed);
}
void DDBot::left() {
writeDirections(LOW, HIGH, LOW, LOW);
}
void DDBot::left(uint8_t speed) {
writeDirections(LOW, HIGH, LOW, LOW, speed);
}
void DDBot::left(uint8_t leftSpeed, uint8_t rightSpeed) {
writeDirections(LOW, HIGH, LOW, LOW, leftSpeed, rightSpeed);
}
void DDBot::right() {
writeDirections(LOW, LOW, LOW, HIGH);
}
void DDBot::right(uint8_t speed) {
writeDirections(LOW, LOW, LOW, HIGH, speed);
}
void DDBot::right(uint8_t leftSpeed, uint8_t rightSpeed) {
writeDirections(LOW, LOW, LOW, HIGH, leftSpeed, rightSpeed);
}
void DDBot::clockwise() {
writeDirections(LOW, HIGH, HIGH, LOW);
}
void DDBot::clockwise(uint8_t speed) {
writeDirections(LOW, HIGH, HIGH, LOW, speed);
}
void DDBot::clockwise(uint8_t leftSpeed, uint8_t rightSpeed) {
writeDirections(LOW, HIGH, HIGH, LOW, leftSpeed, rightSpeed);
}
void DDBot::counterClockwise() {
writeDirections(HIGH, LOW, LOW, HIGH);
}
void DDBot::counterClockwise(uint8_t speed) {
writeDirections(HIGH, LOW, LOW, HIGH, speed);
}
void DDBot::counterClockwise(uint8_t leftSpeed, uint8_t rightSpeed) {
writeDirections(HIGH, LOW, LOW, HIGH, leftSpeed, rightSpeed);
}
void DDBot::stop() {
writeDirections(LOW, LOW, LOW, LOW);
}
ForwardDDBot::ForwardDDBot() {}
ForwardDDBot::~ForwardDDBot() {}
ForwardDDBot::ForwardDDBot(uint8_t maxPWM, float adjustment) {
this->maxPWM = maxPWM;
this->adjustment = adjustment;
} | {
"domain": "codereview.stackexchange",
"id": 44597,
"lm_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++, library, embedded, arduino",
"url": null
} |
c++, library, embedded, arduino
ForwardDDBot::ForwardDDBot(uint8_t directionPins[4], uint8_t PWMPins[2]) {
for (size_t i = 0; i < 4; i++) {
this->directionPins[i] = directionPins[i];
}
for (size_t i = 0; i < 2; i++) {
this->PWMPins[i] = PWMPins[i];
}
}
ForwardDDBot::ForwardDDBot(uint8_t directionPins[4], uint8_t PWMPins[2], uint8_t maxPWM, float adjustment) {
for (size_t i = 0; i < 4; i++) {
this->directionPins[i] = directionPins[i];
}
for (size_t i = 0; i < 2; i++) {
this->PWMPins[i] = PWMPins[i];
}
this->maxPWM = maxPWM;
this->adjustment = adjustment;
}
void ForwardDDBot::calculateAdjustedPWM() {
// this is the value used to "slow down" a motor
// it is used when we want to turn, but don't want to set the speed of the other motor to 0
_adjustedPWM = this->maxPWM * this->adjustment;
}
void ForwardDDBot::init() {
setPinModes();
calculateAdjustedPWM();
this->leftActualPWM = maxPWM;
this->rightActualPWM = maxPWM;
// set the robot to perpetually move forward
forward(leftActualPWM, rightActualPWM);
}
// the following methods set the direction of the robot by controlling which
// motor spins faster and which one slower
// the logic here is the same as in the conventional differential drive robot
// and you can figure it out the same way
void ForwardDDBot::left() {
leftTargetPWM = _adjustedPWM;
rightTargetPWM = maxPWM;
}
void ForwardDDBot::right() {
leftTargetPWM = maxPWM;
rightTargetPWM = _adjustedPWM;
}
void ForwardDDBot::centre() {
leftTargetPWM = maxPWM;
rightTargetPWM = maxPWM;
}
void ForwardDDBot::stop() {
leftTargetPWM = 0;
rightTargetPWM = 0;
} | {
"domain": "codereview.stackexchange",
"id": 44597,
"lm_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++, library, embedded, arduino",
"url": null
} |
c++, library, embedded, arduino
void ForwardDDBot::stop() {
leftTargetPWM = 0;
rightTargetPWM = 0;
}
void ForwardDDBot::write() {
// update "actual" PWM values so that they get closer to the "target" values
// this will eventually get the values to equal, as exponential decay (but
// with integer division)
leftActualPWM = (leftTargetPWM + leftActualPWM) / 2;
rightActualPWM = (rightTargetPWM + rightActualPWM) / 2;
// write the actual PWM values to the motor driver
analogWrite(PWMPins[0], leftActualPWM);
analogWrite(PWMPins[1], rightActualPWM);
}
#endif // DDBot_cpp
examples/Square/Square.ino
/* Square
This example shows how to use the DDBot library to make the robot move in a square.
The robot will move forward for 2 seconds, then turn right for 1 second, then move forward for 2 seconds, then turn right for 1 second, and so on.
The circuit:
* Pin 2 to left motor forward
* Pin 3 to left motor backward
* Pin 4 to right motor forward
* Pin 5 to right motor backward
* Pin 10 to left motor speed
* Pin 11 to right motor speed
*/
#include <Arduino.h>
#include <DDBot.h>
// define the pins used by the motors
uint8_t directionPins[4] = {2, 3, 4, 5};
uint8_t speedPins[2] = {10, 11};
// create an instance of the DDBot class
// this allows you to potentially control multiple robots at once using multiple instances
DDBot bot(directionPins, speedPins);
void setup() {
// set the pin modes for the motor DIO pins
bot.setPinModes();
}
void loop() {
// move forward with full speed for 2 seconds
bot.forward(255);
delay(2000);
// turn right with full speed for 1 second
bot.right(255);
delay(1000);
}
examples/SpeedTuner/SpeedTuner.ino
/* SpeedTuner
This example shows how to use the DDBot library to figure out the right values for tuning
PWM parameters for use with the Forward-biased Differential Drive robot. | {
"domain": "codereview.stackexchange",
"id": 44597,
"lm_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++, library, embedded, arduino",
"url": null
} |
c++, library, embedded, arduino
The robot will start with 0 adjustment. It will then increase the adjustment by
0.05, attempt to forward for 3 seconds, and then increase the adjustment by 0.05 again.
This process repeats until the adjustment is 1.0, at which point the robot will stop.
It will then repeat the process while going backwards, increasing the adjustment from 0 to
1.0 in 0.05 increments.
At each stage, it will output the adjustment value and the adjusted PWM to the Serial monitor,
so that you can determine when it has sufficient PWM to accelerate.
The circuit:
* Pin 2 to left motor forward
* Pin 3 to left motor backward
* Pin 4 to right motor forward
* Pin 5 to right motor backward
* Pin 10 to left motor speed
* Pin 11 to right motor speed
*/
#include <Arduino.h>
#include <DDBot.h>
// define the pins used by the motors
uint8_t directionPins[4] = {2, 3, 4, 5};
uint8_t speedPins[2] = {10, 11};
// create an instance of the DDBot class
// this allows you to potentially control multiple robots at once using multiple instances
ForwardDDBot bot(directionPins, speedPins);
void setup() {
// use the maximum possible PWM value
bot.maxPWM = 255;
// set the pin modes for the motor DIO pins
bot.init();
// initialize the adjustment value
bot.adjustment = 0.0;
// open the Serial connection
Serial.begin(115200);
bot.forward();
// 1 / 0.05 per increment = 20 increments, so we have 20 iterations
for (int counter = 0; counter < 20; counter++) {
bot.adjustment += 0.05;
bot.calculateAdjustedPWM();
Serial.print("[Forward] Adjustment: ");
Serial.print(bot.adjustment);
Serial.print(", Adjusted PWM: ");
Serial.println(bot.maxPWM * bot.adjustment); | {
"domain": "codereview.stackexchange",
"id": 44597,
"lm_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++, library, embedded, arduino",
"url": null
} |
c++, library, embedded, arduino
// we need to update the PWM values to allow the feedback loop to work
// we do this by calling the write() method 300 times, with a 10 ms delay between each call,
// which is a total of 3 seconds
for (int i = 0; i < 300; i++) {
delay(10);
bot.write();
}
}
// stop the robot for 5 seconds
bot.stop();
delay(5000);
// reset the adjustment value
bot.adjustment = 0.0;
bot.backward();
// again, we have 20 iterations, for a total of 1.0 adjustment over 3 seconds
for (int counter = 0; counter < 20; counter++) {
bot.adjustment += 0.05;
bot.calculateAdjustedPWM();
Serial.print("[Backward] Adjustment: ");
Serial.print(bot.adjustment);
Serial.print(", Adjusted PWM: ");
Serial.println(bot.maxPWM * bot.adjustment);
// again, we need to update the PWM values to allow the feedback loop to work
// so 300 iterations * 10 ms per iteration = 3 seconds
for (int i = 0; i < 300; i++) {
delay(10);
bot.write();
}
}
bot.stop();
}
void loop() {}
``` | {
"domain": "codereview.stackexchange",
"id": 44597,
"lm_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++, library, embedded, arduino",
"url": null
} |
c++, library, embedded, arduino
bot.stop();
}
void loop() {}
```
Answer: It's great that you have a library that works for you, but now you should think of redesigning it. I see that class DDBot is implementing the low-level functionality (controlling pins and PWM values), and class ForwardDDBot provides a more high-level interface that also takes care of scaling values and smoothly changing motor speeds. If that is the case, then I see some issues:
Keep DDBot as simple as possible
There are so many functions in DDBot, but do you really need them all? If this is supposed to be for low-level control of the motors, I think you only need one function that sets the speed of the left and right motor. By taking the parameters as signed integers, you avoid having to pass the directions:
void DDBot::setSpeed(int leftSpeed, int rightSpeed) {
digitalWrite(directionPins[0], left > 0);
digitalWrite(directionPins[1], left < 0);
digitalWrite(directionPins[2], right > 0);
digitalWrite(directionPins[3], right < 0);
analogWrite(PWMPins[0], abs(leftSpeed));
analogWrite(PWMPins[1], abs(rightSpeed));
} | {
"domain": "codereview.stackexchange",
"id": 44597,
"lm_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++, library, embedded, arduino",
"url": null
} |
c++, library, embedded, arduino
You can do any move you want with just this function.
Think about physical units
If I would ask you "how fast can your robot go?", would your answer be "255"? No, you would say something like "X meters per second". For a higher level interface, it would be nice to provide such a physical unit, and have your library convert it to a PWM setting. The question then is, what does the PWM value control? Is it the rotation speed of the motor? In that case, you could consider using "revolutions per second", or if you know the diameter of the wheels, "meters per second" as the unit for parameters passed to the high level interface.
It could also be that the PWM value doesn't control the speed, but rather the torque. Torque is measured in newton meters, and given the mass of your robot, you could calculate the acceleration a given torque would provide. Once the robot reaches a certain speed, the torque is canceled out by friction, and the robot will then stay at that speed. This could also be measured or calculated to some degree, so that you could provide an interface where you provide speed in meters per second, and it will then convert that to the right PWM value to reach that speed.
There is no feedback control
You mention "feedback control" in your comments, however what you have implemented does not rely on feedback at all, instead it's an open-loop controller to smooth the transition from one speed to another. This will indeed help smooth the motion of the robot, but the way you implemented it is very naive. | {
"domain": "codereview.stackexchange",
"id": 44597,
"lm_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++, library, embedded, arduino",
"url": null
} |
c++, library, embedded, arduino
First, consider that the smoothing depends entirely on how often write() is called. But what should the delay between calls to write() be? If you call it too often, the robot will move jerky again. If you don't call it often enough, the robot will take a long time to reach the desired speed. You could actually check in write() how long it was since the last time it was called, and take the actual delay into account. That would remove the responsibility of calling write() at exactly the right interval from the caller into your library.
But then consider that the first call to write(), you take a large step, and subsequent calls make smaller and smaller steps. So it can still make a jerky movement when you make a large speed change. A smoother way to change speeds is to just add or subtract one from the actual PWM value in each call to write(), until you reach the desired value.
Note that jerk is a mathematically well-defined concept. Since it is the derivative of the acceleration, it's easy to see that you should keep changes in acceleration as low as possible to minimize jerk.
Be careful when doing math with integers
Consider this line of code:
leftActualPWM = (leftTargetPWM + leftActualPWM) / 2; | {
"domain": "codereview.stackexchange",
"id": 44597,
"lm_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++, library, embedded, arduino",
"url": null
} |
c++, library, embedded, arduino
Depending on the type of the variables, the addition could overflow before the division is performed, which would result in an unexpected result, possibly leading to badly behaving motor speed.
While it might actually be safe here due to integer promotion rules, you could explicitly convert the values to a type that you know is safe for the given operation:
leftActualPWM = (static_cast<uint16_t>(leftTargetPWM) + leftActualPWM) / 2;
Or if possible, as Toby Speight suggested, use C++20's std::midpoint():
leftActualPWM = std::midpoint(leftTargetPWM, leftActualPWM);
Alternatively, if the CPU in your Arduino has hardware support for floating point operations, I would rather store most variables as float, and only convert to uint8_t PWM values right before calling analogWrite(). | {
"domain": "codereview.stackexchange",
"id": 44597,
"lm_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++, library, embedded, arduino",
"url": null
} |
c#, .net, reflection
Title: Copy object without reference using reflection
Question: Recently I was in need of a method to copy an object and pass it to a method which alters the data. Since a class is passed by reference this would alter the class in the caller which I don't want.
So, I wrote a generic extension method which does the trick. Yet i'm unsure if this is a good solution to my problem. I would like to use reflection to achieve the goal. I can't use ICloneable and I would like to avoid serializing and deserializing the class. I have also looked into making the class a struct but will refrain from this since the classes can be way larger than 16 bytes and don't really suit the basic guidelines of when to use a struct.
Here is my extension method:
public static T CreateNonReferencedObject<T>(this T obj)
{
var tObj = (T)Activator.CreateInstance(typeof(T));
if (obj == null) return tObj;
var properties = obj.GetType().GetProperties();
foreach (var property in properties)
{
var value = property.GetValue(obj);
tObj.GetType().GetProperty(property.Name).SetValue(tObj, value);
}
return tObj;
}
Answer: After a deeper dive as to why I exactly made this function I have found out that I made this extension method to remove the reference from an entity I Get() with Entityframework facepalm. I have rewritten the code to .AsNoTracking() instead so the code actually makes sense. The CreateNonReferencedObject() method is now unnecessary. | {
"domain": "codereview.stackexchange",
"id": 44598,
"lm_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, reflection",
"url": null
} |
c++, classes
Title: any bits unsigned integer
Question: This is a class that acts as an unsigned integer with a variable amount of bits.
#include <iostream>
#include <cstdint>
// any amount of bits inteter
// note: stores with size of uint64_t
template <uint8_t bits_g>
class uintx_t {
private:
uint64_t Val;
uint8_t bits;
constexpr inline uint64_t _formatBits(
const uint64_t& val,
const uint16_t& _bits
) {return val & UINT64_MAX >> (64-_bits);}
public:
uintx_t(const int64_t& val) {
bits = bits_g;
if (bits > 64) bits = 64;
else if (bits < 1 ) bits = 1;
Val = _formatBits(val, bits);
}
void operator= (uintx_t& val) {
Val = _formatBits(val.Val, bits);
}
void operator= (const int64_t& val) {
Val = _formatBits(val, bits);
}
bool operator== (const int64_t& val) {
return (Val == val);
}
bool operator!= (const int64_t& val) {
return (Val != val);
}
bool operator> (const int64_t& val) {
return (Val > val);
}
bool operator< (const int64_t& val) {
return (Val < val);
}
bool operator>= (const int64_t& val) {
return (Val >= val);
}
bool operator<= (const int64_t& val) {
return (Val <= val);
} | {
"domain": "codereview.stackexchange",
"id": 44599,
"lm_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++, classes",
"url": null
} |
c++, classes
int64_t operator+ (const int64_t& val) {
return (_formatBits(Val + val, bits));
}
int64_t operator- (const int64_t& val) {
return (_formatBits(Val - val, bits));
}
int64_t operator* (const int64_t& val) {
return (_formatBits(Val * val, bits));
}
int64_t operator/ (const int64_t& val) {
return (_formatBits(Val / val, bits));
}
int64_t operator% (const int64_t& val) {
return (_formatBits(Val % val, bits));
}
int64_t operator| (const int64_t& val) {
return (_formatBits(Val | val, bits));
}
int64_t operator& (const int64_t& val) {
return (_formatBits(Val & val, bits));
}
int64_t operator^ (const int64_t& val) {
return (_formatBits(Val ^ val, bits));
}
int64_t operator<< (const int64_t& val) {
return (_formatBits(Val << val, bits));
}
int64_t operator>> (const int64_t& val) {
return (_formatBits(Val >> val, bits));
}
uintx_t& operator++ () {
Val = _formatBits(++Val, bits);
return *this;
}
uintx_t& operator-- () {
Val = _formatBits(--Val, bits);
return *this;
}
uintx_t operator++ (int) {
Val = _formatBits(++Val, bits);
return *this;
}
uintx_t operator-- (int) {
Val = _formatBits(--Val, bits);
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 44599,
"lm_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++, classes",
"url": null
} |
c++, classes
void operator+= (const int64_t& val) {
Val = _formatBits(Val+val, bits);
}
void operator-= (const int64_t& val) {
Val = _formatBits(Val-val, bits);
}
void operator*= (const int64_t& val) {
Val = _formatBits(Val*val, bits);
}
void operator/= (const int64_t& val) {
Val = _formatBits(Val/val, bits);
}
void operator%= (const int64_t& val) {
Val = _formatBits(Val%val, bits);
}
void operator|= (const int64_t& val) {
Val = _formatBits(Val|val, bits);
}
void operator&= (const int64_t& val) {
Val = _formatBits(Val&val, bits);
}
void operator^= (const int64_t& val) {
Val = _formatBits(Val^val, bits);
}
void operator<<= (const int64_t& val) {
Val = _formatBits(Val<<val, bits);
}
void operator>>= (const int64_t& val) {
Val = _formatBits(Val>>val, bits);
}
friend std::ostream& operator<< (
std::ostream& os,
uintx_t& UX
) {
os << std::to_string(UX.Val);
return os;
}
template <typename T>
explicit operator T() const {
return (T)Val;
}
};
The issue I have with this right now is that overloading an operator with another uintx_t doesn't work without having it casted to another type. I tried to overload the operators specifically for uintx_t but since 2 objects could have differing amount of bits, I couldn't figure out how to get it to work.
Answer: Code Style
Your coding style changes throughout your code, you should try to stick to one. Also, you should never name things starting with an _, this is reserved for the standard library and compilers.
Some rules I like (based on the standard library) are for example:
name your templates in PascalCase,
name your members in snake_case. | {
"domain": "codereview.stackexchange",
"id": 44599,
"lm_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++, classes",
"url": null
} |
c++, classes
name your templates in PascalCase,
name your members in snake_case.
Bits between 1 and 64
I feel like it is misleading to allow the user to use bit values less than 1 or bigger than 64, and silently put it in that range. I would recommend doing the following instead:
template <std::uint8_t bits>
requires(bits >= 1 && bits <= 64)
struct uintx_t {
This way, if the user tries to have a number of bits higher than 64 or less than 1, the code will not compile.
bits member
Why do you have a member uint8_t bits? If the only reason is the one above, then you can remove it. If you absolutely want to keep it you should mark it static constexpr, this will avoid having a copy on all your objects. Also, thanks to memory alignment, having the uint8_t makes the struct 128 bits on my computer, so it doubles the size of the struct.
const uint64_t& val
You should not pass integers by const &, they are small enough that a copy does not matter (I mean that it is the same to copy a 64 bits pointer and a 64 bits integer), it removes an indirection, and it makes the code cleaner.
Format bits
For someone just reading the code, it is unclear what the priorities are in the format bit function, so I would recommend adding parenthesis.
You can also add the static qualifier. I would argue you can even move the function out of the class, this would make it more testable.
With all the above comments taken into account as well, this gives:
constexpr static inline uint64_t formatBits(uint64_t val, uint16_t bits) {
return val & (UINT64_MAX >> (64 - bits));
}
Operators
Not really feedback here, but more a question. Why do the operators return an int64_t and not a uintx_t ?
Regarding your issue with overloading your operators for uintx_t, you can just template your operators: template <uint8_t OtherBits>. Should you require more assistance, I would recommend heading over to StackOverflow. | {
"domain": "codereview.stackexchange",
"id": 44599,
"lm_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++, classes",
"url": null
} |
performance, c
Title: Moving increments into condition checks?
Question: I am reading the second edition of the C Programming Language by Kernighan and Ritchie. In it, the authors introduce things like:
void strcpy(char *s, char*t) {
while(*s++ = *t++);
}
on page 106, and follow it with "Although this may seem cryptic at first sight, the notational convenience is considerable, and the idiom should be mastered because you will see it frequently in C programs". Which I could agree with if being idiomatic or convenient were the only goals of a program. However, I'm left wondering why programmers would standardize on moving all those operations into the conditional. I would prefer to write
void strcpy(char *s, char *t) {
while(*t) {
*s = *t;
++s;
++t;
}
}
. So, why are the authors recommending this terse, cryptic, syntax? I tried to answer this on my own using compiler explorer.
I wrote two functions terse(...) and not_terse(...). Then, I reviewed the assembly with -O3 and, sure enough the terse condition compiles to less instructions, but is that really it; are there other reasons this is recommended? Please help me understand the motivations for the authors statements and if this or additional benefits are the actual motivation as I have trouble seeing the notational convenience as much of a benefit. | {
"domain": "codereview.stackexchange",
"id": 44600,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c",
"url": null
} |
performance, c
Answer: A couple of things:
First: those two code samples are not actually identical functionally.
In terse, the memory address at s is set to t and then the value at s is evaluated to determine if it's the null terminator. In not_terse the value at t is evaluated and then, only if it's not the null terminator the value is copied. The difference is, terse will copy the null terminator whereas not_terse will exit the loop before copying the null terminator.
We could make the functionality identical by storing the value at s in a variable after setting it and only evaluating it after the copy:
void strcpy(char * s, char * t)
{
char val = 1;
while(val)
{
val = *s = *t;
++s;
++t;
}
}
Which you'll see produces identical assembly code to terse: https://godbolt.org/z/Gb97GWG4f
But all this is somewhat irrelevant to the more important Second point which is that you're programming in C, not Assembly. You should not primarily base your decisions on how to program by what the generated Assembly code looks like. Instead, readability and maintainability should be your first concern.
The terse example is more readable to people with a good grasp of C. It might look a bit unintuitive at first, but when you get used to seeing the incrementing operator used inside of a statement and conditional checks on assignments it's very easy to follow that loop. By contrast, splitting it up forces you to try to understand each part independently. More verbose isn't always more clear.
Some of this does come down to a matter of taste, and it's not unreasonable to program in one way as a beginner and adjust your style as you become more experienced. | {
"domain": "codereview.stackexchange",
"id": 44600,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c",
"url": null
} |
algorithm, c, comparative-review, generics, c-preprocessor
Title: Instance specific code generation
Question: Disclaimer: I've asked this question before on Stack overflow and got a response that this place would be a better fit so I am copy pasting the question here.
I've come up with two different approaches for implementing generic algorithms and data structures in C. And I need your help in deciding which is better.
I've been juggling between the two for the past couple of weeks trying to decide on which approach is better suitable to be used inside of company environment. Which approach produces higher code quality, is easier to debug, is more future proof, is more readable, maintainable and easier for new people to grasp. The better approach will not necessary excel at all of the aforementioned qualities.
Below I will show the two implementations with code samples and some benefits and weaknesses that I've observed. These samples are only a tiny fraction of what an actual generic data structure would contain.
#1 Instance specific compile-time code generation
FIFO.h
#if !defined(FIFO_H_)
#define FIFO_H_
#include <stdbool.h>
#include <stddef.h>
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
#define PREPROC_PASTE_TWO(_1, _2) PREPROC_PASTE_TWO_(_1, _2)
#define PREPROC_PASTE_TWO_(_1, _2) _1##_2
#define PREPROC_PASTE_THREE(_1, _2, _3) PREPROC_PASTE_THREE_(_1, _2, _3)
#define PREPROC_PASTE_THREE_(_1, _2, _3) _1##_2##_3
/**
* FIFO control.
*/
typedef struct FIFO_Control
{
size_t Head; /**< Head index. */
size_t Tail; /**< Tail index. */
size_t NofAdds; /**< Total number of elements added to FIFO. */
size_t NofTakes; /**< Total number of elements taken from FIFO. */
} FIFO_Control_s;
#define FIFO_t(tag) struct PREPROC_PASTE_TWO(FIFO_, tag)
#define FIFO_STATIC_DEFINE(handle) {.Control = {0}, .Size = ARRAY_SIZE((handle).Buffer)} | {
"domain": "codereview.stackexchange",
"id": 44601,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, c, comparative-review, generics, c-preprocessor",
"url": null
} |
algorithm, c, comparative-review, generics, c-preprocessor
#define FIFO_STATIC_DEFINE(handle) {.Control = {0}, .Size = ARRAY_SIZE((handle).Buffer)}
#define FIFO_Occupied(tag, pHandle) PREPROC_PASTE_THREE(FIFO_, tag, _Occupied)(pHandle)
#define FIFO_Free(tag, pHandle) PREPROC_PASTE_THREE(FIFO_, tag, _Free)(pHandle)
#define FIFO_IsFull(tag, pHandle) PREPROC_PASTE_THREE(FIFO_, tag, _IsFull)(pHandle)
#define FIFO_IsEmpty(tag, pHandle) PREPROC_PASTE_THREE(FIFO_, tag, _IsEmpty)(pHandle)
#define FIFO_Add(tag, pHandle, pElement) PREPROC_PASTE_THREE(FIFO_, tag, _Add)(pHandle, pElement)
#define FIFO_Take(tag, pHandle, pElement) PREPROC_PASTE_THREE(FIFO_, tag, _Take)(pHandle, pElement)
#define FIFO_Seek(tag, pHandle, offset) PREPROC_PASTE_THREE(FIFO_, tag, _Seek)(pHandle, offset)
#define FIFO_Peek(tag, pHandle, offset) PREPROC_PASTE_THREE(FIFO_, tag, _Peek)(pHandle, offset)
static inline void FIFO_AdvanceIndex(size_t *const pIndex, const size_t size, const size_t n)
{
*pIndex = (*pIndex < (size - n)) ? *pIndex + n : *pIndex - (size - n);
}
static inline void FIFO_AdvanceHead(FIFO_Control_s *const pControl, const size_t size, const size_t n)
{
FIFO_AdvanceIndex(&pControl->Head, size, n);
pControl->NofAdds += n;
}
static inline void FIFO_AdvanceTail(FIFO_Control_s *const pControl, const size_t size, const size_t n)
{
FIFO_AdvanceIndex(&pControl->Tail, size, n);
pControl->NofTakes += n;
}
static inline size_t FIFO_Head(const FIFO_Control_s *const pControl)
{
return pControl->Head;
}
static inline size_t FIFO_Tail(const FIFO_Control_s *const pControl)
{
return pControl->Tail;
}
static inline size_t FIFO_NofOccupied(const FIFO_Control_s *const pControl)
{
return (pControl->NofAdds - pControl->NofTakes);
}
static inline size_t FIFO_NofFree(const FIFO_Control_s *const pControl, const size_t size)
{
return (size - FIFO_NofOccupied(pControl));
} | {
"domain": "codereview.stackexchange",
"id": 44601,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, c, comparative-review, generics, c-preprocessor",
"url": null
} |
algorithm, c, comparative-review, generics, c-preprocessor
static inline bool FIFO_IsBufferFull(const FIFO_Control_s *const pControl, const size_t size)
{
return (FIFO_NofOccupied(pControl) == size);
}
static inline bool FIFO_IsBufferEmpty(const FIFO_Control_s *const pControl)
{
return (FIFO_NofOccupied(pControl) == 0);
}
#endif /* FIFO_H_ */
/* Instance specific compile-time code generation from here to end of file. */
#if !defined(FIFO_CONFIG_ADD_LOCK) && !defined(FIFO_CONFIG_ADD_UNLOCK)
#define FIFO_CONFIG_ADD_LOCK() (void)0
#define FIFO_CONFIG_ADD_UNLOCK() (void)0
#endif
#if !defined(FIFO_CONFIG_TAKE_LOCK) && !defined(FIFO_CONFIG_TAKE_UNLOCK)
#define FIFO_CONFIG_TAKE_LOCK() (void)0
#define FIFO_CONFIG_TAKE_UNLOCK() (void)0
#endif
/**
* Instance specific FIFO.
*/
FIFO_t(FIFO_CONFIG_TAG)
{
FIFO_Control_s Control; /**< FIFO control. */
const size_t Size; /**< Buffer size. */
FIFO_CONFIG_TYPE Buffer[FIFO_CONFIG_SIZE]; /**< Statically allocated buffer. */
};
static inline size_t FIFO_Occupied(FIFO_CONFIG_TAG, const FIFO_t(FIFO_CONFIG_TAG) *const pHandle)
{
return FIFO_NofOccupied(&pHandle->Control);
}
static inline size_t FIFO_Free(FIFO_CONFIG_TAG, const FIFO_t(FIFO_CONFIG_TAG) *const pHandle)
{
return FIFO_NofFree(&pHandle->Control, pHandle->Size);
}
static inline bool FIFO_IsFull(FIFO_CONFIG_TAG, const FIFO_t(FIFO_CONFIG_TAG) *const pHandle)
{
return FIFO_IsBufferFull(&pHandle->Control, pHandle->Size);
}
static inline bool FIFO_IsEmpty(FIFO_CONFIG_TAG, const FIFO_t(FIFO_CONFIG_TAG) *const pHandle)
{
return FIFO_IsBufferEmpty(&pHandle->Control);
}
static bool FIFO_Add(FIFO_CONFIG_TAG, FIFO_t(FIFO_CONFIG_TAG) *const pHandle, const FIFO_CONFIG_TYPE *const pElement)
{
#if !defined(FIFO_CONFIG_OVERWRITE_FULL)
if (FIFO_IsFull(FIFO_CONFIG_TAG, pHandle))
{
return false;
}
#endif
FIFO_CONFIG_ADD_LOCK(); | {
"domain": "codereview.stackexchange",
"id": 44601,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, c, comparative-review, generics, c-preprocessor",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.