text stringlengths 1 2.12k | source dict |
|---|---|
c++, multithreading, parsing
If I replace std::string with std::string_view here, the overall execution time increases from 1.7 seconds to 2.85 seconds, which is 1.67 times degradation for the whole task, so this place suffers even larger performance degradation. The reason is quite simple, with the large text data, your approach is cache unfriendly. Every access to string will most likely hit another cache page, killing existing cache and leading to significant memory bottlenecks, since lexem strings will be sparse in memory. In my case they are located much denser.
On the excessive creation of std::string, this could lead only to one copy; in most cases it wouldn’t lead even to extra memory allocation because of SSO (short string optimization); so the price is not so high.
On the expected performance
Starting and stopping threads today is not so expensive when I need the amount of threads equal to the number of cores on CPU and load each thread for seconds of work.
Of course, I am aware of Amdahl's law, but do you really think it should be a showstopper for parallel algorithms? Even if on N cores I could achieve N/2 speed up, doesn’t it worth doing on today’s CPU and GPU?
Simple std::copy shows that I can process gigabytes per second, so I am definitely not memory-bound so far, at least, overall. Although, I would agree that caching could suffer. Again, is it a showstopper to get some performance improvement?
On atomic/mutex, I totally agree with you. But (a) it works and works now about 4.5 times faster on 16 cores CPU than a single threaded version; (b) that is exactly the reason I published the code, to learn if this task could be solved better and faster with other approaches.
Every thread gives time decrease, so charting is not so necessary here. The key question is different, namely, is the approach correct? | {
"domain": "codereview.stackexchange",
"id": 45504,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
On my performance expectations. If I get something like speed up about 0.75*CPU cores number, I would consider this a success, but having 0.5*CPU cores number would be a good enough result.
Again, I am not saying that the approach is the best, as I stated above, the main goal of the posting this question was to get some help with the approach itself. I feel this could be solved faster, but can’t get this done so far.
Answer: About your feedback
Taking into account a huge size of data, the slowest thread shouldn’t be much slower that any other as they have almost the same amount of lexems on average;
The problem isn't the number of lexems, but rather the variation in time it takes to process each lexem. Part of that is because there is a varying amount of work per lexem (hash map lookup and insertion are not deterministic), and part of it comes from the operating system needing to do stuff, other programs running their threads, the CPU handling interrupts, and many other things that are happening. These variations do not cancel each other out over a long time, but slowly add up (it's like a random walk). The total variation at the end will just be a small fraction of the total time your program runs, so you could ignore it, but you could also avoid mostly it.
I have exactly as many threads as CPU cores […] reducing this number by one to give one thread to OS and other stuff, I even tried 2 times more and less threads; nothing changed dramatically,
If the total time your program runs is not changed when you use 2 times less threads, then that means your program is not CPU-bound, and instead having more threads just makes it less efficient. You want to see a dramatic change when adding or removing threads; ideally having twice the number of threads should halve the time your program takes. If not, consider that those threads could be doing something more useful for another program, or just be idle so they don't consume energy. | {
"domain": "codereview.stackexchange",
"id": 45504,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
My chunks can’t be small by functional specification. With gigabytes of text, I would need millions of CPU cores to have small chunks.
You should decouple the size of the chunk from the number of cores. For example, if you have 8 cores and 16 chunks, you start 8 threads and have each thread process 2 chunks.
Is it worth to extract one line of obvious code only with a sole purpose to name it?
If it becomes even more obvious afterwards, yes.
Of course, I am aware of Amdahl's law, but do you really think it should be a showstopper for parallel algorithms? Even if on N cores I could achieve N/2 speed up, doesn’t it worth doing on today’s CPU and GPU?
It depends. Sometimes a parallel algorithm is much slower per core than a non-parallel one. In that case, while you could still throw lots of cores at it for some speedup, you are wasting more energy to run the program than if everything was running on a single core.
Another reason I mentioned this is that if parallelism doesn't give you the speedup you expected, then maybe you should focus your attention to the serial steps in your algorithm. Maybe those can be improved, or maybe some of the serial steps you have could be made parallel as well.
Simple std::copy shows that I can process gigabytes per second, so I am definitely not memory-bound so far, at least, overall.
std::copy is the best case scenario for memory access. Your algorithm might not be able to achieve the same bandwidth.
it works and works now about 4.5 times faster on 16 cores CPU than a single threaded version | {
"domain": "codereview.stackexchange",
"id": 45504,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
it works and works now about 4.5 times faster on 16 cores CPU than a single threaded version
Ok, so in your parallel version, that sounds like each thread is running 3.56 times slower than the single threaded version. Either that, or the serial steps in your algorithm are indeed quite large (23.3% of the total runtime according to Amdahl's law), or something inbetween.
I think it is likely you can get more performance. I would first identify where the bottleneck really is, and measure the time for setting up the chunks, for running the threads, and for creating the compiled_text vector afterwards. Using a profiler like perf might also help finding out where most of the time is spent.
Avoid code duplication
tokenize_chunk() and tokenize_chunk_to() are almost identical. You can implement one using the other:
std::vector<lexem_t> TextBaseMultiThreaded::tokenize_chunk(std::string_view text, lexem_t start_id) {
std::vector<lexem_t> compiled;
tokenize_chunk_to(compiled, text, start_id);
return compiled;
}
But TextBaseSingleThreaded::tokenize() also looks very similar to TextBaseMultiThreaded::tokenize_chunk(). Ideally you avoid that duplication as well. Or do you need TextBaseSingleThreaded at all? Why not call TextBaseMultiThreaded::tokenize() with just 1 chunk? That does start a separate thread though, but you could detect the case of n_chunks == 1 and use std::launch::deferred instead of std::launch::async.
Incorrect start_id being passed?
When you create the async tasks, you pass chunk * chunk_size as the start_id parameter. However, shouldn't that be chunk_start instead? | {
"domain": "codereview.stackexchange",
"id": 45504,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c#, beginner, tic-tac-toe
Title: Beginner C# console TicTacToe program
Question: I've been learning to program in C# for a couple months and wanted some feedback regarding a project I completed. Criticism and constructive feedback is what I'm after, so bring it on! I know there are improvements to be made, but I'm not sure how to implement them without crazy repetition. Where could I improve? Is my variable naming scheme wack? Let me know!
Console.WriteLine("Welcome to Tic-Tac-Toe!\n\n");
Console.WriteLine("Please enter your name:");
string[,] boardState = new string[3, 3] { // initialize the 3D array containing whitespace instead of X's and O's
{" ", " ", " "}, // my logic will replace these whitespaces as the player or CPU adds to the board
{" ", " ", " "},
{" ", " ", " "}
};
string nameSelection = "";
string spaceSelection = "";
string? readResult = Console.ReadLine();
if (readResult != null)
{
nameSelection = readResult;
}
Console.Clear();
Console.WriteLine("GAME READY:\n\npress Enter to continue:");
Console.ReadLine();
Random roll = new Random();
int playerSelection = roll.Next(1, 3); // selecting who goes first in the game
if (playerSelection == 1)
{
Console.WriteLine("CPU goes first!\n\nPress Enter");
Console.ReadLine();
while (GameWon(boardState) == false) // main game loop if the cpu goes first
{
CPUmove(boardState);
DisplayGameBoard(boardState);
GetSelection();
// boardState changes depending on the coordinates gotten from the ParseSelection array
boardState[ParseSelection(spaceSelection)[0], ParseSelection(spaceSelection)[1]] = "X";
DisplayGameBoard(boardState);
}
} | {
"domain": "codereview.stackexchange",
"id": 45505,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, tic-tac-toe",
"url": null
} |
c#, beginner, tic-tac-toe
DisplayGameBoard(boardState);
}
}
else if (playerSelection == 2)
{
Console.WriteLine($"{nameSelection} goes first!\n\nPress Enter");
Console.ReadLine();
while (GameWon(boardState) == false) // main game loop if the player goes first
{
DisplayGameBoard(boardState);
GetSelection();
boardState[ParseSelection(spaceSelection)[0], ParseSelection(spaceSelection)[1]] = "X";
DisplayGameBoard(boardState);
CPUmove(boardState);
}
}
Console.WriteLine($"\n\nGame Over!"); // i'm not sure how to announce who won...not without a lot of repetition
Console.WriteLine("\n\nPress Enter to end program.");
Console.ReadLine();
void CPUmove(string[,] boardState) // method to make the cpu claim a space, was originally going to be a random
// seleciton of difficulty but im not sure how to do that.
{
bool moved = false;
while (moved == false)
{
Random roll = new Random();
int difficultyRoll = 0;
switch (difficultyRoll)
{
case 0:
{
if (boardState[1, 1] == " ")
{
boardState[1, 1] = "O";
moved = true;
}
else if (boardState[2, 0] == " ")
{
boardState[2, 0] = "O";
moved = true;
}
else if (boardState[0, 2] == " ")
{
boardState[0, 2] = "O";
moved = true;
}
else if (boardState[2, 2] == " ")
{
boardState[2, 2] = "O";
moved = true;
} | {
"domain": "codereview.stackexchange",
"id": 45505,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, tic-tac-toe",
"url": null
} |
c#, beginner, tic-tac-toe
else if (boardState[0, 0] == " ")
{
boardState[0, 0] = "O";
moved = true;
}
else if (boardState[1, 2] == " ")
{
boardState[1, 2] = "O";
moved = true;
}
else if (boardState[1, 0] == " ")
{
boardState[1, 0] = "O";
moved = true;
}
else if (boardState[2, 1] == " ")
{
boardState[2, 1] = "O";
moved = true;
}
else if (boardState[0, 1] == " ")
{
boardState[0, 1] = "O";
moved = true;
}
break;
}
}
}
}
int[] ParseSelection(string selection) // takes the player's input and splits it into two seperate integers
{
char[] selectionChar = selection.ToCharArray();
switch (selectionChar[0]) // this switch determines what row to change to a char containing a corresponding number
{
case 'a':
{
selectionChar[0] = '0';
break;
}
case 'b':
{
selectionChar[0] = '1';
break;
}
case 'c':
{
selectionChar[0] = '2';
break;
}
}
string[] spaceIndex = { " ", " " };
spaceIndex[0] = selectionChar[0].ToString(); // these two operations convert each literal character into a usable string
spaceIndex[1] = selectionChar[1].ToString(); | {
"domain": "codereview.stackexchange",
"id": 45505,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, tic-tac-toe",
"url": null
} |
c#, beginner, tic-tac-toe
int[] indexFinal = { 0, 0 };
indexFinal[0] = int.Parse(spaceIndex[0]); // these two convert each string into an integer and store it in an array
indexFinal[1] = int.Parse(spaceIndex[1]);
return indexFinal; // returns the indexFinal array loaded with the coordinates of the selected space
}
void DisplayGameBoard(string[,] boardState) // displays the board with default values
{
Console.Clear();
Console.WriteLine("\t\t\t0\t\t1\t\t2");
Console.WriteLine($"\n\ta\t|\t{boardState[0, 0]}\t|\t{boardState[0, 1]}\t|\t{boardState[0, 2]}\t|");
Console.WriteLine("\t__________________________________________________");
Console.WriteLine($"\n\tb\t|\t{boardState[1, 0]}\t|\t{boardState[1, 1]}\t|\t{boardState[1, 2]}\t|");
Console.WriteLine("\t__________________________________________________");
Console.WriteLine($"\n\tc\t|\t{boardState[2, 0]}\t|\t{boardState[2, 1]}\t|\t{boardState[2, 2]}\t|");
Console.WriteLine("\n\nPlease pick a space 'a1' is an example space choice!");
}
string GetSelection() // basic null avoidance (i'm not sure if this is necessary)
{
readResult = Console.ReadLine();
if (readResult != null)
{
spaceSelection = readResult.ToLower().Trim();
}
return spaceSelection;
}
bool GameWon(string[,] board) // checks every possible win condition for either all X's or O's (could be simpler but i'm not too sure how)
{
if ((board[0, 0], board[1, 1], board[2, 2]) == ("X", "X", "X"))
{
return true;
}
else if ((board[0, 0], board[1, 1], board[2, 2]) == ("O", "O", "O"))
{
return true;
}
else if ((board[0, 0], board[0, 1], board[0, 2]) == ("X", "X", "X"))
{
return true;
} | {
"domain": "codereview.stackexchange",
"id": 45505,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, tic-tac-toe",
"url": null
} |
c#, beginner, tic-tac-toe
else if ((board[0, 0], board[0, 1], board[0, 2]) == ("O", "O", "O"))
{
return true;
}
else if ((board[1, 0], board[1, 1], board[1, 2]) == ("X", "X", "X"))
{
return true;
}
else if ((board[1, 0], board[1, 1], board[1, 2]) == ("O", "O", "O"))
{
return true;
}
else if ((board[2, 0], board[2, 1], board[2, 2]) == ("X", "X", "X"))
{
return true;
}
else if ((board[2, 0], board[2, 1], board[2, 2]) == ("O", "O", "O"))
{
return true;
}
else if ((board[0, 0], board[1, 0], board[2, 0]) == ("X", "X", "X"))
{
return true;
}
else if ((board[0, 0], board[1, 0], board[2, 0]) == ("O", "O", "O"))
{
return true;
}
else if ((board[0, 1], board[1, 1], board[2, 1]) == ("X", "X", "X"))
{
return true;
}
else if ((board[0, 1], board[1, 1], board[2, 1]) == ("O", "O", "O"))
{
return true;
}
else if ((board[0, 2], board[1, 2], board[2, 2]) == ("X", "X", "X"))
{
return true;
}
else if ((board[0, 2], board[1, 2], board[2, 2]) == ("O", "O", "O"))
{
return true;
}
else if ((board[2, 0], board[1, 1], board[0, 2]) == ("X", "X", "X"))
{
return true;
}
else if ((board[2, 0], board[1, 1], board[0, 2]) == ("O", "O", "O"))
{
return true;
}
else
{
return false;
}
} | {
"domain": "codereview.stackexchange",
"id": 45505,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, tic-tac-toe",
"url": null
} |
c#, beginner, tic-tac-toe
Answer: First of all, congratulations on completing the project! A working program that does what you want is an important first step. There's a lot here that you can build on and the organization is decent.
As a general note, I'll say that anytime you are writing similar code over and over, you should wonder if there is a better approach. In particular, GameWon is ripe for cleaning up. One way to draw inspiration is to think how you would handle a variable board size. The way you wrote it, moving to a 4x4 board requires totally rewriting this function. The central checking could be more like:
// check for a win on the diagonal
bool xWinsDiag = true;
for (int i=0; i < BoardSize; ++i)
{
xWinsDiag = xWinsDiag && board[i, i] == "X";
}
if (xWinsDiag)
return true;
// check for a horizontal win
for (int row = 0; row < BoardSize; ++row)
{
bool xWinsRow = true;
for (int col = 0; col < BoardSize; ++col)
{
xWinsRow = xWinsRow && board[col, row] == "X";
}
if (xWinsRow)
return true;
}
// don't forget to check the anti-diagonal and columns
Another thought for this function is that it could be called GetGameState return a type like:
enum GameState {Active, XWon, YWon, Draw}
Now, I have X hard-coded in here and you also need to check for O, which you can do with a loop over the player. Or you could realize that in each case (diagonal, row, column) the symbol in the first spot is the only player than can win that row, so you only need to check that the others match.
Similarly, CPUmove is a lot of duplicated code, can you think of a simpler way to write it? The same code repeated suggests a loop; what you are doing is testing the squares in a particular order and taking the first open one. If you had that order stored in an array, you could simply loop over them.
Your main game loop is two very similar blocks of code. In the first case, the loop goes: | {
"domain": "codereview.stackexchange",
"id": 45505,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, tic-tac-toe",
"url": null
} |
c#, beginner, tic-tac-toe
CPUmove
DisplayGameBoard
GetSelection
DisplayGameBoard
CPUmove
DisplayGameBoard
GetSelection
DisplayGameBoard
etc
And in the second case, the loop is:
DisplayGameBoard
GetSelection
DisplayGameBoard
CPUmove
DisplayGameBoard
GetSelection
DisplayGameBoard
CPUmove
etc | {
"domain": "codereview.stackexchange",
"id": 45505,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, tic-tac-toe",
"url": null
} |
c#, beginner, tic-tac-toe
Hopefully you see how similar those are: the only difference with the first list is that the CPU moves first. So you can have that conditionally occur, and then enter a common loop. And that makes sense, when it's the players first turn, either the board will be empty or it will contain a single O, but other than that the game logic is identical.
The other area that could use cleaning up is handling user input. It looks like it'll work correctly if the user enters the values exactly like they are supposed to, but if they don't any number of bad things will happen. You also don't check if the square is empty, which means X can steal O's squares! Your GetSelection needs to run in a loop until the user enters a value that matches the expected format (a-c, 0-2) that names an empty square. If the input is invalid, the program needs to say why. Writing this loop might make you realize it's not always possible to exit - what if the board is full i.e. the game is a tie? (You might have also discovered this case writing your main loop - is a win the only way for a game to end?) I know the validation feels unnecessary because you know what your program expects, but it's a good habit to get into and is crucial if anyone else is going to use this program.
You also have a few global variables like spaceSelection that you are using for processing input. I would get rid of those and have the functions return values that you store in a local variable. Code is much easier to read if it's clear how the data flows, and global variables obscure that.
As for organization, this is a simple enough program that it's ok to put it all in one file. If you wanted to pull out classes, the Board class is pretty obvious. It would maintain state and could look like
class Board
{
void MakeMove(int c, int r, char player);
GameState GetGameState();
void PrintBoard();
} | {
"domain": "codereview.stackexchange",
"id": 45505,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, tic-tac-toe",
"url": null
} |
c#, beginner, tic-tac-toe
I think a CPU class makes sense, and you could have different implementations to adjust the difficulty level.
interface ICpu
{
void PlayNextMove(Board b);
}
class EasyCpu : ICpu {}
class HardCpu : ICpu {}
class ExpertCpu : ICpu {}
It would be nice to put all of the input parsing and validating in one place, maybe
class UserInput
{
Tuple<int, int> ReadNextMove();
}
It feels like I've written a lot, but really it's because your code is very close to being quite good. I think you're just a few insights away from being able to improve it a lot. | {
"domain": "codereview.stackexchange",
"id": 45505,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, tic-tac-toe",
"url": null
} |
beginner, c, file-system, linux
Title: Remove all text files with non-US-ASCII text encoding from current folder on Linux
Question: /* let's compile using: gcc main.c -Wall -Wextra --pedantic --std=c2x -D_GNU_SOURCE -Ofast -march=corei7 -mtune=corei7 */
/* Linux headers begin */
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
/* Linux headers end */
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define ALLOCATION_ATTEMPT_LIMIT 4
#define SUCCESS 0
#define FAIL -1
char * concat_file_path(const char * directory, const char * file_name)
{
const char * separator = "/";
char * result = NULL;
size_t directory_length = strlen(directory);
size_t file_name_length = strlen(file_name);
size_t separator_length = strlen(separator);
char count = 0;
while (((result = malloc(sizeof(char) * (directory_length + separator_length + file_name_length + 1))) == NULL) && (++count < ALLOCATION_ATTEMPT_LIMIT))
sleep(1);
if (result == NULL)
{
perror("Error: memory allocation failed.");
exit(EXIT_FAILURE);
}
memcpy(result, directory, directory_length);
memcpy(result + directory_length, separator, separator_length);
memcpy(result + directory_length + separator_length, file_name, file_name_length + 1);
return result;
}
void close_directory(DIR * directory_pointer)
{
if (closedir(directory_pointer) == 0)
{
puts("Directory was closed.");
}
else
perror("Error: closing directory failed.");
}
DIR * open_directory(const char * directory_path)
{
DIR * directory_pointer = opendir(directory_path);
if (directory_pointer == NULL)
{
perror("Error: directory stream is NULL.");
exit(EXIT_FAILURE);
}
return directory_pointer;
}
char check_for_non_ascii(FILE * text_file_pointer)
{
char current = fgetc (text_file_pointer);
if (current == EOF)
return FAIL; | {
"domain": "codereview.stackexchange",
"id": 45506,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, file-system, linux",
"url": null
} |
beginner, c, file-system, linux
if (current == EOF)
return FAIL;
do
{
if (isascii(current) == 0)
return FAIL;
}
while ((current = fgetc (text_file_pointer)) != EOF);
return SUCCESS;
}
void remove_if_non_us_ascii(char * full_path)
{
FILE * text_file_pointer = fopen(full_path, "r");
if (text_file_pointer == NULL)
{
perror("Error: file opening error.");
exit(EXIT_FAILURE);
}
if (check_for_non_ascii(text_file_pointer) == 0)
{
fclose(text_file_pointer);
if (remove(full_path) == 0)
{
puts("File removed.");
}
else
{
printf("Occured an error on removing a file on the path: %s", full_path);
}
}
else
fclose(text_file_pointer);
}
void perform_if_regular_file(DIR * directory_pointer, char * full_path)
{
struct stat stat_buffer;
if (lstat(full_path, &stat_buffer) == 0)
{
if ((stat_buffer.st_mode & S_IFMT) == S_IFREG)
{
remove_if_non_us_ascii(full_path);
}
}
else
{
perror("Error: getting file information failed.");
close_directory(directory_pointer);
exit(EXIT_FAILURE);
}
}
void main_loop(DIR * directory_pointer, const char * directory_path)
{
struct dirent * directory_entry_struct = NULL;
char * full_path = NULL;
while ((directory_entry_struct = readdir (directory_pointer)) != NULL)
{
full_path = concat_file_path(directory_path, directory_entry_struct->d_name);
perform_if_regular_file(directory_pointer, full_path);
}
}
int main (void)
{
const char * directory_path = ".";
DIR * directory_pointer = open_directory(directory_path);
errno = 0;
main_loop(directory_pointer, directory_path); | {
"domain": "codereview.stackexchange",
"id": 45506,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, file-system, linux",
"url": null
} |
beginner, c, file-system, linux
main_loop(directory_pointer, directory_path);
if (errno != 0)
{
perror("Error: reading directory entry failed.");
close_directory(directory_pointer);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
I am new to C. Please, give an advice on reliability of program, programming style and performance. You have to put program executable into a folder containing text files in any encoding on Linux machine. After running it you could have only US ASCII text files in the folder. I have tested this code on a 11 GiB storage.
Answer: I'd have a function to check if a file is ASCII compatible (a positive check just to be sure that we don't get double negatives). Then if that's not the case I'd remove the file. Then I would have a generic function to remove a file if it isn't.
The whole stack perform_if_regular_file -> remove_if_non_us_ascii -> check_for_non_ascii seems strange to me. I would expect (in pseudo-code):
for all f in files
if !regularfile(f) continue
if !is_ascii(f) remove(f)
exit(EXIT_FAILURE) in remove_if_non_us_ascii and perform_if_regular_file
That doesn't seem to be a good idea: if an unexpected file is encountered then the operation is stopped midway, with no indication to the user which state the folder is in. Either continue or save up a list of files and then remove them, but don't exit prematurely.
Many OS vendors could also learn from this, by the way.
while (((result = malloc(sizeof(char) * (directory_length + separator_length + file_name_length + 1))) == NULL) && (++count < ALLOCATION_ATTEMPT_LIMIT))
sleep(1);
No, just try once. If it isn't even possible to get a file name constructed then it is not time to try again, it is time to abort.
puts("File removed.");
That's trace information. I'd use a logging implementation for that. But to be honest, this only makes sense if you actually output the file name as well. | {
"domain": "codereview.stackexchange",
"id": 45506,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, file-system, linux",
"url": null
} |
beginner, c, file-system, linux
Note that isascii will also return a positive value if the character is non-printable. Also note that Microsoft documentation tells us that it is Microsoft specific - although I have certainly found it in other systems.
Funny enough I then found a newsgroup thread from 1990 that includes a comment from my old prof Tanenbaum.
Maybe better to define a macro yourself, do you really expect that a character value of 0x00 (NUL) or 0x7F (DEL) should be acceptable? But you might think differently about LF, CR and HT. | {
"domain": "codereview.stackexchange",
"id": 45506,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, file-system, linux",
"url": null
} |
c, unit-testing, library, assertions
Title: A simple unit test library for C - version II
Question: I have improved my code here and it looks like this:
Code
assertlib.h:
#ifndef COM_GITHUB_CODERODDE_ASSERTLIB_H
#define COM_GITHUB_CODERODDE_ASSERTLIB_H
void print_test_statistics();
int get_exit_status();
#define ASSERT_IMPL(COND, FILE, LINE) assert_impl(COND, #COND, FILE, LINE);
#define ASSERT(COND) ASSERT_IMPL(COND, __FILE__, __LINE__)
#endif
assertlib.c:
#include "assertlib.h"
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#define COMPLETION_BAR_LENGTH 80
static size_t passes = 0;
static size_t failed = 0;
void assert_impl(bool passed,
const char* condition_text,
const char* file_name,
size_t line_number) {
if (passed) {
passes++;
} else {
failed++;
fprintf(stderr,
"Failed condition \"%s\" in file \"%s\" at line %zu.\n",
condition_text,
file_name,
line_number);
}
}
int get_exit_status() {
return failed == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}
static void print_bar(size_t bar_length) {
size_t total_assertions = passes + failed;
char* bar = calloc(bar_length + 16, sizeof(char));
if (bar == NULL) {
return;
}
bar[0] = '[';
bar[bar_length + 1] = ']';
float ratio = (float)(passes) / (float)(total_assertions);
size_t hash_symbols = (size_t)(bar_length * ratio);
for (size_t i = 0; i < hash_symbols; i++) {
bar[i + 1] = '#';
}
for (size_t i = 0; i < bar_length - hash_symbols; i++) {
bar[i + 1 + hash_symbols] = '.';
}
printf("%s: %.2f%%.\n", bar, 100.0f * ratio);
free(bar);
}
void print_test_statistics() {
printf("Passes: %zu, failures: %zu, total assertions: %zu.\n",
passes,
failed,
passes + failed);
print_bar(COMPLETION_BAR_LENGTH);
}
main.c:
#include "assertlib.h" | {
"domain": "codereview.stackexchange",
"id": 45507,
"lm_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, unit-testing, library, assertions",
"url": null
} |
c, unit-testing, library, assertions
print_bar(COMPLETION_BAR_LENGTH);
}
main.c:
#include "assertlib.h"
int main()
{
ASSERT(1 + 1 == 2);
ASSERT(1);
ASSERT(1 != 1);
ASSERT(1 + 2 == 3);
print_test_statistics();
return get_exit_status();
}
Unit test output
The output looks like this:
Failed condition "1 != 1" in file "C:\Users\rodio\Documents\VSProjects\assertlib.h\main.c" at line 7.
Passes: 3, failures: 1, total assertions: 4.
[############################################################....................]: 75.00%.
Critique request
As always, I would like to hear anything that comes to mind.
Answer: In C, void get_exit_status() declares a function that takes an unspecified number of parameters, not a function that takes none.
If the function expects no arguments, it should be defined with the keyword void, unless you are compiling with C2X, where empty parentheses defines a function that takes no arguments, akin to C++. In which case you should also remove the inclusion of stdbool.h, as bool, true, and false are keywords in C23.
You also do not require the inclusion of stddef.h, as stdio.h already declares size_t.
As print_bar() is always passed in COMPLETION_BAR_LENGTH, we can do away with the call to calloc() and replace it with a fixed-size array:
#if 0
char* bar = calloc(bar_length + 16, sizeof(char));
#else
char bar[COMPLETION_BAR_LENGTH + 16] = {0};
#endif
Though I do not see why the memory needs to be zero-initialized, especially when it is overwritten right after its initialization.
Note that sizeof(char) is defined by the C standard to be 1, so you can safely replace it with 1.
Consider conditionally dealing with passed and returning early in assert_impl().
That way you can deal with failed unconditionally, saving four spaces of indent. | {
"domain": "codereview.stackexchange",
"id": 45507,
"lm_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, unit-testing, library, assertions",
"url": null
} |
java, object-oriented, design-patterns, strategy-pattern
Title: Calculator Object Oriented Design
Question: I am aiming to implement a calculator in an object-oriented way.
Here is the solution by using the strategy pattern.
Looking forward to some valuable comments.
package oopdesign.calculator;
public class AdditionStrategy implements CalculationStrategy {
@Override
public int calculate(int value1, int value2) {
return value1 + value2;
}
}
package oopdesign.calculator;
public interface CalculationStrategy {
int calculate(int value1, int value2);
}
package oopdesign.calculator;
public class Calculator {
public static Calculator instance = null;
CalculationStrategy calculationStrategy;
public void setCalculationStrategy(CalculationStrategy calculationStrategy) {
this.calculationStrategy = calculationStrategy;
}
public static Calculator getInstance(){
if(instance == null){
instance = new Calculator();
}
return instance;
}
public int calculate(int value1, int value2) {
return calculationStrategy.calculate(value1, value2);
}
}
package oopdesign.calculator;
public class CalculatorMain {
public static void main(String[] args) {
Calculator c = Calculator.getInstance();
c.setCalculationStrategy(new AdditionStrategy());
System.out.println(c.calculate(5 ,2));
c.setCalculationStrategy(new SubtractionStrategy());
System.out.println(c.calculate(5 ,2));
c.setCalculationStrategy(new MultiplicationStrategy());
System.out.println(c.calculate(5 ,2));
c.setCalculationStrategy(new DivideStrategy());
System.out.println(c.calculate(5 ,2));
}
}
package oopdesign.calculator;
public class DivideStrategy implements CalculationStrategy {
@Override
public int calculate(int value1, int value2) {
return value1 / value2;
}
}
package oopdesign.calculator;
public class MultiplicationStrategy implements CalculationStrategy{ | {
"domain": "codereview.stackexchange",
"id": 45508,
"lm_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, object-oriented, design-patterns, strategy-pattern",
"url": null
} |
java, object-oriented, design-patterns, strategy-pattern
package oopdesign.calculator;
public class MultiplicationStrategy implements CalculationStrategy{
@Override
public int calculate(int value1, int value2) {
return value1 * value2;
}
}
package oopdesign.calculator;
public class SubtractionStrategy implements CalculationStrategy {
@Override
public int calculate(int value1, int value2) {
return value1 - value2;
}
}
Answer: Review:
From extensibility and in pro of having the possibility of including in future versions more operations, it is a good approach. The code is very simple, and it is easy to read so it is very good your design proposal.
The main purpose of applying design patterns is to simplify things, to reach the maximum level of abstraction and allow you to write meaningful code, not just repeat stuff
So, you did good.
However, there are some observations:
package oopdesign.calculator;
//Singleton is a good approach for this problem
public class Calculator {
//By default any object is null
//Do not put it as public, you have the getInstance method
private static Calculator instance;
//You are limiting the operations to handle
CalculationStrategy calculationStrategy;
//This is not a Singleton if you allow the default constructor (its public by default)
private Calculator() {
}
public void setCalculationStrategy(CalculationStrategy calculationStrategy) {
this.calculationStrategy = calculationStrategy;
}
public static Calculator getInstance() {
if (instance == null)
instance = new Calculator();
return instance;
}
//You should think about handle the most general data type (this case double)
public double calculate(double value1, double value2) {
return calculationStrategy.calculate(value1, value2);
}
}
package oopdesign.calculator;
public class CalculatorMain {
public static void main(String[] args) {
Calculator c = Calculator.getInstance(); | {
"domain": "codereview.stackexchange",
"id": 45508,
"lm_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, object-oriented, design-patterns, strategy-pattern",
"url": null
} |
java, object-oriented, design-patterns, strategy-pattern
public static void main(String[] args) {
Calculator c = Calculator.getInstance();
//There is a problem with it, you need to instanciate the strategies
//each time you need to use it
c.setCalculationStrategy(new AdditionStrategy());
System.out.println(c.calculate(5,2));
//It requires space, plus you are not being efficient by storing
//there operations (calculation strategies)
c.setCalculationStrategy(new SubtractionStrategy());
System.out.println(c.calculate(5,2));
c.setCalculationStrategy(new MultiplicationStrategy());
System.out.println(c.calculate(5,2));
c.setCalculationStrategy(new DivideStrategy());
System.out.println(c.calculate(5,2));
}
}
An alternative
import java.util.HashMap;
import java.util.Map;
public class Calculator {
private static Calculator instance;
//search in Constant time (approximately)
private Map<String, CalculationStrategy> calculationStrategies;
private Calculator() {
calculationStrategies = new HashMap<>();
}
public void addCalculationStrategy(String name, CalculationStrategy strategy) {
calculationStrategies.put(name, strategy);
}
public static Calculator getInstance() {
if (instance == null)
instance = new Calculator();
return instance;
}
//double b... means that there may be 0 to n parameters
//consider that there are unitary operators or functions in a calculator
public double calculate(String name, double a, double... b) {
return calculationStrategies.get(name).calculate(a, b);
}
}
package oopdesign.calculator;
public class Main {
public static void main(String[] args) {
Calculator calculator = Calculator.getInstance(); | {
"domain": "codereview.stackexchange",
"id": 45508,
"lm_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, object-oriented, design-patterns, strategy-pattern",
"url": null
} |
java, object-oriented, design-patterns, strategy-pattern
//Use a lambda instead
calculator.addCalculationStrategy("+", (a, b) -> a + b[0]);
//[b] is taken as an array but is a variadic parameter
calculator.addCalculationStrategy("-", (a, b) -> a - b[0]);
calculator.addCalculationStrategy("*", (a, b) -> a * b[0]);
calculator.addCalculationStrategy("/", (a, b) -> a / b[0]);
calculator.addCalculationStrategy("Abs", (a, b) -> Math.abs(a));
calculator.addCalculationStrategy("Cos", (a, b) -> Math.cos(a));
calculator.addCalculationStrategy("Sin", (a, b) -> Math.sin(a));
System.out.println(calculator.calculate("+", 1, 3));
System.out.println(calculator.calculate("-", 1, 3));
System.out.println(calculator.calculate("*", 1, 3));
System.out.println(calculator.calculate("/", 1, 3));
System.out.println(calculator.calculate("Abs", -66));
System.out.println(calculator.calculate("Cos", 75));
System.out.println(calculator.calculate("Sin", 28));
System.out.println(calculator.calculate("+", 666, 777));
}
}
About double b... read this post about Variadic function parameters, as I said, it is a way to have multiple parameters, From 0 To N parameters
Thanks for reading this answer. | {
"domain": "codereview.stackexchange",
"id": 45508,
"lm_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, object-oriented, design-patterns, strategy-pattern",
"url": null
} |
php, laravel
Title: Handling large amount of traits and properties in classes
Question: I've got an open-source project that I've been working on for a while, and I'm looking for advice on handling large classes. It's a Laravel 10+ package for building forms, and everything works fine, but every time I look at these field classes, I feel like there could be a better way or that I might be doing this inefficiently.
This package couples with a frontend package that is also open source (utilising Vue3 & Vuetify) to load the forms; this is partly why there are many attributes, as Vuetify offers many options in their fields.
Below is an example of the AutoCompleteField. In my next update, I'd like to do a big cleanup and start implementing some better structure, so condensing the files down like so is on the list:
Current Setup:
<?php
namespace PlusTimeIT\EasyForms\Fields; | {
"domain": "codereview.stackexchange",
"id": 45509,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, laravel",
"url": null
} |
php, laravel
namespace PlusTimeIT\EasyForms\Fields;
use PlusTimeIT\EasyForms\Base\EasyField;
use PlusTimeIT\EasyForms\Traits\Attributes\HasAnyField;
use PlusTimeIT\EasyForms\Traits\Attributes\HasAutoSelectFirst;
use PlusTimeIT\EasyForms\Traits\Attributes\HasChips;
use PlusTimeIT\EasyForms\Traits\Attributes\HasClosableChips;
use PlusTimeIT\EasyForms\Traits\Attributes\HasCloseText;
use PlusTimeIT\EasyForms\Traits\Attributes\HasCounter;
use PlusTimeIT\EasyForms\Traits\Attributes\HasDirection;
use PlusTimeIT\EasyForms\Traits\Attributes\HasFilterKeys;
use PlusTimeIT\EasyForms\Traits\Attributes\HasFilterMode;
use PlusTimeIT\EasyForms\Traits\Attributes\HasHideNoData;
use PlusTimeIT\EasyForms\Traits\Attributes\HasHideSelected;
use PlusTimeIT\EasyForms\Traits\Attributes\HasItemChildren;
use PlusTimeIT\EasyForms\Traits\Attributes\HasItemColor;
use PlusTimeIT\EasyForms\Traits\Attributes\HasItemId;
use PlusTimeIT\EasyForms\Traits\Attributes\HasItemProps;
use PlusTimeIT\EasyForms\Traits\Attributes\HasItems;
use PlusTimeIT\EasyForms\Traits\Attributes\HasItemTitle;
use PlusTimeIT\EasyForms\Traits\Attributes\HasItemValue;
use PlusTimeIT\EasyForms\Traits\Attributes\HasLoadable;
use PlusTimeIT\EasyForms\Traits\Attributes\HasMenu;
use PlusTimeIT\EasyForms\Traits\Attributes\HasMultiple;
use PlusTimeIT\EasyForms\Traits\Attributes\HasNoDataText;
use PlusTimeIT\EasyForms\Traits\Attributes\HasNoFilter;
use PlusTimeIT\EasyForms\Traits\Attributes\HasOpenOnClear;
use PlusTimeIT\EasyForms\Traits\Attributes\HasOpenText;
use PlusTimeIT\EasyForms\Traits\Attributes\HasReturnObject;
use PlusTimeIT\EasyForms\Traits\Attributes\HasSearch;
use PlusTimeIT\EasyForms\Traits\Attributes\HasTransition;
use PlusTimeIT\EasyForms\Traits\Creatable;
use PlusTimeIT\EasyForms\Traits\Transformable; | {
"domain": "codereview.stackexchange",
"id": 45509,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, laravel",
"url": null
} |
php, laravel
/**
* Represents an autocomplete field in a form.
*
* @extends EasyField
*/
class AutoCompleteField extends EasyField
{
use Creatable;
use HasAnyField;
use HasAutoSelectFirst;
use HasChips;
use HasClosableChips;
use HasCloseText;
use HasCounter;
use HasDirection;
use HasFilterKeys;
use HasFilterMode;
use HasHideNoData;
use HasHideSelected;
use HasItemChildren;
use HasItemColor;
use HasItemId;
use HasItemProps;
use HasItems;
use HasItemTitle;
use HasItemValue;
use HasLoadable;
use HasMenu;
use HasMultiple;
use HasNoDataText;
use HasNoFilter;
use HasOpenOnClear;
use HasOpenText;
use HasReturnObject;
use HasSearch;
use HasTransition;
use Transformable;
protected string $component = 'v-autocomplete';
protected string $discriminator = 'AutoCompleteField';
protected string $type = 'text';
}
Potential Update
<?php
namespace PlusTimeIT\EasyForms\Fields; | {
"domain": "codereview.stackexchange",
"id": 45509,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, laravel",
"url": null
} |
php, laravel
/**
* Represents an autocomplete field in a form.
*
* @extends \PlusTimeIT\EasyForms\Base\EasyField
*/
class AutoCompleteField extends \PlusTimeIT\EasyForms\Base\EasyField
{
use \PlusTimeIT\EasyForms\Traits\Creatable;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasAnyField;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasAutoSelectFirst;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasChips;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasClosableChips;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasCloseText;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasCounter;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasDirection;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasFilterKeys;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasFilterMode;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasHideNoData;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasHideSelected;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasItemChildren;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasItemColor;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasItemId;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasItemProps;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasItems;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasItemTitle;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasItemValue;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasLoadable;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasMenu;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasMultiple;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasNoDataText;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasNoFilter;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasOpenOnClear;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasOpenText;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasReturnObject;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasSearch;
use \PlusTimeIT\EasyForms\Traits\Attributes\HasTransition; | {
"domain": "codereview.stackexchange",
"id": 45509,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, laravel",
"url": null
} |
php, laravel
use \PlusTimeIT\EasyForms\Traits\Attributes\HasTransition;
use \PlusTimeIT\EasyForms\Traits\Transformable; | {
"domain": "codereview.stackexchange",
"id": 45509,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, laravel",
"url": null
} |
php, laravel
protected string $component = 'v-autocomplete';
protected string $discriminator = 'AutoCompleteField';
protected string $type = 'text';
}
Example of Attribute:
<?php
namespace PlusTimeIT\EasyForms\Traits\Attributes;
trait HasAnyField
{
protected bool $any_field = false;
public function getAnyField(): bool
{
return $this->any_field;
}
public function setAnyField(bool $any_field): self
{
$this->any_field = $any_field;
return $this;
}
}
The reason these all have setters is to try and keep it chainable. Should I update these attributes to be public and then remove the getters? (keep setters so they are still chainable?)
Any other ideas on improving and making some updates would be much appreciated. If anyone has the time (or will), I'd love another set of eyes to review the full project structure at some point as well.
Additional Info:
I've already split common properties that are found among all components, and these reside in the parent class: PlusTimeIT\EasyForms\Base\EasyField
I've coupled some attributes that are only required with each other
Any help would be appreciated.
Answer: To reduce redundancy and increase maintainability, you can make the following improvements:
Group related traits to reduce the number of use statements and organize your code better.
If all traits in a category (like items) are used together frequently, combine them into a single trait.
Consider using inheritance or a base class with the main properties and methods shared across different form fields.
Here's an example of how you might start to restructure the code for more efficiency:
namespace PlusTimeIT\EasyForms\Fields;
use PlusTimeIT\EasyForms\Base\EasyField;
use PlusTimeIT\EasyForms\Traits\FormFieldTraits; // This would be a new trait encapsulating several common traits. | {
"domain": "codereview.stackexchange",
"id": 45509,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, laravel",
"url": null
} |
php, laravel
/**
* Represents an autocomplete field in a form.
*
* @extends EasyField
*/
class AutoCompleteField extends EasyField
{
use FormFieldTraits; // Include the new combined trait.
protected string $component = 'v-autocomplete';
protected string $discriminator = 'AutoCompleteField';
protected string $type = 'text';
}
Step 2: Adjust the Written Code to Reflect Structural Changes
Let's adjust the traits section by combining related traits into a new composite trait. An example composite trait might look like this:
namespace PlusTimeIT\EasyForms\Traits;
use PlusTimeIT\EasyForms\Traits\Attributes\{HasItems, HasItemValue, HasItemTitle, ...}; // and so on
trait FormFieldTraits
{
use HasItems, HasItemValue, HasItemTitle, ...; // Import all relevant item-related traits.
}
Step 3: Write a Clear Example of an Attribute
An example attribute trait, following our optimized structure, could look like this:
namespace PlusTimeIT\EasyForms\Traits\Attributes;
trait HasItems
{
protected array $items = [];
public function getItems(): array
{
return $this->items;
}
public function setItems(array $items): self
{
$this->items = $items;
return $this;
}
}
In this example, HasItems might be one of the several traits consolidated into the FormFieldTraits composite trait if it makes sense based on how AutoCompleteField and other field classes are used within the application. | {
"domain": "codereview.stackexchange",
"id": 45509,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, laravel",
"url": null
} |
c#
Title: Based on ranges, for a given number, I want to increment it by another number
Question: What is the most efficient way to use a look-up table in C# that works like a range? For a given number, I want to increment it by another number.
I have a look-up table like so
1 1
5 6
10 60
So if the number is 1-4, increment them by 1, if the number is 5-9, increment them by 6, if the number is 10 or more, increment them by 60.
Currently, I've got a working solution by doing the following but I was wondering if there's a better way to achieve the same thing?
public int GetNewValue(int input)
{
var range = "1,1;2,1;3,1;4,1;5,6;6,6;7,6;8,6;9,6;10,60";
Dictionary<int, int> dic = ParseRanges(range);
int increment;
int total;
if (dic.TryGetValue(input, out increment))
{
total = input + increment;
}
else
{
dic.TryGetValue(10, out increment);
total = input + increment;
};
return total;
}
private static Dictionary<int, int> ParseRanges(string rangeString)
{
if (string.IsNullOrWhiteSpace(rangeString))
{
return null;
}
try
{
var newRange = new Dictionary<int, int>();
var ranges = rangeString.Split(';');
foreach (var range in ranges)
{
var minMax = range.Split(',');
if (minMax.Length != 2)
{
continue;
}
newRange.Add(Convert.ToInt16(minMax[0]), Convert.ToInt16(minMax[1]));
}
return newRange;
}
catch (Exception e)
{
}
return null;
}
}
Answer: Since you have consecutive numbers as input starting at 1, storing the increments in an array where the array index is the input will be faster than a dictionary.
// index = 0 1 2 3 4 5 6 7 8 9 10
private readonly int[] _increments = [0, 1, 1, 1, 1, 6, 6, 6, 6, 6, 60]; | {
"domain": "codereview.stackexchange",
"id": 45510,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
c#
public int GetNewValue(int input)
{
if (input < 1) throw new ArgumentOutOfRangeException("Must be > 0", nameof(input));
// OR, alternatively:
// if (input < 1) return input; // I.e., add increment 0
int increment = input >= _increments.Length
? _increments[^1]
: _increments[input];
return input + increment;
}
Since array indexes are 0-based, we add a dummy entry 0 to the array.
_increments[^1] is equivalent to _increments[_increments.Length - 1].
Both, the dictionary and the array have an O(1) access time; however, dictionary operations have quite and overhead associated with them.
If you want to create an increment array from a string, I suggest using your original (non-expanded) representation like "1 1;5 6;10 60" and to use the following method to expand the ranges into an array:
private static int[] ExpandRanges(string rangeString)
{
string[] parts = rangeString.Split([' ', ';']);
if (parts.Length % 2 != 0) {
throw new ArgumentException("Must contain an even number of integers", nameof(rangeString));
}
var numbers = parts
.Select(s => Int32.Parse(s))
.ToList();
int lastRangeStart = numbers[^2]; // Used to calculate the array length
int[] expanded = new int[lastRangeStart + 1];
// Range and increments alternate in the numbers list.
// Therefore, we step by 2 (i += 2)
for (int i = 0; i < numbers.Count - 1; i += 2) {
int rangeMin = numbers[i];
int rangeMax = i < numbers.Count - 3 ? numbers[i + 2] - 1 : rangeMin;
int increment = numbers[i + 1];
for (int j = rangeMin; j <= rangeMax; j++) {
expanded[j] = increment;
}
}
return expanded;
}
Note that like in the first example, I would store the array in a field and create it once instead of repeating this at each call of GetNewValue. | {
"domain": "codereview.stackexchange",
"id": 45510,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
c#
The increments could also be expanded from tuples of range/increment-pairs:
private static int[] ExpandRanges(params (int range, int increment)[] ranges)
{
int lastRangeStart = ranges[^1].range;
int[] expanded = new int[lastRangeStart + 1];
for (int i = 0; i < ranges.Length; i++) {
var (rangeMin, increment) = ranges[i];
int rangeMax = i < ranges.Length - 1 ? ranges[i + 1].range - 1 : rangeMin;
for (int j = rangeMin; j <= rangeMax; j++) {
expanded[j] = increment;
}
}
return expanded;
}
like this:
private readonly int[] _increments = ExpandRanges((1, 1), (5, 6), (10, 60)); | {
"domain": "codereview.stackexchange",
"id": 45510,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
python, fibonacci-sequence
Title: Find the n-th Fibonacci number in O(log n) time
Question: I was reading this website.
It mentioned how to use matrix exponents to find the n-th Fibonacci number in O(log n) time. I tried implementing it Python along with a fast exponent algorithm.
I'm not sure if this algorithm I have really is O(log n) time, and would also appreciate feedback on code style / practices. Here's my code:
def fibonnaci(n):
# find the nth fibonacci number using matrices and exponents
# (1 1) ** n = (F(n+1) F(n) )
# (1 0) (F(n) F(n-1))
return matrix_2x2_exponent([[1, 1], [1, 0]], n)[1][1] # formula is incorrect I think
def multiply_matrices(matrix1, matrix2):
result = [[0, 0],
[0, 0]]
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
result[i][j] += matrix1[i][k] * matrix2[k][j]
return result
def matrix_2x2_exponent(matrix, n):
# brings a matrix of dimensions 2x2 to the power n, using recursive algorithm
if n == 0:
return [[1, 0],
[0, 1]] # identity matrix
result = matrix_2x2_exponent(matrix, n // 2)
if n % 2 == 1:
return multiply_matrices(multiply_matrices(result, result), [[1, 1], [1, 0]])
else:
return multiply_matrices(result, result)
print(fibonnaci(int(input())))
Answer: Use the Correct Function Name
fibonnaci should be fibonacci.
Perhaps you intentionally wanted this spelling, but I will work on the assumption that it was unintentional.
Use Type Hinting, At Least on Public Functions:
def fibonacci(n):
becomes:
def fibonacci(n: int) -> int:
Prefer Docstrings to Comments When Describing What a Function Does
For example, you have a perfectly good comment at the start of function fibonacci that would be better as a docstring:
def fibonacci(n):
"""Find the nth fibonacci number using matrices and exponents
(1 1) ** n = (F(n+1) F(n) )
(1 0) (F(n) F(n-1))""" | {
"domain": "codereview.stackexchange",
"id": 45511,
"lm_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, fibonacci-sequence",
"url": null
} |
python, fibonacci-sequence
Add Tests and Make the Module Importable
There are various testing frameworks you can use. But for simplicity you could use simple assertions.
Currently, if this module were imported it would execute print(fibonacci(int(input()))), which is not what you would want. I would place such code within a if __name__ == '__main__': block and I would add a prompt so somebody running this as a script would know what is expected. For example:
def _tests() -> None:
assert fibonacci(1) == 0
assert fibonacci(2) == 1
assert fibonacci(3) == 1
assert fibonacci(4) == 2
assert fibonacci(301) == 222232244629420445529739893461909967206666939096499764990979600
if __name__ == '__main__':
# First run some tests:
_tests()
while True:
try:
print(fibonacci(int(input('Enter integer n to compute the nth Fibonacci number: '))))
except Exception as e:
#print(e)
pass
else:
break
The name of anything at global scope that you do not want imported if the user executes from fibonacci import * (I am assuming the source is in module fibonacci.py), should start with an underscore character. Alternatively, you can specify a __all__ list at the end the source naming those globals that should be imported. For example:
__all__ = ['fibonacci']
The advantage of using names that start with an underscore is that it also suggests that the global should be considered "private".
Putting It All Together
def fibonacci(n):
"""Find the nth Fibonacci number using matrices and exponents
(1 1) ** n = (F(n+1) F(n) )
(1 0) (F(n) F(n-1))"""
return matrix_2x2_exponent([[1, 1], [1, 0]], n)[1][1]
def multiply_matrices(matrix1, matrix2):
result = [[0, 0],
[0, 0]]
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
result[i][j] += matrix1[i][k] * matrix2[k][j]
return result | {
"domain": "codereview.stackexchange",
"id": 45511,
"lm_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, fibonacci-sequence",
"url": null
} |
python, fibonacci-sequence
return result
def matrix_2x2_exponent(matrix, n):
"""brings a matrix of dimensions 2x2 to the power n, using recursive algorithm"""
if n == 0:
return [[1, 0],
[0, 1]] # identity matrix
result = matrix_2x2_exponent(matrix, n // 2)
if n % 2 == 1:
return multiply_matrices(multiply_matrices(result, result), [[1, 1], [1, 0]])
else:
return multiply_matrices(result, result)
def _tests() -> None:
assert fibonacci(1) == 0
assert fibonacci(2) == 1
assert fibonacci(3) == 1
assert fibonacci(4) == 2
assert fibonacci(301) == 222232244629420445529739893461909967206666939096499764990979600
if __name__ == '__main__':
# First run some tests:
_tests()
while True:
try:
print(fibonacci(int(input('Enter integer n to compute the nth Fibonacci number: '))))
except Exception as e:
#print(e)
pass
else:
break | {
"domain": "codereview.stackexchange",
"id": 45511,
"lm_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, fibonacci-sequence",
"url": null
} |
python, template
Title: Refactoring many prints statements with specific conditions
Question: How should I refactor the following Python 3.8 snippet?
import enum
import typing
class Number(enum.Enum):
one = 1
two = 2
three = 3
four = 4
five = 5
six = 6
class Color(enum.Enum):
white = 1
black = 2
class Animal(enum.Enum):
cat = 1
dog = 2
class Toy(enum.Enum):
ball = 1
leash = 2
amounts: typing.Dict[typing.Tuple[Color, Number, typing.Optional[object]], int] = {
(Color.white, Number.one, Animal.cat): 1,
(Color.white, Number.one, Animal.dog): 2,
(Color.white, Number.two, Animal.cat): 4,
(Color.white, Number.two, Animal.dog): 5,
(Color.white, Number.three, Toy.ball): 6,
(Color.white, Number.three, Toy.leash): 7,
(Color.white, Number.four, Toy.ball): 8,
(Color.white, Number.four, Toy.leash): 10,
(Color.white, Number.five, None): 11,
(Color.white, Number.six, None): 14,
(Color.black, Number.one, Animal.cat): 15,
(Color.black, Number.one, Animal.dog): 16,
(Color.black, Number.two, Animal.cat): 17,
(Color.black, Number.two, Animal.dog): 19,
} | {
"domain": "codereview.stackexchange",
"id": 45512,
"lm_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, template",
"url": null
} |
python, template
print(f'I. White Animals: {sum(value for (color, _, _), value in amounts.items() if color == Color.white)}')
print(f'1. Numbers One and Two: {sum(value for (color, number, _), value in amounts.items() if color == Color.white and number in (Number.one, Number.two))}')
print(f'1.1. Number One: {sum(value for (color, number, _), value in amounts.items() if color == Color.white and number == Number.one)}')
print(f' First White Cats: {sum(value for (color, number, animal), value in amounts.items() if color == Color.white and number == Number.one and animal == Animal.cat)}')
print(f' First White Dogs: {sum(value for (color, number, animal), value in amounts.items() if color == Color.white and number == Number.one and animal == Animal.dog)}')
print(f'1.2. Number Two: {sum(value for (color, number, _), value in amounts.items() if color == Color.white and number == Number.two)}')
print(f' Second White Cats: {sum(value for (color, number, animal), value in amounts.items() if color == Color.white and number == Number.two and animal == Animal.cat)}')
print(f' Second White Dogs: {sum(value for (color, number, animal), value in amounts.items() if color == Color.white and number == Number.two and animal == Animal.dog)}')
print(f'2. Numbers Three and Four: {sum(value for (color, number, _), value in amounts.items() if color == Color.white and number in (Number.three, Number.four))}')
print(f'2.1. Number Three: {sum(value for (color, number, _), value in amounts.items() if color == Color.white and number == Number.three)}')
print(f' Balls: {sum(value for (color, number, toy), value in amounts.items() if color == Color.white and number == Number.three and toy == Toy.ball)}')
print(f' Leashes: {sum(value for (color, number, toy), value in amounts.items() if color == Color.white and number == Number.three and toy == Toy.leash)}') | {
"domain": "codereview.stackexchange",
"id": 45512,
"lm_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, template",
"url": null
} |
python, template
print(f'2.2. Number Four: {sum(value for (color, number, _), value in amounts.items() if color == Color.white and number == Number.four)}')
print(f' Balls: {sum(value for (color, number, toy), value in amounts.items() if color == Color.white and number == Number.four and toy == Toy.ball)}')
print(f' Leashes: {sum(value for (color, number, toy), value in amounts.items() if color == Color.white and number == Number.four and toy == Toy.leash)}')
print(f'3. Number Five: {sum(value for (color, number, _), value in amounts.items() if color == Color.white and number == Number.five)}')
print(f'4. Number Six: {sum(value for (color, number, _), value in amounts.items() if color == Color.white and number == Number.six)}')
print(f'II. Black Animals: {sum(value for (color, _, _), value in amounts.items() if color == Color.black)}')
print(f' First Black Cats: {sum(value for (color, number, animal), value in amounts.items() if color == Color.black and number == Number.one and animal == Animal.cat)}')
print(f' First Black Dogs: {sum(value for (color, number, animal), value in amounts.items() if color == Color.black and number == Number.one and animal == Animal.dog)}')
print(f' Second Black Cats: {sum(value for (color, number, animal), value in amounts.items() if color == Color.black and number == Number.two and animal == Animal.cat)}')
print(f' Second Black Dogs: {sum(value for (color, number, animal), value in amounts.items() if color == Color.black and number == Number.two and animal == Animal.dog)}') | {
"domain": "codereview.stackexchange",
"id": 45512,
"lm_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, template",
"url": null
} |
python, template
Although the context of the code was changed (it's not about cats and dogs), the code must have these 22 print statements and must filter amounts using each shown condition on its respective print statement.
Note that sections I. and II. filter animals based on their color, sections 1., 2., 3., 4. filter animals based on their number, and the remaining sections have some specific filters depending on its parent section.
I don't know how a for-loop could solve that.
Answer: Typically the members of enum classes should be capitalised since they're constants.
Run a PEP8 linter on this code. Your inter-class spacing is not correct.
Don't use object during typing. If you truly don't know anything about a type, write Any.
Lots of ways to reduce the repetition in the last part of the code. Fundamentally, your selectors have an O(n^2) problem since you need to re-express the tree root every time you navigate. You could write a navigation tree structure that is traversed by a recursive function:
import enum
from typing import Iterator, Sequence
class Number(enum.Enum):
one = 1
two = 2
three = 3
four = 4
five = 5
six = 6
class Color(enum.Enum):
white = 1
black = 2
class Animal(enum.Enum):
cat = 1
dog = 2
class Toy(enum.Enum):
ball = 1
leash = 2
Amounts = Sequence[
tuple[
tuple[
Color,
Number,
None | Animal | Toy,
],
int,
]
]
KeySet = set[Color | Number | Animal | Toy] | None
MatchTree = Sequence[ # recursive
tuple[KeySet, Sequence | str]
]
def filter_tree(
amounts: Amounts,
tree: MatchTree,
) -> Iterator[tuple[str, int]]:
for key, subtree in tree:
sub_amounts = [
(indices[1:], amount)
for indices, amount in amounts
if key is None or indices[0] in key
] | {
"domain": "codereview.stackexchange",
"id": 45512,
"lm_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, template",
"url": null
} |
python, template
if isinstance(subtree, str):
yield subtree, sum(a for k, a in sub_amounts)
else:
yield from filter_tree(sub_amounts, subtree)
def print_filter(amounts: Amounts, tree: MatchTree) -> None:
for prefix, total in filter_tree(amounts, tree):
print(f'{prefix}: {total}') | {
"domain": "codereview.stackexchange",
"id": 45512,
"lm_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, template",
"url": null
} |
python, template
def demo() -> None:
amounts = {
(Color.white, Number.one, Animal.cat): 1,
(Color.white, Number.one, Animal.dog): 2,
(Color.white, Number.two, Animal.cat): 4,
(Color.white, Number.two, Animal.dog): 5,
(Color.white, Number.three, Toy.ball): 6,
(Color.white, Number.three, Toy.leash): 7,
(Color.white, Number.four, Toy.ball): 8,
(Color.white, Number.four, Toy.leash): 10,
(Color.white, Number.five, None): 11,
(Color.white, Number.six, None): 14,
(Color.black, Number.one, Animal.cat): 15,
(Color.black, Number.one, Animal.dog): 16,
(Color.black, Number.two, Animal.cat): 17,
(Color.black, Number.two, Animal.dog): 19,
}
tree = (
({Color.white}, (
(None, 'I. White Animals'),
({Number.one, Number.two}, '1. Numbers One and Two'),
({Number.one}, (
(None, '1.1. Number One'),
({Animal.cat}, ' First White Cats'),
({Animal.dog}, ' First White Dogs'),
)),
({Number.two}, (
(None, '1.2. Number Two'),
({Animal.cat}, ' Second White Cats'),
({Animal.dog}, ' Second White Dogs'),
)),
({Number.three, Number.four}, '2. Numbers Three and Four'),
({Number.three}, (
(None, '2.1. Number Three'),
({Toy.ball}, ' Balls'),
({Toy.leash}, ' Leashes'),
)),
({Number.four}, (
(None, '2.2. Number Four'),
({Toy.ball}, ' Balls'),
({Toy.leash}, ' Leashes'),
)),
({Number.five}, '3. Number Five'),
({Number.six}, '4. Number Six'),
)),
({Color.black}, (
(None, 'II. Black Animals'),
({Number.one}, ( | {
"domain": "codereview.stackexchange",
"id": 45512,
"lm_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, template",
"url": null
} |
python, template
({Color.black}, (
(None, 'II. Black Animals'),
({Number.one}, (
({Animal.cat}, ' First Black Cats'),
({Animal.dog}, ' First Black Dogs'),
)),
({Number.two}, (
({Animal.cat}, ' Second Black Cats'),
({Animal.dog}, ' Second Black Dogs'),
)),
)),
) | {
"domain": "codereview.stackexchange",
"id": 45512,
"lm_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, template",
"url": null
} |
python, template
print_filter(amounts.items(), tree)
if __name__ == '__main__':
demo()
I. White Animals: 68
1. Numbers One and Two: 12
1.1. Number One: 3
First White Cats: 1
First White Dogs: 2
1.2. Number Two: 9
Second White Cats: 4
Second White Dogs: 5
2. Numbers Three and Four: 31
2.1. Number Three: 13
Balls: 6
Leashes: 7
2.2. Number Four: 18
Balls: 8
Leashes: 10
3. Number Five: 11
4. Number Six: 14
II. Black Animals: 67
First Black Cats: 15
First Black Dogs: 16
Second Black Cats: 17
Second Black Dogs: 19 | {
"domain": "codereview.stackexchange",
"id": 45512,
"lm_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, template",
"url": null
} |
c, reinventing-the-wheel, base64
Title: Bare bones base 64 encoding/decoding
Question: I wrote a bare-bones, no fluff, base 64 library in C. My goal was to make it as small as possible. I'm wondering if there are any further size optimizations I can make (without sacrificing too much readability).
#include <arpa/inet.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#define ALPHABET "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
#define INVALID_SEXTET 64
static char
convert_sextet(unsigned char sextet)
{
return ALPHABET[sextet];
}
static unsigned char
deconvert_sextet(char c)
{
if (c >= 'A' && c <= 'Z') {
return c - 'A';
}
else if (c >= 'a' && c <= 'z') {
return 26 + (c - 'a');
}
else if (c >= '0' && c <= '9') {
return 52 + (c - '0');
}
else if (c == '+') {
return 62;
}
else if (c == '/') {
return 63;
}
else {
return INVALID_SEXTET;
}
}
void
mini64_encode(const unsigned char *data, size_t len, char *dst)
{
if (!data || len == 0 || !dst) {
return;
}
for (size_t k = 0; k < len; k += 3) {
unsigned int group_size = MIN(3, len - k);
uint32_t group = 0;
char word[5] = "====";
memcpy((unsigned char *)&group + 1, data + k, group_size);
group = ntohl(group);
for (unsigned int j = 0; j <= group_size; j++) {
unsigned char sextet = (group >> 18) & 0x3f;
word[j] = convert_sextet(sextet);
group <<= 6;
}
sprintf(dst, "%s", word);
dst += 4;
}
}
int
mini64_decode(const char *string, size_t len, unsigned char *dst, size_t *data_len)
{
unsigned char *orig_dst = dst;
if (!string || len == 0 || !dst || !data_len) {
return -1;
}
if (len % 4 != 0) {
return -1;
} | {
"domain": "codereview.stackexchange",
"id": 45513,
"lm_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, reinventing-the-wheel, base64",
"url": null
} |
c, reinventing-the-wheel, base64
if (len % 4 != 0) {
return -1;
}
for (size_t k = 0; k < len; k += 4) {
unsigned int group_size = 3;
uint32_t group = 0;
for (unsigned int j = 0; j < 4; j++) {
char c = string[k + j];
unsigned char sextet;
group <<= 6;
if (c == '=') {
unsigned char check_mask;
if (k != len - 4 || j < 2 || (j == 2 && string[k + 3] != '=')) {
return -1;
}
if (j == 2) {
check_mask = 0x0f;
group <<= 6;
}
else {
check_mask = 0x03;
}
if (deconvert_sextet(string[k + j - 1]) & check_mask) {
return -1;
}
group_size = j - 1;
break;
}
sextet = deconvert_sextet(c);
if (sextet == INVALID_SEXTET) {
return -1;
}
group |= sextet;
}
group = htonl(group);
memcpy(dst, (unsigned char *)&group + 1, group_size);
dst += group_size;
}
*data_len = dst - orig_dst;
return 0;
};
Answer: I'd not name the functions mini64_encode and mini64_decode. In the code the user doesn't care if this is a minimal implementation, and base64 should definitely be in there. Don't care about name clashes, if a base 64 encoding is already available then these methods should not be required (be happy to be corrected on this).
It's nice that the code should be correct independent on the systems' byte order (ntohl call).
if (!data || len == 0 || !dst) {
return;
I'd return an error code if one of the pointers aren't set. | {
"domain": "codereview.stackexchange",
"id": 45513,
"lm_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, reinventing-the-wheel, base64",
"url": null
} |
c, reinventing-the-wheel, base64
I'd return an error code if one of the pointers aren't set.
A function to calculate the required dst size is missing. Without it the user is prone to create buffer overruns.
One trick is to have a positive return value or a separate ref. parameter set to the actual output size. If dst is NULL then only the required output size could be returned. That way the user knows the data size (in case the buffer is larger) and they can also create the exact required size if needed (trick taken from the PKCS#11 / Cryptoki interface spec).
sprintf is a function call. Function calls should be avoided for this kind of functionality.
char word[5] = "====";
That's only 4 characters if you would not assign it a zero-terminated string, and only up to 2 characters are ever used (a single byte will still occupy 2 base 64 characters after all). I'd just add one or two = characters programmatically.
uint32_t group = 0;
...
group = ntohl(group);
The initial assignment is unnecessary if the variable will be assigned a value anyway.
k and j don't really indicate what the variables are for. This is a localized problem though, so not very important.
For faster operation I would unroll the for loop (with j as the variable) and then perform the last operation and the padding separately. That removes a simple branch in the inner loop. So just shift by 18, 12 and 6 during encoding for instance.
One trick to speed up encoding / decoding is to perform bitwise trickery instead of using an alphabet. This is quite a lot harder to do, but implementations should exist.
I'd always reference the base 64 encoding / decoding that is performed. I would e.g. reference the precise encoding in RFC 4648.
During decoding I would definitely use different error codes for having:
an incorrectly sized input
a wrong base 64 character
possibly a = padding character at the wrong spot (but read onto the next comment) | {
"domain": "codereview.stackexchange",
"id": 45513,
"lm_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, reinventing-the-wheel, base64",
"url": null
} |
c, reinventing-the-wheel, base64
The check for the padding character is only required at the last part of the base 64 encoding. It is not required to check for padding characters for any block but the last. Again, the loop can be unrolled and the last block can be handled separately. | {
"domain": "codereview.stackexchange",
"id": 45513,
"lm_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, reinventing-the-wheel, base64",
"url": null
} |
python, parsing, reinventing-the-wheel, math-expression-eval
Title: Evaluating Polish Prefix Notation and Polish Postfix Notation
Question: In Polish postfix notation, the operators follow their operands. For example, to add 3 and 4 together, the expression is 3 4 + rather than 3 + 4. The conventional notation expression 3 − 4 + 5 becomes 3 4 − 5 + in Polish postfix notation: 4 is first subtracted from 3, then 5 is added to it.
Polish prefix notation, on the other hand, require that its operators precede the operands they work on. 3 + 4 would then be as + 3 4.
The algorithm used for parsing the postfix expression is simple:
while not end of file
read token into var
if (var is num)
push var
else if (var is operator)
if (operands >= 2)
pop into rhs
pop into lhs
push lhs operator rhs
else
throw exception
else
return fail
pop into var
return var
The code uses a stack to implement it. Prefix notation is parsed in the same manner, except that the tokens are reversed and the operands are swapped for each operation.
Parentheses are not supported.
Code:
#!/usr/bin/env python3
from typing import Union # For older Python versions.
OPCODES = {
"+": lambda lhs, rhs: lhs + rhs,
"-": lambda lhs, rhs: lhs - rhs,
"*": lambda lhs, rhs: lhs * rhs,
"/": lambda lhs, rhs: lhs / rhs,
"//": lambda lhs, rhs: lhs // rhs,
"%": lambda lhs, rhs: lhs % rhs,
"^": lambda lhs, rhs: lhs ** rhs,
}
def _eval_op(
lhs: Union[int, float], rhs: Union[int, float], opcode: str
) -> Union[int, float]:
return OPCODES[opcode](lhs, rhs)
def eval_postfix_expr(expr: str) -> Union[int, float]:
"""
Evaluate a postfix expression.
Supported operators:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
- Floor Division (//)
- Modulo (%)
- Exponentiation (^) | {
"domain": "codereview.stackexchange",
"id": 45514,
"lm_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, parsing, reinventing-the-wheel, math-expression-eval",
"url": null
} |
python, parsing, reinventing-the-wheel, math-expression-eval
Raises:
ValueError: If 'expr' is an invalid postfix expression.
"""
tokens = expr.split()
if tokens[-1] not in OPCODES.keys() or not tokens[0].isdigit():
raise ValueError("Invalid expression.")
stack = []
for tok in tokens:
if tok.isdigit():
stack.append(int(tok))
elif tok in OPCODES.keys():
if len(stack) >= 2:
rhs = stack.pop()
lhs = stack.pop()
stack.append(_eval_op(lhs, rhs, tok))
else:
raise ValueError("Invalid expression.")
return stack.pop()
def eval_prefix_expr(expr: str) -> Union[int, float]:
"""
Evaluate a prefix expression.
Supported operators:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
- Floor Division (//)
- Modulo (%)
- Exponentiation (^)
Raises:
ValueError: If 'expr' is an invalid prefix expression.
"""
tokens = expr.split()
if tokens[0] not in OPCODES.keys() or not tokens[-1].isdigit():
raise ValueError("Invalid expression.")
tokens = reversed(tokens)
stack = []
for tok in tokens:
if tok.isdigit():
stack.append(int(tok))
elif tok in OPCODES.keys():
if len(stack) >= 2:
lhs = stack.pop()
rhs = stack.pop()
stack.append(_eval_op(lhs, rhs, tok))
else:
raise ValueError("Invalid expression.")
return stack.pop()
def run_tests(func, test_data) -> None:
func_len = len(func.__name__)
max_expr_len = max(len(repr(expr)) for expr, _ in test_data) | {
"domain": "codereview.stackexchange",
"id": 45514,
"lm_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, parsing, reinventing-the-wheel, math-expression-eval",
"url": null
} |
python, parsing, reinventing-the-wheel, math-expression-eval
for expr, res in test_data:
func_name = func.__name__
expr_repr = repr(expr)
print(
f"func: {func_name:<{func_len}}, expr: {expr_repr:<{max_expr_len}}",
end="",
)
try:
rv = func(expr)
assert rv == res, f"Expected: {res}, Received: {rv}"
except Exception as e:
rv = e
print(f", result: {repr(rv)}")
def main() -> None:
post_test_data = [
("3 4 +", 7),
("3 4 + 5 4 ^ +", 632),
("+ 10a 29", 0),
("10 5 * 6 2 + /", 6.25),
("10 7 2 3 * + -", -3),
("icaoscasjcs", 0),
("* 10 5 * 7 3 + // 2 -", 3),
]
pre_test_data = [
("+ 3 4", 7),
("+ ^ 5 4 + 3 4", 632),
("+ 10a 29", 0),
("/ * 10 5 + 6 2", 6.25),
("- 10 + 7 * 2 3", -3),
("icaoscasjcs", 0),
("1038 - // * 10 5 + 7 3 2", 3),
]
run_tests(eval_postfix_expr, post_test_data)
print()
run_tests(eval_prefix_expr, pre_test_data)
if __name__ == "__main__":
main()
Prints:
func: eval_postfix_expr, expr: '3 4 +' , result: 7
func: eval_postfix_expr, expr: '3 4 + 5 4 ^ +' , result: 632
func: eval_postfix_expr, expr: '+ 10a 29' , result: ValueError('Invalid expression.')
func: eval_postfix_expr, expr: '10 5 * 6 2 + /' , result: 6.25
func: eval_postfix_expr, expr: '10 7 2 3 * + -' , result: -3
func: eval_postfix_expr, expr: 'icaoscasjcs' , result: ValueError('Invalid expression.')
func: eval_postfix_expr, expr: '* 10 5 * 7 3 + // 2 -', result: ValueError('Invalid expression.') | {
"domain": "codereview.stackexchange",
"id": 45514,
"lm_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, parsing, reinventing-the-wheel, math-expression-eval",
"url": null
} |
python, parsing, reinventing-the-wheel, math-expression-eval
func: eval_prefix_expr, expr: '+ 3 4' , result: 7
func: eval_prefix_expr, expr: '+ ^ 5 4 + 3 4' , result: 632
func: eval_prefix_expr, expr: '+ 10a 29' , result: ValueError('Invalid expression.')
func: eval_prefix_expr, expr: '/ * 10 5 + 6 2' , result: 6.25
func: eval_prefix_expr, expr: '- 10 + 7 * 2 3' , result: -3
func: eval_prefix_expr, expr: 'icaoscasjcs' , result: ValueError('Invalid expression.')
func: eval_prefix_expr, expr: '1038 - // * 10 5 + 7 3 2', result: ValueError('Invalid expression.')
Review Request:
There's some duplication in the docstrings. How can that be helped?
Are there any bugs in my code? Did I miss something?
I should have liked to implement eval_prefix_expr() with eval_postfix_expr(), but I did not see a way to swap the operands for each operator. Do you?
General coding comments, style, naming, et cetera.
Answer: operator module
OPCODES = {
"+": lambda lhs, rhs: lhs + rhs, ...
The lambdas are nice enough, they get the job done.
We could have just mentioned
operator.add,
floordiv, and so on.
ints are floats
def _eval_op(
lhs: Union[int, float], ...
Well, ok, clearly an int is not a float, nor does it inherit.
But rather than writing e.g. lhs: int | float,
Pep-484
explains that
when an argument is annotated as having type float, an argument of type int is acceptable | {
"domain": "codereview.stackexchange",
"id": 45514,
"lm_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, parsing, reinventing-the-wheel, math-expression-eval",
"url": null
} |
python, parsing, reinventing-the-wheel, math-expression-eval
when an argument is annotated as having type float, an argument of type int is acceptable
So prefer to shorten such annotations, as int is implicit.
short docstring
The docstring for eval_postfix_expr() is lovely.
You lamented the repetition of longish docstrings.
Maybe include the operators by reference?
That is, refer the interested reader
over to OPCODES, which could have its own docstring.
And then a one-liner of "+ - * / // % ^" suffices.
It goes on to comment on ValueError, suggesting
that's the only Bad Thing that could happen.
Maybe any error that gets raised is self explanatory,
and doesn't need a mention?
Or maybe enumerate the others here, such as ZeroDivisionError.
Too bad there's no i operator.
This turns out to be a very poor substitute:
print((-1) ** .5)
(6.123233995736766e-17+1j)
unary minus
if tok.isdigit():
It makes me sad that "3 -1 +" won't parse,
since "-".isdigit() == False
I agree with @vnp's EAFP suggestion.
Directly accepting an input operand of "-3.14" seems simple enough,
without making me divide 314 by 100.
silent error
elif tok in OPCODES.keys():
if len(stack) >= 2:
rhs = stack.pop()
lhs = stack.pop()
stack.append(_eval_op(lhs, rhs, tok))
else:
When presented with a short stack (bad input expression!)
we just silently move on without comment?!?
Worse, this could happen in the middle of an expression,
leading to a debugging nightmare.
(A dozen properly nested items, then short stack,
followed by another dozen properly nested items.
Where's the bad entry, we wonder?)
long stack
Evaluating "1 2 3 +" will return 5 but will leave 1 on the stack.
I feel this should be a fatal error reported to the user.
DRY
eval_prefix_expr() is Too Long.
It should reverse, and then call eval_postfix_expr().
Or both should call a common _helper().
I did not see a way to swap the operands for each operator. | {
"domain": "codereview.stackexchange",
"id": 45514,
"lm_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, parsing, reinventing-the-wheel, math-expression-eval",
"url": null
} |
python, parsing, reinventing-the-wheel, math-expression-eval
I did not see a way to swap the operands for each operator.
Yeah, I see what you mean.
Define a postfix_swap(a, b) helper which does nothing
(identity function), and a prefix_swap(a, b) helper
which swaps its args, and pass in the swapper function
as part of the call.
Or maybe pass in (0, 1) and (1, 0) arg_selector tuples,
the indexes of a and b.
simple tests
The custom run_tests() routine is nice.
We could tighten up a few things, like {func_name:<{func_len}}
is just {func_name}, and we could assign func_name just once
if we need it at all.
Consider phrasing this test in terms of from unittest import TestCase.
assert rv == res
This equality test works for now.
But soon you'll want self.assertAlmostEqual(), I think.
commutativity
I really do appreciate the emphasis on "simple" here.
post_test_data = [ ...
("10 5 * 6 2 + /", 6.25),
...
pre_test_data = [ ...
("/ * 10 5 + 6 2", 6.25),
Those say nearly the same thing.
But the one is not a reversal of the other.
In mathematics, addition over the reals commutes.
Similarly for multiplication.
In IEEE-754, addition is not commutative, nor is multiplication.
Order of evaluation matters.
We worry about catastrophic cancellation.
One way to avoid cumulative rounding errors in a long sum
is to order FP operands by magnitude and sum the little ones
before the big ones.
So consider ditching pre_test_data,
in favor of just reversing post_test_data.
hypothesis
Consider writing a postfix_to_infix() converter,
whose parenthesized output you can just hand to eval().
Now you have an "oracle" that knows the right answer.
With that in hand you can invite
hypothesis
to dream up random expressions of limited length,
and then you verify that the evaluations match.
I predict you will learn new things about
your code and about FP.
This code achieves most of its design goals.
I would be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 45514,
"lm_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, parsing, reinventing-the-wheel, math-expression-eval",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
Title: Semi-dynamic range minimum query (RMQ) tree in Java
Question: Introduction
I have this semi-dynamic range minimum query (RMQ) tree in Java. It is called semi-dynamic due to the fact that it cannot be modified after it is constructed. However, the values associated with the keys may be updated.
An RMQ tree maintains a set of (distinct) keys and associates a value with each key. The tree in question provides two important operations:
update(key, value) - if value associated with the key key is smaller than the current value of key (current_value), sets the value of the key to value overwriting the current_value,
getRangeMinimum(leftKey, rightKey) - in the range R = [leftKey ... rightKey] returns the minimum value stored somewhere in R.
Both above operations run in exact \$\Theta(\log n)\$ time where \$n\$ is the number of keys in the tree. Building the tree runs in \$\mathcal{O}(n \log n)\$ time.
Also note that all keys are associated with only leaf nodes of the tree and if we traverse the leaves from left to right, the keys will come out in strictly increasing order, that is, the keys are stored in sorted order.
Code
com.github.coderodde.util.AbstractRMQTreeNode.java:
package com.github.coderodde.util;
public abstract class AbstractRMQTreeNode<V> {
protected V value;
protected AbstractRMQTreeNode<V> parent;
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public AbstractRMQTreeNode<V> getParent() {
return parent;
}
public void setParent(AbstractRMQTreeNode<V> parent) {
this.parent = parent;
}
}
com.github.coderodde.util.InternalRMQTreeNode.java:
package com.github.coderodde.util;
import java.util.Objects;
public final class InternalRMQTreeNode<V> extends AbstractRMQTreeNode<V> {
private AbstractRMQTreeNode<V> leftChild;
private AbstractRMQTreeNode<V> rightChild; | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
public AbstractRMQTreeNode<V> getLeftChild() {
return leftChild;
}
public AbstractRMQTreeNode<V> getRightChild() {
return rightChild;
}
public void setLeftChild(AbstractRMQTreeNode<V> leftChild) {
this.leftChild = leftChild;
}
public void setRightChild(AbstractRMQTreeNode<V> rightChild) {
this.rightChild = rightChild;
}
@Override
public String toString() {
return String.format("[INTERNAL: value = \"%s\"]",
Objects.toString(value));
}
}
com.github.coderodde.util.LeafRMQTreeNode.java:
package com.github.coderodde.util;
import java.util.Objects;
public final class LeafRMQTreeNode<V> extends AbstractRMQTreeNode<V> {
@Override
public String toString() {
return String.format("[LEAF: value = \"%s\"]",
Objects.toString(getValue()));
}
}
com.github.coderodde.util.KeyValuePair.java:
package com.github.coderodde.util;
import java.util.Objects;
public final class KeyValuePair<K extends Comparable<? super K>, V>
implements Comparable<KeyValuePair<K, V>> {
private final K key;
private final V value;
public KeyValuePair(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public int compareTo(KeyValuePair<K, V> o) {
return key.compareTo(o.key);
}
@Override
public String toString() {
return String.format("[KeyValuePair: key = \"%s\", value = \"%s\"]",
Objects.toString(key),
Objects.toString(value));
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
com.github.coderodde.util.SemiDynamicRMQTree.java:
package com.github.coderodde.util; | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
com.github.coderodde.util.SemiDynamicRMQTree.java:
package com.github.coderodde.util;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import com.github.coderodde.util.SemiDynamicRMQTreeBuilder.RMQTreeBuilderResult;
import static com.github.coderodde.util.Utils.min; | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
/**
* This class implements a semi-dynamic RMQ (range minimum query) tree. While
* it does not support modification of the tree, it supports update of leaf node
* values. The operation
* {@link #update(java.lang.Comparable, java.lang.Comparable)} runs in exact
* logarithmic time; so does the
* {@link #getRangeMinimum(java.lang.Comparable, java.lang.Comparable) }.
*
* @param <K> the key type.
* @param <V> the value type.
*/
public final class SemiDynamicRMQTree<K extends Comparable<? super K>,
V extends Comparable<? super V>> {
private final AbstractRMQTreeNode<V> root;
private final Map<K, LeafRMQTreeNode<V>> leafMap;
public SemiDynamicRMQTree(Set<KeyValuePair<K, V>> keyValuePairSet) {
RMQTreeBuilderResult<K, V> result =
SemiDynamicRMQTreeBuilder.buildRMQTree(keyValuePairSet);
root = result.getRoot();
leafMap = result.getLeafMap();
}
/**
* Returns the root node of this tree. Is package-private in order to be
* accessible from the unit tests.
*
* @return the root node of this tree.
*/
AbstractRMQTreeNode<V> getRoot() {
return root;
}
/**
* Returns the string representation of this tree.
*
* @return the string representation of this tree.
*/
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
toStringImpl(stringBuilder);
return stringBuilder.toString();
}
/**
* Associates the value {@code newValue} with the key {@code key}. Runs in
* exact logarithmic time.
*
* @param key the target key.
* @param newValue the new value for the target key.
*/
public void update(K key, V newValue) {
AbstractRMQTreeNode<V> node = leafMap.get(key);
while (node != null) {
node.setValue(min(node.getValue(), newValue)); | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
while (node != null) {
node.setValue(min(node.getValue(), newValue));
node = node.getParent();
}
}
/**
* Given the range {@code R = [leftKey ... rightKey]}, return the minimum
* value in {@code R}. Runs in exact logarithmic time.
*
* @param leftKey the leftmost key of the range.
* @param rightKey the rightmost key of the range.
* @return the minimum value in {@code R}.
*/
public V getRangeMinimum(K leftKey, K rightKey) {
AbstractRMQTreeNode<V> leftLeaf = leafMap.get(leftKey);
Objects.requireNonNull(
leftLeaf,
String.format(
"The left key [%s] is not in this tree.",
leftKey));
AbstractRMQTreeNode<V> rightLeaf = leafMap.get(rightKey);
Objects.requireNonNull(
rightLeaf,
String.format(
"The right key [%s] is not in this tree.",
rightKey));
if (leftKey.compareTo(rightKey) > 0) {
String exceptionMessage =
String.format(
"The specified range [%s, %s] is descending.",
leftKey,
rightKey);
throw new IllegalArgumentException(exceptionMessage);
}
AbstractRMQTreeNode<V> splitNode =
computeSplitNode(leftLeaf,
rightLeaf);
List<AbstractRMQTreeNode<V>> leftPath = getPath(splitNode,
leftLeaf);
List<AbstractRMQTreeNode<V>> rightPath = getPath(splitNode,
rightLeaf);
List<AbstractRMQTreeNode<V>> leftPathV =
computeLeftPathV(leftPath); | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
List<AbstractRMQTreeNode<V>> leftPathV =
computeLeftPathV(leftPath);
List<AbstractRMQTreeNode<V>> rightPathV =
computeRightPartV(rightPath);
V vl = computeMinimum(leftPathV);
V vr = computeMinimum(rightPathV);
if (vl == null) {
vl = leftLeaf.getValue();
}
if (vr == null) {
vr = rightLeaf.getValue();
}
vl = min(vl, leftLeaf.getValue());
vr = min(vr, rightLeaf.getValue());
return min(vl, vr);
}
/**
* Computes the minimum value in {@code nodes}.
*
* @param <V> the value type.
* @param nodes the list of values.
* @return the minimum value or {@code null} if the input list is empty.
*/
private <V extends Comparable<? super V>>
V computeMinimum(List<AbstractRMQTreeNode<V>> nodes) {
if (nodes.isEmpty()) {
return null;
}
V minValue = nodes.get(0).getValue();
for (int i = 1; i < nodes.size(); i++) {
AbstractRMQTreeNode<V> node = nodes.get(i);
minValue = min(minValue, node.getValue());
}
return minValue;
}
/**
* Computes the so called {@code V'}.
*
* @param path the target path.
* @return the {@code V'} set.
*/
private List<AbstractRMQTreeNode<V>>
computeLeftPathV(List<AbstractRMQTreeNode<V>> path) {
Set<AbstractRMQTreeNode<V>> pathSet = new HashSet<>(path);
List<AbstractRMQTreeNode<V>> nodeList = new ArrayList<>();
for (int i = 0; i < path.size(); i++) {
InternalRMQTreeNode<V> parent =
(InternalRMQTreeNode<V>) path.get(i);
AbstractRMQTreeNode<V> leftChild = parent.getLeftChild(); | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
AbstractRMQTreeNode<V> leftChild = parent.getLeftChild();
AbstractRMQTreeNode<V> rightChild = parent.getRightChild();
if (pathSet.contains(leftChild)) {
nodeList.add(rightChild);
}
}
return nodeList;
}
/**
* Computes the so called {@code V''}.
*
* @param path the target path.
* @return the {@code V''} set.
*/
private List<AbstractRMQTreeNode<V>>
computeRightPartV(List<AbstractRMQTreeNode<V>> path) {
Set<AbstractRMQTreeNode<V>> pathSet = new HashSet<>(path);
List<AbstractRMQTreeNode<V>> nodeList = new ArrayList<>();
for (int i = 0; i < path.size() - 1; i++) {
InternalRMQTreeNode<V> parent =
(InternalRMQTreeNode<V>) path.get(i);
AbstractRMQTreeNode<V> leftChild = parent.getLeftChild();
AbstractRMQTreeNode<V> rightChild = parent.getRightChild();
if (pathSet.contains(rightChild)) {
nodeList.add(leftChild);
}
}
return nodeList;
}
/**
* Gets the path from {@code splitNode} to the {@code leaf}. The returned
* path will, however, exclude {@code splitNode} and {@code leaf}.
*
* @param splitNode the starting path node.
* @param leafNode the target node.
* @return the path from {@code splitNode} to {@code leaf};
*/
private List<AbstractRMQTreeNode<V>>
getPath(AbstractRMQTreeNode<V> splitNode,
AbstractRMQTreeNode<V> leafNode) {
List<AbstractRMQTreeNode<V>> path = new ArrayList<>();
AbstractRMQTreeNode<V> node = leafNode.getParent();
while (node != null && !node.equals(splitNode)) {
path.add(node);
node = node.getParent();
}
Collections.reverse(path); | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
node = node.getParent();
}
Collections.reverse(path);
return path;
}
/**
* Computes the node at which the path from the root splits towards
* {@code leftLeaf} and {@code rightLeaf}.
*
* @param leftLeaf the left leaf.
* @param rightLeaf the right leaf.
* @return the split node.
*/
private AbstractRMQTreeNode<V>
computeSplitNode(AbstractRMQTreeNode<V> leftLeaf,
AbstractRMQTreeNode<V> rightLeaf) {
Set<AbstractRMQTreeNode<V>> leftPathSet = new HashSet<>();
AbstractRMQTreeNode<V> node = leftLeaf;
while (node != null) {
leftPathSet.add(node);
node = node.getParent();
}
node = rightLeaf;
while (node != null) {
if (leftPathSet.contains(node)) {
return node;
}
node = node.getParent();
}
throw new IllegalStateException("Should not get here.");
}
/**
* Implements the actual conversion from the tree to the string.
*
* @param stringBuilder the string builder to which dump the string data.
*/
private void toStringImpl(StringBuilder stringBuilder) {
Deque<AbstractRMQTreeNode<V>> queue =
new ArrayDeque<>();
queue.addLast(root);
AbstractRMQTreeNode<V> levelEnd = root;
while (!queue.isEmpty()) {
AbstractRMQTreeNode<V> currentNode = queue.removeFirst();
stringBuilder.append(String.format("%s ", currentNode));
if (currentNode instanceof InternalRMQTreeNode) {
AbstractRMQTreeNode<V> leftChild =
((InternalRMQTreeNode<V>) currentNode)
.getLeftChild(); | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
.getLeftChild();
AbstractRMQTreeNode<V> rightChild =
((InternalRMQTreeNode<V>) currentNode)
.getRightChild();
queue.addLast(leftChild);
queue.addLast(rightChild);
}
if (currentNode.equals(levelEnd)) {
if (!queue.isEmpty()) {
levelEnd = queue.getLast();
}
stringBuilder.append("\n");
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
com.github.coderodde.util.SemiDynamicRMQTreeBuilder.java:
package com.github.coderodde.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import static com.github.coderodde.util.Utils.min;
public final class SemiDynamicRMQTreeBuilder<K extends Comparable<? super K>,
V extends Comparable<? super V>> { | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
/**
* Implements the actual tree building.'
*
* @param <K> the key type.
* @param <V> the value type.
* @param keyValuePairSet the set of key/value pairs.
* @return the tree data.
*/
static <K extends Comparable<? super K>,
V extends Comparable<? super V>>
RMQTreeBuilderResult<K, V>
buildRMQTree(Set<KeyValuePair<K, V>> keyValuePairSet) {
Map<K, LeafRMQTreeNode<V>> leafMap = new HashMap<>();
loadLeafMap(leafMap, keyValuePairSet);
Objects.requireNonNull(
keyValuePairSet,
"The input KeyValuePair set is null.");
if (keyValuePairSet.isEmpty()) {
throw new IllegalArgumentException(
"No key/value pairs to process.");
}
List<KeyValuePair<K, V>> keyValuePairList =
new ArrayList<>(keyValuePairSet);
Collections.sort(keyValuePairList);
Map<K, LeafRMQTreeNode<V>> mapKeyToLeafNode = new HashMap<>();
RMQTreeBuilderResult<K, V> result = new RMQTreeBuilderResult();
AbstractRMQTreeNode<V> root =
buildRMQTreeImpl(keyValuePairList,
mapKeyToLeafNode);
result.setLeafMap(mapKeyToLeafNode);
result.setRoot(root);
return result;
}
/**
* Implements the actual, recursive building routine.
* <p>
* This algorithm seems much like in Task9, yet it differs: this one does
* not stored actual keys to the internal nodes, except to the leaf nodes,
* unlike the algorithm in Task9.java.
*
* @param <K> the key type.
* @param <V> the value type.
* @param keyValuePairs the set of key/value pairs.
* @param mapKeyToLeafNodes the map mapping keys to leaf nodes.
* @return local root of the tree constructed.
*/ | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
* @return local root of the tree constructed.
*/
private static <K extends Comparable<? super K>,
V extends Comparable<? super V>>
AbstractRMQTreeNode<V>
buildRMQTreeImpl(List<KeyValuePair<K, V>> keyValuePairs,
Map<K, LeafRMQTreeNode<V>> mapKeyToLeafNodes) {
if (keyValuePairs.size() == 1) {
KeyValuePair<K, V> keyValuePair = keyValuePairs.get(0);
LeafRMQTreeNode<V> leaf = new LeafRMQTreeNode<>();
leaf.setValue(keyValuePair.getValue());
mapKeyToLeafNodes.put(keyValuePair.getKey(), leaf);
return leaf;
}
// middleIndex goes to the right:
int middleIndex = keyValuePairs.size() / 2; | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
AbstractRMQTreeNode<V> leftSubTreeRoot
= buildRMQTreeImpl(
keyValuePairs.subList(0, middleIndex),
mapKeyToLeafNodes);
AbstractRMQTreeNode<V> rightSubTreeRoot
= buildRMQTreeImpl(
keyValuePairs.subList(
middleIndex,
keyValuePairs.size()),
mapKeyToLeafNodes);
InternalRMQTreeNode<V> localRoot = new InternalRMQTreeNode<>();
// Link the children and their parent:
localRoot.setLeftChild(leftSubTreeRoot);
localRoot.setRightChild(rightSubTreeRoot);
leftSubTreeRoot.setParent(localRoot);
rightSubTreeRoot.setParent(localRoot);
localRoot.setValue(min(leftSubTreeRoot.getValue(), // Important step!
rightSubTreeRoot.getValue())); | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
return localRoot;
}
/**
* Loads the map mapping keys to leaf nodes.
* '
* @param <K> the key type.
* @param <V> the value type.
* @param leafMap the map to populate.
* @param keyValuePairSet the key/value pair set.
*/
private static <K extends Comparable<? super K>,
V extends Comparable<? super V>>
void loadLeafMap(Map<K, LeafRMQTreeNode<V>> leafMap,
Set<KeyValuePair<K, V>> keyValuePairSet) {
for (KeyValuePair<K, V> keyValuePair : keyValuePairSet) {
LeafRMQTreeNode<V> leaf = new LeafRMQTreeNode<>();
leaf.setValue(keyValuePair.getValue());
leafMap.put(keyValuePair.getKey(), leaf);
}
}
static final
class RMQTreeBuilderResult<K extends Comparable<? super K>,
V extends Comparable<? super V>> {
private Map<K, LeafRMQTreeNode<V>> leafMap;
private AbstractRMQTreeNode<V> root;
public void setLeafMap(Map<K, LeafRMQTreeNode<V>> leafMap) {
this.leafMap = leafMap;
}
public void setRoot(AbstractRMQTreeNode<V> root) {
this.root = root;
}
Map<K, LeafRMQTreeNode<V>> getLeafMap() {
return leafMap;
}
AbstractRMQTreeNode<V> getRoot() {
return root;
}
}
}
com.github.coderodde.util.SemiDynamicRMQTreeDemo.java:
package com.github.coderodde.util;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set; | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public final class SemiDynamicRMQTreeDemo {
private static final int INITIAL_TREE_SIZE = 4;
private static SemiDynamicRMQTree<Integer, Long> tree =
constructREPLTree(INITIAL_TREE_SIZE);
public static void main(String[] args) {
replInterface();
}
private static SemiDynamicRMQTree<Integer, Long>
constructREPLTree(int size) {
long start = System.nanoTime();
Set<KeyValuePair<Integer, Long>> keyValuePairSet = new HashSet<>(size);
for (int i = 0; i < size; i++) {
Integer key = i + 1;
Long value = Long.valueOf(i + 1);
KeyValuePair<Integer, Long> keyValuePair = new KeyValuePair<>(key, value);
keyValuePairSet.add(keyValuePair);
}
long end = System.nanoTime();
long total = end - start;
System.out.printf(
"Built the key/value pairs in %,d nanoseconds.\n",
total);
start = System.nanoTime();
SemiDynamicRMQTree<Integer, Long> tree =
new SemiDynamicRMQTree<>(keyValuePairSet); | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
end = System.nanoTime();
System.out.printf("Built the RMQ tree in %,d nanoseconds.\n",
end - start);
total += end - start;
System.out.printf(
"Total time building the RMQ tree: %,d nanoseconds.\n",
total);
return tree;
}
private static void replInterface() {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("> ");
String commandLine = scanner.nextLine().trim();
try {
String[] commandLineParts = commandLine.split(" ");
String command = commandLineParts[0].trim();
switch (command) {
case "update":
runUpdate(commandLineParts[1],
commandLineParts[2]);
break;
case "rmq":
Long value = runRMQ(commandLineParts[1],
commandLineParts[2]);
System.out.println(value);
break;
case "print":
System.out.println(tree);
break;
case "new":
int size = Integer.parseInt(commandLineParts[1]);
tree = constructREPLTree(size);
break;
case "help":
printHelp();
break; | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
case "help":
printHelp();
break;
case "quit":
case "exit":
System.out.println("Bye!");
return;
}
} catch (Exception ex) {
System.out.printf(
"ERROR: Could not parse command \"%s\".\n",
commandLine);
}
}
}
private static void printHelp() {
final String help = "update KEY VALUE\n" +
"rmq KEY1 KEY2\n" +
"print\n" +
"new TREE_SIZE\n" +
"help";
System.out.println(help);
}
private static void runUpdate(String keyString, String newValueString) {
Integer key = Integer.valueOf(keyString);
Long value = Long.valueOf(newValueString);
long start = System.nanoTime();
tree.update(key, value);
long end = System.nanoTime();
System.out.printf("update in %,d nanoseconds.\n", end - start);
}
private static Long runRMQ(String leftKeyString, String rightKeyString) {
Integer leftKey = Integer.valueOf(leftKeyString);
Integer rightKey = Integer.valueOf(rightKeyString);
long start = System.nanoTime();
Long returnValue = tree.getRangeMinimum(leftKey, rightKey);
long end = System.nanoTime();
System.out.printf("rmq in %,d nanoseconds.\n", end - start);
return returnValue;
}
}
com.github.coderodde.util.Utils.java:
package com.github.coderodde.util; | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
com.github.coderodde.util.Utils.java:
package com.github.coderodde.util;
public final class Utils {
/**
* Returns the smaller of the two given values.
*
* @param <E> the value of type. Must be {@link java.lang.Comparable}.
* @param value1 the first value.
* @param value2 the second value.
* @return the smaller of the two input values.
*/
public static <E extends Comparable<? super E>> E min(E value1, E value2) {
return value1.compareTo(value2) < 0 ? value1 : value2;
}
}
com.github.coderodde.util.SemiDynamicRMQTreeTest.java:
package com.github.coderodde.util;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import org.junit.Test; | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
public class SemiDynamicRMQTreeTest {
@Test
public void passesOnTreeWith4Nodes() {
Set<KeyValuePair<Integer, Long>> keyValuePairSet = new HashSet<>(4);
keyValuePairSet.add(new KeyValuePair<>(2, 2L));
keyValuePairSet.add(new KeyValuePair<>(4, 4L));
keyValuePairSet.add(new KeyValuePair<>(1, 1L));
keyValuePairSet.add(new KeyValuePair<>(3, 3L));
SemiDynamicRMQTree<Integer, Long> tree =
new SemiDynamicRMQTree<>(keyValuePairSet);
InternalRMQTreeNode<Long> root =
(InternalRMQTreeNode<Long>) tree.getRoot();
InternalRMQTreeNode<Long> leftMiddleNode =
(InternalRMQTreeNode<Long>) root.getLeftChild();
InternalRMQTreeNode<Long> rightMiddleNode =
(InternalRMQTreeNode<Long>) root.getRightChild();
LeafRMQTreeNode<Long> leaf1 = (LeafRMQTreeNode<Long>) leftMiddleNode.getLeftChild();
LeafRMQTreeNode<Long> leaf2 = (LeafRMQTreeNode<Long>) leftMiddleNode.getRightChild();
LeafRMQTreeNode<Long> leaf3 = (LeafRMQTreeNode<Long>) rightMiddleNode.getLeftChild();
LeafRMQTreeNode<Long> leaf4 = (LeafRMQTreeNode<Long>) rightMiddleNode.getRightChild();
assertEquals(Long.valueOf(1L), root.getValue());
assertEquals(Long.valueOf(1L), leftMiddleNode.getValue());
assertEquals(Long.valueOf(3L), rightMiddleNode.getValue());
assertEquals(Long.valueOf(1L), leaf1.getValue());
assertEquals(Long.valueOf(2L), leaf2.getValue());
assertEquals(Long.valueOf(3L), leaf3.getValue());
assertEquals(Long.valueOf(4L), leaf4.getValue());
assertEquals(Long.valueOf(1L),
tree.getRangeMinimum(Integer.valueOf(1),
Integer.valueOf(2)));
assertEquals(Long.valueOf(3L), | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
assertEquals(Long.valueOf(3L),
tree.getRangeMinimum(Integer.valueOf(3),
Integer.valueOf(4)));
assertEquals(Long.valueOf(2L),
tree.getRangeMinimum(Integer.valueOf(2),
Integer.valueOf(4)));
assertEquals(Long.valueOf(1L),
tree.getRangeMinimum(Integer.valueOf(1),
Integer.valueOf(4)));
tree.update(4, -1L);
assertEquals(Long.valueOf(-1L), leaf4.getValue());
assertEquals(Long.valueOf(-1L), rightMiddleNode.getValue());
assertEquals(Long.valueOf(-1L), root.getValue());
}
@Test
public void passesOnTreeWith3Nodes() {
Set<KeyValuePair<Integer, Long>> keyValuePairSet = new HashSet<>(4);
keyValuePairSet.add(new KeyValuePair<>(2, 2L));
keyValuePairSet.add(new KeyValuePair<>(1, 1L));
keyValuePairSet.add(new KeyValuePair<>(3, 3L));
SemiDynamicRMQTree<Integer, Long> tree =
new SemiDynamicRMQTree<>(keyValuePairSet);
InternalRMQTreeNode<Long> root =
(InternalRMQTreeNode<Long>) tree.getRoot();
assertEquals(Long.valueOf(1L), root.getValue());
InternalRMQTreeNode<Long> middleInternalNode =
(InternalRMQTreeNode<Long>) root.getRightChild();
assertEquals(Long.valueOf(2L), middleInternalNode.getValue());
LeafRMQTreeNode<Long> leaf1 = (LeafRMQTreeNode<Long>) root.getLeftChild();
LeafRMQTreeNode<Long> leaf2 = (LeafRMQTreeNode<Long>) middleInternalNode.getLeftChild();
LeafRMQTreeNode<Long> leaf3 = (LeafRMQTreeNode<Long>) middleInternalNode.getRightChild();
assertEquals(Long.valueOf(1L), leaf1.getValue());
assertEquals(Long.valueOf(2L), leaf2.getValue()); | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
assertEquals(Long.valueOf(2L), leaf2.getValue());
assertEquals(Long.valueOf(3L), leaf3.getValue());
}
} | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
Typical output
Built the key/value pairs in 1 628 500 nanoseconds.
Built the RMQ tree in 8 127 200 nanoseconds.
Total time building the RMQ tree: 9 755 700 nanoseconds.
> new 10000000
Built the key/value pairs in 5 512 051 500 nanoseconds.
Built the RMQ tree in 25 338 403 700 nanoseconds.
Total time building the RMQ tree: 30 850 455 200 nanoseconds.
> rmq 1 10000000
rmq in 1 012 800 nanoseconds.
1
> update 26 -1
update in 55 300 nanoseconds.
> rmq 1 10000000
rmq in 278 200 nanoseconds.
-1
>
Critique request
Please tell me anything that comes to mind. | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
Answer: Context
RMQ is not as a well known problem as say sorting, so I personally had to search the web first to even know what this is exactly about. I had a quick look at the Wikipedia article, where one of the solutions is to use a Cartesian tree, but I wasn't even sure if your tree is a Cartesian tree or something else because there's zero explanation.
I also have had a quick look at Google results for "range minimum query tree" and the first result was something called Segment Tree and again I didn't know it it was the type of tree you implemented or something else.
At this point I gave up on trying to understand what exactly your tree is and I have a feeling, that this lack of context is one of the reasons this question got so little attention.
Thus the rest of the review will focus solely on code organization and skip the question whether the algorithm/data structure you implemented could be somehow optimized/improved.
Overblown class hierarchy
You have THREE classes for your tree nodes (abstract base, internal, leaf), the only method that is ever overridden is toString() (having almost exactly the same behaviour, differing only with constant used) and internal nodes do not enforce non-null on at least 1 of their children. In the rest of the code, there's only 1 place that differentiates between a leaf and an internal node by doing instanceof: this is often a very strong indicator, that something is wrong with your class hierarchy.
Furthermore, if you joined these 3 classes into 1, it would save you lots of casting that you currently need all around the code... | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
It is possible, that these classes were extracted from some bigger code base where there were some additional methods, that would justify having 3 separate classes, but for the purpose of this review it would be much better to have just 1 RMQTreeNode class with additional boolean isLeaf field. This would make the code much quicker to comprehend. I'm guessing that this is the 2nd reason why this question got so little attention: honestly when I first saw it I was like "oh boy, so many classes: this is BIIIG, it will require a LOT of undivided time to review!" and gave up until now...
Now on top of the above there's KeyValuePair, that can be replaced by AbstractMap.SimpleEntry and Utils with a single 1-line static helper method that could be moved for example to SemiDynamicRMQTree...
As pointed before, even if in some broader context there's a reason for having these 3 *RMQTreeNode classes, I think it would be cleaner to have isLeaf() method in the abstract base and use it instead of instanceof.
Code style
Everyone is usually quite opinionated regarding code style guidelines and I'm usually fine with that, but I strongly believe that 99% of Java devs in the world would agree that blank lines in the middle of method headers are misleading. I literally spent like 30 seconds staring before I finally realized what I was looking at ;-)
Unnecessary boilerplate
Java has a bad reputation for requiring a lot of boilerplate. This is to some degree caused by developers perpetuating overly strict (IMO) coding style guidelines, like that every class, even dumb DTOs like RMQTreeBuilderResult must have all fields private accompanied by accessor methods. However from the point of view of access control, making a field private final and providing a getter brings absolutely zero value comparing to making it public final and no getter is necessary then. | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
java, algorithm, tree, bioinformatics, binary-tree
Furthermore, I've noticed on github that language level is set to 20, in which case the whole RMQTreeBuilderResult can be converted into a 2 line record.
Similarly with fields in *RMQTreeNode classes: they are all private and then both getters and setters are provided: this is totally unnecessary IMO: if you provide both a getter and a setter it's equivalent to just making the field public and no boilerplate methods are necessary then.
Unused code
SemiDynamicRMQTreeBuilder has only static methods: it does not need type params
toString() methods of *RMQTreeNode classes have unnecessary calls to Objects.toString(...) | {
"domain": "codereview.stackexchange",
"id": 45515,
"lm_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, algorithm, tree, bioinformatics, binary-tree",
"url": null
} |
c, interpreter, brainfuck
Title: Basic Brainfuck Interpreter in C
Question: I have written a small Brainfuck interpreter in C. More recent version hosted here.
I have found it very hard to test my interpreter because writing a program in Brainfuck is somewhat hard (or at least very tedious) and many snippets I found online either don't give output or do so very cryptically, so I don't know 100% sure if everything works as intended.
I have tested a few programs on it though, and that which I tested works.
Any criticism/advice would be very nice.
#include <stdio.h>
#define MEMSIZE 30000
int memory[MEMSIZE];
int instructions[MEMSIZE];
int memptr = 0;
int insptr = 0;
int isInstruction(char);
void runInstruction(char);
int main(int argc, char *argv[]) {
// Open input file
FILE *file = fopen(argv[1], "r");
if (file == 0){
printf("Error: Could not open source file\n");
return 0;
}
// Read all instructions from input
char c;
int i = 0;
int balance = 0; // Keeps track of `[` and `]` balance
while ((c = fgetc(file)) != EOF && i < MEMSIZE){
if(isInstruction(c)){
instructions[i] = c;
i++;
if (c == '[')
balance++;
if (c == ']')
balance--;
}
}
// Close input file
fclose(file);
// Error if amount of instructions is more than permitted
if (c != EOF && i >= MEMSIZE){
printf("Error: cannot read more than 30000 instructions\n");
return 0;
}
// Error if `[` and `]` aren't balanced
if (balance != 0){
printf("Error: `[` and `]` were not balanced\n");
return 0;
}
// Run the program
while(insptr < MEMSIZE && instructions[insptr] != 0){
runInstruction(instructions[insptr]);
insptr++;
}
} | {
"domain": "codereview.stackexchange",
"id": 45516,
"lm_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, interpreter, brainfuck",
"url": null
} |
c, interpreter, brainfuck
int isInstruction(char c) {
if(c == '+' || c == '-' || c == '>' || c == '<' || c == '[' || c == ']' ||
c == '.' || c == ','){
return 1;
} else {
return 0;
}
}
void runInstruction(char c) {
switch(c){
case '+':
memory[memptr]++;
break;
case '-':
memory[memptr]--;
break;
case '>':
if (memptr < MEMSIZE - 1)
memptr++;
else
memptr = 0;
break;
case '<':
if (memptr > 0)
memptr--;
else
memptr = MEMSIZE - 1;
break;
case '[':
if (memory[memptr] == 0)
// seek `]` forward
while(instructions[insptr] != ']'){
insptr++;
}
break;
case ']':
if (memory[memptr] != 0)
// seek `[` backward
while(instructions[insptr] != '['){
insptr--;
}
break;
case '.':
putchar(memory[memptr]);
break;
case ',':
memory[memptr] = getchar();
break;
default:
printf("Error: Encountered unknown instruction `%c`\n",c);
}
}
Answer: Use NULL for null pointers
NULL conveys your intention to use a pointer better than 0:
if (file == NULL) { ... }
As a bonus, in C the macro NULL typically expands to something like (void*)0; if you have warnings for potentially unsafe type conversions enabled (-Wconversion for GCC), the compiler will notify you, if you try to assign 0 to a pointer or NULL to an integer, which helps to find potential errors.
Use puts when you don't use string formatting
printf("Error: Could not open source file\n");
could just as well be
puts("Error: Could not open source file"); | {
"domain": "codereview.stackexchange",
"id": 45516,
"lm_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, interpreter, brainfuck",
"url": null
} |
c, interpreter, brainfuck
could just as well be
puts("Error: Could not open source file");
While printf is great for formatted output, the look for formatting specifiers carries a computational overhead that puts doesn't have. Some compilers (like GCC) will perform that optimization automatically for you, if you use a format string literal without format specifiers.
Checking whether a characters is in a set of characters
In isInstruction(char), instead of using a series of disjoint (joint with the || operator) equality comparisons, you could much better express your intent and the source character set with strchr:
return strchr("+-><[].,", c) != NULL;
A possible improvements might be:
const static char brainfuck_alphabet[] = {'+', '-', '>', '<', '[', ']', '.', ','};
return memchr(brainfuck_alphabet, c, sizeof(brainfuck_alphabet));
The improvements lies in the fact that the algorithm of memchr can make an assumption about the size of the memory region to check while strchr cannot. This could lead to a performance improvement.
Use bool for boolean values
The header <stdbool.h> declares boolean-like types. You can use them to express your intention for a boolean return value of isInstruction():
bool isInstruction(char c) { ... }
Don't repeat yourself
While you generally did will to adhere to that principle, I want to point out one small spot that could use improvement:
printf("Error: cannot read more than 30000 instructions\n");
could be
printf("Error: cannot read more than %d instructions\n", MEMSIZE); | {
"domain": "codereview.stackexchange",
"id": 45516,
"lm_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, interpreter, brainfuck",
"url": null
} |
c, interpreter, brainfuck
could be
printf("Error: cannot read more than %d instructions\n", MEMSIZE);
That way the error message would reflect the actual buffer size in case MEMSIZE was redefined. Since the argument list of printf is variadic and doesn't carry type information, it would be better yet to not make assumptions on the width of the integer type of MEMSIZE. What if someone defined MEMSIZE to be larger than MAX_INT? The best course of action would be to force MEMSIZE into the type size_t (more about that later).
printf("Error: cannot read more than %zu instructions\n", (size_t)(MEMSIZE));
Data types
You only ever store chars in instructions, so its type could just as well be:
char instructions[…];
On all 32- and 64-bit platforms you just saved 3*MEMSIZE bytes (which you could use to increase MEMSIZE again if that is a concern).
memptr, insptr and i are indexes of plain arrays. Therefore they should have type size_t, which is the type meant to reflect the size or position of things in memory.
Make the code flow of branches based on mutually exclusive conditions mutually exclusive
In the above code the conditions c == '[' and c == ']' cannot both be true since c isn't altered between them. To make this obvious to the reader and the compiler (though a good one should find that optimization itself), you should use mutually exclusive if … else if … statements:
if (c == '[')
balance++;
else if (c == ']')
balance--;
Exit with an error status in case of an error
Programs may convey information in their exit status. By convention the status 0 means “no error, everything performed according to your instructions”. Every other status value usually refers to an error condition but there is no general convention on what each value means. One attempt to conventionalize them can be found in the sysexits.h header. You could use it like this in your program:
if (file == NULL) {
// ...
return EX_NOINPUT;
} | {
"domain": "codereview.stackexchange",
"id": 45516,
"lm_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, interpreter, brainfuck",
"url": null
} |
c, interpreter, brainfuck
if (balance < 0) {
// ...
return EX_DATAERR;
}
if (c != EOF && i >= MEMSIZE) {
// ...
return EX_SOFTWARE;
}
In a similar fashion you could return an error from runInstruction(), but we already know that we didn't accept any illegal instructions.
Print error messages on stderr
printf and puts write their data to stdout, the standard output stream, but you're also writing program output to stdout via putchar. To avoid mixing program output and error messages, you should write the latter to stderr instead:
fprintf(stderr, ...);
fputs(..., stderr);
Be aware that fputs doesn't append a new-line character like puts.
Print operating system error messages to provide hints to the user
Like many library functions relying on system calls, fopen sets the global errno variable to report the type of error. You can use functions like strerror or perror to decode the value of errno into a human-readable, localized(!) error message:
if (file == NULL) {
perror("Could not open source file");
// ...
}
Respect the principle of locality, avoid global variables
Global variables clutter the name space and make it more difficult to follow the flow of the program. They also prevent a method or set of methods from being reentrant, a property that allows them to be executed concurrently. (This matters not just for multi-threaded programs, but also if you wanted to, say, interpret multiple Brainfuck programs one instructions at a time in a round-robin fashion to see which program terminates first.)
One way to achieve this is to move more data and logic into the method:
int main(int argc, char *argv[])
{
// ...
char instructions[MEMSIZE];
// ...
runInstructions(instructions, i);
return EX_OK;
}
void runInstructions(const char *const instructions, size_t instruction_count)
{
size_t memptr = 0;
size_t insptr = 0;
int memory[MEMSIZE]; | {
"domain": "codereview.stackexchange",
"id": 45516,
"lm_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, interpreter, brainfuck",
"url": null
} |
c, interpreter, brainfuck
while (insptr < instruction_count) {
switch(instructions[insptr]) {
// ...
}
}
}
You could also use an instruction pointer instead of an instruction index:
void runInstructions(const char *const instructions, size_t instruction_count)
{
size_t memptr = 0;
const char *insptr = instructions;
const char *const instructions_end = instructions + instruction_count;
int memory[MEMSIZE];
while (insptr < instructions_end) {
switch(*insptr) {
// ...
case '[':
if (memory[memptr] == 0)
// seek `]` forward
while (*insptr != ']')
insptr++;
break;
case ']':
if (memory[memptr] != 0)
// seek `[` backward
while(*insptr != '[')
insptr--;
break;
// ...
}
}
}
Use library functions where possible
Library functions unburden you from writing your own code. They're (usually) less likely to contain errors than hand-rolled solutions and the library authors may have included arcane, platform-specific performance optimizations in them.
To find the next closing bracket instruction you could write:
case '[':
if (memory[memptr] == 0) {
// seek `]` forward
insptr = memchr(insptr + 1, ']', (size_t)(instructions_end - insptr - 1));
}
break;
To find the last opening bracket you could write:
case ']':
if (memory[memptr] != 0) {
// seek `[` backward
insptr = memrchr(instructions, '[', (size_t)(insptr - instructions - 1));
}
break;
Avoid undefined behaviour | {
"domain": "codereview.stackexchange",
"id": 45516,
"lm_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, interpreter, brainfuck",
"url": null
} |
c, interpreter, brainfuck
Avoid undefined behaviour
You can't be sure that argv[1] is defined. If it isn't its value may have NULL or garbage content. Check the value of argc first and print an appropriate error message if it's too small:
if (argc < 2) {
fputs("Error: No source file specified.\n", stderr);
return EX_USAGE;
}
If the Brainfuck program happens to have a branch depth greater than INT_MAX, the balance variable would overflow. It typically overflows to the value -1, which would be caught with a subsequent balance < 0 check, but in C signed integer overflow results in undefined behaviour. That means the compiler may assume that overflow never happens and optimize the negative balance check to always be false, which would leave your program in a weird state.
If you decide to care about that (INT_MAX+1 is 2^31 which would require a program of at least 2 GiB, all [, to trigger the bug on modern architectures after all), there are basically two approaches:
Use ssize_t instead of int. ssize_t covers a branching depth of almost (half) as many levels as the address space has bytes. It's quasi-impossible to generate and load a program of that size into the memory of your interpreter anyway, so you could consider your bases covered.
Check for overflow before increasing balance:
if (c == '[') {
if (balance == INT_MAX) {
fprintf(stderr, "Error: Cannot handle branches deeper than %d levels.\n", INT_MAX);
return EX_DATAERR;
}
balance++;
}
Provide some debugging info to the programmer using your interpreter
It might be helpful for the user to know where in the program a parser error occurred, so you should keep track of the amount of bytes read so far:
size_t i = 0;
while (i < MEMSIZE && (c = fgetc(file)) != EOF) {
read++;
if(isInstruction(c)) { ... }
} | {
"domain": "codereview.stackexchange",
"id": 45516,
"lm_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, interpreter, brainfuck",
"url": null
} |
c, interpreter, brainfuck
You can now report that value in parser error messages like so:
fprintf(stderr, "Error:%zu: Cannot handle branches deeper than %d levels.\n", read, INT_MAX);
fprintf(stderr, "Error:%zu: Encountered `]` before matching `[`\n", read);
fprintf(stderr, "Error:%zu: cannot read more than %zu instructions\n", (size_t)(MEMSIZE), read + 1); | {
"domain": "codereview.stackexchange",
"id": 45516,
"lm_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, interpreter, brainfuck",
"url": null
} |
javascript, performance, minecraft
Title: Is it possible to make this Minecraft Bedrock addon script less resource intensive, so that it no longer triggers performance warnings? | {
"domain": "codereview.stackexchange",
"id": 45517,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, performance, minecraft",
"url": null
} |
javascript, performance, minecraft
Question: Following the notice that block events will be removed in a future update, I have been implementing custom block mechanics (such as crop growth and groundcover spreading) using server-side scripts instead. This particular script accompanies a custom block called 'rhizome' which randomly spreads to adjacent blocks, and decays if covered by a solid block, in the same way as vanilla grass/mycelium blocks do.
It works exactly as intended, and doesn't seem to be causing perceptible lag, but occasionally displays warnings of the type
[Scripting][warning]-[Watchdog] 180.289 ms script spike detected in behavior pack 'PackName'
which leads me to believe it may be unreasonably resource intensive. (For comparison, I have implemented multiple other custom features using scripts, including some that run many sequential setblock and fill commands, and have never gotten this kind of warning before.)
The problem seems to be the nested for loops to check for all blocks of a certain type within 16 blocks of the player: reducing the radius from 20 down to the current 16 blocks decreased the number of milliseconds in the warning from ~340 to ~180, indicating that this is indeed the bottleneck.
It doesn't seem like there is a built-in API method for getting all blocks of a certain type within an area, like there is for entities (with dimension.getEntities()). No such method is listed in the dimension documentation. So, I'm not sure that there's an alternative to using nested loops like this, but would like to know if there are any performance improvements possible without decreasing the radius even further.
While 180 milliseconds doesn't seem like much of an issue, I have only tested my addon in singleplayer, and anticipate it could be a much larger problem on a multiplayer server where allPlayers.length > 1. I would like the addon to be compatible with multiplayer as well as singleplayer worlds.
import { world, system } from "@minecraft/server" | {
"domain": "codereview.stackexchange",
"id": 45517,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, performance, minecraft",
"url": null
} |
javascript, performance, minecraft
const worldHeightLimit = 320;
const worldDepthLimit = -64; | {
"domain": "codereview.stackexchange",
"id": 45517,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, performance, minecraft",
"url": null
} |
javascript, performance, minecraft
/* Within 16 blocks of a player, check for rhizome spreading to adjacent end stone blocks, or decaying if there is a solid block directly on top of it */
function processRhizome(player) {
var centerX = player.location.x;
var centerY = player.location.y;
var centerZ = player.location.z;
var dim = player.dimension;
var rB = []; // Will store all rhizome blocks
var block;
for (var y = -16; y <= 16; y++) {
// If layer is below bottom bedrock level, skip to next layer
if ((centerY + y) < worldDepthLimit) {
continue;
} else if ((centerY + y) > worldHeightLimit) { // If layer is above height limit, exit loop
break;
} else {
for (var x = -16; x <= 16; x++) {
for (var z = -16; z <= 16; z++) {
block = dim.getBlock({x: centerX + x, y: centerY + y, z: centerZ + z});
if (block.typeId === "end:rhizome") {
rB.push(block);
}
}
}
}
}
/* If a rhizome block has adjacent end stone block neighbors (which do not have a solid block directly above them), generate a random number to test whether the rhizome should spread.
If yes, then choose an end stone block from among the neighboring blocks at random and convert it to another rhizome block.
If the rhizome block has a solid block directly above it, generate a different random number to test whether the rhizome block should decay into end stone. */
var b;
for (var i = 0; i < rB.length; i++) {
b = rB[i];
// Decay chance = 25% per random tick
if (!b.above(1).isAir && !b.above(1).isLiquid && (Math.random() < 0.25)) {
(async () => {
await dim.runCommandAsync("setblock " + b.x + " " + b.y + " " + b.z + " minecraft:end_stone replace");
})(); | {
"domain": "codereview.stackexchange",
"id": 45517,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, performance, minecraft",
"url": null
} |
javascript, performance, minecraft
})();
} else if (Math.random() < 0.05) { // Spread chance = 5% per random tick
var neighbors = [];
for (var y = -1; y <= 1; y++) {
if ((b.y + y) < worldDepthLimit) {
continue;
} else if ((b.y + y) > worldHeightLimit) {
break;
} else {
for (var x = -1; x <= 1; x++) {
for (var z = -1; z <= 1; z++) {
block = dim.getBlock({x: b.x + x, y: b.y + y, z: b.z + z});
// Do not add block to neighbors array if it is directly under a solid block, or if it is directly above the current rhizome block
if (block.typeId === "minecraft:end_stone" && (block.above(1).isAir || block.above(1).isLiquid) && ([x, y, z].toString() !== "0,1,0")) {
neighbors.push(block);
}
}
}
}
}
if (neighbors.length > 0) {
var spreadToBlock = neighbors[Math.floor(Math.random()*neighbors.length)];
(async () => {
await dim.runCommandAsync("setblock " + spreadToBlock.x + " " + spreadToBlock.y + " " + spreadToBlock.z + " end:rhizome replace");
})();
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45517,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, performance, minecraft",
"url": null
} |
javascript, performance, minecraft
function doRandomTickEventsForEachPlayer() {
const allPlayers = world.getAllPlayers();
for (var p = 0; p < allPlayers.length; p++) {
processRhizome(allPlayers[p]);
}
var nextInterval = 60 + Math.round(Math.random()*40); // Between 3 and 5 seconds
system.runTimeout(doRandomTickEventsForEachPlayer, nextInterval);
}
doRandomTickEventsForEachPlayer();
Answer: While you could go about optimizing the detection of rhizome blocks using deltas, caching, and all sorts of smart heuristics, there is also a simpler optimization available that utilizes the probabilistic nature of your actions.
Currently, you check every block to test if its rhizome, and then if it is you still ignore its decay 75% of the time and its spreading 95% of the time. What would be better would be to only check 25% of the blocks for rhizome, and decay these (if applicable) 100% of the time (similarly, check 5% of the blocks for rhizome to spread).
This alone is a ~4x speedup, but you could also reduce the lag spikes by smoothing out your random ticks using a similar trick. You could check half as many blocks for decay, twice as often, resulting in smaller lag spikes (or any fraction you want). This of course won't improve your overall efficiency, it will just make the server run smoother.
In reality, you're probably best off merging these improvements with some of the optimizations shared by J_H, so you get the free 4x speedup on top of some heuristics to generally avoid wasting time searching non-rhizome blocks. | {
"domain": "codereview.stackexchange",
"id": 45517,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, performance, minecraft",
"url": null
} |
java, beginner, object-oriented, game, 2048
Title: 2048 game in Java
Question: I am a beginner learning Java, and I coded a command line version of the game 2048 for practice. Any feedback, especially regarding best practices, object-oriented principles, and tidying up the code logic, is appreciated.
import java.util.Scanner;
class Cell {
int value = 0;
boolean hasMerged = false;
}
class Game {
final int BOARD_SIZE = 4;
Cell[][] cells;
void create() {
cells = new Cell[BOARD_SIZE][BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
cells[i][j] = new Cell();
cells[i][j].value = 0;
}
}
}
int rowStart = 0;
int columnStart = 0;
int rowStep = 0;
int columnStep = 0;
int nextRow = 0;
int nextColumn = 0;
//to be used for move() and isLegal()
void setDirection (char direction) {
switch (direction) {
case 'W':
rowStart = 1;
columnStart = 0;
rowStep = 1;
columnStep = 1;
nextRow = -1;
nextColumn = 0;
break;
case 'A':
rowStart = 0;
columnStart = 1;
rowStep = 1;
columnStep = 1;
nextRow = 0;
nextColumn = -1;
break;
case 'S':
rowStart = 2;
columnStart = 0;
rowStep = -1;
columnStep = 1;
nextRow = 1;
nextColumn = 0;
break;
case 'D':
rowStart = 0;
columnStart = 2;
rowStep = 1;
columnStep = -1;
nextRow = 0;
nextColumn = 1;
break;
}
} | {
"domain": "codereview.stackexchange",
"id": 45518,
"lm_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, game, 2048",
"url": null
} |
java, beginner, object-oriented, game, 2048
void move() {
boolean changed = true;
while (changed) {
changed = false;
for (int i = rowStart; i >= 0 && i < BOARD_SIZE; i += rowStep) {
for (int j = columnStart; j >= 0 && j < BOARD_SIZE; j += columnStep) {
if (cells[i][j].value != 0 && cells[i + nextRow][j + nextColumn].value == 0) {
changed = true;
cells[i + nextRow][j + nextColumn].value = cells[i][j].value;
cells[i + nextRow][j + nextColumn].hasMerged = cells[i][j].hasMerged;
cells[i][j].value = 0;
cells[i][j].hasMerged = false;
}
else if (cells[i][j].value != 0 && cells[i + nextRow][j + nextColumn].value == cells[i][j].value && !(cells[i][j].hasMerged || cells[i + nextRow][j + nextColumn].hasMerged)) {
changed = true;
cells[i + nextRow][j + nextColumn].value *= 2;
cells[i + nextRow][j + nextColumn].hasMerged = true;
cells[i][j].value = 0;
cells[i][j].hasMerged = false;
}
}
}
}
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
cells[i][j].hasMerged = false;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45518,
"lm_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, game, 2048",
"url": null
} |
java, beginner, object-oriented, game, 2048
void generateRandomCell() {
int count = 0;
int[][] empty = new int[16][2];
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (cells[i][j].value == 0) {
empty[count][0] = i;
empty[count][1] = j;
count += 1;
}
}
}
int randomIndex = (int) (Math.random() * count);
if (Math.random() < 0.9) {
cells[empty[randomIndex][0]][empty[randomIndex][1]].value = 2;
}
else {
cells[empty[randomIndex][0]][empty[randomIndex][1]].value = 4;
}
}
boolean isLegal() {
for (int i = rowStart; i >= 0 && i < BOARD_SIZE; i += rowStep) {
for (int j = columnStart; j >= 0 && j < BOARD_SIZE; j += columnStep) {
if (cells[i][j].value != 0 && (cells[i + nextRow][j + nextColumn].value == 0 || cells[i][j].value == cells[i + nextRow][j + nextColumn].value)) {
return true;
}
}
}
return false;
}
boolean isOver() {
char[] directions = {'W', 'A', 'S', 'D'};
for (int i = 0; i < BOARD_SIZE; i++) {
setDirection(directions[i]);
if (isLegal()) {
return false;
}
}
return true;
} | {
"domain": "codereview.stackexchange",
"id": 45518,
"lm_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, game, 2048",
"url": null
} |
java, beginner, object-oriented, game, 2048
void printBoard() {
int width = 5;
int space;
System.out.print("\n");
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
space = width - String.valueOf(cells[i][j].value).length();
if (cells[i][j].value != 0) {
System.out.print(cells[i][j].value);
}
else
{
System.out.print("_");
}
System.out.print(" ".repeat(space));
}
System.out.print("\n\n");
}
System.out.println("");
}
}
class Game2048 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Game game = new Game();
game.create();
game.generateRandomCell();
System.out.print("\n\nHello!\nEnter W, A, S, D to move, and Q to quit.\n\n");
while (!game.isOver()) {
game.printBoard();
System.out.println("Enter your move: ");
String userInput = scanner.nextLine();
if (userInput.length() != 1) {
System.out.print("\nInvalid!\n");
continue;
}
char userMove = userInput.charAt(0);
if (userMove == 'Q') {
System.exit(0);
}
else if (userMove != 'W' && userMove != 'A' && userMove != 'S' && userMove != 'D') {
System.out.print("\nInvalid!\n");
continue;
}
game.setDirection(userMove);
if (game.isLegal()) {
game.move();
game.generateRandomCell();
}
else {
System.out.print("\nIllegal!\n");
}
}
System.out.println("Game over!");
}
}
Answer: UX | {
"domain": "codereview.stackexchange",
"id": 45518,
"lm_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, game, 2048",
"url": null
} |
java, beginner, object-oriented, game, 2048
System.out.println("Game over!");
}
}
Answer: UX
it would be more convenient if both lower and upper case letters were accepted. This can be achieved easily using Character.toUpperCase(...) method when initializing userMove in main.
it's quite annoying to have to press Enter each time, since every input is always just 1 char anyway. I've just learnt, that there's no portable way to fix it without an additional lib. For mac & linux you can follow this 2 line trick and then use java.io.Reader obtained with System.console().reader(), but if you want it to work on M$ Windows also, then you need to use for example jLine or jCurses.
it would be even better if arrow keys were also accepted (in addition to w, a, s, d).
Organizing code dealing with UI
Whenever you are developing an interactive program that has some user-interface (regardless if it's a text-terminal UI, or some graphic UI like desktop Swing, mobile Android or web GWT), it is a good habit to clearly divide your code into the following parts:
a part that deals solely with core logic of a given issue, usually called a Model or an Engine, in case of "2048" game that would be a class holding the state of the board with methods to obtain such state and to make a move.
a part that deals solely with a given UI, usually divided into Screens or Views or Submenus, in case of "2048" game, there's only 1 such View displaying the board and capturing user input on it.
finally some code that glues the previous 2 parts together, depending on its design called a Presenter or a Controller or a ViewModel or other... | {
"domain": "codereview.stackexchange",
"id": 45518,
"lm_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, game, 2048",
"url": null
} |
java, beginner, object-oriented, game, 2048
Model and View parts usually have abstract interfaces for the gluing part to deal with them, so in case of "2048" game they could be looking for example something like this:
public interface Game2048Model {
GameState performAction(Action action) throws IllegalMoveException;
GameState getGameState(); // for UI redrawing and to see the initial board
class GameState { public State state; public int[][] board; }
enum State {LOST, WON, ONGOING}
enum Action {LEFT, RIGHT, UP, DOWN, RESTART}
class IllegalMoveException extends Exception {}
}
public interface Game2048View {
void updateBoardDisplay(int[][] newBoardState);
void updateStateDisplay(Game2048Model.State newState);
void signalIllegalMove();
void registerUserInputListener(Consumer<UserInput> listener);
enum UserInput {LEFT, RIGHT, UP, DOWN, RESTART, QUIT} // Action + QUIT
// registerUserInputListener(listener) is the way it is, because most
// GUI frameworks are event-driven. If it's confusing at this stage,
// in case of text-UI only, you can replace it with
// UserInput getUserInput();
}
Among several others, such approach has the following benefits: | {
"domain": "codereview.stackexchange",
"id": 45518,
"lm_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, game, 2048",
"url": null
} |
java, beginner, object-oriented, game, 2048
Among several others, such approach has the following benefits:
for anyone looking at these interfaces, it will be immediately clear what a user can do during the game and roughly how the UI may look like (regardless again if it's a text or some GUI).
abstract UserInput enum forces you to put details of input validation/recognition into the UI layer (checking characters from keyboard for text-UI, checking which button was tapped for mobile and so on), making the higher-level glue code easier to read and independent from the UI type.
if you decide to provide another type of UI apart from the current text one, you can reuse your Model (and possibly the glue part if designed appropriately) and just provide a new implementation of Game2048View (using Swing/Android/GWT widgets). Also any changes in layout that you may want to do later, will not affect the other 2 parts.
you can easily write tests that concern only the Model right away, you can write tests that concern only the gluing part by providing mock implementations for both Game2048Model and Game2048View (for example using EasyMock or Mockito).
There are a few "well-established" design patterns related to this, 2 of the simplest and most popular are model-view-presenter and model-view-controller, which in case of an app with a single screen will result in roughly similar code.
Game class
create()
This code should be moved to constructor basically.
generateRandomCell()
use BOARD_SIZE*BOARD_SIZE instead of 16.
using the same random value both for choosing the cell and deciding whether put there 2 or 4 determines which cells may get 2 and which 4 when chosen.
instead of (int) (Math.random() * count) it's probably better to do have an instance of Random and do random.nextInt(count).
isOver() | {
"domain": "codereview.stackexchange",
"id": 45518,
"lm_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, game, 2048",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.