text stringlengths 1 2.12k | source dict |
|---|---|
c++, c++11, design-patterns, template, decorator-pattern
// note: not virtual
void save (std::ostream& os) const
{
os << get_tag() << '\n';
saveParticular(os);
}
// need this, too; must be virtual but doesn't need to be public.
virtual std::string get_tag() const { return "Person"; }
protected:
// note: virtual, and protected
virtual void saveParticular (std::ostream& os) const { os << name << '\n'; }
};
class Worker : public Person {
int ID;
public:
Worker (const std::string& name, int i) : Person(name), ID(i) { }
std::string get_tag() const override { return "Worker"; }
protected:
void saveParticular (std::ostream& os) const override
{
Person::saveParticular(os);
os << ID << '\n';
}
};
class Teacher : public Worker {
std::string school;
public:
Teacher (const std::string& name, int ID, const std::string& s) : Worker(name, ID), school(s) { }
std::string get_tag() const override { return "Teacher"; }
protected:
void saveParticular (std::ostream& os) const override
{
Teacher::saveParticular(os);
os << school << '\n';
}
};
Compared to your design, there are no drawbacks. Any drawbacks already have parallels:
If you forget to implement get_tag(), then you’ll get the parent’s tag. Same thing would happen if you forget to add the static tag member in your version.
If you forget to implement saveParticular(), then you’ll get the parent’s behaviour. Same thing would happen if you forgot to implement save() with your version.
If you do a sloppy copy-paste and forget to change the parent class name in saveParticular(), you’ll get the parent’s behaviour again. Same thing would happen if you do a sloppy copy-paste and forget to add the current class name to the makeSaveDecorator() list.) | {
"domain": "codereview.stackexchange",
"id": 43071,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, design-patterns, template, decorator-pattern",
"url": null
} |
c++, c++11, design-patterns, template, decorator-pattern
The benefits compared to your design, however, are numerous.
First: simplicity. You won’t go cross-eyed trying to mentally parse recursive parameter pack expansions, or aliases-of-pointers-to-member-functions. I shudder to think of the error messages you might get if you mistype something somewhere in your version.
Second: robustness. The big problem with your design—the thing that would make me veto ever using it in any of my projects—is the need to list the inheritance chain:
makeSaveDecorator<Teacher, Worker, Person>()(...);
The number of ways this can break silently is impressive. You could misorder the classes:
makeSaveDecorator<Worker, Teacher, Person>()(...);
You could forget a step in the hierarchy:
makeSaveDecorator<Teacher, Person>()(...);
You could insert random classes into the mix for giggles:
makeSaveDecorator<Teacher, Ninja, Person>()(...); | {
"domain": "codereview.stackexchange",
"id": 43071,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, design-patterns, template, decorator-pattern",
"url": null
} |
c++, c++11, design-patterns, template, decorator-pattern
Or—and this is the worst part, because it means spooky-action-at-a-distance behavioural changes—if anyone ever refactored the class hierarchy, the list may no longer reflect the actual hierarchy. Things would continue to “work”, even though it is no longer correct behaviour.
Third: efficiency. For build efficiency, it’s a no-brainer. There are exactly 3 class instantiations in my version. Do you even know how many there are in yours? I can’t be bothered to even try to count. For run-time efficiency, you might assume the fact that my version involves two dynamic dispatches (one for saveParticular(), plus one for get_tag()) means it’s the obvious loser… but yours has a virtual call… multiple pointer calls (to func in SaveDecorator, recursively), recursive calls (so more stack space is needed), and much, much more. (Plus, because my design is so simple, it will be very easy for the compiler to de-virtualize whenever possible.)
(Note that if you moved beyond C++11… which you should; that version is over a decade old… you could probably take advantage of C++17’s fold expressions. Those would probably simplify things enormously, and eliminate the need for recursive template expansions. With that, the build-time efficiency of your version might get much closer to mine… but still won’t be able to match it.)
As for the generic version… if something isn’t a good solution when done specifically, it certainly isn’t going to be a good solution when implemented generically.
For me, the bottom line is that the NVI idiom solves the main problem you are trying to solve—making sure that tag line is always printed first—and it does so with orders of magnitude more simplicity. The fact that I wouldn’t have to manually list the inheritance chain seals the deal for me. The improved compile times, and better run-time performance are just icing on the cake. | {
"domain": "codereview.stackexchange",
"id": 43071,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, design-patterns, template, decorator-pattern",
"url": null
} |
c++, c++11, design-patterns, template, decorator-pattern
But like I said in the beginning, you haven’t given any real context. Your solution may be the most brilliant solution ultimately possible… or it may be the most ridiculous code ever written. It is impossible to know without knowing what the real intended usage is.
However, if the intended usage really is just to write a standard preamble before polymorphic, class-specific output… then NVI is probably the way to go. | {
"domain": "codereview.stackexchange",
"id": 43071,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, design-patterns, template, decorator-pattern",
"url": null
} |
performance, algorithm, c, strings
Title: Replace string with another string in C
Question: I have written a program that replaces a given c-string with another c-string. My code works well with small files but takes too much time while working with large files (50 Megabytes and larger).
Also, there's a fast_strncat() function which is much much faster than strcat() function.
Please don't get offended for replacing benzene with phenol, it's just a test case.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fast_strncat(char *dest, const char *src, size_t *size)
{
if (dest && src && size)
while ((dest[*size] = *src++))
*size += 1;
}
void strreplace(char **str, const char *old, const char *new_)
{
size_t i, count_old = 0, len_o = strlen(old), len_n = strlen(new_);
const char *temp = (const char *)(*str);
for (i = 0; temp[i] != '\0'; ++i)
{
if (strstr((const char *)&temp[i], old) == &temp[i])
{
count_old++;
i += len_o - 1;
}
}
char *buff = calloc((i + count_old * (len_n - len_o) + 1), sizeof(char));
if (!buff)
{
perror("bad allocation\n");
exit(EXIT_FAILURE);
}
i = 0;
while (*temp)
{
if (strstr(temp, old) == temp)
{
size_t x = 0;
fast_strncat(&buff[i], new_, &x);
i += len_n;
temp += len_o;
}
else
buff[i++] = *temp++;
}
free(*str);
*str = calloc(i + 1, sizeof(char));
if (!(*str))
{
perror("bad allocation\n");
exit(EXIT_FAILURE);
}
i = 0;
fast_strncat(*str, (const char *)buff, &i);
free(buff);
}
int main(void)
{
FILE *fptr = fopen("./benzene.txt", "rb");
if (fptr)
{
fseek(fptr, 0, SEEK_END);
size_t len = ftell(fptr);
fseek(fptr, 0, SEEK_SET); | {
"domain": "codereview.stackexchange",
"id": 43072,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, c, strings",
"url": null
} |
performance, algorithm, c, strings
char *data = calloc(len + 1, sizeof(char));
if (!data)
{
perror("bad allocation\n");
return EXIT_FAILURE;
}
fread(data, sizeof(char), len, fptr);
fclose(fptr);
strreplace(&data, "Benzene", "phenol");
fptr = fopen("./phenol.txt", "wb");
if (!fptr)
{
perror("file not saved.\n");
free(data);
return EXIT_FAILURE;
}
fwrite(data, sizeof(char), strlen((const char *)data), fptr);
fclose(fptr);
free(data);
return EXIT_SUCCESS;
}
perror("file not opened.\n");
return EXIT_FAILURE;
}
I compiled the above program using the command:
gcc -Wall -Wextra main.c -o main
I ran the program for a 50 Megabytes file on zsh on Intel i5-7200U:
./main 29.09s user 0.14s system 97% cpu 30.033 total
Answer: The fast_strncat() is a good idea. The actual copying isn't efficient (though a good optimiser might recognise the pattern), but letting the caller know how much was copied helps avoid a program being Schlemiel the painter.
I don't like the name; it sounds too much like strncat(), which has very different behaviour. Perhaps len_strcpy() or something better conveys the functionality?
And instead of passing a pointer to result, it's generally better to return the result (either as a number of characters as here - though size_t is probably a better choice of type - or perhaps as a pointer to the new string end).
It's possible we don't need it though - see our use of memcpy in the next section.
The way we're using strstr() is very inefficient. We're traversing input a character at a time, repeating the same search until our position reaches the search result. Imagine this in human terms:
"Run down the road to the first red house, and tell me where it is."
It's not this one, so walk ahead to the next house.
"Run down the road to the first red house, and tell me where it is." | {
"domain": "codereview.stackexchange",
"id": 43072,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, c, strings",
"url": null
} |
performance, algorithm, c, strings
Doesn't this sound a lot like Shlemiel's algorithm, that we worked so hard to avoid earlier?
We could consider using strncmp() instead in the same loop, but we can do better. Once we have the result from strstr(), we know there are no matches up to that result. So we can measure the length change much more simply:
size_t count_old = 0;
for (const char *p = *str; (p = strstr(p, old)); ++p) {
++count_old;
}
And we can copy each chunk in one go:
while (*temp) {
const char *next_match = strstr(temp, old);
if (next_match) {
size_t match_len = next_match - temp;
memcpy(buff+i, temp, match_len);
i += match_len;
temp += match_len;
memcpy(buff+i, new, len_n);
i += len_n;
temp += len_o;
} else {
/* no match - copy the remainder */
strcpy(buff+i, temp);
} | {
"domain": "codereview.stackexchange",
"id": 43072,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, c, strings",
"url": null
} |
performance, algorithm, c, strings
The code is quite limited because it will only work with seekable files, it has to read the entire file into memory, and it needs space for the entire output file in memory before it starts writing.
We can make it more efficient (and avoid the need to seek) by reading a buffer of characters, replacing matches within the buffer, and then writing out the buffer, before repeating. There's a small complication that we need to deal with matches that might straddle two reads - we need to write out all but len_o - 1 characters, and then move those last few to the front of the buffer, before reading the next characters after them. If we know we're working with streams, then there's no need to write to a new string array - just fwrite() each chunk as we get there.
On the other hand, if we want a general function to work on in-memory strings, we can avoid needing separate input and output arrays. It's possible to perform replacement in situ, provided our buffer is big enough to hold the bigger of input and output. The code needs to have two branches - working from the end if the replacement string is bigger than the match string, or from the beginning otherwise. I'd definitely recommend using unit tests to guide implementation if you choose to attempt such in-place substitution.
We have no error checking for the fwrite() and fclose() in main(). These functions can and do fail (e.g. disk quota reached), and we mustn't mislead the user that we succeeded if we haven't written all the output.
Minor things: | {
"domain": "codereview.stackexchange",
"id": 43072,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, c, strings",
"url": null
} |
performance, algorithm, c, strings
Minor things:
We don't need to include a newline at the end of the message we give to perror(). That function will append : and error description, then a newline of its own.
temp isn't a great name for a variable. It only tells us that it's short-lived, but doesn't indicate what it's for.
There are many redundant casts - I don't think any of the casts here are necessary (Any Type* converts automatically to Type const* - a cast just costs the reader's time, and makes it harder to spot the true problems).
The if (ptr) test leaves us holding state in our heads for half a screenful - it's easier to read if we test if (!ptr), which has a much shorter block (and also exits the function).
sizeof (char) is always 1 (because sizeof works in units of char), so those expressions can be simplified. | {
"domain": "codereview.stackexchange",
"id": 43072,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, c, strings",
"url": null
} |
python, python-3.x, sorting
Title: Sort a Python list of strings where each item is made with letters and numbers
Question: I have a set of strings that all consist of one or two letters followed by one or two digits. I need to sort by the letters then by the numeric value of the digits.
My solution is quite inefficient in terms of performance; how is it possible to improve it?
import re
unsorted_list = ['A1', 'A11', 'A12', 'A2', 'A3', 'B1', 'B12', 'EC1', 'EC21']
expected_result = ['A1', 'A2', 'A3', 'A11', 'A12', 'B1', 'B12', 'EC1', 'EC21']
unsorted_dict = {}
for item in unsorted_list:
match = re.match(r"([A-Z]+)([0-9]+)", item, re.I)
letters_in_item = match.groups()[0]
numbers_in_item = int(match.groups()[1])
if letters_in_item in unsorted_dict:
unsorted_dict[letters_in_item].append(numbers_in_item)
else:
unsorted_dict[letters_in_item] = [numbers_in_item]
sorted_dict = dict(sorted(unsorted_dict.items()))
result = []
for key in sorted_dict:
for value in sorted(sorted_dict[key]):
result.append(key + str(value))
assert result == expected_result
Answer: Because we need to sort the data, the best we can do in terms of performance is to try and settle for \$O(N \log N\$).
What you have here is called natural sort. Apart from some libraries that you might use (e.g. natsort - which also handles more complex cases), I'm going to try to cleanup a bit your existing implementation.
NOTES:
Using a dictionary doesn't add any value or improvements to your code / algorithm but it rather adds overhead. As a rule of thumb, use dictionaries when you need to associate values with keys, so you can look them up efficiently (by key) later on;
You don't need to use sorted multiple times;
You could separate your code logic into different functions (benefits: easier to read, test, reuse, etc);
Type-hints are always welcome;
First, let's take out the regex you have:
COMPILED = re.compile(r"([A-Z]+)([0-9]+)", re.I) | {
"domain": "codereview.stackexchange",
"id": 43073,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, sorting",
"url": null
} |
python, python-3.x, sorting
First, let's take out the regex you have:
COMPILED = re.compile(r"([A-Z]+)([0-9]+)", re.I)
For me, the biggest benefit to using re.compile() is being able to separate definition of the regex from its use. It might also offer some speed improvements but those cases are quire rare.
Now, what do we need to do?
Split letters group from digits group (regex will take care of this);
Sort by letters group then by digits group;
Normalize data;
From what I can see you already know about sorted() but didn't use it to its fullest. Let's try and change that.
Having the first two points done (split + sort) is as simple as:
def nat_sort(items):
# for me it feels more natural to use re.findall() instead of
# re.match + re.group
items_groups = [
COMPILED.findall(item)[0]
for item in items
]
return sorted(items_groups, key=lambda group: (group[0], int(group[1])))
In the above, items_groups is going to look like this:
[('A', '1'), ('A', '11'), ('A', '12'), ('A', '2'), ('A', '3'), ('B', '1'), ('B', '12'), ('EC', '1'), ('EC', '21')]
The next line is just going to sort our items by the first group (letters), then by the last one (digits), giving us the following:
[('A', '1'), ('A', '2'), ('A', '3'), ('A', '11'), ('A', '12'), ('B', '1'), ('B', '12'), ('EC', '1'), ('EC', '21')]
items_groups could also be sorted in-place to avoid creating an extra list:
def nat_sort(items):
items_groups = [
COMPILED.findall(item)[0]
for item in items
]
items_groups.sort(key=lambda group: (group[0], int(group[1])))
return items_groups
The remaining thing we have to do is to transform the data we have into our desired format:
def main():
items = ['A1', 'A11', 'A12', 'A2', 'A3', 'B1', 'B12', 'EC1', 'EC21']
return [''.join(item) for item in nat_sort(items)]
Full code:
import re
COMPILED = re.compile(r"([A-Z]+)([0-9]+)", re.I) | {
"domain": "codereview.stackexchange",
"id": 43073,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, sorting",
"url": null
} |
python, python-3.x, sorting
Full code:
import re
COMPILED = re.compile(r"([A-Z]+)([0-9]+)", re.I)
def nat_sort(items):
items_groups = [
COMPILED.findall(item)[0]
for item in items
]
items_groups.sort(key=lambda group: (group[0], int(group[1])))
return items_groups
def main():
items = ['A1', 'A11', 'A12', 'A2', 'A3', 'B1', 'B12', 'EC1', 'EC21']
return [''.join(item) for item in nat_sort(items)]
if __name__ == '__main__':
print(main())
Or as recommended in the comments, have everything contained within the same function (BONUS: type-hints included):
import re
from typing import List
COMPILED = re.compile(r"([A-Z]+)([0-9]+)", re.I)
def nat_sort(items: List[str]) -> List[str]:
items_groups = [
COMPILED.findall(item)[0]
for item in items
]
items_groups.sort(key=lambda group: (group[0], int(group[1])))
return [''.join(item) for item in items_groups]
def main() -> List[str]:
items = ['A1', 'A11', 'A12', 'A2', 'A3', 'B1', 'B12', 'EC1', 'EC21']
return nat_sort(items)
if __name__ == '__main__':
print(main())
Not sure if this comes with an improvement in terms of complexity (my complexity analysis is quite rusty) but my suggestion has \$O(N \log N\$) time complexity and \$O(N)\$ space complexity.
There are probably better, easier-to-read, more intuitive ways of doing this but this felt natural to me. | {
"domain": "codereview.stackexchange",
"id": 43073,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, sorting",
"url": null
} |
python, django
Title: Email verification resend implementation Django
Question: I'm trying to build an email verification for user signup using CreateView. This view check whether the user is a new or already existing inactive user? and resend verification if the user is inactive.
Here's how I did it(email sending part),
views.py
class SignUpView(CreateView):
""" SignUp view """
form_class = SignUpForm
success_url = reverse_lazy('login')
template_name = 'registration/register.html'
def send_activation_email(self, request, user):
""" sends email confirmation email """
uidb64 = urlsafe_base64_encode(force_bytes(user.pk))
token = token_generator.make_token(user)
domain = get_current_site(request).domain
schema = request.is_secure() and "https" or "http"
link = reverse('user_activation', kwargs={'uidb64': uidb64, 'token': token})
url = '{}://{}{}'.format(schema, domain, link)
payload = {
'receiver': user.email,
'email_body': {
'username': user.username,
'email_body': 'Verify your email to finish signing up for RapidReady',
'link': url,
'link_text': 'Verify Your Email',
'email_reason': "You're receiving this email because you signed up in {}".format(domain),
'site_name': domain
},
'email_subject': 'Verify your Email',
}
Util.send_email(payload)
messages.success(request, 'Please Confirm your email to complete registration.')
def get(self, request, *args, **kwargs):
""" Prevents authenticated user accessing registration path """
if request.user.is_authenticated:
return redirect('home')
return super(SignUpView, self).get(request, *args, **kwargs)
def form_valid(self, form):
""" Handles valid form """
form = self.form_class(self.request.POST) | {
"domain": "codereview.stackexchange",
"id": 43074,
"lm_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, django",
"url": null
} |
python, django
form = self.form_class(self.request.POST)
user = form.save(commit=False)
user.is_active = False
user.save()
self.send_activation_email(self.request, user)
return render(self.request, 'registration/confirm_email.html', {'email': user.email})
def post(self, request, *args, **kwargs):
""" Handles existing inactive user registration attempt """
form = self.form_class(self.request.POST)
if User.objects.filter(email=request.POST['email']).exists():
user = User.objects.get(email=request.POST['email'])
if not user.is_active:
self.send_activation_email(request, user)
return render(self.request, 'registration/confirm_email.html', {'email': user.email})
# if no record found pass to form_valid
return self.form_valid(form)
util.py
class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return text_type(user.is_active) + text_type(user.pk) + text_type(timestamp)
token_generator = TokenGenerator()
class EmailThread(threading.Thread):
def __init__(self, email):
self.email = email
threading.Thread.__init__(self)
def run(self):
self.email.send()
class Util:
@staticmethod
def send_email(data):
msg_plain = render_to_string('email/email_normal_email.txt', data['email_body'])
msg_html = render_to_string('email/email_normal_email.html', data['email_body'])
msg = EmailMultiAlternatives(data['email_subject'], msg_plain, config('EMAIL_HOST_USER'), [data['receiver']])
msg.attach_alternative(msg_html, "text/html")
EmailThread(msg).start() | {
"domain": "codereview.stackexchange",
"id": 43074,
"lm_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, django",
"url": null
} |
python, django
EmailThread(msg).start()
In the above code, I used form_valid() method to handle a new user registration and the post() method to check whether the user is new or already registered inactive user.
If no record found the post() method will call form_valid() method passing the form as an argument(last line in views). And this logic works just fine.
So, my main question is, 'Are there any negative effects due to this implementation?' and any advice(best practices, improvements, etc.) will be greatly appreciated.
Answer: You have a problem in the post() method.
If the user does not exist you return self.form_valid(form), so if a new user in registration form gives a validation error. You will have an error because you called form_valid() but form is not valid.
You can use return super().post(request, *args, **kwargs) instead of return self.form_valid(form). Like this:
def post(self, request, *args, **kwargs):
""" Handles existing inactive user registration attempt """
form = self.form_class(self.request.POST)
if User.objects.filter(email=request.POST['email']).exists():
user = User.objects.get(email=request.POST['email'])
if not user.is_active:
self.send_activation_email(request, user)
return render(self.request, 'registration/confirm_email.html', {'email': user.email})
# if no record found pass to form_valid
return super().post(request, *args, **kwargs) | {
"domain": "codereview.stackexchange",
"id": 43074,
"lm_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, django",
"url": null
} |
performance, algorithm, rust, median
Title: Median cut algorithm
Question: I have implemented a simple version of the median cut algorithm. It takes a vector of Color structs representing pixel in an image. I also use the ColorChanel enum representing RGBA channels.
pub struct Color {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
}
#[derive(Debug)]
pub enum ColorChannel {
R,
G,
B,
A,
}
impl Color {
pub fn channel_val(&self, channel: &ColorChannel) -> u8 {
match channel {
ColorChannel::R => self.r,
ColorChannel::G => self.g,
ColorChannel::B => self.b,
ColorChannel::A => self.a,
}
}
}
impl PartialEq for Color {
fn eq(&self, other: &Self) -> bool {
self.r == other.r && self.g == other.g && self.b == other.b && self.a == other.a
}
}
For each Color/Pixel vector I look for the channel with the highest range:
/// Returns the color channel with the highest range.
/// IMPORTANT: Ignores alpha channel!
///
/// # Arguments
///
/// * `colors` - Color vector from which the highest range is evaluated.
///
fn highest_range_channel(colors: &Vec<Color>) -> Option<ColorChannel> {
if let Some(ranges) = color_ranges(colors) {
let mut highest_range_channel = ColorChannel::R;
let mut highest_value = ranges.r;
if ranges.g > highest_value {
highest_range_channel = ColorChannel::G;
highest_value = ranges.g;
}
if ranges.b > highest_value {
highest_range_channel = ColorChannel::B;
}
return Some(highest_range_channel);
}
None
} | {
"domain": "codereview.stackexchange",
"id": 43075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, rust, median",
"url": null
} |
performance, algorithm, rust, median
return Some(highest_range_channel);
}
None
}
The color ranges are calculated in the according function:
/// Returns the ranges for each color channel
///
/// # Arguments
///
/// * `colors` - Color vector from which the ranges are calculated.
///
/// # Examples
///
/// ```
/// let colors = Vec::<Color>::new();
/// let color_ranges_data = color_ranges(colors);
/// ```
///
fn color_ranges(colors: &Vec<Color>) -> Option<Color> {
if colors.is_empty() {
return None;
}
// Unwrap is ok here, because `max_by_key` only returns `None` for empty vectors
let r_range = colors.iter().max_by_key(|c| c.r).unwrap().r;
let g_range = colors.iter().max_by_key(|c| c.g).unwrap().g;
let b_range = colors.iter().max_by_key(|c| c.b).unwrap().b;
let a_range = colors.iter().max_by_key(|c| c.a).unwrap().a;
Some(Color {
r: r_range,
g: g_range,
b: b_range,
a: a_range,
})
}
After that I calculate the median value for the channel with the highest range. I am doing this by sorting the vector based on the desired channel and finding the value in the "middle" of the vector.
/// Sort a color vector for a specific channel.
///
/// # Arguments
///
/// * `colors` - Color data which will be sorted.
/// * `channel` - Target channel. The sorting is performed based on this value.
///
/// # Examples
///
/// ```
/// let mut colors = Vec::<Color>::new();
/// sort_colors(&mut colors, &ColorChannel::R);
/// ```
///
fn sort_colors(colors: &mut Vec<Color>, channel: &ColorChannel) {
if colors.is_empty() {
return;
}
match channel {
ColorChannel::R => colors.sort_by(|a, b| a.r.cmp(&b.r)),
ColorChannel::G => colors.sort_by(|a, b| a.g.cmp(&b.g)),
ColorChannel::B => colors.sort_by(|a, b| a.b.cmp(&b.b)),
ColorChannel::A => colors.sort_by(|a, b| a.a.cmp(&b.a)),
}
} | {
"domain": "codereview.stackexchange",
"id": 43075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, rust, median",
"url": null
} |
performance, algorithm, rust, median
/// Returns median value for a specific `ColorChannel`.
///
/// # Arguments
///
/// * `colors` - Color vector from which the median value is calculated.
/// * `channel` - Target channel for which the median is calculated.
///
/// # Examples
/// ```
/// let mut colors = Vec::<Color>::new();
/// let mut result = color_median(&mut colors, &ColorChannel::R);
/// ```
///
fn color_median(colors: &mut Vec<Color>, channel: &ColorChannel) -> Option<u8> {
if colors.is_empty() {
return None;
}
sort_colors(colors, channel);
let mid = colors.len() / 2;
if colors.len() % 2 == 0 {
channel_mean(&vec![colors[mid - 1], colors[mid]], channel)
} else {
channel_value_by_index(colors, mid, channel)
}
}
/// Returns a color value based on the provided channel and index parameters.
///
/// # Arguments
///
/// * `colors` - Color vector from which the value is retreived.
/// * `index` - Index of the target color in the vector.
/// * `channel` - Color channel of the searched value.
///
/// # Examples
///
/// ```
/// let mut colors: Vec<Color> = Vec::new();
/// colors.push(Color { r: 100, g: 22, b: 12, a: 0 });
/// assert_eq!(Some(100), channel_value_by_index(&colors, 0, &ColorChannel::R));
/// ```
///
fn channel_value_by_index(colors: &Vec<Color>, index: usize, channel: &ColorChannel) -> Option<u8> {
if colors.is_empty() || index >= colors.len() {
return None;
}
match channel {
ColorChannel::R => Some(colors[index].r),
ColorChannel::G => Some(colors[index].g),
ColorChannel::B => Some(colors[index].b),
ColorChannel::A => Some(colors[index].a),
}
} | {
"domain": "codereview.stackexchange",
"id": 43075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, rust, median",
"url": null
} |
performance, algorithm, rust, median
/// Calculate the mean value for a specific color channel on a vector of `Color`.
///
/// # Arguments
///
/// * `colors` - Color vector from which the mean value is calculated.
/// * `channel` - Target channel for which the mean is calculated.
///
/// # Examples
///
/// ```
/// let mut colors: Vec<Color> = Vec::new();
/// let mut result = channel_mean(&colors, &ColorChannel::R);
/// ```
///
fn channel_mean(colors: &Vec<Color>, channel: &ColorChannel) -> Option<u8> {
let number_colors = colors.len();
if number_colors == 0 {
return None;
}
match channel {
ColorChannel::R => Some((colors.iter().fold(0, |acc: u32, x| x.r as u32 + acc) / number_colors as u32) as u8),
ColorChannel::G => Some((colors.iter().fold(0, |acc: u32, x| x.g as u32 + acc) / number_colors as u32) as u8),
ColorChannel::B => Some((colors.iter().fold(0, |acc: u32, x| x.b as u32 + acc) / number_colors as u32) as u8),
ColorChannel::A => Some((colors.iter().fold(0, |acc: u32, x| x.a as u32 + acc) / number_colors as u32) as u8),
}
}
Now I create two new vectors/buckets with one containing all Colors above the median value and another with Color values below the median. This entire process is implemented in the median_cut function.
/// Performs the median cut on a single vector (bucket) of `Color`.
/// Returns two `color` vectors representing the colors above and colors below median value.
///
/// # Arguments
///
/// * `colors` - `Color` vector on which the median cut is performed.
///
fn median_cut(colors: &mut Vec<Color>) -> (Vec<Color>, Vec<Color>) {
if colors.is_empty() {
return (Vec::<Color>::new(), Vec::<Color>::new());
} | {
"domain": "codereview.stackexchange",
"id": 43075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, rust, median",
"url": null
} |
performance, algorithm, rust, median
if let Some(highest_range_channel) = highest_range_channel(&colors) {
if let Some(median) = color_median(colors, &highest_range_channel) {
let mut above_median = Vec::<Color>::new();
let mut below_median = Vec::<Color>::new();
for color in colors {
if color.channel_val(&highest_range_channel) > median {
above_median.push(*color);
} else {
below_median.push(*color);
}
}
return (above_median, below_median);
}
}
return (Vec::<Color>::new(), Vec::<Color>::new());
}
In order to perform multiple iterations I call the recurse function. It takes a bucket, performs the median_cut on it calculates the mean color for each output bucket and performs the median_cut on the them. The function stops and returns all mean colors when the amount of iterations reaches 0.
pub fn recurse(bucket: &mut Vec<Color>, iter_count: u8) -> Option<Vec<Color>> {
if iter_count < 1 || bucket.is_empty() {
return None;
}
let mut result = Vec::<Color>::new();
let mut new_buckets = median_cut(bucket);
if !new_buckets.0.is_empty() {
if let Some(c_0) = color_mean(&new_buckets.0) {
result.push(c_0);
}
if let Some(new_colors) = recurse(&mut new_buckets.0, iter_count - 1) {
result.append(&mut new_colors.clone());
}
}
if !new_buckets.1.is_empty() {
if let Some(c_1) = color_mean(&new_buckets.1) {
result.push(c_1);
}
if let Some(new_colors) = recurse(&mut new_buckets.1, iter_count - 1) {
result.append(&mut new_colors.clone());
}
}
Some(result)
} | {
"domain": "codereview.stackexchange",
"id": 43075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, rust, median",
"url": null
} |
performance, algorithm, rust, median
Some(result)
}
/// Returns the mean color value based on the passed colors.
///
/// # Arguments
///
/// * `colors` - Color vector from which the mean color is calculated.
///
/// # Examples
///
/// ```
/// let colors = Vec::<Color>::new();
/// let result = color_mean(&colors);
/// ```
///
fn color_mean(colors: &Vec<Color>) -> Option<Color> {
if colors.is_empty() {
return None;
}
let r_mean = (colors.iter().fold(0, |acc: u32, c| acc + c.r as u32) / colors.len() as u32) as u8;
let g_mean = (colors.iter().fold(0, |acc: u32, c| acc + c.g as u32) / colors.len() as u32) as u8;
let b_mean = (colors.iter().fold(0, |acc: u32, c| acc + c.b as u32) / colors.len() as u32) as u8;
let a_mean = (colors.iter().fold(0, |acc: u32, c| acc + c.a as u32) / colors.len() as u32) as u8;
Some(Color {
r: r_mean,
g: g_mean,
b: b_mean,
a: a_mean,
})
}
So basically a call to the entire algorithm looks like this:
let mut pixels = Vec::new();
// fill pixels with data
if let Some(colors) = recurse(&mut pixels, 3) {
// Do something with the output colors
}
I am very new to rust so my concerns about the code are:
The usage of Option. I second guess if I should have used Result with some meaningful error information. Also I am feeling like the "high level" usage of functions returning Options produces arrow-like code (like in median_cut) which I personally find hard to read.
Overall performance, it feels like there is a lot of iteration and cloning going on.
Algorithm implementation, There are scenarios which return "interesting" results. E.g. if I use an image which only contains red and blue pixels, the algorithm returns a blue, a red and a purple result. As I understand it the algorithm should perform a color reduction.
How could I optimize the code based on the above topics? | {
"domain": "codereview.stackexchange",
"id": 43075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, rust, median",
"url": null
} |
performance, algorithm, rust, median
How could I optimize the code based on the above topics?
Answer: You probably shouldn't award this a bounty; I'm just using your question as an excuse to learn Rust. Specifically, my understanding of how the [de]referencing works is clunky at best.
Does it run?
In order to get your code to compile, I had to add [derive(Debug,Clone,Copy)] to pub struct Color. But even then, we need to know if it works, which means we need something to run it on.
Adding this to what you wrote works:
use std::env;
use image::{Rgba, RgbaImage};
use image::error::ImageResult as ImageResult;
use image::io::Reader as ImageReader;
/// Convert from an image::RgbaImage to the local representation.
fn read_pixels(image: RgbaImage) -> Vec<Color> {
let to_color = |p: Rgba<u8>| Color {r: p[0], g: p[1], b: p[2], a: p[3], };
let mut pixels = Vec::new();
pixels.extend(image.pixels().map(|p| to_color(*p)));
pixels
}
/// Read an image from disk. Returns the RgbaImage and its width and height.
fn read_image(filename: String) -> ImageResult<(RgbaImage, u32, u32)> {
let image = ImageReader::open(&filename)?.decode()?.to_rgba8();
let (w, h) = (image.width(), image.height());
Ok((image, w, h))
}
/// Make a copy of colors, in which every color is replaced by the closest match in palette.
/// Uses Pythagorean distance.
fn assign_colors(colors: Vec<Color>, palette: Vec<Color>) -> Vec<Color> {
// Skip the sqrt, we don't need it. Use u32 to prevent overflows.
let channel_distance = |a: u8, b:u8| ((if a < b {b - a} else {a - b}) as u32).pow(2);
let mut result = Vec::new();
result.extend(colors.iter().map(
|c| palette.iter().min_by_key(
|p| channel_distance(c.r, p.r)
+ channel_distance(c.g, p.g)
+ channel_distance(c.b, p.b)
+ channel_distance(c.a, p.a)
).unwrap()
));
result
} | {
"domain": "codereview.stackexchange",
"id": 43075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, rust, median",
"url": null
} |
performance, algorithm, rust, median
/// Convert from the local representation to an image::RgbaImage.
/// Could theoretically panic in a variety of ways.
fn gather_pixels(colors: Vec<Color>, width: u32, height: u32) -> RgbaImage {
let from_color = |c: Color| Rgba::<u8>::from([c.r, c.g, c.b, c.a]);
RgbaImage::from_fn(width, height,
|x, y| from_color(colors[usize::try_from(x + (width * y)).unwrap()])
)
}
/// The inner "main" function; wraps failure conditions.
fn handle_file(input_file: String, output_file: String) -> Result<(), String> {
let e2str = |e| format!("{}", e);
let (image, width, height) = read_image(input_file).map_err(e2str)?;
let pixels = read_pixels(image);
let palette = recurse(&mut pixels.clone(), 3)
.ok_or(String::from("There was a problem building the palette."))?;
let out_image = gather_pixels(assign_colors(pixels, palette), width, height);
out_image.save(output_file).map_err(e2str)
}
fn main() {
let input_file = env::args().nth(1).expect("Missing argument");
let output_file = env::args().nth(2).expect("Missing argument");
let result = handle_file(input_file, output_file);
if let Err(error) = result {
println!("{}", error);
} else {
println!("Success!");
}
}
It takes about 11 seconds to run (on a 1.3MB 1080x1920 png).
Docstrings
You seem to be following a verbose format for your docstrings.
That's not bad, but it's not what I'd do.
You've done a good job of naming things in general, so adding additional comments for every argument doesn't seem to have much value.
On the other hand, why doesn't recurse have a docsting? It actually needs some explanation. While you're at it, rename it to make_palette.
Are you actually following the algorithm?
From your Wikipedia link: | {
"domain": "codereview.stackexchange",
"id": 43075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, rust, median",
"url": null
} |
performance, algorithm, rust, median
Since the number of buckets doubles with each iteration, this algorithm can only generate a palette with a number of colors that is a power of two. To generate, say, a 12-color palette, one might first generate a 16-color palette and merge some of the colors in some way.
And yet during debugging of my code, I definitely noticed you were generating pallets of 14 colors.
I'm pretty sure the issue is in recurse. After calling median_cut, for each returned bucket, you first push the mean of the bucket into result, and then recurse. For a given approximate palette-size, this will waste slots on lower-saturation colors, compared to only taking the means of "leaf" buckets. This actually makes the function much simpler:
/// Perform the median cut algorithm.
/// Returns a palette with 2^iter_count colors.
/// https://en.wikipedia.org/wiki/Median_cut
pub fn make_palette(bucket: &mut Vec<Color>, iter_count: u8) -> Option<Vec<Color>> {
if iter_count < 1 {
return Some(Vec::from([color_mean(&bucket)?]));
}
let mut new_buckets = median_cut(bucket);
let mut result = make_palette(&mut new_buckets.0, iter_count - 1)?;
result.append(&mut make_palette(&mut new_buckets.1, iter_count - 1)?);
Some(result)
}
Your calculation of the ranges seems to be just checking for the max value; I assume that's a mistake.
Also, why are you ignoring the alpha channel?
Can we make stuff more elegant?
If we replace Color::channel_val with ColorChannel::value, then a lot of the places where we're repeating stuff per-channel can be reduced. channel_value_by_index no longer needs to be a defined function, for example. You can also add a higher-order Color builder function.
This brings the code down to something that feels more intuitive to me:
use std::env;
use image::{Rgba, RgbaImage};
use image::error::ImageResult as ImageResult;
use image::io::Reader as ImageReader; | {
"domain": "codereview.stackexchange",
"id": 43075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, rust, median",
"url": null
} |
performance, algorithm, rust, median
#[derive(Debug,Clone,Copy)]
pub struct Color {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
}
#[derive(Debug,Clone,Copy)]
pub enum ColorChannel {
R,
G,
B,
A,
}
impl ColorChannel {
pub const ALL: [ColorChannel; 4] = [Self::R, Self::G, Self::B, Self::A];
pub fn value(&self, color: &Color) -> u8 {
match self {
ColorChannel::R => color.r,
ColorChannel::G => color.g,
ColorChannel::B => color.b,
ColorChannel::A => color.a,
}
}
}
impl Color {
pub fn from_fn<F>(f: F) -> Option<Color>
where F: Fn(ColorChannel) -> Option<u8> {
Some(Color {r: f(ColorChannel::R)?,
g: f(ColorChannel::G)?,
b: f(ColorChannel::B)?,
a: f(ColorChannel::A)?,
})
}
}
impl PartialEq for Color {
fn eq(&self, other: &Self) -> bool {
ColorChannel::ALL.iter()
.all(|channel| channel.value(self) == channel.value(other))
}
}
/// Returns the color channel with the highest range.
/// IMPORTANT: Ignores alpha channel!
fn highest_range_channel(colors: &Vec<Color>) -> Option<ColorChannel> {
let ranges = color_ranges(colors)?;
let channel: &ColorChannel = ColorChannel::ALL.iter()
.max_by_key(|channel| channel.value(&ranges))?;
Some(*channel)
}
/// Returns the ranges for each color channel
fn color_ranges(colors: &Vec<Color>) -> Option<Color> {
Color::from_fn(|channel|
Some(colors.iter().map(|color| channel.value(color)).max()?
- colors.iter().map(|color| channel.value(color)).min()?))
}
/// Returns median value for a specific `ColorChannel` across `colors`.
fn channel_median(colors: &mut Vec<Color>, channel: &ColorChannel) -> Option<u8> {
colors.sort_by_key(|a| channel.value(a)); | {
"domain": "codereview.stackexchange",
"id": 43075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, rust, median",
"url": null
} |
performance, algorithm, rust, median
let mid = colors.len() / 2;
if colors.len() % 2 == 0 {
channel_mean(&vec![colors[mid - 1], colors[mid]], channel)
} else {
Some(channel.value(colors.get(mid)?))
}
}
/// Calculate the mean value for a specific color channel on a vector of `Color`.
fn channel_mean(colors: &Vec<Color>, channel: &ColorChannel) -> Option<u8> {
let number_colors = colors.len() as u32;
if number_colors == 0 {
return None;
}
let mean = colors.iter()
.fold(0, |acc: u32, x| channel.value(x) as u32 + acc) / number_colors;
Some(mean as u8)
}
/// Performs the median cut on a single vector (bucket) of `Color`.
/// Returns two vectors (buckets) with the colors above and below the chosen median.
fn median_cut(colors: &mut Vec<Color>) -> Option<(Vec<Color>, Vec<Color>)> {
let mut above_median = Vec::<Color>::new();
let mut below_median = Vec::<Color>::new();
let channel = highest_range_channel(&colors)?;
let median = channel_median(colors, &channel)?;
for color in colors {
if channel.value(color) > median {
above_median.push(*color);
} else {
below_median.push(*color);
}
}
return Some((above_median, below_median));
}
/// Perform the median cut algorithm.
/// Returns a palette with 2^iter_count colors.
/// https://en.wikipedia.org/wiki/Median_cut
pub fn make_palette(bucket: &mut Vec<Color>, iter_count: u8) -> Option<Vec<Color>> {
if iter_count < 1 {
return Some(vec![Color::from_fn(|channel| channel_mean(bucket, &channel))?]);
}
let mut new_buckets = median_cut(bucket)?;
let mut result = make_palette(&mut new_buckets.0, iter_count - 1)?;
result.append(&mut make_palette(&mut new_buckets.1, iter_count - 1)?);
Some(result)
} | {
"domain": "codereview.stackexchange",
"id": 43075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, rust, median",
"url": null
} |
performance, algorithm, rust, median
/// Convert from an image::RgbaImage to the local representation.
fn read_pixels(image: RgbaImage) -> Vec<Color> {
let to_color = |p: Rgba<u8>| Color {r: p[0], g: p[1], b: p[2], a: p[3], };
let mut pixels = Vec::new();
pixels.extend(image.pixels().map(|p| to_color(*p)));
pixels
}
/// Read an image from disk. Returns the RgbaImage and its width and height.
fn read_image(filename: String) -> ImageResult<(RgbaImage, u32, u32)> {
let image = ImageReader::open(&filename)?.decode()?.to_rgba8();
let (w, h) = (image.width(), image.height());
Ok((image, w, h))
}
/// Make a copy of colors, with color is replaced by the closest match in palette.
/// Uses Pythagorean distance.
fn assign_colors(colors: Vec<Color>, palette: Vec<Color>) -> Vec<Color> {
// Skip the sqrt, we don't need it. Use u32 to prevent overflows.
let channel_distance = |a: u8, b:u8| ((if a < b {b - a} else {a - b}) as u32).pow(2);
let mut result = Vec::new();
result.extend(colors.iter().map(
|c| palette.iter().min_by_key(
|p| ColorChannel::ALL.iter().map(
|channel| channel_distance(channel.value(c), channel.value(p))
).sum::<u32>()
).unwrap() // Maybe we should check if the palette is empty?
));
result
}
/// Convert from the local representation to an image::RgbaImage.
/// Could theoretically panic in a variety of ways.
fn gather_pixels(colors: Vec<Color>, width: u32, height: u32) -> RgbaImage {
let from_c = |c: Color| Rgba::<u8>::from([c.r, c.g, c.b, c.a]);
RgbaImage::from_fn(width, height,
|x, y| from_c(colors[usize::try_from(x + (width * y)).unwrap()])
)
} | {
"domain": "codereview.stackexchange",
"id": 43075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, rust, median",
"url": null
} |
performance, algorithm, rust, median
/// The inner "main" function; wraps failure conditions.
fn handle_file(input_file: String, output_file: String) -> Result<(), String> {
let e2str = |e| format!("{}", e);
let (image, width, height) = read_image(input_file).map_err(e2str)?;
let pixels = read_pixels(image);
let palette = make_palette(&mut pixels.clone(), 4)
.ok_or(String::from("There was a problem building the palette."))?;
println!("{} colors!", palette.len());
let out_image = gather_pixels(assign_colors(pixels, palette), width, height);
out_image.save(output_file).map_err(e2str)
}
fn main() {
let input_file = env::args().nth(1).expect("Missing argument");
let output_file = env::args().nth(2).expect("Missing argument");
let result = handle_file(input_file, output_file);
if let Err(error) = result {
println!("{}", error);
} else {
println!("Success!");
}
}
On the other hand it now takes about twice as long to run, and I don't know why.
Your questions:
The usage of Option.
Think about what the situation you're trying to represent means. If the situation is "there are no elements", could you just return an empty list? If something's gone wrong, then a Result should be preferred because it will help a user figure out what went wrong. If you're still in the realm of nominal behavior, Option is probably fine.
I think in general, it would be ideal to make your code more "arrow-like", if I understand correctly what you mean by that.
Overall performance.
LOL, IDK. I have some idea's about how we might improve the performance, but it's above my pay grade :)
Algorithm implementation.
I think I've covered this above. | {
"domain": "codereview.stackexchange",
"id": 43075,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, algorithm, rust, median",
"url": null
} |
c++, beginner, algorithm, statistics
Title: Most frequent element in an array, return lowest if multiple
Question: I have been learning C++ for the past 2 weeks.
Following is a problem I solved from Hackerrank. I am somewhat unsure if it's the correct way to solve this, even though I got the desired output. How can I improve this?
Given an array of bird sightings where every element represents a bird type id, determine the id of the most frequently sighted type. If more than 1 type has been spotted that maximum amount, return the smallest of their ids.
Input Format
The first line contains an integer representing the number of observations. The second line
consists of space-separated integers, each a type number of the bird
sighted.
My code:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int n, input;
vector<int> arr;
cin >> n;
while (n--)
{
cin >> input;
arr.push_back(input);
}
int max_count = 0, count=0, max_id;//here max_id is our answer
//sorting the array
sort(arr.begin(), arr.end());
for (int i = 1; i < (int)arr.size(); i++)
{
if (arr[i] == arr[i - 1])
{
count++;
if (count > max_count)
{
max_count = count;//setting the new max count
max_id = arr[i];//setting the new max-count id
}
else if (count == max_count)
{
max_id = (arr[i] < max_id ? arr[i] : max_id);//checking the lowest
}
}
else {
count = 0;
}
}
cout << max_id << endl;
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 43076,
"lm_label": 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, algorithm, statistics",
"url": null
} |
c++, beginner, algorithm, statistics
cout << max_id << endl;
return 0;
}
Answer: I don't know where you've been learning C++, but please avoid anything that presents using namespace std as good practice. It serves to remove one of the benefits of C++ and can actually cause your program to behave in unexpected ways. Stop using that, and instead get used to writing the (intentionally very short) std:: prefix where it's needed.
When we read from std::cin using >>, we should always check the state of the stream before using the streamed-to value. If std::cin is in an error state, then we can't trust what was read, and should abort, rather than continuing with invalid data.
When writing to an output stream, we rarely need to force it to be flushed. We normally want a plain newline (which doesn't flush) and almost never need std::endl. Remember that streams will be flushed when the program exits.
When we know how many observations we'll be reading, it's a good practice to reserve capacity in the vector. This makes it more efficient, as we then know it won't need to resize itself as more input arrives:
arr.reserve(n) | {
"domain": "codereview.stackexchange",
"id": 43076,
"lm_label": 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, algorithm, statistics",
"url": null
} |
c++, beginner, algorithm, statistics
Instead of casting the array size to int, it's probably better to make the type of i match the size - that would be std::size_t i.
There's a bug: the program doesn't produce the correct results if all the sightings are unique (i.e. if all the counts are 1). To fix that, we need to initialise max_id to arr[0] (after the sort(), of course), rather than to 0.
Since we sorted the array, the test within if (count == max_count) isn't necessary. The sorting means that max_id < arr[i], so we don't need to do anything there.
There are algorithms in the standard library that would help simplify the code - look at std::upper_bound() for finding the next element in the vector that's greater than a particular value, and consider how you could use that to count.
We could make the code much simpler by choosing a container type that's much better for counting, though. We could consider a std::multiset, but I think the best choice would be a std::map<int, std::size_t>. Our input loop would then be
while (n--) {
int input;
if (!(std::cin >> input)) {
return EXIT_FAILURE;
}
++counts[input];
}
We can then use the std::max_element() algorithm to find the element with most sightings - we'll need to pass a comparator function that compares values, but it won't need to compare the ids, because std::max_element() returns the earliest element when there are two or more equal maxima, and a std::map is sorted smallest-first.
Assuming we're using C++20, we can use the Ranges version of max_element(), in which we simply need to pass a projection rather than writing our own comparator.
Modified code
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <map>
int main()
{
using id_map = std::map<int, std::size_t>;
std::size_t n; // First input - number of sightings
if (std::cin >> n; !std::cin) {
std::cerr << "Failed to read count\n";
return EXIT_FAILURE;
} | {
"domain": "codereview.stackexchange",
"id": 43076,
"lm_label": 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, algorithm, statistics",
"url": null
} |
c++, beginner, algorithm, statistics
if (n == 0) {
return EXIT_FAILURE; // no sightings, so no output
}
id_map counts; // Read and count the sightings
while (n--) {
if (int input; std::cin >> input) {
++counts[input];
} else {
std::cerr << "Failed to read id\n";
return EXIT_FAILURE;
}
}
// Find the modal element (lowest id if there's a tie)
auto max_it = std::ranges::max_element(counts, std::less<>{},
&id_map::value_type::second);
std::cout << max_it->first << '\n';
} | {
"domain": "codereview.stackexchange",
"id": 43076,
"lm_label": 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, algorithm, statistics",
"url": null
} |
java, algorithm, compression, binary-tree
Title: Huffman coding implementation in java
Question: I wrote a simple huffman coding algorithm for learning and practice. I just used the technique given on the wikipedia page.
Could you tell me my missing points and mistakes?
Node.java
package ged.gont.bst.huffmancode;
public class Node implements Comparable<Node> {
private char letter;
private int freq;
private Node leftChild;
private Node rightChild;
public Node(char letter, int freq, Node leftChild, Node rightChild) {
this.letter = letter;
this.freq = freq;
this.leftChild = leftChild;
this.rightChild = rightChild;
}
public char getLetter() {
return letter;
}
public int getFreq() {
return freq;
}
public Node getLeftChild() {
return leftChild;
}
public Node getRightChild() {
return rightChild;
}
public boolean isLeaf() {
return this.leftChild == null && this.rightChild == null;
}
@Override
public int compareTo(Node arg0) {
return this.freq - arg0.freq;
}
}
HuffmanCode.java
package ged.gont.bst.huffmancode;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.PriorityQueue;
public class HuffmanCode {
private Node root;
Map<Character, String> charMap = new LinkedHashMap<>();
/**
* Encodes string in which most used characters have min codeword length
*
* @param inputString compressed string
* @return encoded string
* @throws IllegelArgumentException if inputString contains invalid ASCII character
*/
public String encode(String inputString) {
char[] letters = inputString.toCharArray();
Map<Character, Integer> charFreq = new LinkedHashMap<>();
PriorityQueue<Node> priorityQueue = new PriorityQueue<>();
String encodedString = ""; | {
"domain": "codereview.stackexchange",
"id": 43077,
"lm_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, compression, binary-tree",
"url": null
} |
java, algorithm, compression, binary-tree
for (char c : letters) {
if ((int) c > 255) {
throw new IllegalArgumentException("Input contains invalid ASCII character");
}
if (charFreq.containsKey(c)) {
charFreq.put(c, charFreq.get(c) + 1);
} else {
charFreq.put(c, 1);
}
}
for (Character c : charFreq.keySet()) {
priorityQueue.offer(new Node(c, charFreq.get(c), null, null));
}
while (priorityQueue.size() > 1) {
Node leftChild = priorityQueue.remove();
Node rightChild = priorityQueue.remove();
priorityQueue.offer(new Node(Character.MIN_VALUE, leftChild.getFreq() + rightChild.getFreq(), leftChild, rightChild));
}
root = priorityQueue.remove();
generatePrefix(root, "");
for (int i = 0; i < inputString.length(); i++) {
encodedString += (charMap.get(inputString.charAt(i)));
}
return encodedString;
}
/**
* Generates prefix code in bit string format
*
* @param root
* @param code
*/
private void generatePrefix(Node root, String prefix) {
if (!root.isLeaf()) {
generatePrefix(root.getLeftChild(), prefix.concat("0"));
generatePrefix(root.getRightChild(), prefix.concat("1"));
} else {
charMap.put(root.getLetter(), prefix);
}
}
/**
* Decodes the given encoded string
*
* @param encodedString
* @return decoded string
*/
public String decode(String encodedString) {
String decodedString = "";
Node currentNode = root;
for (int i = 0; i < encodedString.length(); i++) { | {
"domain": "codereview.stackexchange",
"id": 43077,
"lm_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, compression, binary-tree",
"url": null
} |
java, algorithm, compression, binary-tree
for (int i = 0; i < encodedString.length(); i++) {
if (encodedString.charAt(i) == '0') {
currentNode = currentNode.getLeftChild();
} else if (encodedString.charAt(i) == '1') {
currentNode = currentNode.getRightChild();
}
if (currentNode.isLeaf()) {
decodedString += currentNode.getLetter();
currentNode = root;
}
}
return decodedString;
}
}
TestHuffmanCode.java
package ged.gont.testbst.testhuffmancode;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.*;
import ged.gont.bst.huffmancode.*;
public class TestHuffmanCode {
static HuffmanCode huffmanCode;
static String inputString;
static String expectedEncodedString;
@BeforeAll
public static void init() {
huffmanCode = new HuffmanCode();
inputString = "A_DEAD_DAD_CEDED_A_BAD_BABE_A_BEADED_ABACA_BED";
expectedEncodedString = "1000011101001000110010011101100111001001000111110010011111011111100010001111110100111001001011111011101000111111001";
}
@Test
public void testEncode() {
assertEquals(expectedEncodedString, huffmanCode.encode(inputString));
}
@Test
public void testDecode() {
assertEquals(inputString, huffmanCode.decode(huffmanCode.encode(inputString)));
}
}
Answer: General
Classes not carefully designed for extension should be marked `final`.
root is problematic as a class-level variable. The API of HuffmanCode implies that decode() depends only on the encoded string, and that one could call decode more than once with different values. That will fail, though. The code only works if you call encode directly before the corresponding decode. | {
"domain": "codereview.stackexchange",
"id": 43077,
"lm_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, compression, binary-tree",
"url": null
} |
java, algorithm, compression, binary-tree
It would be better to localize root and do whatever computation is necessary for decode in that method. This would mean changing the output of encode so that the tree can be rebuilt`.
Another option would be to separate out the building of the tree into its own method, and then have encode and decode take the tree as an argument. The downside here is needing to track both the tree and the encoded string.
A third option is to build the HuffmanCode class using a static encode factory method. The class would keep the tree as an instance variable. It could have a public toString method to return the encoded value, and a public decode method to return the decoded value. | {
"domain": "codereview.stackexchange",
"id": 43077,
"lm_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, compression, binary-tree",
"url": null
} |
java, algorithm, compression, binary-tree
Which of these is best depends on your needs. But the API right now will result in cranky users calling encode() multiple times and then trying to decode() multiple times and getting nonsense results.
Node
This class is immutable, so all the variables can be marked as final. This conveys the intent that they cannot be changed, and prevents accidental modification after construction time.
This class is only intended for use inside its package, and should therefore have default (package-private) access, not public.
This class has one constructor, but it should have two, one for leaf node construction and one for internal node construction.
arg0 might be better named as node or otherNode.
HuffmanCode
`charMap` should be `private`.
Abbreviations are confusing and should be avoided. characterFrequency would be preferable to charFreq. Likewise charMap could be characterMap or characterEncodings.
characters can be inlined and still clear to readers.
letters is not a good variable name, since the values are actually ASCII characters, not letters.
It's not necessary to convert a char to an int for numerical comparisons. The compiler can do it natively.
It would be preferable if the invalid ASCII character exception contained both the invalid character and the input string.
Setting the map value to 1 or adding 1 to the map value is cleaner using Map.merge(). It would look like charFreq.merge(c, 1, Integer::sum);
The code could use an int[] instead of a map, since ASCII is a constrained set of ints from 0-255. Using an int[256] and incrementing the values there should be more time and space efficient. Prefer whichever is easier to read unless you have a documented performance bottleneck.
It's preferable to localize variables so they're initialized as close to where they're first used as is reasonable. The convention of declaring them at the top of a method is a holdover from languages where it's not possible to declare them later. | {
"domain": "codereview.stackexchange",
"id": 43077,
"lm_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, compression, binary-tree",
"url": null
} |
java, algorithm, compression, binary-tree
When modifying Strings, it is preferable to use StringBuilder (or StringBuffer if thread safety is an issue). This is for efficiency reasons and clarity-of-intent reasons. The compiler will generally figure it out, but the hint doesn't hurt.
This block:
for (int i = 0; i < inputString.length(); i++) {
encodedString.append(characterEncodings.get(inputString.charAt(i)));
} | {
"domain": "codereview.stackexchange",
"id": 43077,
"lm_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, compression, binary-tree",
"url": null
} |
java, algorithm, compression, binary-tree
can be replaced with
for (char c : inputString.toCharArray()) {
encodedString.append(characterEncodings.get(c));
}
In generatePrefix, it's easier to read if the non-negated case is in the if part and the negation is in the else.
generatePrefix is a confusing name, because it's really generating the character encodings.
In generatePrefix, prefix might be better named encoding. root might be better named node.
It would be preferable if decode() handled invalid input more aggressively, rather than silently continuing if it doesn't see a 0 or 1.
TestHuffmanCode
Only having one test is not especially useful. There should be tests for all boundary conditions, and a variety of interesting inputs. For instance, zero characters, one character, non-ASCII characters only, non-ascii characters embedded in ASCII characters, etc. | {
"domain": "codereview.stackexchange",
"id": 43077,
"lm_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, compression, binary-tree",
"url": null
} |
php, html, mysql
Title: Displaying MySQL data using PHP
Question: I have MySQL data that I am rendering in an HTML table using PHP. This is the full code of my table and PHP. It does output fine and looks how I would expect but I am wondering if there is a better way to write this code. Also, the 'Delete' button specifically, is there a better way to output the button itself as right now, I noticed especially on a mobile device, I will see a text cursor indicator when tapping the button as if I am trying to select the text on the button itself.
<div class="container" style="width: 95%;">
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th class="col-sm-6">
Description
</th>
<th class="col-sm-2">
Date Created
</th>
<th class="col-sm-1">
Created By
</th>
<th class="col-sm-2" style="text-align: right;">
Edit - Delete
</th>
</tr>
<?php
$noLists = "<div>You have no lists. Why dont you create one?</div>";
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$sql = "SELECT DISTINCT lists.id, lists.listdescription, lists.createdon, lists.createdby, lists.sharedlist FROM lists INNER JOIN users ON users.fname = '$displayname' AND users.fname = lists.createdby";
$result = $db->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$listID = $row["id"];
$listDescription = $row["listdescription"];
$createdOn = $row["createdon"];
$createdBy = $row["createdby"]; | {
"domain": "codereview.stackexchange",
"id": 43078,
"lm_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, html, mysql",
"url": null
} |
php, html, mysql
echo "<form>";
echo "<tr>";
echo "<td>$listDescription</td>";
echo "<td>$createdOn</td>";
echo "<td>$createdBy</td>";
echo "<td align=\"right\">";
echo "<form action='account.php' method='post'>";
echo "<input class=\"btn btn-success\" type=\"submit\" name=\"\" value=\"Edit\">";
echo "<a href='includes/deletelist.php?id=$row[id]'><input class=\"btn btn-danger\" value=Delete style=\"width: 85px;\"></a>
<!--<a href=\"index.php?id=$id\">Delete</a>-->
</td>";
}
} else {
echo "</thead>";
echo "<tbody>";
echo "</tbody>";
echo "</table>";
echo "<h4> $noLists</h4>";
}
$db->close();
?> | {
"domain": "codereview.stackexchange",
"id": 43078,
"lm_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, html, mysql",
"url": null
} |
php, html, mysql
?>
Answer: Generally speaking, you should keep your markup and your PHP logic separate.
And the intermediate variables don't really have a purpose, just use the values from the array.
You've got two opening form tags and no closing form tags.
Your first condition (if there are records in the table) does not close the thead or the create a tbody.
Your delete button is no button at all, it's an input wrapped in an anchor tag (<a>). That's why it's not working as expected. Either remove the anchor and give the input a type attribute of "button", or remove the input and put some text in there instead.
Use a prepared statement. It's not cool to throw variables into your queries all willy-nilly. You will anger the code gods.
Here's a quick re-write (assumes you're using PDO - If you're using MySQLi, see the docs to convert the prepared statement to MySQLi)
I'm just going to go ahead and post this since I spent three or four minutes on it, but after looking at this code, there is no way this was working as you had it. This site is for reviewing working code, not fixing broken code. If your code doesn't work you need to ask on StackOverflow in the future.
<?php
// Do all the PHP stuff before you start ouputting
$noLists = "<div>You have no lists. Why dont you create one?</div>";
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
} | {
"domain": "codereview.stackexchange",
"id": 43078,
"lm_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, html, mysql",
"url": null
} |
php, html, mysql
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$sql = "SELECT DISTINCT lists.id, lists.listdescription, lists.createdon, lists.createdby, lists.sharedlist FROM lists INNER JOIN users ON users.fname = ? AND users.fname = lists.createdby";
$result = $db->prepare($sql);
$result->execute(array($displayname));
$output = array();
if ($result->rowCount() > 0) {
// output data of each row
$output[] = "</thead>";
$output[] = "<tbody>";
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$output[] = "<tr>";
$output[] = "<td>{$row["listdescription"]}</td>";
$output[] = "<td>{$row["createdon"]}</td>";
$output[] = "<td>{$createdBy}</td>";
$output[] = "<td align=\"right\">";
$output[] = "<form action='account.php' method='post'>";
$output[] = "<input class=\"btn btn-success\" type=\"submit\" name=\"\" value=\"Edit\">";
$output[] = "</form>";
$output[] = "<a href='includes/deletelist.php?id={$row["id"]}' class=\"btn btn-danger\" style=\"width: 85px;\">Delete</a></td>";
}
$output[] = "</tbody>";
$output[] = "</table>";
} else {
$output[] = "</thead>";
$output[] = "<tbody>";
$output[] = "</tbody>";
$output[] = "</table>";
$output[] = "<h4> $noLists</h4>";
}
$db->close(); | {
"domain": "codereview.stackexchange",
"id": 43078,
"lm_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, html, mysql",
"url": null
} |
php, html, mysql
// Turn the output array back into a string
$output = implode('', $output);
?><div class="container" style="width: 95%;">
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th class="col-sm-6">
Description
</th>
<th class="col-sm-2">
Date Created
</th>
<th class="col-sm-1">
Created By
</th>
<th class="col-sm-2" style="text-align: right;">
Edit - Delete
</th>
</tr>
<?php echo $output; ?>
Edit... you're not closing your table row in the loop either. I'm not gonna bother updating the code snippet. | {
"domain": "codereview.stackexchange",
"id": 43078,
"lm_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, html, mysql",
"url": null
} |
javascript, algorithm, node.js, typescript
Title: Update user's experience points
Question: I have a private method in my class to update user experience.
First of all, I create giveExp based on contentLength (string.length)
In that method I had formula for count level from exp: (Math.sqrt(2 * user.xp - 175) + 25) / 10;
I also need to inform the player that they have leveled up.
Full code
private updateXp(
contentLength: number,
channel: Readonly<WritableChannel>,
xp: string
) {
const giveExp = Math.round(contentLength * 3 * 0.1);
let userXp = Number.parseInt(xp, 10);
const level = (Math.sqrt(2 * userXp - 175) + 25) / 10;
userXp += giveExp < 15 ? giveExp : 15;
const nowLevel = (Math.sqrt(2 * userXp - 175) + 25) / 10;
if (level.toFixed(0) < nowLevel.toFixed(0)) {
void channel.send("Level up");
}
return String(userXp);
} | {
"domain": "codereview.stackexchange",
"id": 43079,
"lm_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, algorithm, node.js, typescript",
"url": null
} |
javascript, algorithm, node.js, typescript
Answer: I found your code hard to read.
In comments, the OP said: "when a number [xp] becomes very large, it can work only as BigInt. I also have a string type in my database."
The parseInt function converts its first argument to a string, parses that string, then returns an integer or, if greater than Number.MAX_VALUE, Infinity. A Number is converted to fixed-point notation, except large numbers (more than 20 digits) are converted to exponential notation. A BigInt is converted to fixed-point notation. The parseInt function returns only the integer portion of exponential notation. Parse xp as BigInt(xp).
Factor out the level formula to make it obvious that you are using the same formula. For a comparison of integer numeric values, don't compare strings. Use Math.round.
JavaScript Number does not support complex numbers. The level formula expression Math.sqrt(2 * xp - 175) propagates NaN if (2 * xp - 175) < 0 or xp < 87.5. Math works with the Number type. The level formula expression Math.sqrt(2 * xp - 175) only handles xp values less than or equal to (Number.MAX_VALUE / 2) or 8.988465674311579e+307.
Binary floating-point numbers (IEEE 754) are an approximation, including the value 0.1. For a more exact result, don't multiply by 0.1, divide by 10.
Reorder code to group related statements together.
Sometimes you used xp, sometimes you used exp. Use xp (or exp) consistently.
You have level and nowLevel. For clarity, use oldLevel and newLevel.
For a math formula, use Math.min instead of the conditional (ternary) operator.
Since the action is "Level up", reverse the test for up to newLevel > oldLevel.
For minified code, use spacing and indentation to enhance readability.
function updateXp(
contentLength,
channel,
xp) {
function levelFormula(xp) {
return Math.round((Math.sqrt(2 * xp - 175) + 25) / 10);
}
let userXp = Number.parseInt(BigInt(xp), 10);
const oldLevel = levelFormula(userXp); | {
"domain": "codereview.stackexchange",
"id": 43079,
"lm_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, algorithm, node.js, typescript",
"url": null
} |
javascript, algorithm, node.js, typescript
let userXp = Number.parseInt(BigInt(xp), 10);
const oldLevel = levelFormula(userXp);
const giveXp = Math.round(contentLength * 3 / 10);
userXp += Math.min(giveXp, 15);
const newLevel = levelFormula(userXp);
if (newLevel > oldLevel) {
void channel.send("Level up");
}
return String(userXp);
} | {
"domain": "codereview.stackexchange",
"id": 43079,
"lm_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, algorithm, node.js, typescript",
"url": null
} |
python, performance, image
Title: Create an image made of many circles
Question: I have written some Python code for creating an image made of lots of circles. It works, but I wonder if it could be made faster, shorter or more pythonic somehow.
Example image (took 28 seconds):
from PIL import Image
from random import randint
from datetime import datetime
def circle(data, center, radius, color, size):
for x in range(size):
for y in range(size):
if (x - center[0]) ** 2 + (y - center[1]) ** 2 <= radius ** 2:
data[x * size + y] = color
return data
def main():
start_time = datetime.now()
size = 500
circle_amount = 200
data = [(0, 0, 0)] * size ** 2
img = Image.new("RGB", (size, size), "black")
for _ in range(circle_amount):
data = circle(data, (randint(0, size), randint(0, size)), randint(0, max(size, size)) / randint(5, 10), (randint(0, 255), randint(0, 255), randint(0, 255)), size)
img.putdata(data)
img.save("image.png")
print(f"Time needed: {datetime.now() - start_time}")
if __name__ == "__main__":
main()
Answer: Don't set the data. Don't iterate over pixels. Iterate over circles only and use PIL's own drawing facilities:
from PIL import Image, ImageDraw
from random import randint, randrange
def circle(draw: ImageDraw, size: int) -> None:
xc, yc = randrange(size), randrange(size)
radius = randrange(size) / randint(5, 10)
color = randrange(256), randrange(256), randrange(256)
draw.ellipse(
xy=(
xc - radius, yc - radius,
xc + radius, yc + radius,
),
fill=color,
)
def main():
size = 500
circle_amount = 100_000
img: Image = Image.new("RGB", (size, size), "black")
draw: ImageDraw = ImageDraw.Draw(img)
for _ in range(circle_amount):
circle(draw, size)
img.save("image.png")
if __name__ == "__main__":
main() | {
"domain": "codereview.stackexchange",
"id": 43080,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, image",
"url": null
} |
python, performance, image
img.save("image.png")
if __name__ == "__main__":
main()
This took about one second for a hundred thousand circles. We expect this approach to be much faster because internally it's not implemented in Python, but rather in C:
static int
ellipseNew(
Imaging im,
int x0,
int y0,
int x1,
int y1,
const void *ink_,
int fill,
int width,
int op) {
DRAW *draw;
INT32 ink;
DRAWINIT();
int a = x1 - x0;
int b = y1 - y0;
if (a < 0 || b < 0) {
return 0;
}
if (fill) {
width = a + b;
}
ellipse_state st;
ellipse_init(&st, a, b, width);
int32_t X0, Y, X1;
while (ellipse_next(&st, &X0, &Y, &X1) != -1) {
draw->hline(im, x0 + (X0 + a) / 2, y0 + (Y + b) / 2, x0 + (X1 + a) / 2, ink);
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 43080,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, image",
"url": null
} |
c
Title: Concept of implementing "generic" types in C using macros
Question: I am interested in opinions of experienced C programmers about a certain approach to creating a "generic" dynamic array in C. The idea is to use macros to generate function declarations and definitions, and to avoid using void pointers (of course, this is nothing unheard of). For simplicity, I will only generate three basic functions - one to create such an array, one to destroy it, and one to append an element to the array.
It seems a practical approach, however, before starting to use this pattern all over, I would like to check if it makes sense and if it suffers from some major drawbacks (which I can not identify). So, let's get started.
First, let us define a few utility macros, whose purpose it primarily to avoid repeating boilerplate "safety" code (eg checking if returned pointers are NULL, etc):
// utils.h
#include <stdio.h>
#include <stdlib.h>
/*
* Exit with an error message.
*
* @param msg String literal, message to display.
*/
#define EXIT_ERROR(msg) \
do { \
printf("Error in %s at line %d: %s - terminating program.\n", __FILE__, __LINE__, msg); \
exit(EXIT_FAILURE); \
} while(0)
/*
* Macro which also checks if the pointer returned by malloc is NULL.
*
* @param ptr Name of pointer to which malloc is assigned.
* @param size Multiple which determines size of malloc'd array
* @param type Type of array element
*/
#define MALLOC_SAFE(ptr, size, type) \
malloc((size) * sizeof(type)); \
if (ptr == NULL) \
EXIT_ERROR("Memory allocation failure") | {
"domain": "codereview.stackexchange",
"id": 43081,
"lm_label": 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
/*
* Macro with additional safety actions to accompany realloc. If
* requested size if 0, frees the pointer. If the call to realloc
* returns NULL, terminates the program. Else, assigns the original
* pointer to the one returned by realloc.
*
* @param ptr Name of pointer to be realloc'd.
* @param size Multiple which determines size of realloc'd array
* @param type Type of array element
*/
#define REALLOC_SAFE(ptr, size, type) \
do { \
if (size == 0) \
FREE_SAFE(ptr); \
else { \
type* p = realloc(ptr, (size) * sizeof(type)); \
if (p == NULL) \
EXIT_ERROR("Memory reallocation failure"); \
ptr = p; \
} \
} while(0)
/*
* Macro which assigns the pointer to null after freeing. Useful
* to avoid dangling pointers.
*
* @param ptr Name of pointer to free.
*/
#define FREE_SAFE(ptr) \
do { \
free(ptr); \
ptr = NULL; \
} while(0)
Next, let us define the header with macros used to generate declarations and definitions, respectively. Also, note that a benefit of this is to make the data type opaque.
// dynarr.h
#ifndef DYNARR_H
#define DYNARR_H
#include <stdlib.h>
#include "utils.h"
/*
* Macro which generates declarations of dynamic array functions,
* along with its opaque type declaration.
*
* @param DYNARRAY_TYPE_NAME Name of the dynamic array type.
* @param DYNARRAY_ITEM_TYPE Type of the item which the dynamic array
* shall contain.
*/
#define GEN_DYNARR_DECL(DYNARRAY_TYPE_NAME, DYNARRAY_ITEM_TYPE) \
typedef struct DYNARRAY_TYPE_NAME DYNARRAY_TYPE_NAME; \
DYNARRAY_TYPE_NAME* DYNARRAY_TYPE_NAME##_create (void); \
void DYNARRAY_TYPE_NAME##_destroy (DYNARRAY_TYPE_NAME** d); \
void DYNARRAY_TYPE_NAME##_append (DYNARRAY_TYPE_NAME* d, DYNARRAY_ITEM_TYPE item); \ | {
"domain": "codereview.stackexchange",
"id": 43081,
"lm_label": 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
/*
* Macro which generates definitions of dynamic array functions,
* along with its type definition.
*
* @param DYNARRAY_TYPE_NAME Name of the dynamic array type.
* @param DYNARRAY_ITEM_TYPE Type of the item which the dynamic array
* shall contain.
*/
#define GEN_DYNARR_DEF(DYNARRAY_TYPE_NAME, DYNARRAY_ITEM_TYPE) \
struct DYNARRAY_TYPE_NAME { \
size_t capacity; \
size_t size; \
DYNARRAY_ITEM_TYPE* arr; \
}; \
\
DYNARRAY_TYPE_NAME* DYNARRAY_TYPE_NAME##_create (void) { \
DYNARRAY_TYPE_NAME* d = MALLOC_SAFE(d, 1, DYNARRAY_TYPE_NAME); \
d->capacity = 0; \
d->size = 0; \
d->arr = NULL; \
return d; \
} \
\
void DYNARRAY_TYPE_NAME##_destroy (DYNARRAY_TYPE_NAME** d) { \
if ((*d) == NULL) \
return; \
FREE_SAFE((*d)->arr); \
FREE_SAFE((*d)); \
} \
\
void DYNARRAY_TYPE_NAME##_append (DYNARRAY_TYPE_NAME* d, DYNARRAY_ITEM_TYPE item) { \
if (d->capacity == 0) {\
d->capacity = 8; \
REALLOC_SAFE(d->arr, d->capacity, DYNARRAY_ITEM_TYPE); \
} \
else if (d->size == d->capacity) { \
size_t new_cap = 2 * d->capacity; \
REALLOC_SAFE(d->arr, new_cap, DYNARRAY_ITEM_TYPE); \
d->capacity = new_cap; \
} \
d->arr[d->size] = item; \
d->size++; \
}
#endif
Finally, let us actually use this. In the following header, we define two types of arrays:
// arrays.h
#ifndef ARRAYS_H
#define ARRAYS_H
#include "dynarr.h"
GEN_DYNARR_DECL(doublearr, double);
GEN_DYNARR_DECL(intarr, int);
#endif
Next, let us accompany the header with the following file:
// arrays.c
#include "arrays.h"
GEN_DYNARR_DEF(doublearr, double);
GEN_DYNARR_DEF(intarr, int);
Now, we can use it in a "dummy" main program:
// main.c
#include "arrays.h"
int main(void) { | {
"domain": "codereview.stackexchange",
"id": 43081,
"lm_label": 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
Now, we can use it in a "dummy" main program:
// main.c
#include "arrays.h"
int main(void) {
doublearr* a1 = doublearr_create();
doublearr_append(a1, 1.1);
doublearr_append(a1, 2.2);
doublearr_destroy(&a1);
intarr* a2 = intarr_create();
intarr_append(a2, 1);
intarr_append(a2, 2);
intarr_destroy(&a2);
return 0;
}
Of course, such an array is not yet useful, however, my main focus here is the concept.
Answer: Overall
A better than usual generic code.
Usage symmetry
Usage took the form of
namearr* x = namearr_create(); // creation
namearr_fun1(x, args); // x not changed
namearr_fun2(&x, args); // x changed
As functions are added the asymmetry of needing to pass x or &x or assign becomes less clear.
I recommend a uniform style:
namearr_fun(&x, args); // x may or may not change - use `const` to distinguish.
To approach RAII, perhaps 1 exception namearr* x = namearr_create();.
Keyword in middle?
Consider leading with keyword
// GEN_DYNARR_DECL(doublearr, double);
// GEN_DYNARR_DEF(doublearr, double);
DYNARR_GEN_DECL(doublearr, double);
DYNARR_GEN_DEF(doublearr, double);
// or simply
DYNARR_DECL(doublearr, double);
DYNARR_DEF(doublearr, double);
Increase uniformity in names
dynarr.h, DYNARRAY to dynarray.h, DYNARRAY or dynarr.h, DYNARR.
type not needed in *ALLOC_SAFE()
Example
//#define REALLOC_SAFE(ptr, size, type) \
...
// type* p = realloc(ptr, (size) * sizeof(type)); \
#define REALLOC_SAFE(ptr, size) \
...
void* p = realloc(ptr, (size) * sizeof *(ptr)); \
NULL ?
_destroy() sets the pointer to NULL, OK. Yet other functions like _append() do not check if the pointer is NULL. So I guess code is hoping for observable undefined behavior when an append happens after the destroy rather than defined behavior? | {
"domain": "codereview.stackexchange",
"id": 43081,
"lm_label": 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
Magic 8
"I set an initial capacity to 8 to save a few reallocations in the beginning." assumes most arrays will be big. If most are small, then wasted space.
So save memory or time? One of those is finite.
I like new_size = old_size*2 + 1. Handles zero well and approach to SIZE_MAX.
Missing functions
Look forward to the size_t _size(), size_t _safe_set(index, data), type _safe_get(), int _apply(int fun(void * state, type), void * state), type _safe_sort(tbd) functions.
Suicide notes deserve stderr
// printf("Error in %s at line %d: %s - terminating program.\n",
// __FILE__, __LINE__, msg);
fprintf(stderr, "Error in %s at line %d: \"%s\" - terminating program.\n",
__FILE__, __LINE__, msg);
Given an error that leads to exit, I like to put sentinels about the msg to add clarity to a potentially rarely tested message. | {
"domain": "codereview.stackexchange",
"id": 43081,
"lm_label": 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++, c++17, circular-list
Title: C++ circular buffer that guarantees contiguous data
Question: For interfacing with C-API that requires data in one contiguous block
I came up with the following, which seems to work nicely, but I wanted
to see if I didn't miss anything crucial. Drawback is of course the reserved
size, which is double - but fine within my use cases.
Requirements for the ring buffer:
access to data in one contiguous block always guaranteed
pushing back of one or more elements
#include <array>
#include <initializer_list>
#include <iterator>
#include <type_traits>
template <typename T, size_t N>
class ContiguousRingBuffer
{
public:
using const_iterator = std::array<T, N*2-1>::const_iterator;
using iterator = std::array<T, N*2-1>::iterator;
// -------------------------------------------------------------------------
ContiguousRingBuffer() = default;
ContiguousRingBuffer(ContiguousRingBuffer&& o) = default;
ContiguousRingBuffer(ContiguousRingBuffer const&) = default;
/// Iterator pair constructor.
template <typename It>
ContiguousRingBuffer(It beg, It end)
{
using from_value_type = typename std::iterator_traits<It>::value_type;
using to_value_type = typename std::iterator_traits<iterator>::value_type;
static_assert(std::is_nothrow_convertible_v<from_value_type, to_value_type>,
"from value type must be convertible to buffer type.");
if (static_cast<size_t>(std::distance(beg, end)) > N) {
m_end = std::copy(std::prev(end, N), end, m_data.begin());
}
else {
m_end = std::copy(beg, end, m_data.begin());
}
}
/// Initialize from any other ContinguousBuffer<S, M>
template <typename S, size_t M>
ContiguousRingBuffer(ContiguousRingBuffer<S, M> const& o)
: ContiguousRingBuffer(o.cbegin(), o.cend())
{} | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
/// Initializer list constructor.
ContiguousRingBuffer(std::initializer_list<T> init)
: ContiguousRingBuffer(init.begin(), init.end())
{}
ContiguousRingBuffer& operator=(ContiguousRingBuffer&&) = default;
ContiguousRingBuffer& operator=(ContiguousRingBuffer const&) = default;
// -------------------------------------------------------------------------
iterator begin() { return m_beg; }
iterator end() { return m_end; }
const_iterator cbegin() const { return m_beg; }
const_iterator cend() const { return m_end; }
// -------------------------------------------------------------------------
T& operator[](size_t pos) { return *std::next(m_beg, pos); }
T const& operator[](size_t pos) const { return *std::next(m_beg, pos); }
// -------------------------------------------------------------------------
constexpr size_t size() const { return std::distance(m_beg, m_end); }
constexpr auto capacity() const { return N; }
T* data() { return &(*m_beg); }
// -------------------------------------------------------------------------
void clear() { m_beg = m_end = m_data.begin(); }
bool is_empty() const { return size() == 0; }
// -------------------------------------------------------------------------
void pop_back()
{
if (m_beg != m_end) {
--m_end;
}
}
// -------------------------------------------------------------------------
void pop_back(size_t num_elements)
{
if (num_elements < size()) {
m_end = std::prev(m_end, num_elements);
}
else {
clear();
}
} | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
// -------------------------------------------------------------------------
void push_back(T&& value)
{
if (m_end != m_data.end())
{
*(m_end++) = std::forward<T>(value);
if (size() > N) { ++m_beg; }
}
else
{
std::swap(m_beg, m_end);
*(m_end++) = std::forward<T>(value);
m_beg = m_data.begin();
std::copy(m_end, m_data.end(), m_beg);
}
}
// -------------------------------------------------------------------------
template <typename It>
void push_back(It beg, It end)
{
using from_value_type = typename std::iterator_traits<It>::value_type;
using to_value_type = typename std::iterator_traits<iterator>::value_type;
static_assert(std::is_nothrow_convertible_v<from_value_type, to_value_type>,
"from value type must be convertible to buffer type.");
// If inserted size is equal or larger than N, just copy the last N
// elements of the range and reset m_beg and m_end
const auto s = std::distance(beg, end);
if (static_cast<size_t>(s) >= N)
{
std::copy(std::prev(end, N), end, m_data.begin());
m_beg = m_data.begin();
m_end = std::next(m_beg, N);
return;
}
const auto space_left = std::distance(m_data.begin(), m_beg);
const auto sz = std::distance(m_beg, m_end);
// Check if there is enough space to copy/append the elements at the end
if (static_cast<size_t>(s) <= 2*N - space_left - 1 - sz)
{
m_end = std::copy(beg, end, m_end);
if (static_cast<size_t>(sz+s) > N) {
m_beg = std::prev(m_end, N);
}
return;
}
m_beg = m_data.begin();
m_end = std::copy(std::prev(m_end, N-s), m_end, m_data.begin());
m_end = std::copy(beg, end, m_end);
}
private:
std::array<T, N*2-1> m_data;
iterator m_beg = m_data.begin();
iterator m_end = m_beg;
}; | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
Answer: Design review
The basic idea isn’t bad if you really need a single, contiguous view of the ring buffer’s contents at all times. I’ve never seen a case where that’s actually necessary—whenever I’ve used a ring buffer that needed to be contiguous, such as in audio code, it’s always been fine to view it as two contiguous chunks—but if your case requires it, sure. The cost is the extra memory—more than double the usual—and the need to occasionally move the whole thing back, but, again, if you really need it, then that cost is probably acceptable.
There are a couple of problems with the way you’ve chosen to implement it, though, mostly stemming from the fact that you’re using an array of T under the hood.
A broken abstraction
Before I get to that, though, there is a bit of weirdness in your ring buffer’s interface. Normally, a ring buffer is, basically, a queue: first in, first out (FIFO). The idea is that you push to the end of the buffer, and pop from the start, so if your pushes and pops are equally interleaved, then the contents of the buffer are continuously changing, always holding the newest data. Visually, that looks like this:
(This buffer is 8 items large. Dots indicate empty slots.)
At the start: ........
After pushing 4 times: ABCD....
After popping 2 times: ..CD....
After pushing 4 times: ..CDEFGH
After popping 1 time: ...DEFGH
After pushing 1 time: I..DEFGH
After popping 2 times: I....FGH
AFter pushing 2 times: IJK..FGH
After popping 2 times: IJK....H
AFter pushing 2 times: IJKLM..H
After popping 2 times: .JKLM...
AFter pushing 2 times: .JKLMNO.
After popping 2 times: ...LMNO.
AFter pushing 2 times: Q..LMNOP | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
You can see how once the pushing and popping settles into an equilibrium of two-and-two at a time, you get a sliding view of 4–6 letters that works its way through the alphabet. That’s the point of a ring buffer: it always contains the most recently added items.
Your class, however, only has pushes and pops at the end. That’s first in, last out (FILO; or last in, first out: LIFO… same difference). That’s a stack.
With the same operations, this is what your class’s data looks like:
At the start: ........
After pushing 4 times: ABCD....
After popping 2 times: AB......
After pushing 4 times: ABEFGH..
After popping 1 time: ABEFG...
After pushing 1 time: ABEFGI..
After popping 2 times: ABEF....
AFter pushing 2 times: ABEFJK..
After popping 2 times: ABEF....
AFter pushing 2 times: ABEFLM..
After popping 2 times: ABEF....
AFter pushing 2 times: ABEFNO..
After popping 2 times: ABEF....
AFter pushing 2 times: ABEFPQ..
You can see that:
The buffer doesn’t contain the 4–6 most recently pushed items. Rather, once things settle, the first 4 items remain untouched, and only the last two keep getting removed/replaced.
Because the buffer is never full, the last few slots never get touched.
When your buffer does become full, only then does it start eating elements at the start. So in that sense… yeah, it’s a ring buffer. In other words, your class only acts like a ring buffer if you never pop. So long as you keep pushing elements, you’ll eventually fill up the buffer and start dropping the oldest stuff, as a ring buffer should. The moment you try to remove anything, it breaks the abstraction.
A ring buffer interface only needs push() (which acts like push_back()) and pop() (which acts like pop_front()). If you want to add push_front() and/or pop_back()… then it’s not really a ring buffer any more, it’s more like a “circular deque”.
For an interface that better suits the ring buffer abstraction: | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
You just need push() and pop().
You might want to have emplace(), too, as a smarter push().
Maybe a try_push() (and try_emplace()) that only pushes if there’s room. And if pop() throws an error or UB when the buffer is empty, then a try_pop() as well.
If you want to be API compatible with standard containers like std::deque and std::list (and only those), then you could also have push_back() and pop_front() just as aliases for push() and pop() (and emplace_back(), too).
pop_back() might have some use, I guess; there may be situations where you might want to cancel/replace the most recently added items. But it would probably be better named remove_last() and replace_last(). pop_back() could be an alias for remove_last().
size() lies
Suppose I create this very simple type:
struct object_t
{
static std::size_t count;
object_t() noexcept { ++count; }
object_t(object_t const&) noexcept { ++count; }
object_t(object_t&&) noexcept { ++count; }
~object_t() { --count; }
auto operator=(object_t const&) noexcept -> object_t& = default;
auto operator=(object_t&&) noexcept -> object_t& = default;
};
std::size_t object_t::count = 0;
And then I put in your ring buffer, and while trying to debug a complex program, I notice this behaviour:
auto main() -> int
{
ContiguousRingBuffer<object_t, 10> buf;
std::cout << "size of buffer: " << buf.size() << '\n';
std::cout << "number of objects: " << object_t::count << '\n';
}
// output:
// size of buffer: 0
// number of objects: 19 | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
// output:
// size of buffer: 0
// number of objects: 19
Now… something is very wrong. Something is broken and lying to me. Either there really are no objects in the buffer, and there’s some bug causing object_t::count to be incorrect… or there are 19 objects in the buffer, and buf.size() is giving the wrong number for some reason.
Since the code above is so trivial, the answer is obvious. But in a real-world, complex program, this could be an ABSOLUTELY INFURIATING debugging issue.
It gets worse. More on that in a moment.
The root issue here is that you’re using a std::array<T, (2 * N) - 1> internally, so the moment I instantiate ContiguousRingBuffer<object_t, 10>, there are \$( 2 \times 10 ) - 1 = 19\$ default-constructed instantiations of object_t… even while the buffer claims to be empty. But the real problem is that your class is lying to me. It’s obvious in your implementation of size(). The correct implementation of size() would be:
constexpr auto size() const noexcept -> std::size_t { return m_data.size(); } | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
But your implementation of size() doesn’t actually tell me how many objects are in an instance… it just tells me the number of objects you care about, and you ignore the rest. That’s bad form.
A static buffer may be impossible
And, as I said, it gets worse. Much worse.
Because, first of all, the number of active objects may not be irrelevant at all. This may not be a simple matter of mismatched counts (bad as that would be). Suppose I use your ring buffer in a low-level kernel routine (where ring buffers are very common) to keep track of processes, with the logic being that there can only be 32 processes open at a time, so: ContiguousRingBuffer<process_t, 32>. Unbeknownst to me, because it’s a hidden detail in the internals of your class, there are actually 63 processes created… and they’re all created at once… right at the start. Then I’m scratching my head about why my kernel is so slow, using so much memory, and crashing randomly.
The problem can show up in a number of ways. Let’s say I’m using the ring buffer for handles to a fixed number of resources. Like, say the system supports a maximum number of 4 open connections to something, and if you try to open a 5th, it blocks until one of those four closes. So I make a ContiguousRingBuffer<connection_t, 4>. Internally, it default constructs 7 connection objects, but that’s no problem, because a default-constructed connection object is closed. So my program starts, no problem, and begins to run, and eventually creates 4 connections. Then I try to create a 5th… and what I expect to happen is that this new connection will overwrite the oldest connection, destructing the object—and the connection is closed in the destructor—then opening the new one. It should work… except… it doesn’t. The program deadlocks. This will happen at random times, and might not even happen at all if the program never happens to need more than 4 connections in a run. It is an intermittent bug… the worst kind. | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
And it gets even worse. Because what if there’s some reason I can’t have objects being default constructed. If they’re simply not default-constructible at all, then the program won’t even compile. But if they are default-constructible, but for some reason, I never want one to be default constructed (because maybe when the class is default-constructed, it does default behaviour that I can’t have, so I always construct with a flag that disables it), then… I’m pretty well screwed, because there’s no way to stop your buffer from default constructing a bunch of objects.
This is something a lot of C++ programmers don’t understand. In particular, I see far too many people thinking that std::vector is just a dynamic array. They think it’s a really basic thing, and they think it’s a simple project they can attempt for practice. It’s not; it’s not any of those things; std::vector is horrifyingly complex… it’s quite easily one of the most complex classes in the entire standard library. Even though your class doesn’t use dynamic memory, it’s falling into the same trap that almost all attempts at making std::vector fall into.
I’m just going to tell you what you need to do to get correct behaviour… but I’m not going to give full details, and I’ll have to skip over some important stuff, because, and again, I can’t stress this enough: WHAT YOU ARE ATTEMPTING TO DO IS ONE OF THE HARDEST THINGS TO DO IN C++ (except that, luckily, you don’t have to worry about dealing with allocators as well). | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
You can’t just use std::array<T, ...>, because that will automatically (default-)construct all the Ts. You need to use std::array<std::byte, sizeof(T) * ...>.
You need to make sure that array is properly aligned.
When you push an item, you need to construct it in place with construct_at() (or uninitialized_copy() for multiple items). Only update m_beg/m_end if that succeeds.
When you pop an item, you need to destroy it with destroy_at() (or destroy() for multiple items).
You need to remember all the other manual memory/object management stuff, like, manually copying/moving, manually destroying everything in the destructor, and so on. | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
It may also be the case that it is IMPOSSIBLE to properly implement some of the operations of your class. For example, it may be impossible to implement copy assignment. With std::vector, you can implement it using a temporary buffer, and then swapping pointers if it succeeds… if it fails, you just dump the temporary buffer, and the original data is untouched. But because you’re using static memory, you don’t have the option of using a temporary buffer; you must destroy the existing data, so if something fails partway… you’re screwed. Even push_back() may be impossible to implement safely. It may still be possible… I’d have to think about it to be sure, because this is all really, really complicated stuff.
Other stuff
Okay, let’s say you don’t care about the extra, invisible objects in your class. You only intend to use the ring buffer with trivial types, so none of the problems I mentioned really matter to you.
You should really consider making a specific iterator type for your class. std::array<T, ...>::iterator is just T*. That does the job, but is dangerous, because you can very easily mix it up with other, random pointers. A bespoke iterator leverages the type system, which is where most of the power of C++ lies.
Now, granted, if you’re stuck using C++17, then you can’t mark an iterator as contiguous. However….
If you can move to C++20, you absolutely should. C++20 is, by far, the biggest update of the language since C++11. It’s already 2022; there’s no point lingering in C++17 anymore.
And, not to put too fine a point on it… you’re already using C++20, whether you realize it or not. You may have tagged this code C++17… but it ain’t C++17 code. Don’t believe me? Try compiling it with a compiler that doesn’t support C++20, or explicitly set the version to C++17. You may be surprised. | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
And once you accept that you’re already using C++20, so much more opens up. Now you can make your iterators truly contiguous (without falling back on using T* as iterator). You can take advantage of concepts to make your code so much more expressive and powerful. You can use the range library to simplify and enhance safety. You can make it constexpr even when objects are being in-place constructed on the fly (rather than all at once when the buffer is constructed). (You can even make it constexpr if dynamically allocated… but you’d probably want allocator support in that case, and that makes things much more complicated.)
Finally, two last things.
Comments. Need more. You don’t need to explain the base mechanics of the code, but you do need to explain the logic of why you did things the way you did. That includes high-level stuff, like why your internal buffer is almost twice the size of what the buffer is supposed to hold… the kind of stuff that requires digging into the actual code to figure out; if someone has to sit down and carefully pore through your entire class to understand the most basic design points… that’s bad.
You also need to comment any non-obvious low-level details. For example, why, in the single item version of push_back(), in the else branch, do you swap m_beg and m_end? I honestly can’t figure this out. I’ve been scratching my head, wondering if maybe it helps with exception guarantees or something.
And last: tests. Code without tests is garbage code; utterly useless to me, and most people—no project worth its salt will accept untested code. You should use a proper testing framework—even a mediocre framework like GoogleTest is better than nothing—but even hacking your own tests is at least something. And best practice is to write the tests before the actual code: that helps you think more carefully about how you design the code.
In point of fact, you have some nasty bugs in your code that would have been trivially caught by some basic tests. | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
Design review summary | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
Consider a more appropriate API. There’s nothing wrong with trying to look like a standard container, but if there’s a better interface for cases where you are using the class specifically because you want a ring buffer, then it would be nice to support that.
Because your class uses static allocation and pre-constructs everything, it is broken for anything but trivial types. Either:
Give up on using static allocation. This will probably mean adding allocator support, and so on.
Keep static allocation, but give up on pre-constructing. In other words, don’t use std::array<T, ...>; use a raw memory buffer (an appropriately aligned array of bytes), and placement-construct objects in it. For safety’s sake, you will probably have to require no-fail copy construction, copy assignment, move construction, and move assignment.
Keep static allocation and pre-constructing, but give up on supporting anything but trivial types.
Make bespoke iterators; don’t use T* as the iterator type.
Comments!
Tests!
Embrace C++20.
Code review
#include <array>
#include <initializer_list>
#include <iterator>
#include <type_traits>
You’re missing a number of includes. At a glance, I’d say you need at least <algorithm> (for std::copy()) and <utility> (for std::forward(); well, technically std::move(), but we’ll get to that later).
template <typename T, size_t N>
class ContiguousRingBuffer
It’s std::size_t.
using const_iterator = std::array<T, N*2-1>::const_iterator;
using iterator = std::array<T, N*2-1>::iterator; | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
I already mentioned in the design review that you should probably make bespoke iterators.
Also, if you really want this to be C++17, you’re gonna need some typenames here.
Now, if you want this class to be recognized as a container, you’re going to need a bunch more aliases, like value_type, size_type, reference, and so on.
Another thing you might want to consider is adding static_asserts to constrain T. Exactly which ones you’ll need depend on how you want to solve the static buffer problem I discussed in the design review. (For example, you might want static_assert(std::is_trivial_v<T>)).
ContiguousRingBuffer() = default;
You’re probably going to want to add a lot to most of the declarations in this class, mostly for the sake of efficiency. For just this default constructor, you’ll probably want:
constexpr ContiguousRingBuffer() noexcept(std::is_nothrow_default_constructible_v<T>) = default;
You’ll probably want constexpr everywhere, and noexcept almost everywhere, possibly qualified.
ContiguousRingBuffer(ContiguousRingBuffer&& o) = default;
ContiguousRingBuffer& operator=(ContiguousRingBuffer const&) = default;
While you may not care enough to add noexcept to the copy operations, it’s important to make moving noexcept if at all possible.
(Is it possible for your type? Only if T is no-fail default constructible and move-assignable or no-fail move-constructible.)
But there’s a bug lurking here. Consider copy construction. The internal array, m_data, is copied from the argument’s internal array… no problem here. But m_beg and m_end are also copied… and they’re pointers to the argument’s internal array… not this’s internal array.
So what will happen is:
auto buf_1 = ContiguousRingBuffer<int, 5>{0, 1, 2, 3, 4};
auto buf_2 = buf_1;
// I want to change the first element of buf_2:
*(buf_2.begin()) = 99;
// But... the contents of the two objects are now:
// buf_1: 99, 1, 2, 3, 4
// buf_2: 0, 1, 2, 3, 4 | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
You see? The iterators point to the wrong data.
My advice? Rather than storing pointers, store indices. Numbers can be copied without worry. And it doesn’t really add any complexity. If you store the start index as m_start and the size as m_size, then begin() would just return m_data.data() + m_start (rather than m_beg), and size() would just return m_size (rather than m_end - m_beg).
template <typename It>
ContiguousRingBuffer(It beg, It end)
{
using from_value_type = typename std::iterator_traits<It>::value_type;
using to_value_type = typename std::iterator_traits<iterator>::value_type;
static_assert(std::is_nothrow_convertible_v<from_value_type, to_value_type>,
"from value type must be convertible to buffer type.");
if (static_cast<size_t>(std::distance(beg, end)) > N) {
m_end = std::copy(std::prev(end, N), end, m_data.begin());
}
else {
m_end = std::copy(beg, end, m_data.begin());
}
}
To future-proof your class, you might want to support an iterator/sentinel pair, rather than just iterator/iterator. You don’t have any other arity 2 constructors, so even in C++17, this is no problem.
Of course, if you just accept that you’re already using C++20, then you can dive right in and do:
template <std::input_iterator It, std::sentinel_for<It> Sen>
requires std::indirectly_copyable<It, T*>
constexpr ContiguousRingBuffer(It beg, Sen end)
{
std::ranges::copy(std::ranges::subrange{beg, end} | std::ranges::views::take(N), m_data.begin());
}
Without C++20… well, first of all, std::is_nothrow_convertible_v doesn’t exist.
More frustratingly, without C++20, you have an issue: your code won’t work properly with input iterators. The problem is that with input iterators, you only get one pass. Once you do std::distance(beg, end), you’ve blown your one pass, so the following std::copy() will do nothing.
You have two options: | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
Give up, and restrict the iterator type to forward iterator or better. In C++17, you’d do that with static_assert(std::is_base_of<std::forward_iterator_tag, typename std::iterator_traits<It>::iterator_category>), possibly using SFINAE.
Write a new algorithm that only copies up to a certain number of elements. I’ve had something like this in my toolkit since C++98, called copy_upto(It, It, Out, std::ptrdiff_t), with multiple, optimized variants. You’d need something like that. (Or you could be lazy and just implement the algorithm ad hoc in place.)
/// Initialize from any other ContinguousBuffer<S, M>
template <typename S, size_t M>
ContiguousRingBuffer(ContiguousRingBuffer<S, M> const& o)
: ContiguousRingBuffer(o.cbegin(), o.cend())
{}
/// Initializer list constructor.
ContiguousRingBuffer(std::initializer_list<T> init)
: ContiguousRingBuffer(init.begin(), init.end())
{}
If you make a general range constructor, you could replace both of these with it, and at the same time be able to convert any range.
But even if you stick with just these, you probably want to make them explicit, because they could be very expensive.
ContiguousRingBuffer& operator=(ContiguousRingBuffer&&) = default;
ContiguousRingBuffer& operator=(ContiguousRingBuffer const&) = default;
As mentioned previously, you should really try hard to make move ops noexcept. If you’re using static allocation, then this won’t be easy.
And, of course, you have the same bug here as in the copy/move constructors.
iterator begin() { return m_beg; }
iterator end() { return m_end; }
const_iterator cbegin() const { return m_beg; }
const_iterator cend() const { return m_end; }
You probably want constexpr and noexcept everywhere here.
You’ll also want const versions of begin() and end().
T& operator[](size_t pos) { return *std::next(m_beg, pos); }
T const& operator[](size_t pos) const { return *std::next(m_beg, pos); } | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
This is really just a style thing, but I don’t see the point of using generic operations like std::next() when what you’re doing is clearly not generic. I mean, you know you have a contiguous buffer… that’s literally the whole point of the class. So you can just do *(m_beg + pos). The next() function really just obscures what’s going on for no benefit.
constexpr size_t size() const { return std::distance(m_beg, m_end); }
constexpr auto capacity() const { return N; }
T* data() { return &(*m_beg); }
// -------------------------------------------------------------------------
void clear() { m_beg = m_end = m_data.begin(); }
bool is_empty() const { return size() == 0; }
Gonna want noexcept for everything here.
Need a const version of data().
For compatibility with standard containers, it’s empty(), not is_empty().
You’ll also want a max_size() function. (I know, it’s stupid and useless, but it’s part of the container requirements.) And while we’re at it, you’ll want a swap() member function. (You don’t really need non-member swap, because it will be synthesized from your move ops. You can add it if you want more efficiency, though.)
You’ll also want operator == and !=, at least. Unfortunately, you can’t use defaults.
void pop_back()
{
if (m_beg != m_end) {
--m_end;
}
}
Note that you’re not actually removing anything from the buffer. Whatever was at the end is still there. You just moved a pointer.
void push_back(T&& value)
{
if (m_end != m_data.end())
{
*(m_end++) = std::forward<T>(value);
I’m guessing by your use of && and std::forward() that you intend for this function to use perfect forwarding. Unfortunately, it does not.
Perfect forwarding works thanks to two things: template parameter deduction and reference collapsing. When you write a function like this:
template <typename U>
void func(U&&);
Then when you call it normally, U gets deduced. | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
Then when you call it normally, U gets deduced.
When you call it with an lvalue foo, it gets deduced to foo& (or foo const&), and (foo&)&& reference collapses to foo& (or (foo const&)&& collapses to foo const&).
When you call it with an rvalue foo, it gets deduced to foo (or foo&&), and (foo)&& reference collapses to foo&& (and (foo&&)&& collapses to foo&&).
Finally, when you do std::forward<U>() and U is foo& or foo const&, std::forward() just expands to… nothing.
When U is foo or foo&&, std::forward() expands to std::move().
That’s how perfect forwarding works.
But when you do:
template <typename T>
struct foo
{
void func(T&&);
};
auto f = foo<int>{};
f.func(...); // <--
… no deduction is happening. It doesn’t matter what you write for the ..., T is always int. That was set in stone in the previous line. f.func() will always take int&&. No deduction means no perfect forwarding.
So for any ContiguousRingBuffer<X, N>, push_back() will always take X&&. That means it always takes only rvalues.
Had you bothered to test your code, you would have noticed this immediately:
ContiguousRingBuffer<int, 5> buf;
buf.push_back(42); // works with rvalues
auto i = 69;
buf.push_back(i); // won't compile; doesn't accept lvalues
If you want perfect forwarding, you need to re-enable deduction. You need to do something like this:
template <typename T, size_t N>
class ContiguousRingBuffer
{
// ... [snip] ...
template <typename U>
void push_back(U&& value)
{
// ... [snip] ...
// you can use std::forward<U>(value) in here to perfect forward value
}
// ... [snip] ...
};
auto buf = ContiguousRingBuffer<double, 8>{}; // T is set as double
buf.push_back(3.14); // U is deduced as (rvalue) `double`
auto val = 6.28;
buf.push_back(val); // U is deduced as `double&` | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, c++17, circular-list
auto val = 6.28;
buf.push_back(val); // U is deduced as `double&`
You’ll probably want to constrain the deduction, though:
template <typename U>
requires std::same_as<std::remove_cvref_t<U>, std::remove_cvref_t<T>>
void push_back(U&& value)
{
// ... [snip] ...
}
This will make sure U only gets deduced to lvalue or rvalue Ts.
One more thing: in the else block:
std::swap(m_beg, m_end);
*(m_end++) = std::forward<T>(value);
You know that m_end is m_data.end()… but you never check what m_beg is. What if m_beg equals m_end? For example, if someone popped everything out of the buffer. (Note I don’t think this can happen with your current API, because your current API doesn’t actually work like a ring buffer and pop from the front. But if you add that capability, then you might get this problem.)
template <typename It>
void push_back(It beg, It end)
{
This has the same problem as the constructor: it won’t work for input iterators, because the call to std::distance(beg, end) at the beginning will eat up the entire sequence before you get around to reading it.
I’m also not a fan of the pattern:
if (...)
{
// abc
return;
}
// xyz
I prefer:
if (...)
{
// abc
}
else
{
// xyz
}
But honestly, once functions start getting longer than ~10 lines, it’s probably time to break them up into smaller functions.
That’s probably enough of a review. I can’t dig much more deeply into the logic when there are no comments to explain what’s supposed to be going on, and no tests that can give me confidence that everything actually works. More than anything else, that’s what you really need to improve this code: comments, and tests. Once you have good, comprehensive tests, then you have the start of a useful library. | {
"domain": "codereview.stackexchange",
"id": 43082,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, circular-list",
"url": null
} |
c++, linked-list, c++17
Title: Forward linked list implementation in C++
Question: I wrote a linked list implementation in C++ to learn the concepts about linked lists as well as C++(17). I decided to use std::unique_ptr to help me avoid leaks and also took a lot of inspiration from std::forward_list.
I am not so worried about bugs, because I wrote some tests and they seem to pass. I am interested in knowing more about what is missing from my implementation compared to a gcc implementation and what the weaknesses are of my implementation. Also, interested in suggestions for making some parts of the implementation simpler (especially thinking about the complexity of merge and sort functions).
#ifndef CUSTOM_LINKED_LIST_HPP
#define CUSTOM_LINKED_LIST_HPP
#include <cstddef>
#include <iterator>
#include <memory>
#include <sstream>
#include <type_traits>
#include <cassert>
#include <iostream>
#include <utility>
namespace custom {
struct node_base {
node_base(): next(nullptr) {}
node_base(std::unique_ptr<node_base>&& n): next(std::move(n)) {}
std::unique_ptr<node_base> next;
};
template<typename T>
struct node : node_base {
node(std::unique_ptr<node_base>&& n, T d): node_base(std::move(n)), data(std::move(d)) {}
T data;
};
template<typename T, typename node_ptr = node_base*>
class linked_list_forward_iterator {
public:
// https://www.internalpointers.com/post/writing-custom-iterators-modern-cpp
using iterator_category = std::forward_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = T;
using reference = T&;
using pointer = T*;
linked_list_forward_iterator(node_ptr ptr): m_ptr(ptr) {};
// copy constructor, copy assignment operator, destructor= default
reference operator*() const {
return data_node()->data;
}
pointer operator->() {
return &data_node()->data;
} | {
"domain": "codereview.stackexchange",
"id": 43083,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list, c++17",
"url": null
} |
c++, linked-list, c++17
pointer operator->() {
return &data_node()->data;
}
bool operator==(linked_list_forward_iterator<T, node_ptr> const& other) const {
return this->m_ptr == other.m_ptr;
}
bool operator!=(linked_list_forward_iterator<T, node_ptr> const& other) const {
return !(*this == other);
}
// prefix increment
node_ptr operator++() {
assert(m_ptr);
m_ptr = m_ptr->next.get();
return m_ptr;
}
// postfix increment
node_ptr operator++(int) {
linked_list_forward_iterator<T, node_ptr> tmp = *this;
++(*this);
return tmp.m_ptr;
}
node<T>* data_node() const {
return static_cast<node<T>*>(m_ptr);
}
node_ptr m_ptr;
};
template<typename T>
class linked_list {
static_assert(std::is_object_v<T>, "T must be object");
public:
using value_type = T;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reference = T&;
using const_reference = T const&;
using pointer = T*;
using const_pointner = T const*;
using iterator = linked_list_forward_iterator<T>;
using const_iterator = linked_list_forward_iterator<const T>;
// constructors && assignments
linked_list(): m_head(std::make_unique<node_base>(nullptr)) {}
explicit linked_list(size_type count): linked_list(count, T{}) {}
explicit linked_list(size_type count, const_reference value)
: linked_list()
{
node_base* last_node = m_head.get();
for (size_type i = 0; i < count; i++) {
last_node->next = std::make_unique<node<T>>(nullptr, value);
last_node = last_node->next.get();
}
}
explicit linked_list(std::initializer_list<T> init): linked_list(init.begin(), init.end()) {} | {
"domain": "codereview.stackexchange",
"id": 43083,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list, c++17",
"url": null
} |
c++, linked-list, c++17
explicit linked_list(std::initializer_list<T> init): linked_list(init.begin(), init.end()) {}
template<class InputIt>
linked_list(InputIt first, InputIt last)
: linked_list()
{
node_base* last_node = m_head.get();
for (auto it = first; it != last; ++it) {
last_node->next = std::make_unique<node<T>>(nullptr, *it);
last_node = last_node->next.get();
}
}
linked_list(const linked_list& other): linked_list(other.cbegin(), other.cend()) {}
linked_list(linked_list&& other) = default;
~linked_list() = default;
linked_list& operator=(linked_list&& other) = default;
linked_list& operator=(const linked_list& other) {
linked_list<T> copy {other};
swap(copy);
return *this;
}
linked_list& operator=(std::initializer_list<T> ilist) {
*this = linked_list<T>(ilist);
return *this;
}
void assign(size_type count, const T& value) {
*this = linked_list<T>(count, value);
}
template<class InputIt>
void assign(InputIt first, InputIt last) {
*this = linked_list<T>(first, last);
}
void assign(std::initializer_list<T> ilist) {
*this = linked_list<T>(ilist);
}
// Element access
T& front() {
assert(m_head);
return *begin();
}
T const& front() const {
assert(m_head);
return *cbegin();
}
// capacity
size_type size() const {
size_type size = 0;
for (auto it = cbegin(); it != cend(); it++) {
size++;
}
return size;
}
bool empty() const {
return !m_head->next;
}
// iterators
iterator before_begin() {
return iterator(m_head.get());
}
const_iterator before_begin() const {
return cbefore_begin();
}
const_iterator cbefore_begin() const {
return const_iterator(m_head.get());
} | {
"domain": "codereview.stackexchange",
"id": 43083,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list, c++17",
"url": null
} |
c++, linked-list, c++17
const_iterator cbefore_begin() const {
return const_iterator(m_head.get());
}
iterator begin() {
return iterator(m_head->next.get());
}
const_iterator begin() const {
return cbegin();
}
const_iterator cbegin() const {
return const_iterator(m_head->next.get());
}
iterator end() {
return nullptr;
}
const_iterator end() const {
return cend();
}
const_iterator cend() const {
return nullptr;
}
// modifiers
iterator insert_after(const_iterator pos, T value) {
assert(pos.m_ptr);
node_base* my_node = pos.m_ptr;
std::unique_ptr<node_base> old_next = std::move(my_node->next);
std::unique_ptr<node<T>> new_node = std::make_unique<node<T>>(std::move(old_next), std::move(value));
my_node->next = std::move(new_node);
return my_node->next.get();
}
iterator insert_after(const_iterator pos, size_type count, const T& value) {
assert(pos.m_ptr);
iterator insert_pos = pos.m_ptr;
for (size_type i=0; i<count; i++) {
insert_pos = insert_after(insert_pos.m_ptr, value);
}
return insert_pos;
}
template<class InputIt>
iterator insert_after(const_iterator pos, InputIt first, InputIt last) {
assert(pos.m_ptr);
iterator insert_pos = pos.m_ptr;
for (auto it = first; it != last; it++) {
insert_pos = insert_after(insert_pos.m_ptr, *it);
}
return insert_pos;
}
iterator insert_after(const_iterator pos, std::initializer_list<T> ilist) {
return insert_after(pos, ilist.begin(), ilist.end());
} | {
"domain": "codereview.stackexchange",
"id": 43083,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list, c++17",
"url": null
} |
c++, linked-list, c++17
template<class... Args>
iterator emplace_after(const_iterator pos, Args&&... args) {
assert(pos.m_ptr);
node_base* my_node = pos.m_ptr;
std::unique_ptr<node_base> old_next = std::move(my_node->next);
std::unique_ptr<node<T>> new_node = std::make_unique<node<T>>(std::move(old_next), T(std::forward<Args...>(args...)));
my_node->next = std::move(new_node);
return my_node->next.get();
}
void push_front(const T& value) {
insert_after(cbefore_begin(), value);
}
void push_front(T&& value) {
insert_after(cbefore_begin(), std::move(value));
}
template<class... Args>
reference emplace_front(Args&&... args) {
return *emplace_after(cbefore_begin(), std::forward<Args...>(args...));
}
void pop_front() {
erase_after(cbefore_begin());
}
iterator erase_after(const_iterator pos) {
assert(pos.m_ptr);
node_base* my_node = pos.m_ptr;
std::unique_ptr<node_base> old_next = std::move(my_node->next);
std::unique_ptr<node_base> new_next = std::move(old_next->next);
my_node->next = std::move(new_next);
return my_node->next.get();
}
iterator erase_after(const_iterator first, const_iterator last) {
// get prev to last node
assert(first.m_ptr);
if (first == last) {
return last.m_ptr;
}
node_base* first_node = first.m_ptr;
node_base* prev_to_last_node = get_prev_to_last_node(first, last).m_ptr;
std::unique_ptr<node_base> new_next = std::move(prev_to_last_node->next);
first_node->next = std::move(new_next);
return first_node->next.get();
}
void clear() {
erase_after(cbefore_begin(), cend());
}
void swap(linked_list& other) {
using std::swap;
swap(m_head, other.m_head);
}
// operations | {
"domain": "codereview.stackexchange",
"id": 43083,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list, c++17",
"url": null
} |
c++, linked-list, c++17
// operations
void merge(linked_list& other) {
// assumes sorted list
if (this == &other) {
return;
}
auto it_1 = this->before_begin();
auto it_2 = other.before_begin();
while (!other.empty()) {
if (end() == it_1.m_ptr->next.get()) {
std::unique_ptr<node_base> node_to_move = std::move(it_2.m_ptr->next);
it_1.m_ptr->next = std::move(node_to_move);
continue;
}
T const& val1 = static_cast<node<T>*>(it_1.m_ptr->next.get())->data;
T const& val2 = static_cast<node<T>*>(it_2.m_ptr->next.get())->data;
if (val1 > val2) {
std::unique_ptr<node_base> node_to_move = std::move(it_2.m_ptr->next);
std::unique_ptr<node_base> old_next_of_node_to_move = std::move(node_to_move->next);
std::unique_ptr<node_base> new_next_of_node_to_move = std::move(it_1.m_ptr->next);
it_2.m_ptr->next = std::move(old_next_of_node_to_move);
node_to_move->next = std::move(new_next_of_node_to_move);
it_1.m_ptr->next = std::move(node_to_move);
}
it_1 ++;
}
}
void splice_after(const_iterator pos, linked_list& other) {
std::unique_ptr<node_base> old_next = std::move(pos.m_ptr->next);
auto before_end_it = get_prev_to_last_node(other.cbegin(), other.cend());
before_end_it.m_ptr->next = std::move(old_next);
std::unique_ptr<node_base> node_to_move = std::move(other.m_head->next);
pos.m_ptr->next = std::move(node_to_move);
} | {
"domain": "codereview.stackexchange",
"id": 43083,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list, c++17",
"url": null
} |
c++, linked-list, c++17
void splice_after(const_iterator pos, linked_list& other, const_iterator it) {
(void) other;
std::unique_ptr<node_base> old_next = std::move(pos.m_ptr->next);
std::unique_ptr<node_base> node_to_move = std::move(it.m_ptr->next);
std::unique_ptr<node_base> others_remaining_next = std::move(node_to_move->next);
it.m_ptr->next = std::move(others_remaining_next);
node_to_move->next = std::move(old_next);
pos.m_ptr->next = std::move(node_to_move);
}
void remove(const T& value) {
return remove_if([&value](const T& val){ return val == value; });
}
template<class UnaryPredicate>
void remove_if(UnaryPredicate p) {
auto it = before_begin();
while (it.m_ptr->next.get() != nullptr) {
T const& val = static_cast<node<T>*>(it.m_ptr->next.get())->data;
if (!p(val)) {
it++;
continue;
}
std::unique_ptr<node_base> remaining = std::move(it.m_ptr->next->next);
it.m_ptr->next = std::move(remaining);
}
}
void reverse() {
std::unique_ptr<node_base> following = nullptr;
std::unique_ptr<node_base> current = std::move(m_head->next);
std::unique_ptr<node_base> previous = nullptr;
while (current) {
following = std::move(current->next);
current->next = std::move(previous);
previous = std::move(current);
current = std::move(following);
}
m_head->next = std::move(previous);
} | {
"domain": "codereview.stackexchange",
"id": 43083,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list, c++17",
"url": null
} |
c++, linked-list, c++17
void unique() {
auto it = begin();
while (it.m_ptr->next.get() != nullptr) {
T const& previous_val = static_cast<node<T>*>(it.m_ptr)->data;
T const& val = static_cast<node<T>*>(it.m_ptr->next.get())->data;
if (previous_val == val) {
std::unique_ptr<node_base> node_to_remove = std::move(it.m_ptr->next);
std::unique_ptr<node_base> new_next = std::move(node_to_remove->next);
it.m_ptr->next = std::move(new_next);
} else {
it ++;
}
}
}
void sort() {
return sort([](const T& a, const T& b){ return a < b; });
}
template<class Compare>
void sort(Compare comp) {
merge_sort(m_head->next, comp);
}
private:
const_iterator get_prev_to_last_node(const_iterator first, const_iterator last) {
assert(first.m_ptr);
assert(first != last);
auto it = first;
auto prev_to_last_it = first;
while (it != last) {
prev_to_last_it = it++;
}
assert(prev_to_last_it.m_ptr);
assert(prev_to_last_it.m_ptr->next.get() == last.m_ptr);
return prev_to_last_it;
}
template<class Compare>
void merge_sort(std::unique_ptr<node_base>& node_to_sort, Compare const& comp) {
if (!node_to_sort || !node_to_sort->next) {
return;
}
std::unique_ptr<node_base> other {nullptr};
split_list(node_to_sort, other);
assert(node_to_sort);
assert(other);
assert(debug_size(node_to_sort)-debug_size(other) <= 1);
merge_sort(node_to_sort, comp);
merge_sort(other, comp);
assert(node_to_sort);
assert(other);
merge_sorted_nodes(node_to_sort, other, comp);
assert(node_to_sort);
assert(!other);
} | {
"domain": "codereview.stackexchange",
"id": 43083,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list, c++17",
"url": null
} |
c++, linked-list, c++17
void split_list(
std::unique_ptr<node_base>& begin_a,
std::unique_ptr<node_base>& begin_b
) {
assert(begin_a);
assert(!begin_b);
std::unique_ptr<node_base>* ptr_1 {&begin_a->next};
std::unique_ptr<node_base>* ptr_2 {&begin_a};
while (*ptr_1) {
ptr_1 = &(*ptr_1)->next;
if (*ptr_1) {
ptr_1 = &(*ptr_1)->next;
ptr_2 = &(*ptr_2)->next;
}
}
begin_b = std::move((*ptr_2)->next);
(*ptr_2)->next = nullptr;
assert(begin_b);
}
template<class Compare>
void merge_sorted_nodes(
std::unique_ptr<node_base>& a,
std::unique_ptr<node_base>& b,
Compare const& comp
) {
// assumes sorted list
std::unique_ptr<node_base> tmp_base = std::make_unique<node_base>(std::move(a));
std::unique_ptr<node_base>* current_node = &tmp_base;
while (b) {
if (!(*current_node)->next) {
(*current_node)->next = std::move(b);
b = nullptr;
continue;
}
T const& val1 = static_cast<node<T>*>((*current_node)->next.get())->data;
T const& val2 = static_cast<node<T>*>(b.get())->data;
if (comp(val2, val1)) { // val2 < val1
std::unique_ptr<node_base> node_to_move = std::move(b);
std::unique_ptr<node_base> old_next_of_node_to_move = std::move(node_to_move->next);
std::unique_ptr<node_base> new_next_of_node_to_move = std::move((*current_node)->next);
b = std::move(old_next_of_node_to_move);
node_to_move->next = std::move(new_next_of_node_to_move);
(*current_node)->next = std::move(node_to_move);
}
current_node = &(*current_node)->next;
}
a = std::move(tmp_base->next);
} | {
"domain": "codereview.stackexchange",
"id": 43083,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list, c++17",
"url": null
} |
c++, linked-list, c++17
std::size_t debug_size(std::unique_ptr<node_base> const& n) {
std::unique_ptr<node_base> const * ptr = &n;
std::size_t i = 0;
while(*ptr) {
ptr = &(*ptr)->next;
i++;
}
return i;
}
std::string debug_string(node_base const* n) {
std::stringstream ss {};
while (n) {
ss << n << ", ";
n = n->next.get();
}
return ss.str();
}
std::unique_ptr<node_base> m_head;
};
template<class T>
bool operator==(const linked_list<T>& lhs, const linked_list<T>& rhs) {
auto it_1 = lhs.begin();
auto it_2 = rhs.begin();
while(it_1 != lhs.end() && it_2 != rhs.end()) {
T const& val1 = it_1.data_node()->data;
T const& val2 = it_2.data_node()->data;;
if (!(val1 == val2)) {
return false;
}
it_1 ++;
it_2 ++;
}
return it_1 == lhs.end() && it_2 == rhs.end();
}
template<class T>
bool operator!=(const linked_list<T>& lhs, const linked_list<T>& rhs) {
return !(lhs == rhs);
}
template<class T>
bool operator<(const linked_list<T>& lhs, const linked_list<T>& rhs) {
auto it_1 = lhs.begin();
auto it_2 = rhs.begin();
while(it_1 != lhs.end() && it_2 != rhs.end()) {
T const& val1 = it_1.data_node()->data;
T const& val2 = it_2.data_node()->data;;
if (!(val1 < val2)) {
return false;
}
it_1 ++;
it_2 ++;
}
return true;
}
template<class T>
bool operator<=(const linked_list<T>& lhs, const linked_list<T>& rhs) {
return (lhs == rhs) || (lhs < rhs);
}
template<class T>
bool operator>(const linked_list<T>& lhs, const linked_list<T>& rhs) {
return !(lhs <= rhs);
}
template<class T>
bool operator>=(const linked_list<T>& lhs, const linked_list<T>& rhs) {
return (lhs == rhs) || (lhs > rhs);
}
}
namespace std { | {
"domain": "codereview.stackexchange",
"id": 43083,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list, c++17",
"url": null
} |
c++, linked-list, c++17
}
namespace std {
template<class T>
void swap(custom::linked_list<T>& lhs, custom::linked_list<T>& rhs) {
lhs.swap(rhs);
}
}
#endif
Edit:
And here are the tests I wrote:
#include <gtest/gtest.h>
#include "linked_list.hpp"
class LinkedListTestFixture : public testing::Test {
protected:
LinkedListTestFixture() {
}
~LinkedListTestFixture() = default;
};
TEST_F(LinkedListTestFixture, test_constructors_assignments_and_iterator) {
custom::linked_list<int> my_list_1 {2, 4, 9};
EXPECT_EQ(3, my_list_1.size());
std::vector<int> tmp_vector {1, 5, 6};
custom::linked_list<int> my_list_2 (tmp_vector.begin(), tmp_vector.end());
EXPECT_EQ(3, my_list_2.size());
my_list_2 = custom::linked_list<int>(std::size_t(5), 9);
EXPECT_EQ(5, my_list_2.size());
custom::linked_list<int> my_list_3 = my_list_2;
my_list_3 = my_list_1;
my_list_3 = my_list_2;
EXPECT_EQ(5, my_list_3.size());
custom::linked_list<int> my_list_4 = std::move(my_list_3);
EXPECT_EQ(5, my_list_4.size());
auto i = 0;
std::vector expected_values = {2, 4, 9};
for (int const& x : my_list_1) {
int const& y = expected_values.at(i);
EXPECT_EQ(y, x);
i++;
}
}
TEST_F(LinkedListTestFixture, test_modifier_funcs) {
custom::linked_list<double> my_list {1, 2, 3};
my_list.insert_after(my_list.cbefore_begin(), -2);
my_list.insert_after(my_list.cbefore_begin(), std::size_t(2), -3);
custom::linked_list<double> tmp_list {10, 20};
my_list.insert_after(my_list.cbegin(), tmp_list.cbegin(), tmp_list.cend());
my_list.insert_after(my_list.cbegin(), {309, 319});
my_list.emplace_after(my_list.cbefore_begin(), 45);
my_list.push_front(44);
my_list.emplace_front(42);
my_list.emplace_front(42);
my_list.pop_front(); | {
"domain": "codereview.stackexchange",
"id": 43083,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list, c++17",
"url": null
} |
c++, linked-list, c++17
auto i = 0;
std::vector<double> expectation = {
42, 44, 45, -3, 309, 319, 10, 20, -3, -2, 1, 2, 3
};
for (double const& x : my_list) {
double const& y = expectation.at(i);
EXPECT_EQ(y, x);
i++;
}
EXPECT_EQ(expectation.size(), my_list.size());
EXPECT_EQ(false, my_list.empty());
my_list.clear();
EXPECT_EQ(true, my_list.empty());
}
TEST_F(LinkedListTestFixture, test_erase_after) {
custom::linked_list<double> my_list {1, 2, 3, 4, 5, 6};
auto start_it = my_list.cbegin();
auto stop_it = start_it;
++stop_it;
++stop_it;
++stop_it;
my_list.erase_after(start_it, stop_it);
auto i = 0;
std::vector<double> expectation = {1, 4, 5, 6};
EXPECT_EQ(expectation.size(), my_list.size());
for (double const& x : my_list) {
double const& y = expectation.at(i);
EXPECT_EQ(y, x);
i++;
}
}
TEST_F(LinkedListTestFixture, test_merge) {
custom::linked_list<int> my_list {2, 4, 6, 7};
my_list.merge(my_list);
EXPECT_EQ(4, my_list.size());
custom::linked_list<int> tmp_list {1, 5, 6};
my_list.merge(tmp_list);
custom::linked_list<int> tmp_list_2 {9, 9};
my_list.merge(tmp_list_2);
EXPECT_EQ(0, tmp_list.size());
auto i = 0;
std::vector<int> expectation = {1, 2, 4, 5, 6, 6, 7, 9, 9};
EXPECT_EQ(expectation.size(), my_list.size());
for (auto const& x : my_list) {
auto const& y = expectation.at(i);
EXPECT_EQ(y, x);
i++;
}
}
TEST_F(LinkedListTestFixture, test_splice) {
custom::linked_list<int> my_list {1, 2, 3};
custom::linked_list<int> tmp_list {10, 12};
my_list.splice_after(my_list.cbegin(), tmp_list);
EXPECT_EQ(0, tmp_list.size());
tmp_list = {21, 22, 23};
my_list.splice_after(my_list.cbegin(), tmp_list, tmp_list.cbegin());
EXPECT_EQ(2, tmp_list.size()); | {
"domain": "codereview.stackexchange",
"id": 43083,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list, c++17",
"url": null
} |
c++, linked-list, c++17
auto i = 0;
std::vector<int> expectation = {1, 22, 10, 12, 2, 3};
EXPECT_EQ(expectation.size(), my_list.size());
for (auto const& x : my_list) {
auto const& y = expectation.at(i);
EXPECT_EQ(y, x);
i++;
}
}
TEST_F(LinkedListTestFixture, test_remove) {
custom::linked_list<int> my_list {1, 2, 3, 5, 7, 5, 3, 2, 1};
my_list.remove(2);
my_list.remove_if([](auto const& val) { return (val == 5) || (val == 7); });
auto i = 0;
std::vector<int> expectation = {1, 3, 3, 1};
EXPECT_EQ(expectation.size(), my_list.size());
for (auto const& x : my_list) {
auto const& y = expectation.at(i);
EXPECT_EQ(y, x);
i++;
}
}
TEST_F(LinkedListTestFixture, test_reverse) {
custom::linked_list<int> my_list {1, 2, 3};
my_list.reverse();
auto i = 0;
std::vector<int> expectation = {3, 2, 1};
EXPECT_EQ(expectation.size(), my_list.size());
for (auto const& x : my_list) {
auto const& y = expectation.at(i);
EXPECT_EQ(y, x);
i++;
}
}
TEST_F(LinkedListTestFixture, test_unique) {
custom::linked_list<int> my_list {1, 2, 2, 2, 3, 2, 2, 3, 2};
my_list.unique();
auto i = 0;
std::vector<int> expectation = {1, 2, 3, 2, 3, 2};
EXPECT_EQ(expectation.size(), my_list.size());
for (auto const& x : my_list) {
auto const& y = expectation.at(i);
EXPECT_EQ(y, x);
i++;
}
}
TEST_F(LinkedListTestFixture, test_sort) {
custom::linked_list<int> my_list {1, 3, 2, 5, 4, 1};
my_list.sort();
auto i = 0;
std::vector<int> expectation = {1, 1, 2, 3, 4, 5};
EXPECT_EQ(expectation.size(), my_list.size());
for (auto const& x : my_list) {
auto const& y = expectation.at(i);
EXPECT_EQ(y, x);
i++;
}
my_list = {1, 3, 2};
my_list.sort(); | {
"domain": "codereview.stackexchange",
"id": 43083,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list, c++17",
"url": null
} |
c++, linked-list, c++17
my_list = {1, 3, 2};
my_list.sort();
i = 0;
expectation = {1, 2, 3};
EXPECT_EQ(expectation.size(), my_list.size());
for (auto const& x : my_list) {
auto const& y = expectation.at(i);
EXPECT_EQ(y, x);
i++;
}
}
TEST_F(LinkedListTestFixture, test_comparison_operators) {
custom::linked_list<int> my_list_1 {1, 2};
custom::linked_list<int> my_list_2 {7, 8, 9};
custom::linked_list<int> my_list_3 {7, 8, 9};
EXPECT_FALSE(my_list_1 == my_list_2);
EXPECT_TRUE(my_list_1 != my_list_2);
EXPECT_FALSE(my_list_1 >= my_list_2);
EXPECT_TRUE(my_list_1 <= my_list_2);
EXPECT_TRUE(my_list_1 < my_list_2);
EXPECT_FALSE(my_list_1 > my_list_2);
EXPECT_TRUE(my_list_2 == my_list_3);
EXPECT_FALSE(my_list_2 != my_list_3);
EXPECT_TRUE(my_list_2 >= my_list_3);
EXPECT_TRUE(my_list_2 <= my_list_3);
EXPECT_FALSE(my_list_2 < my_list_3);
EXPECT_FALSE(my_list_2 > my_list_3);
}
TEST_F(LinkedListTestFixture, test_swap) {
custom::linked_list<int> my_list_1 {1, 2};
custom::linked_list<int> my_list_2 {7, 8, 9};
custom::linked_list<int> my_list_3 {7, 8, 9};
custom::linked_list<int> my_list_4 {1, 2};
std::swap(my_list_1, my_list_2);
EXPECT_TRUE(my_list_1 == my_list_3);
EXPECT_TRUE(my_list_2 == my_list_4);
}
Answer: It appears that memory is well handled, and the API is tidy and tested. Nice code!
Performance
A number of operations do a lot more work than necessary. They're within expected algorithmic complexity (that's good), but constant multipliers do matter too.
For example, the erase_after call iterates over each erased element twice instead of once:
Once during the call to get_prev_to_last_node.
Once during the assignment to next, which leads to a chain of destructors being called. | {
"domain": "codereview.stackexchange",
"id": 43083,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list, c++17",
"url": null
} |
c++, linked-list, c++17
Instead, it could simply pop the elements one at a time until the next element is the end.
Stack Overflow
Pertaining to the above "chain of destructors", a number of operations -- including the destructor -- are susceptible to stack overflows.
If you have a list 1 -> 2 -> 3 -> 4 then:
Calling the destructor of 1,
Will call the destructor of 2,
Will call the destructor of 3,
Will call the destructor of 4,
The latter will complete, returning control to the destructor of 3.
Which will complete, returning control to the destructor of 2.
Which will complete, returning control to the destructor of 1.
Which will complete, returning control to the caller.
This is typically of node-based structures: the depth of the call stack is proportional to the depth of the structure. For balanced binary trees, with O(log n) depth, it's typically not an issue; for linked-lists, with O(n) depth, it very much is.
There's no magic here, you cannot rely on the destructor of unique_ptr to handle the job and must manually convert the recursion to iteration every time.
Note: this typically only manifest for relatively large lists; with stacks a typical 1MB to 8MB, and a call frame taking as little as 16 - 64 bytes, it can take up to 500K elements to trigger the issue. I suggest setting up a test with a few million elements, and testing various operations. | {
"domain": "codereview.stackexchange",
"id": 43083,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, linked-list, c++17",
"url": null
} |
performance, vba, excel
Title: Automating shortages report from BOM list in excel but the total run time to output the report is quite slow. Using Excel 2010 - CLOSED
Question:
I MIGHT REWRITE THIS QUESTION IN A CLEARER WAY WITH SOME SAMPLES TOO AND POST IT AS ANOTHER SOON, AS NOW MY EXPLAINATION HERE IS QUITE HARD TO UNDERSTAND & MIGHT BE PHRASED WRONG.
I do have background knowledge in programming, but this is my first time using VBA so any advice is appreciated.
This code is the final part of the program where it essentially output a report matching demands against supplies based on Sale Order>Need By Date>item hierarchy.
First, the code takes the data in the "tree" sheet which consist of the item/order no. and its respective levels - (1,2,3,...)/hierarchy and puts it into an array. Then, it iterates through to find the relevant data matched based on the order number in another matched data (that matched demands to its corresponding supplies) created in the initial part of the program and puts it in order based on the item hierarchy and output all relevant data on the final report.
The program is taking about 20s to sort/match & output the final data into a spreadsheet, but I need it to be faster then that. Currently the whole process takes about 40s to generate the report for 10k lines of test data, but i have to generate the report for 1 million lines in about a minute.
Sub SortHierarchyList()
With Excel.Application
.ScreenUpdating = False
.Calculation = Excel.xlManual
.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False
End With | {
"domain": "codereview.stackexchange",
"id": 43084,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel",
"url": null
} |
performance, vba, excel
StartTime = Timer
Sheets("Order").Rows(2 & ":" & Rows.Count).Delete
'last row for hierarchy tree sheet
'max column for hierarchy tree sheet
Dim treelastrw As Long, treemaxcol As Long
treelastrw = Sheets("tree").Cells(Rows.Count, "A").End(xlUp).row: treemaxcol = Sheets("tree").Range("A1").SpecialCells(xlCellTypeLastCell).Column
Dim ColumnLetter As String
ColumnLetter = Split(Cells(1, treemaxcol).Address, "$")(1): treeArray = Sheets("tree").Range("A1:" & ColumnLetter & treelastrw): mArray = Sheets("Matcher").Range("A1:X" & treelastrw): outputArray = Sheets("Order").Range("A1:Z" & treelastrw)
'Create Dictionary, adding ranking sheet to the dictionary
'Create Dictionary, adding ranking sheet to the dictionary
Dim RankDict As Object, SortDict As Object
Set RankDict = RankingDict: Set SortDict = SortingDict | {
"domain": "codereview.stackexchange",
"id": 43084,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel",
"url": null
} |
performance, vba, excel
'actual sorting
For treerow = LBound(treeArray, 1) + 1 To UBound(treeArray, 1)
'from second column onwards to max column (max level for bom tree) (1st column is just used for ".")
For i = 3 To treemaxcol
'for each row in hierarchy tree, find the first instance of a value (from second column onwards)
If RankDict.Exists(treeArray(treerow, i)) Then
'sales order will change once the array iterates down the tree to the next sales order
If i = 3 Then
highestlevel = treeArray(treerow, i)
For j = treerow - 1 To 1 Step -1
If treeArray(j, i - 1) <> vbNullString Then
currentSalesOrder = treeArray(j, i - 1)
Exit For
End If
Next j
End If
'find the corresponding demand number by looking one column to the left and up onwards from indexed row to first row
'the first instance of a value would be the corresponding demand number
outputArray(treerow, 25) = highestlevel: outputArray(treerow, 26) = currentSalesOrder: childSupply = treeArray(treerow, i)
For j = treerow - 1 To 1 Step -1
If treeArray(j, i - 1) <> vbNullString Then
parentDemand = treeArray(j, i - 1)
Exit For
End If
Next j
'find in matched list array where demand and supply corresponds to childsupply and parent demand
For matchlistrow = LBound(mArray, 1) + 1 To UBound(mArray, 1)
'check if the item has already been used and listed in the sorted table
If SortDict(matchlistrow) = 0 Then
If mArray(matchlistrow, 5) = parentDemand Then | {
"domain": "codereview.stackexchange",
"id": 43084,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel",
"url": null
} |
performance, vba, excel
If mArray(matchlistrow, 5) = parentDemand Then
If mArray(matchlistrow, 16) = childSupply Then
'lay out the row information
For col = 1 To 24
outputArray(treerow, col) = mArray(matchlistrow, col)
Next col
'swap back to blank field if no suppply available
If outputArray(treerow, 16) = "No Supply" Then
outputArray(treerow, 16) = vbNullString
End If
'update whether the matched row has been used in the sorted sheet already
SortDict(matchlistrow) = 1
GoTo nextloop
End If
End If
End If
Next matchlistrow
End If
Next i
nextloop:
Next treerow
'adds in missing rows
For i = 2 To UBound(outputArray, 1)
If outputArray(i, 11) = vbNullString Then
For j = 3 To treemaxcol
If RankDict.Exists(treeArray(i, j)) Then
For y = 1 To UBound(mArray)
If SortDict(y) = 0 Then
If mArray(y, 16) = treeArray(i, j) Then
For col = 1 To 24
outputArray(i, col) = mArray(y, col)
Next col
SortDict(y) = 1
GoTo nextEmpty
End If
End If
Next y
End If
Next j
End If
nextEmpty:
Next i
'output
Sheets("Order").Range("A1:Z" & treelastrw) = outputArray
'resize columns to fit accordingly | {
"domain": "codereview.stackexchange",
"id": 43084,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel",
"url": null
} |
performance, vba, excel
'resize columns to fit accordingly
SecondsElapsed = Round(Timer - StartTime, 1)
Debug.Print "Sorter Output Time: " & SecondsElapsed & "s"
With Excel.Application
ActiveSheet.DisplayPageBreaks = True
.ScreenUpdating = True
.Calculation = Excel.xlAutomatic
.EnableEvents = True
End With
End Sub | {
"domain": "codereview.stackexchange",
"id": 43084,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel",
"url": null
} |
performance, vba, excel
Function RankingDict() As Dictionary
'last row for ranking sheet
Dim endrow As Long
endrow = Sheets("rank").Cells(Rows.Count, "A").End(xlUp).row
Dim dict As New Dictionary
For i = 1 To endrow
Key = Sheets("rank").Cells(i, 1).Value2: Item = Sheets("rank").Cells(i, 2).Value2
dict.Add Key, Item
Next i
Set RankingDict = dict
End Function
'to check whether the row has been used in the sorted output or not
'helps to avoid duplicates
Function SortingDict() As Dictionary
'last row for ranking sheet
Dim endrow As Long
endrow = Sheets("Matcher").Cells(Rows.Count, "A").End(xlUp).row
Dim dict As New Dictionary
For i = 1 To endrow
Key = i: Item = 0
dict.Add Key, Item
Next i
Set SortingDict = dict
End Function
This is the code that assigns the materials its assembly level and matched them according to the demand/supply order number. This part also took quite awhile to process. about 15s or so. I don't know if it's the sorting part that takes up the most time or what.
Sub bomTree()
With Excel.Application
.ScreenUpdating = False
.Calculation = Excel.xlManual
.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False
End With | {
"domain": "codereview.stackexchange",
"id": 43084,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel",
"url": null
} |
performance, vba, excel
Dim hSh As Worksheet
Dim iRow As Integer, oRow As Integer, hRow As Integer
Dim iCol As Integer, oCol As Integer, hCol As Integer
Dim iParent As String, iChild As String, oNode As String
Dim bParentFound As Boolean, bChildFound As Boolean
Dim hLevel As Integer, cHierarchy As Range
Dim cChildRow As Long, cParentRow As Long
StartTime2 = Timer
'Assign Cell Values
Set hSh = Sheets("tree")
Sheets("rank").Cells.Clear
'Find Ranking Number for Each Node
'Loop Thru Each Cell
lastrow = Sheets("sbs").Cells(Rows.Count, "A").End(xlUp).row
iSh = Sheets("sbs").Range("A1:B" & lastrow)
secondlastrow = Sheets("Matcher").Cells(Rows.Count, "A").End(xlUp).row
oSh = Sheets("rank").Range("A1:B" & secondlastrow)
For iRow = LBound(iSh, 1) To UBound(iSh, 1)
iParent = iSh(iRow, 1): iChild = iSh(iRow, 2)
oRow = 1
bParentFound = False: bChildFound = False
Do While oSh(oRow, 1) <> vbNullString
oNode = oSh(oRow, 1)
If oNode = iParent Then
bParentFound = True: cParentRow = oRow
Else
If oNode = iChild Then
bChildFound = True: cChildRow = oRow
End If
End If
If bParentFound And bChildFound Then
Exit Do
End If
oRow = oRow + 1
Loop
If bParentFound = False Then
While oSh(oRow, 1) <> vbNullString
oRow = oRow + 1
Wend
oSh(oRow, 1) = iParent
oSh(oRow, 2) = 0
cParentRow = oRow
End If
If bChildFound = False Then
While oSh(oRow, 1) <> vbNullString
oRow = oRow + 1
Wend
oSh(oRow, 1) = iChild
cChildRow = oRow
End If
oSh(cChildRow, 2) = "=1+$B$" & cParentRow
Next iRow | {
"domain": "codereview.stackexchange",
"id": 43084,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel",
"url": null
} |
performance, vba, excel
End If
oSh(cChildRow, 2) = "=1+$B$" & cParentRow
Next iRow
Sheets("rank").Range("A1:B" & secondlastrow) = oSh
'Sort Nodes Based on its Ranking
Set oSh = Sheets("rank")
oSh.Sort.SortFields.Clear
oSh.Sort.SortFields.Add Key:=Range("B1:B" & oRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With oSh.Sort
.SetRange Range("A1:B" & oRow)
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Dim RankDict As Object
Set RankDict = RankingDict
SecondsElapsed = Round(Timer - StartTime2, 1)
Debug.Print "rank output time: " & SecondsElapsed & "s"
'Build Hierarchy Chart Table or Organization Chart
'Place Each Node in its Hierarchy Level
StartTime = Timer | {
"domain": "codereview.stackexchange",
"id": 43084,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel",
"url": null
} |
performance, vba, excel
hSh.Cells.Clear
hRow = 1
secondlastrow = oSh.Cells(Rows.Count, "A").End(xlUp).row:
sheetTwoArray = oSh.Range("A1:B" & secondlastrow)
For oRow = LBound(sheetTwoArray, 1) To UBound(sheetTwoArray, 1)
oNode = sheetTwoArray(oRow, 1): hLevel = sheetTwoArray(oRow, 2) + 2
Set cHierarchy = Find_First_In_Range(oNode, hSh.Cells)
If cHierarchy Is Nothing Then
hSh.Cells(hRow, hLevel) = oSh.Cells(oRow, 1)
Else
hRow = cHierarchy.row
End If
For iRow = LBound(iSh, 1) To UBound(iSh, 1)
iParent = iSh(iRow, 1): iChild = iSh(iRow, 2)
If iParent = oNode Then
hRow = hRow + 1
hSh.Rows(hRow & ":" & hRow).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
hSh.Cells(hRow, hLevel + 1) = iChild: hSh.Cells(hRow, 1) = "."
End If
Next iRow
Next oRow
SecondsElapsed = Round(Timer - StartTime, 1)
Debug.Print "tree output time: " & SecondsElapsed & "s"
With Excel.Application
.ScreenUpdating = True
.Calculation = Excel.xlAutomatic
.EnableEvents = True
ActiveSheet.DisplayPageBreaks = True
End With
End Sub
Function Find_First_In_Range(FindString As String, iRng As Range) As Range
Dim rng As Range
If FindString <> vbNullString Then
With iRng
Set rng = .Find(What:=FindString, _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
End With
End If
Set Find_First_In_Range = rng
End Function | {
"domain": "codereview.stackexchange",
"id": 43084,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel",
"url": null
} |
performance, vba, excel
Answer: Use of Dictionaries slows down the process and needs more RAM then a built in Arrays in VBA they are much faster than external use of Dictionaries.
Use of native data structures increases speed, if that's what you are after.
Edit:
I agree with @Greedo(in comments), but there is a catch. Since it is needed to copy the dictionary to other sheet/sheets it is this operation that is realy slow and takes the majoraty of time to be executed. In my personal experiance it was faster to do the operations with dictionary and before putting it out to sheets place it in array
Edit2:
This is the code that assigns the materials its assembly level and
matched them according to the demand/supply order number. This part
also took quite awhile to process. about 15s or so. I don't know if
it's the sorting part that takes up the most time or what.
If you use sorting for Dictionaries then you have misunderstood use of Dictionaries
Suggestion:
Try reading all data before performing calculations
Jumping from workbook to other workbook and sheet to sheet takes time.
if you use delete in VBA you could just skip/ignore the lines instead
Do not loop through Ranges use Arrays to perform search/find it is 50x faster | {
"domain": "codereview.stackexchange",
"id": 43084,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, vba, excel",
"url": null
} |
python, python-3.x
Title: Python snippet for bulk moving files into their parent folder
Question: I wrote this little snippet which moves files from several subfolders to their parent folder. Since the snippet uses different nested for loops I was wondering if it could be refactored to a cleaner and more maintainable solution? I tried extracting the different for loops to separate functions, but they rely on the same variables so I couldn't get this to work.
import os
import shutil
import sys
currentDirectory = os.getcwd()
def changeStructure(currentFolder):
parentDirectory = currentDirectory + "/" + currentFolder
for folder in os.listdir(parentDirectory):
folderPath = parentDirectory + "/" + folder
if os.path.isdir(folderPath):
for file in os.listdir(folderPath):
if not file.startswith('.'):
shutil.move(folderPath + "/" + file, parentDirectory)
shutil.rmtree(folderPath)
print("All folders removed")
if __name__ == '__main__':
globals()[sys.argv[1]](sys.argv[2])
Answer: You should replace os with pathlib equivalents since it has a nicer, object-oriented interface.
currentDirectory (which should be called current_directory) should not be a global. In a situation where you load the module, change the working directory and then call changeStructure this will do the wrong thing.
Add PEP484 type hints.
Consider inverting your if isdir condition to be able to de-dent the rest of the loop.
Your use of globals() is evil. It allows people invoking your application unfettered access to anything that you import and anything that you define on the global namespace, even if it starts with underscores. Do basically anything that isn't this. Since this is a single-method program, in this case just pass the first argument directly to your subroutine.
Suggested
Not tested because I don't want to mangle my filesystem.
import shutil
import sys
from pathlib import Path | {
"domain": "codereview.stackexchange",
"id": 43085,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.