text stringlengths 1 2.12k | source dict |
|---|---|
c++, strings, search
On having Index as a class template and other functions not. […] Is it reasonable or there is a good reason to make them generic in advance?
I think you can apply the YAGNI principle here: unless you are really going to need it, don't make Index a class template. The same goes for SubstringOccurences.
Are you agree with the solution for Index or you had different or better ways to do this?
For the problem of finding repeated subsequences, I think Index is fine. However, the name is very generic of course. So in a larger project, it should either be made more distinct, like SuffixArrayIndex, or ensure it is not visible to other parts of the code, for example by ensuring it is only defined in a .cpp file, or by putting it in a namespace.
Other ideas
I don't see much that can be improved (but maybe other reviewers will). Some ideas you might want to look into though:
C++20 and later introduce ranges and views, and this allows for a more functional approach to writing algorithms. You could give that a go.
You could return the result of std::transform_reduce() directly without storing it in a variable first. On the other hand, this way you are giving a name to the value, which helps document the code. | {
"domain": "codereview.stackexchange",
"id": 45449,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
python, performance, python-3.x, pdf
Title: Speed up search function for PDFs
Question: This function takes a file path to a PDF file, and a search string(s). It spits out a count of the number of times the string(s) shows in the PDF. Any ideas how I can make it faster?
It can be tested with any PDF (not password protected.)
I frequently use this to scan a list of words in a large number of PDFs and it is slow!
import os
import fitz # using PyMuPDF
import string
def count_of_string_in_pdf_file_advanced_alt(next_pdfs_path: str, search_string: str) -> int:
"""
count the number of times a string is in a PDF file. Case insensitive.
Parameters:
next_pdfs_path (str): file path to a PDF file
search_string (str): string to look for/count in PDF file
Returns:
count (int): a count of the number of occurrences
"""
count = 0
flag = True
search_string = str(search_string.lower().strip())
if os.path.isfile(next_pdfs_path): # check file is a real file/filepath
try:
text = ''
with fitz.open(next_pdfs_path) as doc:
for page in doc:
text += page.get_text()
while flag:
text = text.translate(str.maketrans('', '', string.punctuation)) # remove puncuation
words = text.lower().split() # cleanup and split the text into list of words
words = sorted(words)
if search_string in words:
count = words.count(search_string)
break
else:
flag = False
# return count
except (RuntimeError, IOError):
pass
return count | {
"domain": "codereview.stackexchange",
"id": 45450,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, pdf",
"url": null
} |
python, performance, python-3.x, pdf
I profiled it using a single string and this 74 page PDF https://thedocs.worldbank.org/en/doc/79bb914488308f1e75744fccc4e12cb3-0290032021/world-bank-notes-on-debarred-firms-and-individuals-pdf
7998 function calls (7989 primitive calls) in 0.182 seconds
Ordered by: call count | {
"domain": "codereview.stackexchange",
"id": 45450,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, pdf",
"url": null
} |
python, performance, python-3.x, pdf
ncalls tottime percall cumtime percall filename:lineno(function)
453 0.000 0.000 0.000 0.000 {built-in method builtins.getattr}
444 0.000 0.000 0.000 0.000 fitz.py:621(__getitem__)
312 0.000 0.000 0.000 0.000 {built-in method builtins.len}
300 0.000 0.000 0.000 0.000 {method 'own' of 'SwigPyObject' objects}
296 0.000 0.000 0.000 0.000 fitz.py:3003(CheckParent)
296 0.000 0.000 0.000 0.000 fitz.py:3047(<lambda>)
296 0.000 0.000 0.000 0.000 {built-in method builtins.abs}
151 0.000 0.000 0.000 0.000 {method 'items' of 'dict' objects}
149 0.000 0.000 0.000 0.000 fitz.py:5755(__contains__)
149 0.000 0.000 0.000 0.000 fitz.py:4408(page_count)
149 0.000 0.000 0.000 0.000 {built-in method fitz._fitz.Document_page_count}
148 0.000 0.000 0.001 0.000 weakref.py:164(__setitem__)
148 0.000 0.000 0.000 0.000 weakref.py:347(__new__)
148 0.000 0.000 0.000 0.000 {built-in method __new__ of type object at 0x00007FFF295E13D0}
148 0.000 0.000 0.000 0.000 {built-in method _weakref.proxy}
148 0.000 0.000 0.000 0.000 {built-in method builtins.id}
148 0.000 0.000 0.000 0.000 {built-in method builtins.round}
84 0.000 0.000 0.000 0.000 {built-in method builtins.hasattr}
77 0.000 0.000 0.000 0.000 weakref.py:252(popitem)
77 0.000 0.000 0.001 0.000 weakref.py:243(values)
77 0.000 0.000 0.000 0.000 {method 'popitem' of 'dict' objects}
77 0.001 0.000 0.001 0.000 {method 'lower' of 'str' objects}
76 0.000 0.000 0.000 0.000 _weakrefset.py:17(__init__)
76 0.000 0.000 0.000 0.000 _weakrefset.py:27(__exit__) | {
"domain": "codereview.stackexchange",
"id": 45450,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, pdf",
"url": null
} |
python, performance, python-3.x, pdf
76 0.000 0.000 0.000 0.000 _weakrefset.py:27(__exit__)
76 0.000 0.000 0.000 0.000 weakref.py:121(_commit_removals)
76 0.000 0.000 0.000 0.000 _weakrefset.py:21(__enter__)
76 0.000 0.000 0.000 0.000 <frozen _collections_abc>:966(clear)
76 0.000 0.000 0.000 0.000 {method 'values' of 'dict' objects}
76 0.000 0.000 0.000 0.000 {method 'pop' of 'list' objects}
76 0.000 0.000 0.000 0.000 {method 'add' of 'set' objects}
76 0.000 0.000 0.000 0.000 {method 'remove' of 'set' objects}
75 0.000 0.000 0.000 0.000 weakref.py:289(update)
75 0.000 0.000 0.000 0.000 weakref.py:104(__init__)
75 0.000 0.000 0.001 0.000 fitz.py:7227(_reset_annot_refs)
75 0.000 0.000 0.004 0.000 fitz.py:5778(__getitem__)
75 0.000 0.000 0.002 0.000 fitz.py:7240(_erase)
74 0.000 0.000 0.000 0.000 weakref.py:352(__init__)
74 0.000 0.000 0.000 0.000 weakref.py:152(__contains__)
74 0.000 0.000 0.000 0.000 fitz.py:497(__init__)
74 0.000 0.000 0.004 0.000 fitz.py:4146(load_page)
74 0.000 0.000 0.000 0.000 fitz.py:434(util_make_rect)
74 0.001 0.000 0.135 0.002 utils.py:753(get_text)
74 0.000 0.000 0.126 0.002 fitz.py:6009(get_textpage)
74 0.000 0.000 0.000 0.000 fitz.py:926(__init__)
74 0.000 0.000 0.000 0.000 fitz.py:5898(<lambda>)
74 0.000 0.000 0.000 0.000 fitz.py:636(__len__)
74 0.000 0.000 0.001 0.000 fitz.py:3046(JM_TUPLE3)
74 0.000 0.000 0.001 0.000 fitz.py:6892(cropbox)
74 0.000 0.000 0.125 0.002 fitz.py:6002(_get_textpage)
74 0.000 0.000 0.000 0.000 fitz.py:6972(rotation) | {
"domain": "codereview.stackexchange",
"id": 45450,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, pdf",
"url": null
} |
python, performance, python-3.x, pdf
74 0.000 0.000 0.000 0.000 fitz.py:6972(rotation)
74 0.000 0.000 0.000 0.000 fitz.py:5839(_forget_page)
74 0.000 0.000 0.005 0.000 fitz.py:9002(extractText)
74 0.000 0.000 0.000 0.000 fitz.py:8909(<lambda>)
74 0.000 0.000 0.002 0.000 fitz.py:7253(__del__)
74 0.000 0.000 0.005 0.000 fitz.py:8993(_extractText)
74 0.000 0.000 0.002 0.000 fitz.py:9086(__del__)
74 0.000 0.000 0.000 0.000 {built-in method fitz._fitz.util_make_rect}
74 0.003 0.000 0.003 0.000 {built-in method fitz._fitz.Document_load_page}
74 0.000 0.000 0.000 0.000 {built-in method fitz._fitz.delete_Page}
74 0.129 0.002 0.129 0.002 {built-in method fitz._fitz.Page__get_textpage} | {
"domain": "codereview.stackexchange",
"id": 45450,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, pdf",
"url": null
} |
python, performance, python-3.x, pdf
Some things I have tried
# I tested using join rather than concatenating but found it to be slower.
# for page in doc:
# text += page.get_text()
text = ' '.join(page.get_text() for page in doc)
Answer: where did the time go?
Thank you for including measurements.
Ordering the profiler output by call count is uninteresting.
What you care about is time spent,
and the output makes it pretty clear that nearly all
the delay happens in get_text().
Everything else is just noise.
Any ideas how I can make it faster?
If you're not happy with the current PDF text extractor,
then choose another.
It might come with convenient python bindings.
Or it might just produce plain text on stdout,
which a parent python process can consume and grep through.
Consider writing a foo.txt cache file
each time you parse some original foo.pdf document.
Then you will never have to parse a document twice,
and elapsed time on subsequent runs boils down
to time for grep'ing a text file.
This is a time vs. space tradeoff,
where spending disk blocks saves us CPU seconds.
design of API
frequently use this to scan a list of words
The current Public API accepts a single word and reports a count.
If your list of N words starts with "apple", "banana",
the call sequence would be
pdf = "/some/where/World-Bank-Notes-on-Debarred-Firms-and-Individuals.pdf"
a = count_of_string_in_pdf_file_advanced_alt(pdf, "apple")
b = count_of_string_in_pdf_file_advanced_alt(pdf, "banana")
...
You just did N expensive get_text operations
followed by a trivial cost grep-and-count operation.
Rather than a single word at a time, prefer to pass in
a container of words:
>>> from collections import Counter
>>> cnt = Counter(dict(apple=0, banana=0))
>>> cnt
Counter({'apple': 0, 'banana': 0}) | {
"domain": "codereview.stackexchange",
"id": 45450,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, pdf",
"url": null
} |
python, performance, python-3.x, pdf
That way for each .PDF file you can get_text just once,
and report all the desired word counts as a single return value.
An alternate approach would be to pass in a regex:
pattern = re.compile(r'\b(apple|banana)\b', re.I)
long identifiers
def count_of_string_in_pdf_file_advanced_alt(next_pdfs_path, ...
These would probably benefit from being shortened a little.
If you still have more things to say about them,
the very nice existing docstring is a good place to do that.
short identifier
while flag:
That is too vague.
Yes, we can see it is of type bool.
But we don't know what it means.
It should be called not_found.
Or better, invert its meaning and rephrase,
since humans do better with positive identifiers.
while not found:
It's unclear why we're even looping here at all.
The if will either break or change the flag.
Both of those actions cause the loop body's search
to happen exactly once.
Maybe this is leftover debug from when you
were exploring other ways of looping over pages?
ETAF rather than LBYL
if os.path.isfile(next_pdfs_path): # check file is a real file/filepath
It's unclear why this check is needed.
If fitz.open() raises, it raises, no big deal.
And then either caller would see the exception bubble up the stack,
or caller would get a zero count, however you prefer to handle that.
Prefer
Path()
over str when putting pathname parameters in a function signature.
BTW the text.translate() is lovely, it runs very fast on the inside.
You have an opportunity to call str.maketrans() just once when
this module is imported, and then keep re-using that
translation table, but that would be a very tiny savings
in the scheme of things.
Rather than deleting punctuation, you might prefer
to substitute such characters with SPACE.
My concern is that text like "spin-weave"
is being turned into the single word "spinweave",
where likely "spin weave" would be preferable.
unneeded action
words = sorted(words) | {
"domain": "codereview.stackexchange",
"id": 45450,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, pdf",
"url": null
} |
python, performance, python-3.x, pdf
This looks like a setup for calling
groupby()
to obtain counts of every word in the document.
But then we go on to do something else.
Maybe it is leftover debug?
This is a relatively inexpensive operation,
but there's no need to do it
so we may as well drop it.
This codebase achieves many of its design goals.
Apparently its future development will mostly be
about choosing and integrating with faster PDF libraries.
I would be willing to delegate or accept maintenance
tasks on this code. | {
"domain": "codereview.stackexchange",
"id": 45450,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, pdf",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
Title: A collection based on a bitset to store a set of unique integers from a given range (rev. 2) | {
"domain": "codereview.stackexchange",
"id": 45451,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
Question: This is a continuation of this review. I applied most of the proposed changes.
These changes were focused mostly on decoupling the class from the rest of the program and making its interface more like STL collections.
Description of the code:
This is an implementation of a set data structure.
It is optimized to efficiently store a huge amount of unsigned integers (even billions) from a range specified at construction (it always starts at 0).
It it used in very expensive computations so the main goal of this implementation (beside the memory efficiency) is performance.
The most important (for my goals) properties of this set are random read/write access in O(1) time, checking its size in O(1) time and an iterator that can continue iteration after changes in the set are made.
Additionally, the set is kept sorted because of how it is implemented.
This collection is not intended for storing small number of integers from a huge possible range. In such case the memory optimization is terrible and iteration takes too long.
(This is not the case in my program where on average half of the integers from the range is in the set.)
The goal of the review:
The primary goal is still to make sure that I as a self learner don't follow some weird coding patterns that have well established alternatives. (Things that a professional C++ programmer would consider stupid, counter-productive or just weird.) E.g. naming a function getSize() instead of size() (an example from the previous review).
I would like the code to not only work reliably but also be elegant in a way that makes it easy to read and use by other programmers.
I would also like to learn about any tricks or techniques which lack is not pointed out by a compiler but which can be useful in some way or other.
The attribute [[nodiscard]] is example of such thing as it provides additional static analysis of the code. | {
"domain": "codereview.stackexchange",
"id": 45451,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
Another example is the keyword const that not only prevents mistakes in the code but also it may improve optimization.
I'll also gladly take hints on making the code faster.
Actually, I'll take any sensible comments as long as they are not detrimental to the performance.
The code:
CompactSet.hh:
#pragma once | {
"domain": "codereview.stackexchange",
"id": 45451,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iterator>
#include <limits>
#include <vector> | {
"domain": "codereview.stackexchange",
"id": 45451,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
// This container can store unique numbers in range 0..capacity-1 using only about capacity/CHAR_BIT bytes of memory.
// (The memory usage is the same regardles of how many numbers are stored.)
template<typename T>
class CompactSet
{
static_assert(!std::numeric_limits<T>::is_signed);
std::vector<bool> bitset;
std::size_t count = 0;
public:
class const_iterator
{
const CompactSet<T> &compactSet;
std::uint_fast64_t i;
const_iterator(const CompactSet &compactSet, const std::uint_fast64_t i) : compactSet(compactSet), i(i) { }
friend class CompactSet<T>;
public:
[[nodiscard]] bool operator==(const const_iterator &other) const { return this->i == other.i; }
[[nodiscard]] bool operator!=(const const_iterator &other) const { return this->i != other.i; }
inline const_iterator& operator++();
inline const_iterator& operator--();
[[nodiscard]] T operator*() const { return static_cast<T>(i); }
};
explicit inline CompactSet(const std::size_t capacity);
[[nodiscard]] bool operator==(const CompactSet &other) const { return this->bitset == other.bitset; }
[[nodiscard]] bool operator!=(const CompactSet &other) const { return this->bitset != other.bitset; }
[[nodiscard]] bool empty() const { return count == 0; }
[[nodiscard]] bool full() const { return count == bitset.size(); }
[[nodiscard]] std::size_t size() const { return count; }
[[nodiscard]] std::size_t capacity() const { return bitset.size(); }
[[nodiscard]] bool check(const T value) const { return bitset[value]; }
inline bool add(const T value);
inline void add(const CompactSet &other);
inline void add(const CompactSet &other, const std::size_t overlappingCount);
inline bool remove(const T value);
[[nodiscard]] inline const_iterator begin() const;
[[nodiscard]] const_iterator end() const { return {*this, bitset.size()}; } | {
"domain": "codereview.stackexchange",
"id": 45451,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
[[nodiscard]] const_iterator end() const { return {*this, bitset.size()}; }
[[nodiscard]] const_iterator cbegin() const { return begin(); }
[[nodiscard]] const_iterator cend() const { return end(); }
#ifndef NDEBUG
void validate() const;
#endif
}; | {
"domain": "codereview.stackexchange",
"id": 45451,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
template<typename T>
typename CompactSet<T>::const_iterator& CompactSet<T>::const_iterator::operator++()
{
for (++i; i != compactSet.bitset.size() && !compactSet.bitset[i]; ++i) { }
return *this;
}
template<typename T>
typename CompactSet<T>::const_iterator& CompactSet<T>::const_iterator::operator--()
{
for (--i; !compactSet.bitset[i]; --i) { }
return *this;
}
template<typename T>
CompactSet<T>::CompactSet(const std::size_t capacity) :
bitset(capacity, false)
{
assert(capacity == 0 || capacity - 1 <= std::numeric_limits<T>::max());
assert(capacity <= std::numeric_limits<std::uint_fast64_t>::max()); // Otherwise, iterators won't work.
}
template<typename T>
bool CompactSet<T>::add(const T value)
{
const bool previous = check(value);
if (!previous)
{
bitset[value] = true;
++count;
}
return !previous;
}
template<typename T>
void CompactSet<T>::add(const CompactSet &other)
{
for (const T value : other)
add(value);
}
template<typename T>
void CompactSet<T>::add(const CompactSet &other, const std::size_t overlappingCount)
{
std::transform(
other.bitset.cbegin(), other.bitset.cend(),
this->bitset.begin(), this->bitset.begin(),
std::logical_or<bool>());
this->count += other.count - overlappingCount;
}
template<typename T>
bool CompactSet<T>::remove(const T value)
{
const bool previous = check(value);
if (previous)
{
bitset[value] = false;
--count;
}
return previous;
}
template<typename T>
typename CompactSet<T>::const_iterator CompactSet<T>::begin() const
{
const_iterator iter{*this, 0};
if (!bitset.empty() && !bitset[0])
++iter;
return iter;
}
CompactSet.cc:
#include "./CompactSet.hh" | {
"domain": "codereview.stackexchange",
"id": 45451,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
CompactSet.cc:
#include "./CompactSet.hh"
#ifndef NDEBUG
template<typename T>
void CompactSet<T>::validate() const
{
const std::size_t actualCount = std::ranges::count(bitset.cbegin(), bitset.cend(), true);
assert(count == actualCount);
}
#endif
#include "Minterm.hh"
template class CompactSet<Minterm>;
The function validate() is called (in development build only) to make sure mostly that the 2-argument add() was correctly used and in lesser degree to also check if normal add() and remove() are working correctly.
Minterm (an alias for std::uint_fast32_t) is the only type for which this class is used in my code.
Answer: Instead of a static_assert, I'd prefer to use a constraint to ensure we have only unsigned integer types:
#include <concepts>
template<std::unsigned_integral T>
class CompactSet
{
It's somewhat confusing that bitset refers to a std::vector<bool> and not a std::bitset! Perhaps bits might be a better name?
Why is const_iterator::i not a std::size_t, given that it's being used to index the vector? std::uint_fast64_t might not be big enough, at least in theory. Actually, since it represents the value of type T it's pointing at, perhaps it's sufficient to declare T i;, if we make appropriate arrangements for the past-the-end iterator?
The iterator is missing some boilerplate to work properly as a BidirectionalIterator. It needs a default constructor, and also inner types with the following names:
public:
using value_type = T;
using pointer = T*;
using reference = T&;
using difference_type = std::ptrdiff_t;
using iterator_category = std::bidirectional_iterator_tag;
Whilst ++ operator is careful not to index the vector out of range, -- has no such check. | {
"domain": "codereview.stackexchange",
"id": 45451,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
c++, performance, collections, c++20, memory-optimization
Whilst ++ operator is careful not to index the vector out of range, -- has no such check.
I think we can reduce the size of iterator by wrapping std::vector::iterator rather than needing a reference to the container. But perhaps not, given the need to terminate the search in ++ and -- operators. That can be dealt with by over-allocating the vector by 2 elements and providing sentinel values before and after the valid range. We might choose to have a private view of just the valid values, for more convenient indexing.
You should be able to write operator!=(…) = default. In fact, we should be able to use default equality too - alternatively, test count first, to give a faster result in some cases.
The add() overload that allows callers to break the class invariant is dangerous in my opinion, and I wouldn't allow it. (Why not use std::ranges::transform(), instead of passing iterator pairs?)
It would be good to look more like a std::set:
capacity() should be called max_size() (like std::array, this is a fixed-size container).
add(T) should be called insert() and return a pair. Implement the other insert() signatures, too.
check() should be called count().
Provide reverse iterator functions (use std::make_reverse_iterator() for this).
Provide clear(), swap(), emplace(), emplace_hint(), find(), equal_range(), lower_bound() and upper_bound() (these should be mostly trivial).
Provide erase().
We might be able to provide set intersection, union, difference and symmetric-difference operations that are more efficient than the generic <algorithm> ones. Consider adding them, as an enhancement.
I thought we might be able to implement add() more simply using std::exchange():
const bool previous = std::exchange(bitset[value], true);
count += !previous;
return !previous;
Unfortunately, that gets broken because std::vector<bool> violates the Container contract. | {
"domain": "codereview.stackexchange",
"id": 45451,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, collections, c++20, memory-optimization",
"url": null
} |
performance, algorithm, c, error-handling, tic-tac-toe
Title: Beginner's attempt at TicTacToe
Question: This is my attempt at making a basic TicTacToe game to play against another human player or a computer controlled opponent. The project was a lot harder for me than I initially thought it would be!
I have the feeling I've over complicated some things and think that especially the 'AI' part is not very elegant/efficient. For now tho this is the best I could do.
Would appreciate feedback on anything that comes to mind (program structure, optimization, bad practices etc.)
/*
* tictactoe.c
*
* Copyright 2024 Reslashd
*
* A simple program to play Tic Tac Toe versus a friend or a
* (very basic) computer controlled opponent.
*
*/
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
bool checkMove(char grid[][3], int move, bool move_ok);
int checkThree(char grid[][3], int three_row);
int checkTwo(char grid[][3], int move);
void clearScreen(void);
int cpuMove(char grid[][3], int move, int turn, int difficulty);
void drawGrid(char grid[][3]);
int gameLoop(char grid[][3], int choice, int difficulty, int three_row);
int getMove(char grid[][3], int move, char mark, int choice, int turns, int difficulty);
void makeMove(char grid[][3], int move, char mark);
bool needMove(bool need_move, int nX, int nO, int result);
int pickCpuMove(int move, int location);
void pressToContinue(void);
void resetGrid(char grid[][3]);
void resetVars(int *nX_ptr, int *nO_ptr, int *result_ptr);
int setDifficulty(int difficulty);
int showMenu(int choice);
void showScores(int n_owins, int n_xwins, int n_draws);
char startingMark(char mark, int choice);
char switchMark(char mark);
int main(void){
char grid[3][3] = {{'1','2','3'}, {'4','5','6'}, {'7','8','9'}};
int choice = 0;
int difficulty = '1';
int n_draws = 0;
int n_owins = 0;
int n_xwins = 0;
int three_row = 0;
srand((unsigned int)time(NULL)); | {
"domain": "codereview.stackexchange",
"id": 45452,
"lm_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, error-handling, tic-tac-toe",
"url": null
} |
performance, algorithm, c, error-handling, tic-tac-toe
while ((choice = showMenu(choice)) != '5'){
if (choice == '1' || choice == '2'){
three_row = gameLoop(grid, choice, difficulty, three_row);
clearScreen();
drawGrid(grid);
if(three_row == 1){
puts("\nThree in a row!");
puts("O wins!");
n_owins++;
}
else if (three_row == 2){
puts("\nThree in a row!");
puts("X wins!");
n_xwins++;
}
else{
puts("\nIts a draw!");
n_draws++;
}
resetGrid(grid);
three_row = 0;
pressToContinue();
} else if (choice == '3') {
showScores(n_owins, n_xwins, n_draws);
} else if (choice == '4') {
difficulty = setDifficulty(difficulty);
}
}
return EXIT_SUCCESS;
}
bool checkMove(char grid[][3], int move, bool move_ok){
size_t column = 0;
size_t row = 0;
if (move >= '1' && move <= '9'){
for (row = 0 ; row < 3; row++){
for(column = 0; column < 3 ; column++){
if (grid[row][column] == move){
move_ok = 1;
goto end_checkmove;
}
else{
move_ok = 0;
}
}
}
} else {
move_ok = 0;
}
end_checkmove:
return move_ok;
}
int checkThree(char grid[][3], int three_row){
/*
* This functions checks for 'three in a row' by checking the
* total decimal number in a row, column and diagonal.
* 3 times decimal 79 (OOO) = 237
* 3 times decimal 88 (XXX) = 264
* Returns 0 = draw, 1 = O wins, 2 = X wins
*/
size_t column = 0;
size_t row = 0;
int result = 0; | {
"domain": "codereview.stackexchange",
"id": 45452,
"lm_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, error-handling, tic-tac-toe",
"url": null
} |
performance, algorithm, c, error-handling, tic-tac-toe
// check diagonal left to right
for (row = 0 ; row < 3; row++){
result = result + grid[row][row];
if (result == 237 || result == 264){
if (result == 237) {
three_row = 1;
} else{
three_row = 2;
}
goto return_result;
}
}
result = 0;
// check diagonal right to left
for (row = 0 ; row < 3; row++){
result = result + grid[row][3 - row - 1];
if (result == 237 || result == 264){
if (result == 237) {
three_row = 1;
} else{
three_row = 2;
}
goto return_result;
}
}
result = 0;
// check rows
for (row = 0 ; row < 3; row++){
result = grid[row][0]+grid[row][1]+grid[row][2];
if (result == 237 || result == 264){
if (result == 237) {
three_row = 1;
} else{
three_row = 2;
}
goto return_result;
}
}
result = 0;
// check columns
for (column = 0 ; column < 3; column++){
result = grid[0][column]+grid[1][column]+grid[2][column];
if (result == 237 || result == 264){
if (result == 237) {
three_row = 1;
} else{
three_row = 2;
}
}
}
return_result:
return three_row;
} | {
"domain": "codereview.stackexchange",
"id": 45452,
"lm_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, error-handling, tic-tac-toe",
"url": null
} |
performance, algorithm, c, error-handling, tic-tac-toe
return_result:
return three_row;
}
int checkTwo(char grid[][3], int move){
/*
* This function checks if there are 2 XX's or OO's in a row,
* column or one of the diagonals and if a certain counter move by
* the CPU is needed.
*
* If needed it picks (randomly until the empty spot is found) a
* counter move from a set of possible moves to either prevent a loss
* or make a move to win the game.
*
*/
size_t column = 0;
size_t row = 0;
bool need_move = 0;
int nO = 0;
int nX = 0;
int result = 0;
int *nX_ptr = &nX;
int *nO_ptr = &nO;
int *result_ptr = &result;
// check diagonal left to right
for (row = 0 ; row < 3; row++){
result = result + grid[row][row];
if(grid[row][row] == 'X'){
nX++;
}
else if (grid[row][row] == 'O'){
nO++;
}
}
need_move = needMove(need_move, nX, nO, result);
if (need_move == 1){
move = pickCpuMove(move, 1);
goto return_move;
}
resetVars(nX_ptr, nO_ptr, result_ptr);
// check diagonal right to left
for (row = 0 ; row < 3; row++){
result = result + grid[row][3 - row - 1];
if(grid[row][3 - row - 1] == 'X'){
nX++;
}
else if (grid[row][3 - row - 1] == 'O'){
nO++;
}
}
need_move = needMove(need_move, nX, nO, result);
if (need_move == 1){
move = pickCpuMove(move, 2);
goto return_move;
}
resetVars(nX_ptr, nO_ptr, result_ptr); | {
"domain": "codereview.stackexchange",
"id": 45452,
"lm_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, error-handling, tic-tac-toe",
"url": null
} |
performance, algorithm, c, error-handling, tic-tac-toe
resetVars(nX_ptr, nO_ptr, result_ptr);
// check rows
for (row = 0 ; row < 3; row++){
resetVars(nX_ptr, nO_ptr, result_ptr);
for(column = 0 ; column < 3; column++){
if(grid[row][column] == 'X'){
nX++;
}
else if(grid[row][column] == 'O'){
nO++;
}
result = grid[row][0]+grid[row][1]+grid[row][2];
need_move = needMove(need_move, nX, nO, result);
if (need_move == 1){
move = pickCpuMove(move, (int)row + 3); // location 3, 4, 5
goto return_move;
}
}
}
resetVars(nX_ptr, nO_ptr, result_ptr);
// check columns
for (column = 0 ; column < 3; column++){
resetVars(nX_ptr, nO_ptr, result_ptr);
for(row = 0 ; row < 3; row++){
if(grid[row][column] == 'X'){
nX++;
}
else if(grid[row][column] == 'O'){
nO++;
}
result = grid[0][column]+grid[1][column]+grid[2][column];
need_move = needMove(need_move, nX, nO, result);
if (need_move == 1){
move = pickCpuMove(move, (int)column + 6); // location 6, 7, 8
goto return_move;
}
}
}
move = (rand() % 9) + 49; // Failsafe return random move.
return_move:
return move;
}
void clearScreen(void){
#if defined(__linux__) || defined(__unix__) || defined(__APPLE__)
system("clear");
#endif
#if defined(_WIN32) || defined(_WIN64)
system("cls");
#endif
} | {
"domain": "codereview.stackexchange",
"id": 45452,
"lm_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, error-handling, tic-tac-toe",
"url": null
} |
performance, algorithm, c, error-handling, tic-tac-toe
#if defined(_WIN32) || defined(_WIN64)
system("cls");
#endif
}
int cpuMove(char grid[][3], int move, int turn, int difficulty){
char first_turn[5] = {'1','3', '5', '7', '9'};
char second_turn[4] = {'1','3', '7', '9'};
int n = 0;
if(turn == 1){
// First turn strategy - take center or a corner
n = rand() % 5;
move = first_turn[n];
} else if (turn == 2){
// Second turn strategy - take center if possible else a corner
if(grid[1][1] != 'X' && grid[1][1] != 'O'){
move = '5';
}
else if(grid[1][1] == 'X' || grid[1][1] == 'O'){
n = rand() % 4;
move = second_turn[n];
}
} else if (turn == 3){
// Third turn strategy - take center if possible else random move
if(grid[1][1] != 'X' && grid[1][1] != 'O'){
move = '5';
}
else {
move = (rand() % 9) + 49;
}
// Remaining turns
} else {
//easy
if (difficulty == '1'){
move = (rand() % 9) + 49; // Random move '1' - '9'
}
// hard
else if (difficulty == '2'){
move = checkTwo(grid, move); // Analyze grid and make move
}
}
return move;
}
void drawGrid(char grid[][3]){
printf("\n%c | %c | %c\n", grid[0][0], grid[0][1], grid[0][2]);
puts("=========");
printf("%c | %c | %c\n", grid[1][0], grid[1][1], grid[1][2]);
puts("=========");
printf("%c | %c | %c\n", grid[2][0], grid[2][1], grid[2][2]);
} | {
"domain": "codereview.stackexchange",
"id": 45452,
"lm_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, error-handling, tic-tac-toe",
"url": null
} |
performance, algorithm, c, error-handling, tic-tac-toe
int gameLoop(char grid[][3], int choice, int difficulty, int three_row){
int move = 0;
int turn = 1;
char mark = 'X';
mark = startingMark(mark, choice);
clearScreen();
while(turn != 10) {
clearScreen();
drawGrid(grid);
move = getMove(grid, move, mark, choice, turn, difficulty);
makeMove(grid, move, mark);
mark = switchMark(mark);
turn++;
three_row = checkThree(grid, three_row);
if(three_row == 1 || three_row == 2){
break;
}
}
return three_row;
}
void makeMove(char grid[][3], int move, char mark){
size_t column = 0;
size_t row = 0;
for (row = 0 ; row < 3; row++){
for(column = 0; column < 3 ; column++){
if (grid[row][column] == move){
grid[row][column] = mark;
}
}
}
}
bool needMove(bool need_move, int nX, int nO, int result){
if (nX == 2 || nO == 2){
if (result < 237){
need_move = 1;
}
}
else{
need_move = 0;
}
return need_move;
} | {
"domain": "codereview.stackexchange",
"id": 45452,
"lm_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, error-handling, tic-tac-toe",
"url": null
} |
performance, algorithm, c, error-handling, tic-tac-toe
int pickCpuMove(int move, int location){
/*
* Return a (random until empty spot is found) move from a
* selection of moves based on where the sequence XX or OO was
* found on the grid.
*/
int n = 0;
char diag_LR[3] = {'1', '5', '9'}; // location 1
char diag_RL[3] = {'3', '5', '7'}; // location 2
char row_One[3] = {'1', '2', '3'}; // location 3
char row_Two[3] = {'4', '5', '6'}; // location 4
char row_Three[3] = {'7', '8', '9'}; // location 5
char col_One[3] = {'1', '4', '7'}; // location 6
char col_Two[3] = {'2', '5', '8'}; // location 7
char col_Three[3] = {'3', '6', '9'}; // location 8
n = rand() % 3;
if(location == 1){
move = diag_LR[n];
} else if(location == 2){
move = diag_RL[n];
} else if(location == 3){
move = row_One[n];
} else if (location == 4){
move = row_Two[n];
} else if (location == 5){
move = row_Three[n];
} else if(location == 6){
move = col_One[n];
} else if (location == 7){
move = col_Two[n];
} else if (location == 8){
move = col_Three[n];
}
return move;
}
void pressToContinue(void){
puts("\nPress ENTER to continue");
getchar();
getchar();
}
void resetGrid(char grid[][3]){
size_t column = 0;
size_t row = 0;
char first = '1';
for (row = 0 ; row < 3; row++){
for(column = 0; column < 3 ; column++){
grid[row][column] = first;
first++;
}
}
}
void resetVars(int *nX_ptr, int *nO_ptr, int *result_ptr){
*nX_ptr = 0;
*nO_ptr = 0;
*result_ptr = 0;
} | {
"domain": "codereview.stackexchange",
"id": 45452,
"lm_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, error-handling, tic-tac-toe",
"url": null
} |
performance, algorithm, c, error-handling, tic-tac-toe
int setDifficulty(int difficulty){
int input = 0;
clearScreen();
puts("\n***** SET DIFFICULTY *****\n");
if (difficulty == '1'){
puts("Current difficulty is EASY\n");
} else if (difficulty == '2'){
puts("Current difficulty is HARD\n");
}
puts("1 = Easy");
puts("2 = Hard");
fputs("\nChoose your difficulty: ", stdout);
getchar();
input = getchar();
if (input == '1'){
difficulty = '1';
puts("Difficulty set to EASY");
} else if (input == '2'){
difficulty = '2';
puts("Difficulty set to HARD");
}
else{
puts("\nInvalid choice!");
}
pressToContinue();
return difficulty;
}
int showMenu(int choice){
clearScreen();
puts("\nTIC TAC TOE v1.0 by Reslashd");
puts("\n******* MENU *******\n");
puts("1 = 1 Player vs CPU");
puts("2 = 2 Players");
puts("3 = View scores");
puts("4 = Set difficulty");
puts("5 = Exit");
choice = getchar();
return choice;
}
void showScores(int n_owins, int n_xwins, int n_draws){
clearScreen();
puts("\n***** SCORES *****");
printf("\nO has %d wins", n_owins);
printf("\nX has %d wins", n_xwins);
printf("\nThere are %d draws\n", n_draws);
pressToContinue();
}
char startingMark(char mark, int choice){
int start_mark = 0;
puts("\nPlease choose starting player");
if (choice == '1'){
puts("1 = O (CPU)");
} else if (choice == '2'){
puts("1 = O");
}
puts("2 = X");
getchar();
start_mark = getchar();
if (start_mark == '1'){
mark = 'O';
} else if (start_mark == '2'){
mark = 'X';
}
return mark;
}
char switchMark(char mark){
if (mark == 'X'){
mark = 'O';
} else if (mark == 'O') {
mark = 'X';
}
return mark;
} | {
"domain": "codereview.stackexchange",
"id": 45452,
"lm_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, error-handling, tic-tac-toe",
"url": null
} |
performance, algorithm, c, error-handling, tic-tac-toe
int getMove(char grid[][3], int move, char mark, int choice, int turn, int difficulty){
bool move_ok = 0;
// get Human player move
if(choice == '2' || (choice == '1' && mark == 'X')){
while(move_ok != 1){
printf("\nIt is %c's turn, place your mark: ", mark);
while((move = getchar()) == '\n');
move_ok = checkMove(grid, move, move_ok);
if (move_ok != 1){
puts("Invalid move please try again...");
pressToContinue();
clearScreen();
drawGrid(grid);
}
}
}
// get CPU move
else if (choice == '1' && mark == 'O'){
while (move_ok != 1){
move = cpuMove(grid, move, turn, difficulty);
move_ok = checkMove(grid, move, move_ok);
}
}
return move;
}
Answer: First thing that comes to mind is to remove goto (see SO question):
checkMove you only need to check a single cell not up to 9 with loops
bool checkMove(char grid[][3], int move) { // wouldn't pass move_ok
bool move_ok;
if (move >= '1' && move <= '9') {
// convert from ascii to int, then to position
int row = (move - 49) / 3;
int column = (move - 49) % 3;
if(grid[row][column] == move) {
move_ok = 1;
} else {
move_ok = 0;
}
} else {
move_ok = 0;
}
return move_ok;
}
makeMove can be very similar to checkMove (don't need loop)
// convert from ascii to int, then to position
int row = (move - 49) / 3;
int column = (move - 49) % 3;
grid[row][column] = mark
checkThree you could easily check cell equality in a single line, and then return immediately instead of using goto. Also use bool | {
"domain": "codereview.stackexchange",
"id": 45452,
"lm_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, error-handling, tic-tac-toe",
"url": null
} |
performance, algorithm, c, error-handling, tic-tac-toe
bool checkThree(char grid[][3]) {//don't need three_row
// left to right diagonal
if (grid[0][0] == grid[1][1] && grid[1][1] == grid[2][2]) {
return true;
}
...
return false; // you don't treat 1 or 2 differently from this function
this would require slightly different validating
three_row = checkThree(grid);//don't need to pass three_row
if (three_row){
if(mark == 'O') {
return 1;
} else {
return 2;
}
}
...
checkTwo could be very similar to checkThree, just expand the check (I think you can remove needMove, pickCpuMove, or resetVars)
move = '0'
// left to right diagonal
if (grid[0][0] == grid[1][1] && grid[1][1] != grid[2][2]) {
// know 2 are the same, but not the last
return '9';
} else if (grid[0][0] != grid[1][1] && grid[1][1] == grid[2][2]) {
// know last are the same, but not the first
return '1';
} else if (grid[0][0] == grid[2][2]) {
// know ends are the same, but not the mid
return '5'
}
...
Simplify:
if (grid[1][1] != 'X' && grid[1][1] != 'O') can be if (grid[1][1] != '5')
} else if (grid[1][1] != 'X' || grid[1][1] == 'O') { can be } else {
} else if (mark == 'O') { can be } else {
don't need to pass so many arguments
getMove doesn't need move, it should return move (cpuMove, pickCpuMove (unless you remove it as noted above) also don't need it, same reason)
IMO using function parameters as variables is confusing. Generally I treat function parameters as read-only (there are exceptions to this (see pass by reference), but when I read myVar = myFunc(myVar) I don't expect myVar to change inside myFunc). In setDifficulty I would do something like:
if (input == '1') {
puts("Difficulty set to EASY");
return '1';
} else if (input == '2') {
puts("Difficulty set to HARD");
return '2';
} else {
puts("\nInvalid choice! Difficulty will remain the same");
return difficulty
}
EDIT
Based on https://github.com/Reslashd/tictactoe/blob/main/tictactoe.c
Variable/parameter clean up | {
"domain": "codereview.stackexchange",
"id": 45452,
"lm_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, error-handling, tic-tac-toe",
"url": null
} |
performance, algorithm, c, error-handling, tic-tac-toe
clear names: Reading a variable should let future you/devs know what is stored in it.
don't pass basic variables as parameters to edit
in main, three_row has several issues. It isn't very clear what it stores. I'd change it winner and remove it as a parameter to gameLoop. gameLoop without the parameter could just put the check in the if: if(checkThree(grid)) and the final return would be return 0 (no winner)
switchMark is assigning to mark, instead it should just return. Shorter and clearer code. Don't treat parameters as editable variables, generally should be read only
in gameLoop just initialize mark without passing mark: char mark = startingMark(choice) (might rename to getStartingMark). Inside startingMark change the parameter name to be something like numPlayers instead of choice (clear what is being passed in). The logic of startingMark isn't very clear. It initializes start_mark to an int later it's a char (technically stored same, but to be clear to developer distinguish the type better).
showMenu doesn't need choice, it returns the player choice, initialize choice like char choice = getchar();
change parameter names to be different than what you pass. This might help separate use/difference
setDifficulty the parameter could be currentDifficulty. Side note, inside this function input could be initialized in on line with correct type char input = getchar();
switchMark the param could be currentMark
Simplify Again
99% of the time if you see a pattern it can be simplified
checkTwo and checkThree row/col check could be put in a for loop. checkTwo's fail safe return should validate the random choice is a valid move like all the rest (as cpuMove also has a rand choice, you make a rand choice function, then you won't have to check it later):
char randMove;
do{
randMove = (rand() % 9) + 49;
}while(!checkMove(grid, randMove));
return randMove; // Failsafe return random move. | {
"domain": "codereview.stackexchange",
"id": 45452,
"lm_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, error-handling, tic-tac-toe",
"url": null
} |
performance, algorithm, c, error-handling, tic-tac-toe
All these together: https://gist.github.com/depperm/b28798d3730c0f8394fd1ed380fa95e5 (almost 100 lines shorter) | {
"domain": "codereview.stackexchange",
"id": 45452,
"lm_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, error-handling, tic-tac-toe",
"url": null
} |
c++, bitset
Title: A Dynamic Bitset that I wrote and will use in my compression algortithm. This will be used to store the chars as bits from fstream
Question: I have currently implemented an increment method. A method to add bytes. And a method to print out the bitset.
Main.cpp
#include <iostream>
#include "DynamicBitset.h"
int main()
{
DynamicBitset bitset;
unsigned char count = 97;
bitset.addByte(count);
bitset++;
bitset.printArray();
return 0;
}
DynamicBitset.h
#pragma once
#include <cstring>
#include <iostream>
class DynamicBitset
{
private:
unsigned char* array;
unsigned int arrayLength;
unsigned int bitLength;
public:
//Constructors
DynamicBitset();
DynamicBitset(unsigned int bitLength);
//Deconstructor
~DynamicBitset();
//function to add a byte to the bitset
void addByte(unsigned char byte);
void zeroOutArray();
void zeroUpTo(unsigned int bitIndex);
//DynamicBitset& operator++();
void operator++(int);
void printArray();
};
DynamicBitset.cpp
#include "DynamicBitset.h"
DynamicBitset::DynamicBitset()
{
this->array = nullptr;
this->arrayLength = 0;
this->bitLength = 0;
}
DynamicBitset::DynamicBitset(unsigned int bitLength)
{
if (bitLength % 8 == 0)
{
this->arrayLength == bitLength / 8;
this->array = new unsigned char[this->arrayLength];
this->bitLength = bitLength;
}
else if (bitLength % 8 > 0)
{
this->arrayLength = (int)(bitLength / 8) + 1;
this->array = new unsigned char[this->arrayLength];
this->bitLength = bitLength;
}
else
{
this->arrayLength = 0;
this->array = nullptr;
this->bitLength = 0;
}
}
DynamicBitset::~DynamicBitset()
{
delete[] this->array;
} | {
"domain": "codereview.stackexchange",
"id": 45453,
"lm_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++, bitset",
"url": null
} |
c++, bitset
DynamicBitset::~DynamicBitset()
{
delete[] this->array;
}
void DynamicBitset::addByte(unsigned char byte)
{
unsigned char* tempArray = new unsigned char[this->arrayLength + 1];
memcpy(tempArray, this->array, this->arrayLength);
tempArray[this->arrayLength] = byte;
delete[] this->array;
this->array = tempArray;
this->arrayLength++;
this->bitLength += 8;
}
void DynamicBitset::zeroOutArray()
{
for(int i = 0; i < this->arrayLength; i++)
{
this->array[i] = 0;
}
}
void DynamicBitset::zeroUpTo(unsigned int bitIndex)
{
unsigned int subArrayLength = (unsigned int)(bitIndex / 8);
unsigned int lastCharBitIndex = bitIndex - (subArrayLength * 8);
unsigned char powerMask = 1;
unsigned char bitMask = (powerMask << lastCharBitIndex) - 1;
bitMask = ~bitMask;
this->array[subArrayLength] &= bitMask;
for(int i = 0; i < subArrayLength; i++)
{
this->array[i] = 0;
}
}
void DynamicBitset::operator++(int)
{
unsigned int byteCount = 0;
unsigned int shiftAmount = 0;
unsigned int bitIndex = 0;
while (((this->array[byteCount] >> shiftAmount) & 1) != 0)
{
shiftAmount++;
bitIndex++;
if (shiftAmount % 8 == 0)
{
byteCount = bitIndex / 8;
shiftAmount = 0;
}
if ((byteCount >= this->arrayLength) && bitIndex == this->arrayLength * 8)
{
this->zeroOutArray();
std::cout << "This Ran!" << std::endl;
this->addByte(1);
return;
}
}
unsigned int subArrayLength = (unsigned int)(bitIndex / 8);
unsigned int lastCharBitIndex = bitIndex - (subArrayLength * 8);
unsigned char powerMask = 1;
this->zeroUpTo(bitIndex);
this->array[subArrayLength] += (powerMask << lastCharBitIndex);
}
/*
DynamicBitset& DynamicBitset::operator++()
{
return *this;
}
*/ | {
"domain": "codereview.stackexchange",
"id": 45453,
"lm_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++, bitset",
"url": null
} |
c++, bitset
/*
DynamicBitset& DynamicBitset::operator++()
{
return *this;
}
*/
void DynamicBitset::printArray()
{
for (int i = 0; i < this->arrayLength; i++)
{
std::cout << (int) this->array[i] << ", ";
}
}
For anyone who wants to see the current progress of the project here is the github repository: https://github.com/ChristianDoesCode/DynamicBitset.git
Answer: Use namespaces
DynamicBitset might be a sufficiently unique name, but if you put it inside a namespace, you're much less likely to collide with some other class from some library you import.
Default constructor
I recommend that you set default values in the class definition, then default the default constructor:
class DynamicBitset
{
private:
unsigned char* array = nullptr;
unsigned int arrayLength = 0;
unsigned int bitLength = 0;
public:
//Constructors
DynamicBitset() = default;
//...
DynamicBitset::DynamicBitset(unsigned int bitLength)
This function looks at three cases: the first two (bitLength % 8 == 0 and bitLength % 8 > 0) cover all possible cases, the third one will never happen.
The first two cases do the same thing, but compute the array length slightly differently. This is unnecessary, it is possible to compute the array length correctly for all cases as follows:
DynamicBitset::DynamicBitset(unsigned int bitLength)
{
arrayLength = (bitLength + 7) / 8;
array = new unsigned char[this->arrayLength];
bitLength = bitLength;
} | {
"domain": "codereview.stackexchange",
"id": 45453,
"lm_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++, bitset",
"url": null
} |
c++, bitset
(By the way, you had a bug there: this->arrayLength == bitLength / 8 should have used assignment, =, not equality comparison. Turn on all compiler warnings and pay attention to them, your compiler should be able to warn you about typos like this.)
this->
You don't need to say this->array, unless there's another array defined locally that would hide the class definition. array by itself is sufficient.
memcpy
This is a C function, it's been imported into the C++ standard for convenience, but it is best to use actual C++ functions, as they're type safe. Functions such as memcpy will do lots of damage if the memory pointed to is filled with objects that have a constructor or a destructor. Instead do std::copy_n(array, arrayLength, tempArray).
Use the standard library
For example, in void zeroOutArray() you have a loop, instead you can use std::fill or std::fill_n:
void DynamicBitset::zeroOutArray()
{
std::fill_n(array, arrayLength, 0);
}
This is not only faster to type and easier to read (and thus maintain), but potentially also more efficient.
operator++(int)
This operator should return the value of the operand before increment. It is typically implemented as:
DynamicBitset DynamicBitset::operator++(int) {
DynamicBitset tmp = *this; // make a copy
operator++(); // increment object using other overload
return tmp; // return the copy
}
This implementation would then be based on operator++(), the prefix increment, which must return a reference to the object itself:
DynamicBitset& DynamicBitset::operator++() {
// Implement increment here...
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 45453,
"lm_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++, bitset",
"url": null
} |
c++, bitset
I recommend that you look at a reference like cppreference.com when overloading standard operators, to see if you have the right function signature.
Don't use std::endl
std::endl not only outputs a newline, it also flushes the output buffer. This can cause significant delays, and is typically unnecessary. Just output the '\n' character instead:
std::cout << "This Ran!\n";
Console output
Instead of DynamicBitset::printArray(), consider overloading the << operator:
friend std::ostream& operator<< (std::ostream& stream, const DynamicBitset& bitSet) {
for (int i = 0; i < bitSet->arrayLength; i++)
{
stream << (int) bitSet->array[i] << ", ";
}
}
This is much more flexible, as you can now write the bit set contents to a file or to a string (using stingstream).
Documentation
I suggest you add comments to your header file explaining what every class and function does. This might be clear to you now, but it is not clear to us, and might not be clear to you in a year's time.
What's the purpose?
You can add elements to your bit set, increment it, and zero it. But you can't get any of the data out, except for printing it to the console! It seems to me that this makes the class quite useless... I assume it's work in progress? | {
"domain": "codereview.stackexchange",
"id": 45453,
"lm_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++, bitset",
"url": null
} |
c++, c++11, pointers, optional
Title: deep_ptr; a header-only, deep copying, value semantic smart pointer for optionally defined types
Question: Edit: final revision here
A couple days ago I posted a similar question here. Since then, I have refined the implementation a bit further, as the solution I had previously posited was a bit off target. To repeat my problem statement:
Motivation: I found myself with class members of forward declared types in a header, such as:
struct A;
struct B {
A* a;
}
// B.cpp
include "A.h"
// do stuff with a real A
The problem is that this prevented me from using the default move/copy ctors of B while preserving value semantics of a; even though a is defined as a pointer just to get around the undefined issue, I really want a to be a value. However, I do not want to fully define A in B's header due to the import of various headers/etc that I would like to keep hidden. Unfortunately, I am unable to use boost/std::optional with an undefined type.
My revised solution is focused on preserving value semantics for a type which may or may not be defined at the time of declaration. After refactoring my previous Nullable<T> into a deep_ptr<T>, it becomes easy to provide a nullable/optional<T> wrapper around it as I provide below.
The features of the class in its current state are undefined type support (of course), unique_ptr compatibility, deep copying by default, and custom copy and/or delete functions via functors or stateless lambdas. I believe these are the minimum features needed to solve my original problem and provide a solid base from which to build if needed. Tested on msvc15, clean per visual leak detector.
#ifndef _DEEP_PTR_
#define _DEEP_PTR_
#include <cassert> // assert
#include <memory> // std::unique_ptr
namespace ptr { | {
"domain": "codereview.stackexchange",
"id": 45454,
"lm_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, pointers, optional",
"url": null
} |
c++, c++11, pointers, optional
#include <cassert> // assert
#include <memory> // std::unique_ptr
namespace ptr {
namespace detail {
// dispatches delete to functor DeleteOp
template <typename T, typename DeleteOp>
struct delete_dispatcher {
static void op( T* ptr ) {
DeleteOp{}( ptr );
}
}; // delete_dispatcher
// dispatches to copy functor Op
template <typename T, typename Op>
struct copy_dispatcher {
static auto op( const T& what ) {
return Op{}( what );
}
}; // copy_dispatcher
// default copy functor
template <typename T>
struct default_copy {
auto operator()( const T& what ) const {
return new std::decay_t<T>( what );
}
}; // default_copy
template <typename T> using deep_ptr_base = std::unique_ptr<T, void( *)( T* )>;
} // detail ns
// deep-copying, value semantic wrapper around std::unique_ptr
// DeleteOp functor or lambda signature: void operator()(T*)
// CopyOp functor or lambda signature: T* operator()( const T& )
// Stateless lambdas can be provided via constructors and those will override defined types
template <typename T, typename DeleteOp = std::default_delete<T>, typename CopyOp = detail::default_copy<T>>
struct deep_ptr
: private detail::deep_ptr_base<T> {
using base = detail::deep_ptr_base<T>;
// import from unique_ptr
using base::element_type;
using base::get;
using base::release;
using base::reset;
using base::swap;
using base::operator bool;
using base::operator->;
using base::operator*;
using base::pointer;
using deleter_type = DeleteOp;
using copier_type = CopyOp;
// copy function pointer
using copy_fx_type = element_type*( *)( const element_type& );
// returns function pointer to copy dispatcher
static constexpr auto default_copier() {
return &detail::copy_dispatcher<element_type, copier_type>::op;
} | {
"domain": "codereview.stackexchange",
"id": 45454,
"lm_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, pointers, optional",
"url": null
} |
c++, c++11, pointers, optional
// returns function pointer to delete dispatcher
static constexpr auto default_deleter() {
return &detail::delete_dispatcher<element_type, deleter_type>::op;
}
// construct empty ptr
deep_ptr( std::nullptr_t = nullptr )
: base{ nullptr, []( pointer ) {
assert( false ); // should never hit this
} }
, _copy_fx{}
{}
// construct with pointer, deleter
// Deleter and Copier parameters will accept lambda or functor
// Any provided lambda/functor will override the types provided in deep_ptr definition
template <typename Deleter, typename Copier>
deep_ptr( pointer px, Deleter&& dx, Copier&& cx )
: base{ px, std::forward<Deleter>( dx ) }
, _copy_fx{ std::forward<Copier>( cx ) }
{}
// construct with pointer, deleter
// Deleter parameter will accept lambda or functor
template <typename Deleter>
deep_ptr( pointer px, Deleter&& dx )
: deep_ptr{
px
, std::forward<Deleter>( dx )
, default_copier()
}
{}
// construct with pointer, default delete/copy
deep_ptr( pointer px )
: deep_ptr{
px
, default_deleter()
, default_copier()
} // delegate
{}
// construct from unique_ptr<T, Dx>
template <typename Dx>
deep_ptr( std::unique_ptr<element_type, Dx>&& what )
: deep_ptr{
what.release()
, &detail::delete_dispatcher<element_type, Dx>::op
}
{}
// default move ctor
deep_ptr( deep_ptr&& ) = default;
// default move assign
deep_ptr& operator=( deep_ptr&& ) = default;
// deep copy constructor
deep_ptr( const deep_ptr& rhs )
: deep_ptr{} {
*this = rhs;
}
// deep copy assignment operator
deep_ptr& operator=( const deep_ptr& rhs ) {
if ( this == &rhs )
return *this; | {
"domain": "codereview.stackexchange",
"id": 45454,
"lm_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, pointers, optional",
"url": null
} |
c++, c++11, pointers, optional
if ( this == &rhs )
return *this;
// execute copy op
if ( rhs ) {
assert( rhs.get_copier() != nullptr );
*this = {
rhs.get_copier()( *rhs.get() )
, rhs.get_deleter()
, rhs.get_copier()
}; // copier expected to return T*, which can be null
}
else
*this = nullptr;
return *this;
} // op=(const& deep_ptr)
// returns copier, analagous to unique_ptr get_deleter()
copy_fx_type get_copier() const {
return this->_copy_fx;
}
private:
// copy function pointer
copy_fx_type _copy_fx;
}; // deep_ptr
} // ns
#endif
Tests/usage:
using namespace ptr;
// test undefined in MyStruct from deep_ptr.h
MyStruct s{ new undefined{7} };
assert( s.val->foo == 7 );
// test default move with deep_ptr<undefined>
auto s1 = std::move( s );
assert( s1.val->foo == 7 );
assert( !s.val );
// test default copy with deep_ptr<undefined>
auto s2 = s1;
assert( s2.val->foo == 7 );
assert( s1.val->foo == 7 );
struct A;
struct B {
int foo;
int bar;
};
struct C : B {
int baz;
};
{
// undefined type
deep_ptr<A> undefined{};
assert( undefined.get() == nullptr );
assert( !undefined );
// define A
struct A { int blah; };
deep_ptr<A> a{ new A{3} };
assert( ( *a ).blah == 3 );
assert( (bool)a );
}
{
deep_ptr<B> defined{ new B{1,2} };
auto defined2 = defined; // copy op=
assert( defined2->foo == 1 );
assert( defined2->bar == 2 );
deep_ptr<B> defined3{ defined2 }; // copy ctor
assert( defined3->foo == 1 );
assert( defined3->bar == 2 );
deep_ptr<B> defined4{ std::move( defined2 ) };// move ctor
assert( defined4->foo == 1 );
assert( defined4->bar == 2 );
assert( !defined2 ); | {
"domain": "codereview.stackexchange",
"id": 45454,
"lm_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, pointers, optional",
"url": null
} |
c++, c++11, pointers, optional
auto defined5 = std::move( defined3 ); // move op
assert( defined5->foo == 1 );
assert( defined5->bar == 2 );
assert( !defined3 );
// nullptr_t assignment
defined5 = nullptr;// reset
assert( !defined5 );
}
// deep_ptr with functor deleter
static bool mydeleter_test_passed = false;
{
struct mydeleter {
void operator()( B* ptr ) const {
delete ptr;
mydeleter_test_passed = true;
}
};
deep_ptr<B, mydeleter> functor{ new B{ 1,2 } };
}
assert( mydeleter_test_passed );
// deep_ptr with stateless lambda deleter
static bool lambda_deleter_test_passed = false;
{
deep_ptr<B> lambda{ new B{ 1,2 }, []( B* ptr ) {
delete ptr;
lambda_deleter_test_passed = true;
} };
}
assert( lambda_deleter_test_passed );
// deep_ptr with copy functor
static bool mycopier_test_passed = false;
{
struct mycopier {
auto operator()( const B& what ) const {
mycopier_test_passed = true;
return new B{ what };
}
};
deep_ptr<B, std::default_delete<B>, mycopier> copy_functor{ new B{ 1,2 } };
auto mycopy = copy_functor;
assert( mycopy->foo == 1 );
assert( mycopy->bar == 2 );
}
assert( mycopier_test_passed );
// deep_ptr with stateless lambda copier
static bool lambda_copier_test_passed = false;
{
deep_ptr<B> lambda{
new B{ 1,2 }
, deep_ptr<B>::default_deleter()
, []( const B& what ) {
lambda_copier_test_passed = true;
return new B{ what };
}
};
auto copy = lambda;// try custom copier
}
assert( lambda_copier_test_passed );
// derived type custom copier
{
C c{};
c.foo = 1;
c.bar = 2;
c.baz = 3; | {
"domain": "codereview.stackexchange",
"id": 45454,
"lm_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, pointers, optional",
"url": null
} |
c++, c++11, pointers, optional
// derived type custom copier
{
C c{};
c.foo = 1;
c.bar = 2;
c.baz = 3;
deep_ptr<B> lambda{
new C{c}
, deep_ptr<B>::default_deleter()
, []( const B& what ) -> B* { // must return B*
return new C{ static_cast<const C&>( what ) }; // cast what to const C&, copy construct a C
}
};
auto copy = lambda;// execute
assert( static_cast<C&>( *copy ).baz == 3 );
}
// construct from std::unique_ptr<T, Deleter>
static bool uptr_deleter_test_passed = false;
{
struct my_deleter {
void operator()( int* ptr ) {
delete ptr;
uptr_deleter_test_passed = true;
}
};
deep_ptr<int> deepint{};
{
std::unique_ptr<int, my_deleter> myint{ new int( 5 ) };
deepint = std::move( myint ); // op=(unique_ptr<T, Dx>&&)
assert( !myint );
assert( *deepint == 5 );
}
assert( !uptr_deleter_test_passed ); // deleter should not have been called yet
}
assert( uptr_deleter_test_passed );
Finally, my Nullable<T> class reimplemented using deep_ptr<T>:
// Example polymorphic optional using deep_ptr with undefined type support
template <typename T, typename Copier>
struct Nullable {
private:
using _value_type = T;
using _data_type = ptr::deep_ptr<_value_type, std::default_delete<_value_type>, Copier>;
_data_type _data;
// Get T*
auto _get() { return this->_data.get(); }
// Get const T*
auto _get() const { return this->_data.get(); }
public:
using value_type = _value_type;
using nullopt_t = std::nullptr_t;
Nullable() = default;
// Construct with value_type
Nullable( value_type what )
: _data{ new value_type{ std::move( what ) } }
{}
// Construct with derived type
// todo: some SFINAE on Derived, maybe
template <typename Derived>
Nullable( Derived d )
: _data{ new Derived{std::move( d )} }
{} | {
"domain": "codereview.stackexchange",
"id": 45454,
"lm_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, pointers, optional",
"url": null
} |
c++, c++11, pointers, optional
// returns stored value, UB if none
value_type& operator*() { return *this->_get(); }
const value_type& operator*() const { return *this->_get(); }
// returns pointer to stored value, UB if none
const value_type* operator->() const { return this->_get(); }
// returns pointer to stored value, UB if none
value_type* operator->() { return this->_get(); }
// returns flag if this has value
explicit constexpr operator bool() const {
return this->_get() != nullptr;
}
// returns flag if this has value
constexpr bool has_value() const { return bool( *this ); }
// returns T&, or throws if value undefined
value_type& value() {
if ( auto ptr = this->_get() )
return *ptr;
throw std::logic_error{ "Value not set" };
}
// returns const T&, or throws if value undefined
const value_type& value() const {
if ( auto ptr = this->_get() )
return *ptr;
throw std::logic_error{ "Value not set" };
}
// resets value
void reset() { this->_data = {}; }
}; // Nullable
Tests/usage of Nullable<T>
// example usage: Polymorphic Nullable
struct base {
int foo;
base( int foo_ ) :foo{ foo_ } {}
virtual base* clone() const { return new base{ *this }; }
};
struct derived : base {
int bar;
derived( int foo_, int bar_ ) : base{ foo_ } , bar{ bar_ } {}
base* clone() const override { return new derived{ *this }; }
};
struct PolymorphicCopier {
base* operator()( const base& what ) const {
return what.clone();
}
};
::Nullable<base, PolymorphicCopier> myopt{};
// test with base class
myopt = base{ 1 };
assert( myopt.value().foo == 1 );
auto myopt2 = myopt; // copy
assert( myopt2.value().foo == 1 ); | {
"domain": "codereview.stackexchange",
"id": 45454,
"lm_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, pointers, optional",
"url": null
} |
c++, c++11, pointers, optional
auto myopt2 = myopt; // copy
assert( myopt2.value().foo == 1 );
// test with derived class in Nullable<base>
myopt = derived{ 8,9 };
assert( static_cast<const derived&>( myopt.value() ).bar == 9 );
auto myopt3 = myopt; // copy
assert( static_cast<const derived&>( myopt3.value() ).bar == 9 ); // look ma, no slicing!
auto myopt4 = std::move( myopt3 ); // move
assert( !myopt3.has_value() );
assert( static_cast<const derived&>( myopt4.value() ).bar == 9 ); // look ma, no slicing!
Thoughts and feedback appreciated. Off the top of my head, I'm not sure if there's a better way to handle the dispatching of the functors/lambdas in deep_ptr, as I'm trying to avoid holding a std::function due to size bloat, and I'm expecting the compiler to optimize the lambdas/functors to pointers. Or, in keeping with the "you don't pay for what you don't use" paradigm of C++, some way to minimize the size of deep_ptr in the case of using the default delete/copy handlers. Seems like I would need to store two function pointers at minimum, but maybe there's a better way.
Answer: It would have been helpful to have the unit tests as part of this review. That helps reviewers see what use-cases have been provided for and can help identify gaps in testing. Really good tests also show what's expected to be invalid (using the Detection Idiom to verify rejection).
In the template, we need to tell the compiler which base identifiers represent types, using typename:
using typename base::element_type;
using base::get;
using base::release;
using base::reset;
using base::swap;
using base::operator bool;
using base::operator->;
using base::operator*;
using typename base::pointer;
With that change, I can compile cleanly using GCC.
I think that this constructor ought to be explicit:
deep_ptr( pointer px )
Just like std::unique_ptr, we don't want to accidentally take ownership of an existing object. That might lead to unexpected early deletion. | {
"domain": "codereview.stackexchange",
"id": 45454,
"lm_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, pointers, optional",
"url": null
} |
c++, c++11, pointers, optional
This smart pointer is less flexible than std::unique_ptr in terms of deleter. We only accept function pointers, but I think we should accept any function object, by inheriting from std::unique_ptr<T, DeleteOp>, and do away with the despatchers.
Since copying a deep pointer has value semantics, I think it's reasonable to create a pointer-to-mutable from a pointer-to-const, like this:
const int *a = new int{6};
ptr::deep_ptr<const int> p = &a;
ptr::deep_ptr<int> q = p;
assert(p.get() != q.get());
That's ill-formed, which is unfortunate.
A constructor that copies from a const T& would be useful, particularly when writing constructors:
struct B {
ptr::deep_ptr<A> a;
B(const A& a) : a{ptr::deep_ptr<A>{a}} {} // INVALID!
};
Rather than a constructor, perhaps a function to copy a value into a deep pointer?
template<typename T,
typename Deleter = std::default_delete<T>,
typename Copier = detail::default_copy<T>>
deep_ptr<T, Deleter, Copier>
deep_copy(const T& object, Deleter = {}, Copier c = {})
{
return {c(object),
// this would be easier if we could simply pass the
// function objects
&detail::delete_dispatcher<T, Deleter>::op,
&detail::copy_dispatcher<T, Copier>::op};
}
That permits
B(const A& a) : a{ptr::deep_copy(a)} {}
The assignment operator allocates memory (by creating a new deep pointer), but that shouldn't be necessary when T is copy-assignable. Avoiding allocation for this common case will improve performance and eliminate a possible source of std::bad_alloc. | {
"domain": "codereview.stackexchange",
"id": 45454,
"lm_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, pointers, optional",
"url": null
} |
c++, array, c++20
Title: Writing a multidimensional array view for contiguous arrays in C++20
Question: When creating little games or other programs I often need multidimensional arrays. Usually I just do the simple std::vector<std::vector<T>> thing for simplicity's sake. However, this runs way more allocations and the data is not stored in one contiguous location, which brings some drawbacks with it. To fix this I wanted to create a multidimensional array view, with which I can just have something along the following lines (with an example of an array transformed to a 3x3 matrix):
std::vector<int> vec{ /* ... */ };
MDSpan<int, 3, 3> view{ vec.data() };
view[1][2] = 123;
My first approach was only templated on the datatype, but not the dimensions. This allowed for dynamic resizing and reshaping of the view, but it didn't allow for the multiple subscript operators returning different types, either new views, or values if the span is one-dimensional.
After that I restructured my code to be templated on the dimensions as well, which got rid of the previously mentioned subscript problem and additionally got compile time constant evaluation possibilities.
#pragma once
#include <concepts>
#include <utility>
#include <array>
template <template<typename, auto...> typename U, typename V, auto first, auto... others>
struct DropFirstPackValue {
using type = U<V, others...>;
};
template <template<typename, auto...> typename U, typename V, auto first, auto... others>
using DropFirstPackValue_t = DropFirstPackValue<U, V, first, others...>::type; | {
"domain": "codereview.stackexchange",
"id": 45455,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, c++20",
"url": null
} |
c++, array, c++20
template <typename T, std::size_t... strides>
requires (sizeof...(strides) > 0)
class MDSpan {
public:
constexpr MDSpan() = default;
constexpr MDSpan(T* begin) {
reset(begin);
}
constexpr void reset(T* begin) {
m_begin = begin;
}
constexpr const T& at(std::integral auto... indices) const requires(sizeof...(strides) == sizeof...(indices)) {
const std::array arr{ indices... };
std::size_t offset{};
for (std::size_t i{}, size{ arr.size() }; i < size; ++i) {
offset += getStridesProduct(size - 1 - i) * arr[i];
}
return *(m_begin + offset);
}
constexpr T& at(std::integral auto... indices) requires(sizeof...(strides) == sizeof...(indices)) {
return const_cast<T&>(std::as_const(*this).at(indices...));
}
constexpr const T& operator[](std::size_t index) const requires(sizeof...(strides) == 1) {
return at(index);
}
constexpr T& operator[](std::size_t index) requires(sizeof...(strides) == 1) {
return at(index);
}
constexpr auto operator[](std::size_t index) requires(sizeof...(strides) > 1) {
const std::size_t offset{ getStridesProduct(dimensions()) };
T* begin{ m_begin + index * offset };
return DropFirstPackValue_t<MDSpan, T, strides...>{ begin };
}
constexpr T* data() {
return m_begin;
}
constexpr auto begin() {
return Iterator{ *this };
}
constexpr auto end() {
return Iterator{ *this, stride(0) };
}
constexpr static std::size_t dimensions() {
return m_strides.size();
}
constexpr static std::size_t stride(std::size_t index) {
return m_strides[index];
}
constexpr bool empty() const {
return !m_begin;
}
constexpr operator bool() const {
return !empty();
} | {
"domain": "codereview.stackexchange",
"id": 45455,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, c++20",
"url": null
} |
c++, array, c++20
constexpr bool operator==(const MDSpan& other) const {
return m_begin == other.m_begin;
}
constexpr bool operator!=(const MDSpan& other) const {
return !(*this == other);
}
private:
constexpr static std::size_t getStridesProduct(std::size_t index) {
std::size_t product{ 1 };
for (std::size_t i{}; i + 1 < index; ++i) {
product *= stride(dimensions() - 1 - i);
}
return product;
}
private:
T* m_begin;
inline constexpr static std::array m_strides{ strides... };
private:
class Iterator {
public:
constexpr Iterator operator++(int) {
return Iterator{ m_owner, m_index++ };
}
constexpr Iterator operator++() {
++m_index;
return *this;
}
constexpr Iterator operator--(int) {
return Iterator{ m_owner, m_index-- };
}
constexpr Iterator operator--() {
--m_index;
return *this;
}
constexpr auto operator*() {
return m_owner[m_index];
}
constexpr bool operator==(const Iterator& other) const {
return m_owner == other.m_owner && m_index == other.m_index;
}
constexpr bool operator!=(const Iterator& other) const {
return !(*this == other);
}
private:
constexpr Iterator(MDSpan& owner, std::size_t index = 0)
: m_owner{ owner }, m_index{ index } {
}
friend class MDSpan;
private:
MDSpan& m_owner;
std::size_t m_index;
};
};
I would appreciate any kind of review and criticism, but have some specific questions, too: | {
"domain": "codereview.stackexchange",
"id": 45455,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, c++20",
"url": null
} |
c++, array, c++20
I would appreciate any kind of review and criticism, but have some specific questions, too:
MDSpan::operator[] returning a sub-view could be marked as const, since it does not modify this in any way. However it still grants access to the underlying data. The same applies for MDSpan::data(), MDSpan::begin() and MDSpan::end(). Therefore it should not be const in my opinion. Is this the right decision?
In the non-const version of MDSpan::at() I use the const one with a const_cast. Since I am just dropping the previously applied const qualifier, this should be well defined, but is it good practice to do so?
MDSpan::Iterator::operator*() and MDSpan::operator[] return new MDSpan objects, and not references. Is there a way to work around this? While those MDSpans are lightweight and you can still achieve the same as with references, since those are views, there might still be some confusion as in e.g. range based for loops not being able to use references.
In my first approach, the dynamic one, I was checking for indexing out of bounds via assert() from <cassert>, however, since my static one should be able to be used as constexpr, I can't do this anymore so I dropped all checks, which makes it more lightweight as well. Should I still keep the checks, or maybe switch to exceptions instead and just use the preprocessor to enable/disable error checking for debug/release builds? And if I use bounds checking, should I disallow access with greater/equal indices to one of the strides or only disallow indexing which would access not owned memory?
(I know about C++23's std::mdspan, but wanted to implement my own multidimensional view. This is just for private projects and might even not get used at all.)
Answer: Overall impression: well-written and well presented. It's pretty clear what's going on. I would have liked to have seen the unit tests, too - that generally helps reviewers. | {
"domain": "codereview.stackexchange",
"id": 45455,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, c++20",
"url": null
} |
c++, array, c++20
The constructor default-initialises m_begin, then assigns. It's better to use a real initialiser:
constexpr MDSpan(T* begin)
m_begin{begin}
{
}
*(m_begin + offset) is more conventionally written m_begin[offset].
We could really use a constructor for creating a MDSpan<const T> from MDSpan<T> where T is non-const.
To make Iterator fully functional, it needs a public default constructor and the crucial members for its traits to work:
public:
using value_type = T;
using pointer = T*;
using reference = T&;
using difference_type = std::ptrdiff_t;
using iterator_category = std::bidirectional_iterator_tag;
It shouldn't be too hard to make it satisfy the requirements for a random access iterator, which can improve its utility with standard algorithms.
The span class lacks cbegin()/cend(). I mention that because iterator should convert to const_iterator but not vice versa, which can be slightly tricky if we template the iterator to avoid writing it out twice.
Reverse iterator functions would also be good to have, and trivially implemented using std::make_reverse_iterator().
Answering the specific questions:
I agree that the subview [] operator mustn't be const if it allows read-write access to elements. However, we could provide a const version that provides a subview of const T elements. Use concepts to avoid collision when T is already const.
That's safe, but when you move to C++23, be aware of deducing this, which is the modern way to write a single member function for both const and mutable objects.
We could overload the operators for different number of dimensions, using constraints. | {
"domain": "codereview.stackexchange",
"id": 45455,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, c++20",
"url": null
} |
c++, array, c++20
We could overload the operators for different number of dimensions, using constraints.
As a user, I wouldn't expect to pay the cost of bounds checking unless I specifically ask for it. That's the main difference between at() and [] in standard collections, for example.
I would throw std::out_of_range from the at() member when attempting to access outside the bounds of the span (regardless of whether that's within the underlying object, it's clearly erroneous - std::string_view is a good model to imitate for this). | {
"domain": "codereview.stackexchange",
"id": 45455,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, c++20",
"url": null
} |
c++
Title: Graphical Visualizer in terminal V[2]: using it visualizing: falling sand sim, sorting algorithms and the game of life
Question: this is the second version of this project, you can check previous post here: Terminal Graphical Visualizer, using a queue of different matrices
I implemented bare-bones version of ncurses library (without using it obviously), and using it I implemented 3 visualizations:
falling sand simulation - drop a line of sand particles of random length, if it encounters a particle below or the floor it stops, i used links of the send being dropped and removing the sand particle from the link if it encounters a position where it can't keep falling, it got 2 version of simulation, one it falls only in y axis and the second it can fall diagonally if encounters a particle below but diagonally down to the left or right is not occupied it falls there.
sorting algorithm visualization - sorts columns based on height and visualizing each step of the sort, I used the matrix of the falling sand and sorted it.
game of life - well it is the game of life I won't be posting the rules of it but you can search it up the rules are very simple, I added a function that configures the matrix to the glider gun.
Code:
graphical_visualizer.hpp
#pragma once
#include <chrono>
#include <map>
#include <queue>
#include <string>
#include <unordered_map>
#include <vector>
const std::unordered_map<std::string, char const *> colors = {{"red", "\033[31m"}, {"green", "\033[32m"}, {"blue", "\033[34m"}, {"yellow", "\033[33m"}, {"reset", "\033[0m"}};
void gotoxy(size_t x, size_t y);
struct Pixel { // represents every single character on terminal
char character;
char const *color_code;
bool operator==(Pixel const &compare);
bool operator!=(Pixel const &compare);
};
using frame_matrix = std::vector<std::vector<Pixel>>; | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
using frame_matrix = std::vector<std::vector<Pixel>>;
class Frame { // consists of a pixel matrix, methods to manipulate and print the frame and consts for more flexebility
private:
void initialize_frame();
bool is_valid_input(std::string const &height_start, std::string const &height_length, std::string const &range_start, std::string const &range_length, std::string const &printable_char, std::string const &color);
public:
frame_matrix current_frame;
const static size_t AMOUNT_OF_INPUT_OPTIONS = 6;
const static size_t FRAME_WIDTH = 40;
const static size_t FRAME_HEIGHT = 20;
const static char INPUT_DELIMITER = ',';
const static char BACKGROUND = ' ';
Frame();
Frame(std::string const &input);
frame_matrix get_current_frame() const;
void alter_frame(std::string const &input);
void set_current_frame(frame_matrix const &new_current_frame);
void print_frame();
void print_frame(Frame const &prev_frame);
bool parse_input(std::string const &input);
};
class GraphicalVisualizer { // consists of a queue of frames and methods that manipulate the queue and prints the frames in order
private:
std::queue<Frame> frame_queue;
public:
GraphicalVisualizer();
std::queue<Frame> get_frame_queue() const;
void add_frame(Frame frame);
void print_sequence(const std::chrono::milliseconds millis);
void print_sequence_no_clear(const std::chrono::milliseconds millis);
};
graphical_visualizer.cpp
#include "graphical_visualizer.hpp"
#include <cstring>
#include <iostream>
#include <sstream>
#include <thread>
void gotoxy(size_t x, size_t y) {
std::cout << "\033[" << y << ";" << x << "H";
}
bool Pixel::operator==(Pixel const &compare) {
return character == compare.character && std::strcmp(color_code, compare.color_code);
}
bool Pixel::operator!=(Pixel const &compare) {
return character != compare.character || !std::strcmp(color_code, compare.color_code);
} | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
Frame::Frame() { initialize_frame(); } // without parameters initializes the frame to an empty frame of FRAME::HEIGHT * FRAME::WIDTH filled with white FRAME::BACKGROUND characters
Frame::Frame(const std::string &input) { // with input from user initilizes the frame and sets it to according to the input
initialize_frame();
alter_frame(input);
}
frame_matrix Frame::get_current_frame() const { return current_frame; }
void Frame::alter_frame(std::string const &input) { // if parse_input found invalid input prints the message otherwise parse_input just does the job of actually altering the frame
if (!parse_input(input))
std::cout << "Invalid input \n";
}
void Frame::set_current_frame(frame_matrix const &new_current_frame) {
current_frame = new_current_frame;
}
void Frame::print_frame() { // prints frame char by char first sets the color of the char then prints the char itself and then resets the color back to white
for (auto const &line : current_frame) {
for (auto const ¤t_pixel : line) {
std::cout << current_pixel.color_code << current_pixel.character;
std::cout << colors.at("reset");
}
std::cout << std::endl;
}
}
void Frame::print_frame(Frame const &prev_frame) { // prints the frame using goto, used to print the frame without calling system("clear") every frame
for (size_t i = 0; i < FRAME_HEIGHT; ++i) {
for (size_t j = 0; j < FRAME_WIDTH; ++j) {
if (current_frame[i][j] != prev_frame.current_frame[i][j]) {
gotoxy(j, i);
std::cout << current_frame[i][j].color_code << current_frame[i][j].character;
std::cout << colors.at("reset");
}
}
}
}
bool Frame::parse_input(std::string const &input) { // parses the input that consists of "heigh_start,height_length,range_start,range_length,shape,color"
std::stringstream input_stream(input); | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
std::string input_sections[AMOUNT_OF_INPUT_OPTIONS];
size_t input_sections_index = 0;
while (std::getline(input_stream, input_sections[input_sections_index], INPUT_DELIMITER)) // inserts the input into sections of an array
++input_sections_index;
if (!is_valid_input(input_sections[0], input_sections[1], input_sections[2], input_sections[3], input_sections[4], input_sections[5]))
return false;
int height_start = std::stoi(input_sections[0]); // convers input into usable types
int height_length = std::stoi(input_sections[1]);
int range_start = std::stoi(input_sections[2]);
int range_length = std::stoi(input_sections[3]);
char const *color = colors.at(input_sections[5]);
char printable_char = input_sections[4][0]; // should always be a string of length 1
for (size_t i = height_start; i <= height_start + height_length - 1; ++i) { // alters the frame based on the input
for (size_t j = range_start; j <= range_start + range_length - 1; ++j) {
current_frame[i][j].character = printable_char;
current_frame[i][j].color_code = color;
}
}
return true;
}
void Frame::initialize_frame() { // initializes the frame with Frame::BACKGROUND and white color
for (size_t i = 0; i < FRAME_HEIGHT; ++i) {
std::vector<Pixel> line;
line.reserve(FRAME_WIDTH);
for (size_t j = 0; j < FRAME_WIDTH; ++j)
line.push_back({BACKGROUND, colors.at("reset")});
current_frame.push_back(line);
}
}
bool is_a_number(std::string const &number) {
for (char const &ch : number) {
if (!std::isdigit(ch))
return false;
}
return true;
}
bool Frame::is_valid_input(std::string const &height_start, std::string const &height_length, std::string const &range_start, std::string const &range_length, std::string const &printable_char, std::string const &color) {
auto pos = colors.find(color); | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
auto pos = colors.find(color);
if (pos == colors.end())
return false;
if (!is_a_number(height_start) || !is_a_number(height_start) || !is_a_number(height_start) || !is_a_number(height_start)) { // checks if all passed numbers are actuall numbers
return false;
}
if (printable_char.size() != 1)
return false;
int height_start_int = std::stoi(height_start);
int height_length_int = std::stoi(height_length);
int range_start_int = std::stoi(range_start);
int range_length_int = std::stoi(range_length);
// checks if the numbers passed are in range
if (height_start_int < 0 ||
height_length_int + height_length_int - 1 >= FRAME_HEIGHT ||
range_start_int < 0 ||
range_start_int + range_length_int - 1 >= FRAME_WIDTH)
return false;
return true;
}
GraphicalVisualizer::GraphicalVisualizer() { frame_queue = {}; } // initializes an empty queue
std::queue<Frame> GraphicalVisualizer::get_frame_queue() const {
return frame_queue;
}
void GraphicalVisualizer::add_frame(Frame frame) { frame_queue.push(frame); }
void GraphicalVisualizer::print_sequence(const std::chrono::milliseconds millis) { // accepts a parameter of time between each frame
std::queue<Frame> local_temp_queue = frame_queue;
while (local_temp_queue.size() > 1) { // prints the frame then pops it from the queue, sleeps for provided time and clears the terminal for the next frame
local_temp_queue.front().print_frame();
local_temp_queue.pop();
std::this_thread::sleep_for(millis);
system("clear");
}
local_temp_queue.front().print_frame(); // prints last frame without clearing it from the terminal
local_temp_queue.pop();
} | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
// prints the frames same as print_sequence but without using system("clear") insted providing the previous frame so it can just update the pixels that are different
void GraphicalVisualizer::print_sequence_no_clear(const std::chrono::milliseconds millis) {
std::queue<Frame> local_temp_queue = frame_queue;
local_temp_queue.front().print_frame();
while (local_temp_queue.size() > 1) {
Frame last_frame = local_temp_queue.front();
local_temp_queue.pop();
local_temp_queue.front().print_frame(last_frame);
std::this_thread::sleep_for(millis);
// system("clear");
}
local_temp_queue.front().print_frame();
local_temp_queue.pop();
system("clear");
}
falling_sand.hpp
#pragma once
#include "graphical_visualizer.hpp"
#include <chrono>
#include <queue>
#include <string>
#include <vector>
using namespace std::chrono_literals;
const char SAND_SHAPE = '@';
const std::string SAND_DEFAULT_COLOR = "red";
const int SAND_BLOCK_AMOUNT = 15;
const int MIN_SAND_LENGTH = 5;
const int MAX_SAND_LENGTH = 15;
const std::chrono::milliseconds millis_per_frame_falling_sand = 20ms;
struct SandBlock { // represent a line of falling sand, each line consists of vector of pairs that represent the position of each sand particle within the block
int length;
int starting_position;
char shape;
std::string color;
std::vector<std::pair<size_t, size_t>> links;
SandBlock();
SandBlock(std::string color);
};
class FallingSand { // consists of a frame that changes, the visualizer that prints the frames and a queue of sand blocks that after reaching a stop the next in queue falls
private:
Frame field;
GraphicalVisualizer visualizer;
std::queue<SandBlock> sand_blocks;
public:
FallingSand();
void generate_sand_blocks();
void simulate_fall();
void simualte_diag_fall();
Frame get_field() const;
};
falling_sand.cpp
#include "falling_sand.hpp"
#include <random> | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
Frame get_field() const;
};
falling_sand.cpp
#include "falling_sand.hpp"
#include <random>
int generate_random_length() {
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist(MIN_SAND_LENGTH, MAX_SAND_LENGTH); // distribution in range [MIN_SAND_LENGTH, MAX_SAND_LENGTH]
return dist(rng);
}
int generate_random_start_pos(int sand_length) {
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist(0, Frame::FRAME_WIDTH - sand_length);
return dist(rng);
}
SandBlock::SandBlock() { // generate random starting possition and length of the block and the pushes the particles into the vector of links
length = generate_random_length();
starting_position = generate_random_start_pos(length);
shape = SAND_SHAPE;
color = SAND_DEFAULT_COLOR;
for (size_t i = starting_position; i <= starting_position + length - 1; ++i) {
links.push_back({0, i});
}
}
SandBlock::SandBlock(std::string color) : color(color) { // same as without params but sets the color to the provided one instead of default const
length = generate_random_length();
starting_position = generate_random_start_pos(length);
shape = SAND_SHAPE;
for (size_t i = starting_position; i <= starting_position + length - 1; ++i) {
links.push_back({0, i});
}
}
FallingSand::FallingSand() {
generate_sand_blocks();
// simulate_fall();
simualte_diag_fall();
system("clear");
visualizer.print_sequence(millis_per_frame_falling_sand);
}
void FallingSand::generate_sand_blocks() {
for (size_t i = 1; i <= SAND_BLOCK_AMOUNT; ++i) {
sand_blocks.push(SandBlock());
}
}
void FallingSand::simulate_fall() { // the simulation itself this is version without daig falls of sand particles only in the y axis
while (!sand_blocks.empty()) {
SandBlock current_block = sand_blocks.front(); | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
while (!sand_blocks.empty()) {
SandBlock current_block = sand_blocks.front();
bool did_move = true;
while (did_move) {
did_move = false;
visualizer.add_frame(field); // adds the current state of frame to the visualizer queue
frame_matrix new_frame = field.get_current_frame();
for (size_t i = 0; i < current_block.links.size(); ++i) {
std::pair<size_t, size_t> link = current_block.links[i]; // tracks the current sand particle
// checks for bounds
if (link.first != Frame::FRAME_HEIGHT - 1 && field.get_current_frame()[link.first + 1][link.second].character != current_block.shape) {
did_move = true;
// resets the color and shape of current place, then updates the color and shape of the one below
new_frame[current_block.links[i].first][current_block.links[i].second] = {Frame::BACKGROUND, colors.at("reset")};
current_block.links[i].first += 1;
new_frame[current_block.links[i].first][current_block.links[i].second] = {current_block.shape, colors.at(current_block.color)};
}
}
field.set_current_frame(new_frame);
}
sand_blocks.pop();
}
}
int generate_random_direction() { // generates random direction for diag fall either fall left or right
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist(0, 1);
return dist(rng);
}
void FallingSand::simualte_diag_fall() {
while (!sand_blocks.empty()) {
SandBlock current_block = sand_blocks.front();
bool did_move = true;
while (did_move) {
did_move = false;
visualizer.add_frame(field);
frame_matrix new_frame = field.get_current_frame(); | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
for (size_t i = 0; i < current_block.links.size(); ++i) {
std::pair<size_t, size_t> link = current_block.links[i];
// same as without diag fall but it does not stop when encounters anothe particle below
if (link.first != Frame::FRAME_HEIGHT - 1 && field.get_current_frame()[link.first + 1][link.second].character != current_block.shape) {
did_move = true;
new_frame[current_block.links[i].first][current_block.links[i].second] = {Frame::BACKGROUND, colors.at("reset")};
current_block.links[i].first += 1;
new_frame[current_block.links[i].first][current_block.links[i].second] = {current_block.shape, colors.at(current_block.color)};
} else if (link.first != Frame::FRAME_HEIGHT - 1 && field.get_current_frame()[link.first + 1][link.second].character == current_block.shape) {
int direction = generate_random_direction(); | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
int direction = generate_random_direction();
// checks if generated 1 in direction and also for bounds and posibility to fall diagonally to the left else checks right
if (link.second != Frame::FRAME_WIDTH - 1 && direction == 1 && field.get_current_frame()[link.first + 1][link.second + 1].character != current_block.shape) {
new_frame[current_block.links[i].first][current_block.links[i].second] = {Frame::BACKGROUND, colors.at("reset")};
current_block.links[i].first += 1;
current_block.links[i].second += 1;
new_frame[current_block.links[i].first][current_block.links[i].second] = {current_block.shape, colors.at(current_block.color)};
} else if (link.second != 0 && field.get_current_frame()[link.first + 1][link.second - 1].character != current_block.shape) {
new_frame[current_block.links[i].first][current_block.links[i].second] = {Frame::BACKGROUND, colors.at("reset")};
current_block.links[i].first += 1;
current_block.links[i].second -= 1;
new_frame[current_block.links[i].first][current_block.links[i].second] = {current_block.shape, colors.at(current_block.color)};
}
}
}
field.set_current_frame(new_frame);
}
sand_blocks.pop();
}
}
Frame FallingSand::get_field() const {
return field;
}
algorithm_visualizer.hpp
#pragma once
#include "falling_sand.hpp"
#include "graphical_visualizer.hpp"
#include <chrono>
#include <iterator>
#include <queue>
#include <string>
using namespace std::chrono_literals;
using grid = std::vector<std::pair<int, char const *>>; // represents the frame in heights of columns and remembers the color of the column
const std::chrono::milliseconds millis_per_frame_algo_vis = 50ms; | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
class AlgorithmVisualizer { // consists of the visualizer to print the frames, a frame that is changing and different kind of sorting algos that works on grid
private:
GraphicalVisualizer visualizer;
Frame to_sort;
public:
AlgorithmVisualizer(Frame to_sort, char symbol);
std::vector<std::pair<int, char const *>> frame_matrix_to_num(frame_matrix convert_from, char symbol_to_count);
frame_matrix num_to_frame_matrix(std::vector<std::pair<int, char const *>> convert_from, char symbol_to_insert);
void bubble_sort(grid &vect_to_sort, char symbol);
void merge_sort(grid &vect_to_sort, char symbol);
void merge_sort(grid &vect_to_sort, char symbol, size_t start, size_t end, std::vector<std::pair<int, char const *>> &printable_frame);
void quick_sort(grid &vect_to_sort, char symbol, size_t start, size_t end);
};
algorithm_visualizer.cpp
#include "algorithm_visualizer.hpp"
#include <algorithm>
#include <iostream>
#include <random>
char const *generate_random_color() {
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist(0, colors.size() - 1);
auto it = colors.begin();
for (size_t i = 0; i < dist(rng); ++i) {
it++;
}
if (it->first == "reset")
return colors.at("red");
return it->second;
}
void change_frame_colors(Frame &frame_to_color, char symbol_to_color) {
for (size_t j = 0; j < frame_to_color.current_frame[0].size(); ++j) {
char const *color = generate_random_color();
for (size_t i = 0; i < frame_to_color.current_frame.size(); ++i) {
if (frame_to_color.current_frame[i][j].character == symbol_to_color)
frame_to_color.current_frame[i][j].color_code = color;
}
}
}
AlgorithmVisualizer::AlgorithmVisualizer(Frame to_sort, char symbol) : to_sort(to_sort) { // place the algorithm to visualize in the body remove or comment the others | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
change_frame_colors(to_sort, SAND_SHAPE);
grid frame_to_vec = frame_matrix_to_num(to_sort.current_frame, symbol);
// bubble_sort(frame_to_vec, symbol);
// merge_sort(frame_to_vec, symbol);
quick_sort(frame_to_vec, symbol, 0, frame_to_vec.size());
system("clear");
visualizer.print_sequence(millis_per_frame_algo_vis);
}
grid AlgorithmVisualizer::frame_matrix_to_num(frame_matrix convert_from, char symbol_to_count) { // converts a frame matrix into a vector of numbers and colors so the soring algos can work on it
grid convert_to;
// calculate the height of each column
for (size_t i = 0; i < convert_from[0].size(); ++i) {
int symbol_counter = 0;
char const *color = colors.at("reset");
for (size_t j = 0; j < convert_from.size(); ++j) {
if (convert_from[j][i].character == symbol_to_count) {
symbol_counter++;
color = convert_from[j][i].color_code;
}
}
convert_to.push_back({symbol_counter, color});
}
return convert_to;
}
frame_matrix AlgorithmVisualizer::num_to_frame_matrix(grid convert_from, char symbol_to_insert) { // converts the grid back into a frame_matrix so it could be inserted into the visualizer queue
frame_matrix convert_to;
// initializes a frame
for (size_t i = 0; i < Frame::FRAME_HEIGHT; ++i) {
std::vector<Pixel> line;
for (size_t j = 0; j < Frame::FRAME_WIDTH; ++j)
line.push_back({Frame::BACKGROUND, colors.at("reset")});
convert_to.push_back(line);
} | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
convert_to.push_back(line);
}
int matrix_index = 0;
// places the shape and color to insert into the frame goes column by column
for (auto height : convert_from) {
if (height.first >= Frame::FRAME_HEIGHT)
return {};
for (int j = 0; j < height.first; ++j) {
convert_to[convert_to.size() - j - 1][matrix_index] = {symbol_to_insert, height.second};
}
matrix_index++;
}
return convert_to;
}
void AlgorithmVisualizer::bubble_sort(grid &vect_to_sort, char symbol) {
for (size_t i = 0; i < vect_to_sort.size() - 1; ++i) {
bool is_swapped = false;
for (size_t j = 0; j < vect_to_sort.size() - i - 1; ++j) {
to_sort.set_current_frame(num_to_frame_matrix(vect_to_sort, symbol));
visualizer.add_frame(to_sort);
if (vect_to_sort[j].first >= vect_to_sort[j + 1].first) {
std::swap(vect_to_sort[j], vect_to_sort[j + 1]);
is_swapped = true;
}
}
if (!is_swapped)
break;
}
}
void AlgorithmVisualizer::merge_sort(grid &vect_to_sort, char symbol) {
if (vect_to_sort.size() <= 1)
return;
size_t mid = (vect_to_sort.size() / 2);
grid left(vect_to_sort.cbegin(), vect_to_sort.cbegin() + mid);
grid right(vect_to_sort.cbegin() + mid, vect_to_sort.cend());
vect_to_sort.clear();
merge_sort(left, symbol);
merge_sort(right, symbol); | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
size_t left_index = 0;
size_t right_index = 0;
while (vect_to_sort.size() < left.size() + right.size()) {
if (left_index == left.size())
vect_to_sort.insert(vect_to_sort.end(), right.begin() + right_index, right.end());
else if (right_index == right.size())
vect_to_sort.insert(vect_to_sort.end(), left.begin() + left_index, left.end());
else {
if (left[left_index].first > right[right_index].first) {
vect_to_sort.push_back(left[left_index]);
left_index++;
} else {
vect_to_sort.push_back(right[right_index]);
right_index++;
}
}
}
to_sort.set_current_frame(num_to_frame_matrix(vect_to_sort, symbol));
visualizer.add_frame(to_sort);
}
// same as the default merge_sort but with saving the new vector shape so the frame can show the whole vector changing
void AlgorithmVisualizer::merge_sort(grid &vect_to_sort, char symbol, size_t start, size_t end, grid &printable_frame) {
if (vect_to_sort.size() <= 1)
return;
size_t mid = (vect_to_sort.size() / 2);
grid left(vect_to_sort.cbegin(), vect_to_sort.cbegin() + mid);
grid right(vect_to_sort.cbegin() + mid, vect_to_sort.cend());
vect_to_sort.clear();
merge_sort(left, symbol, start, mid, printable_frame);
merge_sort(right, symbol, mid, end, printable_frame); | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
size_t left_index = 0;
size_t right_index = 0;
while (vect_to_sort.size() < left.size() + right.size()) {
if (left_index == left.size())
vect_to_sort.insert(vect_to_sort.end(), right.begin() + right_index, right.end());
else if (right_index == right.size())
vect_to_sort.insert(vect_to_sort.end(), left.begin() + left_index, left.end());
else {
if (left[left_index].first > right[right_index].first) {
vect_to_sort.push_back(left[left_index]);
left_index++;
} else {
vect_to_sort.push_back(right[right_index]);
right_index++;
}
}
}
for (size_t i = 0; i < vect_to_sort.size(); ++i) {
if (start < end) {
printable_frame[start] = vect_to_sort[i];
start++;
}
}
to_sort.set_current_frame(num_to_frame_matrix(printable_frame, symbol));
visualizer.add_frame(to_sort);
}
void AlgorithmVisualizer::quick_sort(grid &vect_to_sort, char symbol, size_t start, size_t end) {
if (end - start <= 0)
return;
size_t pivot = end - 1;
size_t first_bigger_than_pivot = start;
bool is_bigger_found = vect_to_sort[first_bigger_than_pivot].first > vect_to_sort[pivot].first;
for (size_t i = start; i < pivot; ++i) {
if (!is_bigger_found && vect_to_sort[i].first > vect_to_sort[pivot].first) {
is_bigger_found = true;
first_bigger_than_pivot = i;
}
if (is_bigger_found && vect_to_sort[i].first <= vect_to_sort[pivot].first) {
std::rotate(vect_to_sort.begin() + first_bigger_than_pivot, vect_to_sort.begin() + i, vect_to_sort.begin() + i + 1);
to_sort.set_current_frame(num_to_frame_matrix(vect_to_sort, symbol));
visualizer.add_frame(to_sort);
first_bigger_than_pivot += 1;
}
} | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
if (is_bigger_found) {
std::swap(vect_to_sort[pivot], vect_to_sort[first_bigger_than_pivot]);
pivot = first_bigger_than_pivot;
to_sort.set_current_frame(num_to_frame_matrix(vect_to_sort, symbol));
visualizer.add_frame(to_sort);
}
quick_sort(vect_to_sort, symbol, start, pivot);
quick_sort(vect_to_sort, symbol, pivot + 1, end);
}
game_of_life.hpp
#pragma once
#include "graphical_visualizer.hpp"
#include <string>
using namespace std::chrono_literals;
namespace game_of_life {
char const CELL_SHAPE = '*';
std::string const CELL_COLOR = "blue";
const std::chrono::milliseconds millis_per_frame_game_of_life = 100ms;
}
bool is_cell_alive(frame_matrix const &grid, size_t x, size_t y);
void simulate_game_of_life(Frame &frame, size_t amount_of_cycles, void (*game_conf)(frame_matrix &));
void glider_gun_conf(frame_matrix &grid);
game_of_life.cpp
#include "game_of_life.hpp"
#include <set>
bool is_cell_alive(frame_matrix const &grid, size_t x, size_t y) {
int amount_of_neighbors = 0;
if (x > 0) {
if (grid[y][x - 1].character == game_of_life::CELL_SHAPE)
++amount_of_neighbors;
if (y > 0 && grid[y - 1][x - 1].character == game_of_life::CELL_SHAPE)
++amount_of_neighbors;
if (y < Frame::FRAME_HEIGHT - 1 && grid[y + 1][x - 1].character == game_of_life::CELL_SHAPE)
++amount_of_neighbors;
}
if (x < Frame::FRAME_WIDTH - 1) {
if (grid[y][x + 1].character == game_of_life::CELL_SHAPE)
++amount_of_neighbors;
if (y > 0 && grid[y - 1][x + 1].character == game_of_life::CELL_SHAPE)
++amount_of_neighbors;
if (y < Frame::FRAME_HEIGHT - 1 && grid[y + 1][x + 1].character == game_of_life::CELL_SHAPE)
++amount_of_neighbors;
} | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
if (y > 0 && grid[y - 1][x].character == game_of_life::CELL_SHAPE)
++amount_of_neighbors;
if (y < Frame::FRAME_HEIGHT - 1 && grid[y + 1][x].character == game_of_life::CELL_SHAPE)
++amount_of_neighbors;
if (grid[y][x].character == game_of_life::CELL_SHAPE && amount_of_neighbors < 2)
return false;
else if (grid[y][x].character == game_of_life::CELL_SHAPE && amount_of_neighbors > 3)
return false;
else if (grid[y][x].character == Frame::BACKGROUND && amount_of_neighbors != 3)
return false;
return true;
}
void simulate_game_of_life(Frame &frame, size_t amount_of_cycles, void (*game_conf)(frame_matrix &)) {
GraphicalVisualizer visualizer;
game_conf(frame.current_frame);
visualizer.add_frame(frame);
for (size_t cycle = 1; cycle <= amount_of_cycles; ++cycle) {
std::set<std::pair<size_t, size_t>> alive_cells;
for (size_t i = 0; i < Frame::FRAME_HEIGHT; ++i) {
for (size_t j = 0; j < Frame::FRAME_WIDTH; ++j) {
if (is_cell_alive(frame.current_frame, j, i))
alive_cells.insert({j, i});
}
}
for (size_t i = 0; i < Frame::FRAME_WIDTH; ++i) {
for (size_t j = 0; j < Frame::FRAME_HEIGHT; ++j) {
auto find_cell = alive_cells.find({i, j});
if (find_cell != alive_cells.cend())
frame.current_frame[j][i] = {game_of_life::CELL_SHAPE, colors.at(game_of_life::CELL_COLOR)};
else
frame.current_frame[j][i] = {Frame::BACKGROUND, colors.at("reset")};
}
}
visualizer.add_frame(frame);
}
visualizer.print_sequence(game_of_life::millis_per_frame_game_of_life);
}
void glider_gun_conf(frame_matrix &grid) {
size_t ref_point_y = Frame::FRAME_HEIGHT / 4;
size_t ref_point_x = Frame::FRAME_WIDTH / 4; | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
using namespace game_of_life;
// left square
grid[ref_point_y][ref_point_x] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 1][ref_point_x] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y][ref_point_x + 1] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 1][ref_point_x + 1] = {CELL_SHAPE, colors.at(CELL_COLOR)};
// left square
// middle part 10 to right
ref_point_x += 10;
grid[ref_point_y][ref_point_x] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 1][ref_point_x] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 2][ref_point_x] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y - 1][ref_point_x + 1] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 3][ref_point_x + 1] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y - 2][ref_point_x + 2] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 4][ref_point_x + 2] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y - 2][ref_point_x + 3] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 4][ref_point_x + 3] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 1][ref_point_x + 4] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y - 1][ref_point_x + 5] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 3][ref_point_x + 5] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y][ref_point_x + 6] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 1][ref_point_x + 6] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 2][ref_point_x + 6] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 1][ref_point_x + 7] = {CELL_SHAPE, colors.at(CELL_COLOR)};
// middle part
// right part
ref_point_x += 10;
ref_point_y -= 2; | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
// right part
ref_point_x += 10;
ref_point_y -= 2;
grid[ref_point_y][ref_point_x] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 1][ref_point_x] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 2][ref_point_x] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y][ref_point_x + 1] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 1][ref_point_x + 1] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 2][ref_point_x + 1] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y - 1][ref_point_x + 2] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 3][ref_point_x + 2] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y - 1][ref_point_x + 4] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y - 2][ref_point_x + 4] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 3][ref_point_x + 4] = {CELL_SHAPE, colors.at(CELL_COLOR)};
grid[ref_point_y + 4][ref_point_x + 4] = {CELL_SHAPE, colors.at(CELL_COLOR)};
// right part
}
main.cpp
#include <chrono>
#include <iostream>
#include <string>
#include "algorithm_visualizer.hpp"
#include "falling_sand.hpp"
#include "game_of_life.hpp"
using namespace std::chrono_literals;
int main(int, char **) {
auto start = std::chrono::high_resolution_clock::now();
FallingSand simualtion;
AlgorithmVisualizer algo_vis(simualtion.get_field(), SAND_SHAPE);
Frame frame;
simulate_game_of_life(frame, 100, &glider_gun_conf);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration = end - start;
std::cout << "Execution time: " << duration.count() << " seconds." << std::endl;
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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++
return 0;
}
couple of notes: in graphical_visualizer I tried adding another version of printing the sequence without using clear it semi-works and I still prefer the system("clear") because I got annoyed trying to solve stupid bugs with it.
second in algorithm_visualizer I have 2 versions of merge sort, one is prints sequence of sorted sub arrays, the second shows the whole array getting sorted.
Answer: Overall seems really cute, but here are some possible points for improvements:
generate_random_direction is a free function inside some cpp file of a class. I might be a better practice to make it a private function (maybe even private static function) of the class.
simualte_diag_fall seems like a really big function. I think it'd be better to split it into multiple functions.
millis_per_frame_game_of_life is out of naming convention.
For free functions, consider using a namespace to make it more encapsulated.
Overall seems good! Good luck! | {
"domain": "codereview.stackexchange",
"id": 45456,
"lm_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
} |
rust
Title: Handling default std::io::Error in Rust
Question: I'm really new to Rust with less than a day of rusting. I'd like to know if the following code is ok or could it be written somehow better, and specifically, which would be the preferred way to handle the actual error case.
The return type bool represents whether a packet was received or not, so that the call to tryReceiveUdp can be chained using bool::then to do something else instead.
fn tryReceiveUdp(socket:UdpSocket) -> std::io::Result<bool>
{
let mut buf = [0; 1024];
let r = match socket.recv_from(&mut buf)
{
Ok((bytes,src)) => {
handleUdp(buf[..bytes].to_vec(),src)?;
false
},
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => true,
//Err(e) => Err(e) <-- Is this better than the next line?
e => {e?;true}
};
Ok(r)
}
Edit:
There's a mistake in the above. The code initially didn't have Ok(r) at the end. Instead the specific question was between these two
Err(e) => Err(e), //<-- Is this better than the next line?
e => {e?;Ok(true)},
Answer: The path I would take with the error processing in this code would be to remove the let r = ...; Ok(r) and have the match compute the return value directly:
fn tryReceiveUdp(socket:UdpSocket) -> std::io::Result<bool>
{
let mut buf = [0; 1024];
match socket.recv_from(&mut buf)
{
Ok((bytes,src)) => {
handleUdp(buf[..bytes].to_vec(),src)?;
Ok(false)
},
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => Ok(true),
Err(e) => Err(e),
}
} | {
"domain": "codereview.stackexchange",
"id": 45457,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
This has more duplicated Oks, but it is easy to see at a glance whether each case is either a success or a failure.
As to the exact choice of error propagation operation Err(e) => Err(e): I generally prefer not to use the ? operator with a value known to be an error. In this case, it's simple to not early-return at all and just let the match pass the Err out, but in the case where an early-return is necessary, I'd still rather write return Err(e); or return result; rather than using an ? that appears to unconditionally return. I avoid that use of ? for several reasons:
it's potentially confusing to readers,
it contains a pointless branch that can never be taken (though that will of course be optimized out), and
it requires you to write something after it that type-checks as if control flow could continue past that point (the ;true in your code).
Other things I notice in review:
Your function takes the socket by value, so you'll only be able to receive one packet. Consider taking it by reference instead (&UdpSocket).
Consider importing modules to use shorter paths rather than repeating std:: everywhere.
Rust functions should be named with snake_case, not camelCase.
Use standard code formatting, as performed by cargo fmt.
With all of those changed:
use std::io;
use std::net::UdpSocket;
fn try_receive_udp(socket: &UdpSocket) -> io::Result<bool> {
let mut buf = [0; 1024];
match socket.recv_from(&mut buf) {
Ok((bytes, src)) => {
handle_udp(buf[..bytes].to_vec(), src)?;
Ok(false)
}
Err(e) if e.kind() == io::ErrorKind::WouldBlock => Ok(true),
Err(e) => Err(e),
}
} | {
"domain": "codereview.stackexchange",
"id": 45457,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
python, file-system, compression, file-structure
Title: Looking for help simplifying a general purpose compression function
Question: The following is a general purpose file compression function with the following features:
It can take either a single file or directory as the source input
It defaults to the source directory when to destination is input
It will compress all files of a type associated with the extension parameter
It removes the original files if desired
This allows for a simple minimum working input of providing only the source directory (for which it defaults to compressing all containing files) While allowing specific destinations, individual files, or specific file extensions to be compressed.
import glob
import zipfile
import os
def _zip_and_delete_prot(src, dst = None, arcname = None, remove_uncompressed = True, extension = ""):
"""Takes either an individual or list of filenames from the source (src)
folder and compresses them into the destination (dst) with the option to
delete the original.
Parameters:
src: the path to the source directory
sdt: the path to the destination directory. If left empty
it will default to the directory of the source files
arcname: the name of the compressed file (and file path) must correspond
to the number of files grabbed from the source
remove_uncompressed: if True deletes the original input files
extension: The extension of the batch of files you want compressed
in the source directory, examples are ".txt", ".csv", ".xls"
"""
# Checks if a destination other than the source is provided, if not defaults to src
if dst is None:
if os.path.isdir(src) is True:
dst = src
else:
dst = os.path.dirname(src) | {
"domain": "codereview.stackexchange",
"id": 45458,
"lm_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, file-system, compression, file-structure",
"url": null
} |
python, file-system, compression, file-structure
# Checks if the src is a file or a directory, if a directory we then group all files
# with the extension given by the extension parameter.
if os.path.isdir(src) is True:
fnames = sorted(glob.glob(src + f'\*{extension}'))
else:
fnames = [src]
# Iterating over all files and compressing them
for _file in fnames:
# Creating a variable with the .zip filename extension
file_bn_zip = os.path.basename(_file)[:-3]+"zip"
zip_dst = dst + "\\" + file_bn_zip
# Create a Zip file in write mode
with zipfile.ZipFile(zip_dst, 'w', zipfile.ZIP_DEFLATED) as zipf:
# Write to archive without directory structure included in the compression
if arcname is None:
zipf.write(_file, arcname = os.path.basename(_file))
print(f"File {os.path.basename(_file)} written to {file_bn_zip}")
# If arcname is provided try to use the provided arcname
else:
try:
zipf.write(_file, arcname)
print(f"Arcname {arcname} supplied and compressed")
except:
print(f"Arcnane {arcname} failed, check that structure
corresponds to the src files structure")
# Removing uncompressed files if desired
if remove_uncompressed is True:
os.remove(_file)
print(f"Input file {os.path.basename(_file)} removed")
Answer: Replace your os module import with pathlib and use more Path.
Add PEP484 types to your function signatures.
sdt is spelled dst in your parameters.
Raw concatenation of an extension string to a glob pattern is asking for trouble; call escape() on it.
Re. # Create a Zip file in write mode - never
# Do thing
do_thing() | {
"domain": "codereview.stackexchange",
"id": 45458,
"lm_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, file-system, compression, file-structure",
"url": null
} |
python, file-system, compression, file-structure
Obvious comments are more harmful than having no comment at all.
Don't is True; use boolean variables as predicates directly.
Suggested
Only lightly tested -
import glob
import zipfile
from pathlib import Path
def _zip_and_delete_prot(
src: Path,
dst: Path | None = None,
arcname: str | None = None,
remove_uncompressed: bool = True,
extension: str = '',
) -> None:
"""Takes either an individual or list of filenames from the source (src)
folder and compresses them into the destination (dst) with the option to
delete the original.
Parameters:
src: the path to the source directory
dst: the path to the destination directory. If left empty
it will default to the directory of the source files
arcname: the name of the compressed file (and file path) must correspond
to the number of files grabbed from the source
remove_uncompressed: if True deletes the original input files
extension: The extension of the batch of files you want compressed
in the source directory, examples are '.txt', '.csv', '.xls'
"""
# Checks if a destination other than the source is provided, if not defaults to src
if dst is None:
if src.is_dir():
dst = src
else:
dst = src.parent
# Checks if the src is a file or a directory, if a directory we then group all files
# with the extension given by the extension parameter.
if src.is_dir():
fnames = sorted(src.glob('*' + glob.escape(extension)))
else:
fnames = src,
# Iterating over all files and compressing them
for file in fnames:
file_bn_zip = file.with_suffix('.zip')
zip_dst = dst / file_bn_zip.name | {
"domain": "codereview.stackexchange",
"id": 45458,
"lm_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, file-system, compression, file-structure",
"url": null
} |
python, file-system, compression, file-structure
# Write to archive without directory structure included in the compression
# If arcname is provided try to use the provided arcname
if arcname is None:
arcname_inner = file.name
else:
arcname_inner = arcname
with zipfile.ZipFile(file=zip_dst, mode='w', compression=zipfile.ZIP_DEFLATED) as zipf:
try:
zipf.write(filename=file, arcname=arcname_inner)
print(f'File {arcname_inner} written to {zip_dst}')
except IOError:
print(f'File {arcname_inner} failed; check that structure '
'corresponds to the src files structure')
if remove_uncompressed:
file.unlink()
print(f'Input file {file.name} removed') | {
"domain": "codereview.stackexchange",
"id": 45458,
"lm_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, file-system, compression, file-structure",
"url": null
} |
c++, linked-list, file
Title: Count the frequencies of each word in a file
Question: I have tried to implement a code that does the following:
store words in an array (unordered)
use function order_array() to place repetitions for the same word near (so the result, given a sample text file, could be: mom mom mom mom lamb lamb eye eye pain tears)
use function count_frequency to store every word one single time + its frequency (I store them in a linked list)
print the linked list to obtain given result
The code works, but it appears (to my eye) cumbersone and unefficient. How can I improve it?
Note that I am not familiar with concepts like vectors, hash maps or dictionaries yet, but I have a good grasp of basic data structures (eg linked lists, stacks, queues, binary search trees). Still, any hint, help or advice would be greatly appreciated
using namespace std;
#include<iostream>
#include<fstream>
#include<string>
const int DIM = 50;
int count = 0;
string list[DIM];
string ordered_list[DIM];
struct node
{
string word;
int frequency;
node* next;
};
node* head = NULL;
node* remove_node(node* &h)
{
node* s = head;
head = s->next;
return s; // and then remove everything
}
void add_node(string &w, int &f, node* &h)
{
node* t = new node;
t->word = w;
t-> frequency = f;
t->next = h;
h = t;
}
void print_highestf(node* &h)
{
node* s = h;
int higherf = 0;
while(s!=NULL)
{
if((s->frequency) >= higherf)
{
higherf = s->frequency;
}
s = s->next;
}
cout << "The highest frequency for a word is: " << higherf << endl;
}
void print_res(node* &h)
{
for(node* s = head; s != NULL; s = s->next)
{
cout << "Frequency for word " << s->word << ": " << s->frequency << endl;
cout << "\n";
}
}
void upload_array(string &w, string a[])
{
a[count] = w;
count ++;
} | {
"domain": "codereview.stackexchange",
"id": 45459,
"lm_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, file",
"url": null
} |
c++, linked-list, file
void upload_array(string &w, string a[])
{
a[count] = w;
count ++;
}
bool is_new_string(string &word, int position) //check better
{
bool repeated = false;
for(int i = 0; i < position; i++)
{
if(word == list[i] && repeated == true)
{
return false;
}
else if(word == list[i] && repeated == false)
{
repeated = true;
}
}
return true;
}
void order_array(string a[], string oa[])
{
int i = 0;
int times = 0;
while(i!= count)
{
int j = i;
while(j != count)
{
if((a[i] == a[j]) && is_new_string((a[i]), i+1))
{
//new node
oa[times]=a[i];
times++;
}
j++;
}
i++;
}
}
void count_frequency(string oa[])
{
int frequency = 1;
for(int i = 0; i<count-1; i++)
{
if(oa[i] != oa[i+1])
{
add_node(oa[i], frequency, head);
frequency = 1;
}
else if(oa[i] == oa[i+1])
{
frequency++;
}
}
}
int main()
{
fstream mystream;
mystream.open("words.txt", ios::in);
string word;
//upload array of strings
while(!mystream.eof())
{
mystream >> word;
upload_array(word, list);
}
order_array(list, ordered_list);
count_frequency(ordered_list);
print_res(head);
print_highestf(head);
for(node* s= head; s!=NULL; s = s->next)
{
node* r = remove_node(head);
delete r;
}
cout << "\nDeinitialization executed. " << endl;
mystream.close();
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 45459,
"lm_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, file",
"url": null
} |
c++, linked-list, file
Answer: Kudos on writing a working program! You already sense that things can be improved, which is also great. Toby Speight already pointed out some issues in your code. You are a beginning C++ programmer, so it's normal that you don't write optimal code yet; you have just learned the basic tools. To show you how a more experienced C++ programmer would tackle the problem of counting frequencies, let me show you this implementation:
#include <cstdlib>
#include <algorithm>
#include <format>
#include <fstream>
#include <iostream>
#include <ranges>
#include <unordered_map>
#include <vector>
// A struct to hold a value and its frequency
template<typename T>
struct counted_value {
std::size_t count;
T value;
// Add a default comparison operator so we can sort on these structs
friend auto operator<=>(const counted_value&, const counted_value&) = default;
};
// A templated function that can take any kind of input
template<std::ranges::input_range Range>
auto count_frequencies(Range&& range) {
// Deduce the type of values stored in the range
using value_type = decltype(std::ranges::begin(range))::value_type;
// Count frequencies in a hash map
std::unordered_map<value_type, std::size_t> counters;
for (const auto& value: range) {
counters[value]++;
}
// Copy the result into a vector
std::vector<counted_value<value_type>> result;
result.reserve(counters.size());
for (const auto& [value, count]: counters) {
result.emplace_back(count, value);
}
// Sort the vector on the frequency count, largest count first
std::ranges::sort(result, std::greater{});
return result;
}
int main() {
std::ifstream input("words.txt");
// Create a view of the words in the input stream
auto words = std::ranges::istream_view<std::string>(input);
auto frequencies = count_frequencies(words); | {
"domain": "codereview.stackexchange",
"id": 45459,
"lm_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, file",
"url": null
} |
c++, linked-list, file
auto frequencies = count_frequencies(words);
// We should have reached the end, if we didn't something went wrong
if (!input.eof()) {
std::cerr << "Error reading input\n";
return EXIT_FAILURE;
}
for (const auto& item: frequencies) {
std::cout << std::format("Frequency for word {}: {}\n",
item.value, item.count);
}
}
I've used a lot of features from the standard library and from the language itself, in particular features from C++20. I'll list them here with links to cppreference.com: | {
"domain": "codereview.stackexchange",
"id": 45459,
"lm_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, file",
"url": null
} |
c++, linked-list, file
template so you can create a frequency counting function that can count any kind of input, not just an array of strings.
A default comparison operator to make a struct comparable, which helps it sort later.
The concept std::ranges::input_range to restrict the input of count_frequencies() to ranges that can be iterated over. It's not really necessary here, but it results in nicer error messages if you call the function with the wrong type of input.
using to declare a type alias, this is just to save typing.
decltype() to deduce the type of values stored in the input range.
std::unordered_map is basically a dictionary, we use it to count how often a given value appears in the input.
Range-based for loops, this is often simpler and safer than the old for loops where you manually iterate.
std::vector is basically a dynamically sized array. It takes care of memory allocation for you. We use it to store the final result.
std::ranges::sort() provides an easy way to sort containers. Normally it sorts so the smallest value comes first, but we pass it std::greater so we sort it largest value first.
The auto type lets the compiler deduce the type for you. This saves typing and reduces the chance of making mistakes.
std::ranges::istream_view() is a helper that allows you to convert an input stream (like the file you open) into a view that can be iterated over using range-based for loops and with other algorithms.
std::format() makes it much easier to format strings. C++23 also introduced std::print() which makes it even easier to print things, but not all compilers support it yet.
Don't worry about all of this, just continue your programming journey, and eventually you learn most or all of the above. | {
"domain": "codereview.stackexchange",
"id": 45459,
"lm_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, file",
"url": null
} |
java, object-oriented
Title: Java Queue data structure
Question: Could you review this implementation of a queue data structure according to the principles of Object Oriented Programming and Clean Code?
import java.util.ArrayList;
public class SecurityCheckQueue<E extends ByAir> {
private ArrayList<E> queue;
public SecurityCheckQueue() {
queue = new ArrayList<E>();
}
public int getQueueLength() {
return queue.size();
}
public E peek() {
validateLength();
return queue.get(0);
}
public void enqueue(E elem) {
if (elem == null)
throw new IllegalArgumentException("Null");
queue.add(elem);
}
public E dequeue() {
validateLength();
return queue.remove(0);
}
public void validateLength() {
if (getQueueLength() == 0)
throw new IllegalStateException("Empty queue");
}
private void checkFlight(String flight) {
if (flight == null)
throw new IllegalArgumentException("Null");
}
private ArrayList<E> selectByFlight(String flight) {
checkFlight(flight);
ArrayList<E> out = new ArrayList<E>();
for (E elem : queue) {
if (elem.getFlightNumber().equals(flight))
out.add(elem);
}
return out;
}
private void removeFromQueue(ArrayList<E> elements) {
queue.removeAll(elements);
}
public void cancelFlight(String flight) {
checkFlight(flight);
validateLength();
ArrayList<E> elements = selectByFlight(flight);
removeFromQueue(elements);
}
public void expedite(String flight) {
checkFlight(flight);
validateLength();
ArrayList<E> elements = selectByFlight(flight);
removeFromQueue(elements);
queue.addAll(0, elements);
} | {
"domain": "codereview.stackexchange",
"id": 45460,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, object-oriented",
"url": null
} |
java, object-oriented
public void delay(String flight) {
checkFlight(flight);
validateLength();
ArrayList<E> elements = selectByFlight(flight);
removeFromQueue(elements);
queue.addAll(elements);
}
}
Answer: Advice 1 - Put the class in a package
It is customary in industrial code to put each class in a specific package. Perhaps you could start with this:
package com.cardstdani.flightqueue;
Advice 2 - On type parameter name
You have:
public class SecurityCheckQueue<E extends ByAir>
In Java, it is customary to name type parameters only using one letter, yet it make sense in your case to stick to ByAir. Just telling.
Advice 3 - On field list
You have:
private ArrayList<E> queue;
I suggest this:
private final List<E> queue = new ArrayList<>();
final makes sure that you cannot accidentally reassign to queue. Plus, on the type definition of queue you can use bare interface (List) instead of implementation type (ArrayList). Finally, since Java 7, you can do diamond inference: instead of
... = new ArrayList<E>();
you need only
... = new ArrayList<>();
Advice 4 - Remove constructor
So far, we don't really need the constructor since we initalized the class object state in field initializers. Remove the constructor.
Advice 5 - On getQueueLength()
Usually, again, in Java, it is customary to call the length of something as size():
public int size() {
return queue.size();
}
Advice 6 - Throw proper exception class in validateLength
You have:
public void validateLength() {
if (getQueueLength() == 0)
throw new IllegalStateException("Empty queue");
}
How about this?
import java.util.NoSuchElementException;
...
public void validateLength() {
if (size() == 0) {
throw new NoSuchElementException("Empty queue");
}
} | {
"domain": "codereview.stackexchange",
"id": 45460,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, object-oriented",
"url": null
} |
java, object-oriented
(Also note the curly braces around the throw statement; it's a Java custom, too.
Advice 7 - checkFlight
private void checkFlight(String flight) {
if (flight == null)
throw new IllegalArgumentException("Null");
}
Why not this?
private void checkFlight(String flight) {
Objects.requireNonNull(flight, "The input flight is null.");
}
Hope that helps. | {
"domain": "codereview.stackexchange",
"id": 45460,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, object-oriented",
"url": null
} |
c++, performance, c++20
Title: Split command in C++20
Question: The Windows OS doesn't feature a Split command and although I do have a Linux partition, I mainly use Windows 11. As such, I implemented the Split command in C++20 so that I can use it on Windows.
The program seems pretty fast; I used it with a large Linux ISO(~4GB) and it took only few seconds to finish(<10s). Please review it and tell me if there is room for some performance gains:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <filesystem>
#define defaultChunkSize 500'000'000UL;
namespace fs = std::filesystem;
void splitFile(const std::string& source, const std::string& outputPrefix, unsigned long chunkSize) {
std::ifstream inputFile(source, std::ios::binary);
if (!inputFile) {
std::cerr << "Error opening file" << std::endl;
exit(1);
}
unsigned long long fileSize = fs::file_size(source);
unsigned long numChunks = fileSize / chunkSize + (fileSize % chunkSize != 0);
std::string outputFilename;
char buffer[1024];
unsigned long i = 0;
for (i = 0; i < numChunks; i++) {
outputFilename = outputPrefix + std::to_string(i);
std::ofstream outputFile(outputFilename, std::ios::binary);
if (!outputFile) {
std::cerr << "Error opening output file" << std::endl;
inputFile.close();
exit(1);
}
unsigned long bytesToWrite = chunkSize;
while (bytesToWrite > 0) {
unsigned long readSize = sizeof(buffer) < bytesToWrite ? sizeof(buffer) : bytesToWrite;
inputFile.read(buffer, readSize);
outputFile.write(buffer, readSize);
if (!inputFile) {
break;
}
bytesToWrite -= readSize;
}
outputFile.close();
}
inputFile.close();
} | {
"domain": "codereview.stackexchange",
"id": 45461,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, c++20",
"url": null
} |
c++, performance, c++20
int main(int argc, char* argv[]) {
if (argc != 3 && argc != 4) {
std::cerr << "Usage: " << argv[0] << " <source_file> <output_prefix> [chunk_size_in_bytes]" << std::endl;
return 1;
}
std::string sourceFile = argv[1];
std::string outputPrefix = argv[2];
unsigned long chunkSize = (argc == 4) ? std::strtoul(argv[3], nullptr, 10) : defaultChunkSize;
if (chunkSize == 0) {
std::cerr << "Invalid chunk size." << std::endl;
return 1;
}
splitFile(sourceFile, outputPrefix, chunkSize);
return 0;
}
Answer: I'm repeatedly surprised by the basic tools that Windows users somehow manage without. This is a worthwhile objective.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <filesystem>
That's very nearly sorted; it's useful to have standard includes in order, as it makes it easy to check whether the one you need is already present.
#define defaultChunkSize 500'000'000UL;
I'd write that as
static constexpr auto defaultChunkSize = 500'000'000UL;
No need to get the preprocessor involved here.
std::cerr << "Error opening file" << std::endl;
exit(1);
No need to flush std::err here, since exiting will do that for us. We might be able to provide more information by using std:perror() (from <cstdio>) instead.
std::exit is misspelt, and it's not defined, as we failed to include <cstdlib>. It's not the best error-handling technique, as it will not call destructors of in-scope objects.
if (!outputFile) {
std::cerr << "Error opening output file" << std::endl;
inputFile.close();
That close() would be unnecessary if we simply returned an appropriate failure indication (or exception) rather than calling std::exit().
char buffer[1024];
That's a very small buffer size for copying file contents. Consider something much larger. | {
"domain": "codereview.stackexchange",
"id": 45461,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, c++20",
"url": null
} |
c++, performance, c++20
That's a very small buffer size for copying file contents. Consider something much larger.
inputFile.read(buffer, readSize);
outputFile.write(buffer, readSize);
if (!inputFile) {
break;
}
We need to check that the read() was successful before writing the buffer contents. If it fails having performed a partial read, we'll need to write inputFile.gcount() characters rather than readSize.
We're completely missing any check that the write was successful. It can fail for many reasons, the most obvious being reaching one of the size limits (quota, filesystem or process limit).
outputFile.close();
Discarding the return value of close() means that we don't know whether the file was successfully written. That's a Bad Thing, as it means that the program could fail to perform its task without any error message.
It shouldn't be necessary to measure the input file or to compute numChunks in advance. In any case, the information could be out of date by the time we use it. Instead, just keep reading from the input file until we reach EOF (or get an error), and start a new file whenever we have written the chunk size to the current one.
std::cerr << "Invalid chunk size." << std::endl;
return 1;
Consider using the EXIT_FAILURE and EXIT_SUCCESS macros from <cstdlib> for clearer return values from main(). | {
"domain": "codereview.stackexchange",
"id": 45461,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, c++20",
"url": null
} |
c, generics, c11
Title: Generic map-like function
Question: This function mimics Python's map() function (No, it doesn't support generic return types for the function or multiple iterables) by applying the provided function func to each element of the array iter. It returns a new array containing the results which must be passed to free().
#include <stdlib.h>
#define map(count, iter, func) _Generic (*iter, \
char: map_c, \
unsigned char: map_uc, \
short int: map_si, \
unsigned short int: map_usi, \
int: map_i, \
unsigned int: map_ui, \
long int: map_li, \
unsigned long int: map_uli, \
long long int: map_lli, \
unsigned long long int: map_ulli, \
float: map_f, \
double: map_d, \
long double: map_ld, \
_Bool: map_b, \
char *: map_s \
)(count, iter, func)
#define gen_map(_suffix, _type) \
_type *map_##_suffix(size_t count, _type iter[static count], \
_type (*func)(_type x)) \
{ \
_type *out = malloc(sizeof *out * count); \
\
if (!out) { \
return NULL; \
} \
for (size_t i = 0; i < count; ++i) { \
out[i] = func(iter[i]); \
} \
return out; \
} | {
"domain": "codereview.stackexchange",
"id": 45462,
"lm_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, generics, c11",
"url": null
} |
c, generics, c11
gen_map(c, char)
gen_map(uc, unsigned char)
gen_map(si, short int)
gen_map(usi, unsigned short int)
gen_map(i, int)
gen_map(ui, unsigned int)
gen_map(li, long int)
gen_map(uli, unsigned long int)
gen_map(lli, long long int)
gen_map(ulli, unsigned long long int)
gen_map(f, float)
gen_map(d, double)
gen_map(ld, long double)
gen_map(b, _Bool)
char **map_s(size_t count, char *iter[static count],
char *(*func)(char *s))
{
char **out = malloc(sizeof *out * count);
if (!out) {
return NULL;
}
for (size_t i = 0; i < count; ++i) {
out[i] = func(iter[i]);
}
return out;
}
#ifdef TEST_MAIN
#include <stdio.h>
#include <string.h>
static int square(int x)
{
/* This can overflow, but we don't care for now. */
return x * x;
}
static int cube(int x)
{
return x * x * x;
}
static char *rev(char *s)
{
if (!*s) {
/* So that it can be passed to free(). */
return strdup("");
}
const size_t len = strlen(s);
char *const t = malloc(len + 1);
if (!t) {
return NULL;
}
for (size_t i = 0, j = len - 1; s[i]; ++i, --j) {
t[i] = s[j];
}
t[len] = '\0';
return t;
}
int main(void)
{
int items[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
size_t const item_count = sizeof items / sizeof *items;
int *const squares = map(item_count, items, square);
int *const cubes = map(item_count, items, cube);
for (size_t i = 0; i < item_count; ++i) {
printf("Number: %d, Square: %d, Cube: %d.\n", items[i], squares[i],
cubes[i]);
}
putchar('\n');
free(squares);
free(cubes);
char *strs[] = { "", "a", "abc", "abcd", "abcde" };
const size_t strs_count = sizeof strs / sizeof *strs;
char **rev_strs = map(strs_count, strs, rev);
for (size_t i = 0; i < strs_count; ++i) {
printf("%s ----> %s\n", strs[i], rev_strs[i]);
free(rev_strs[i]);
}
free(rev_strs);
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 45462,
"lm_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, generics, c11",
"url": null
} |
c, generics, c11
free(rev_strs);
return EXIT_SUCCESS;
}
#endif /* TEST_MAIN */
This is what the preprocessor produced (after running gcc -E map.c -o map.i, removing irrelevant code, and formatting):
static char *map_c(size_t len, const char iter[static len],
char (*func)(char x))
{
char *out = malloc(sizeof *out * len);
if (!out) {
return ((void *) 0);
}
for (size_t i = 0; i < len; ++i) {
out[i] = func(iter[i]);
} return out;
}
static unsigned char *map_uc(size_t len, const unsigned char iter[static len],
unsigned char (*func)(unsigned char x))
{
unsigned char *out = malloc(sizeof *out * len);
if (!out) {
return ((void *) 0);
}
for (size_t i = 0; i < len; ++i) {
out[i] = func(iter[i]);
} return out;
}
static short int *map_si(size_t len, const short int iter[static len],
short int (*func)(short int x))
{
short int *out = malloc(sizeof *out * len);
if (!out) {
return ((void *) 0);
}
for (size_t i = 0; i < len; ++i) {
out[i] = func(iter[i]);
} return out;
}
static unsigned short int *map_usi(size_t len,
const unsigned short int iter[static len],
unsigned short int (*func)(unsigned short int x))
{
unsigned short int *out = malloc(sizeof *out * len);
if (!out) {
return ((void *) 0);
}
for (size_t i = 0; i < len; ++i) {
out[i] = func(iter[i]);
} return out;
}
static int *map_i(size_t len, const int iter[static len], int (*func)(int x))
{
int *out = malloc(sizeof *out * len);
if (!out) {
return ((void *) 0);
}
for (size_t i = 0; i < len; ++i) {
out[i] = func(iter[i]);
} return out;
}
static unsigned int *map_ui(size_t len, const unsigned int iter[static len],
unsigned int (*func)(unsigned int x))
{
unsigned int *out = malloc(sizeof *out * len); | {
"domain": "codereview.stackexchange",
"id": 45462,
"lm_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, generics, c11",
"url": null
} |
c, generics, c11
if (!out) {
return ((void *) 0);
}
for (size_t i = 0; i < len; ++i) {
out[i] = func(iter[i]);
} return out;
}
static long int *map_li(size_t len, const long int iter[static len],
long int (*func)(long int x))
{
long int *out = malloc(sizeof *out * len);
if (!out) {
return ((void *) 0);
}
for (size_t i = 0; i < len; ++i) {
out[i] = func(iter[i]);
} return out;
}
static unsigned long int *map_uli(size_t len,
const unsigned long int iter[static len],
unsigned long int (*func)(unsigned long int x))
{
unsigned long int *out = malloc(sizeof *out * len);
if (!out) {
return ((void *) 0);
}
for (size_t i = 0; i < len; ++i) {
out[i] = func(iter[i]);
} return out;
}
static long long int *map_lli(size_t len, const long long int iter[static len],
long long int (*func)(long long int x))
{
long long int *out = malloc(sizeof *out * len);
if (!out) {
return ((void *) 0);
}
for (size_t i = 0; i < len; ++i) {
out[i] = func(iter[i]);
} return out;
}
static unsigned long long int *map_ulli(size_t len,
const unsigned long long int iter[static len],
unsigned long long int (*func)(unsigned long long int x))
{
unsigned long long int *out = malloc(sizeof *out * len);
if (!out) {
return ((void *) 0);
}
for (size_t i = 0; i < len; ++i) {
out[i] = func(iter[i]);
} return out;
}
static float *map_f(size_t len, const float iter[static len],
float (*func)(float x))
{
float *out = malloc(sizeof *out * len);
if (!out) {
return ((void *) 0);
}
for (size_t i = 0; i < len; ++i) {
out[i] = func(iter[i]);
} return out;
}
static double *map_d(size_t len, const double iter[static len],
double (*func)(double x))
{
double *out = malloc(sizeof *out * len); | {
"domain": "codereview.stackexchange",
"id": 45462,
"lm_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, generics, c11",
"url": null
} |
c, generics, c11
if (!out) {
return ((void *) 0);
}
for (size_t i = 0; i < len; ++i) {
out[i] = func(iter[i]);
} return out;
}
static long double *map_ld(size_t len, const long double iter[static len],
long double (*func)(long double x))
{
long double *out = malloc(sizeof *out * len);
if (!out) {
return ((void *) 0);
}
for (size_t i = 0; i < len; ++i) {
out[i] = func(iter[i]);
} return out;
}
static _Bool *map_b(size_t len, const _Bool iter[static len],
_Bool (*func)(_Bool x))
{
_Bool *out = malloc(sizeof *out * len);
if (!out) {
return ((void *) 0);
}
for (size_t i = 0; i < len; ++i) {
out[i] = func(iter[i]);
} return out;
}
static char **map_s(size_t len, char *iter[const static len],
char *(*func)(char *s))
{
char **out = malloc(sizeof *out * len);
if (!out) {
return ((void *) 0);
}
for (size_t i = 0; i < len; ++i) {
out[i] = func(iter[i]);
}
return out;
}
And here's the output of the test program:
$ make CPPFLAGS=-DTEST_MAIN CFLAGS="-Wall -Werror -Wpedantic" map
cc -Wall -Werror -Wpedantic -DTEST_MAIN map.c -o map
$ ./map
Number: 1, Square: 1, Cube: 1.
Number: 2, Square: 4, Cube: 8.
Number: 3, Square: 9, Cube: 27.
Number: 4, Square: 16, Cube: 64.
Number: 5, Square: 25, Cube: 125.
Number: 6, Square: 36, Cube: 216.
Number: 7, Square: 49, Cube: 343.
Number: 8, Square: 64, Cube: 512.
Number: 9, Square: 81, Cube: 729.
Number: 10, Square: 100, Cube: 1000.
---->
a ----> a
abc ----> cba
abcd ----> dcba
abcde ----> edcba
Review Goals:
Is this foolproof?
Can it be structured better?
Is the behavior of the code defined?
Have I missed any types? What should the default case be?
PS: Why do this? It served as a good exercise. | {
"domain": "codereview.stackexchange",
"id": 45462,
"lm_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, generics, c11",
"url": null
} |
c, generics, c11
PS: Why do this? It served as a good exercise.
Answer: This is Inflexible
It always allocates an output buffer on the heap, which the caller must free(). It cannot write to a buffer allocated by the caller. It cannot use a map function whose output type is different than the input type. It does not support user-defined types.
Be Aware of the Rules for Generic Types
The C17 Standard requires that, in a _Generic expression,
No two generic associations in the same generic selection shall specify compatible types. The type of the controlling expression is the type of the expression as if it had undergone an lvalue conversion [....]
So, if you expand the list of types, you need to ensure that no two types are compatible.
A void* Implementation is Surprisingly Good
Consider the following implementation, which uses a similar interface to qsort() or bsearch():
#include <stddef.h>
typedef void (*map_func)(const void*, void*);
/* Fills the destination array dest with the image of the source array src
* under the map function f.
*
* The source array must contain at least n elements of size src_elem_size.
* The destination array must contain at least n elements of size dest_elem_size.
* Both arrays must be correctly-aligned, and must not overlap.
* Returns a pointer to the destination array.
*/
inline void* map_generic( const map_func f,
const size_t n,
const void* const src,
const size_t src_elem_size,
void* const dest,
const size_t dest_elem_size ) {
for (size_t i = 0; i < n; ++i) {
const char* const srcp = (char*)src + src_elem_size*i;
char* const destp = (char*)dest + dest_elem_size*i;
f( srcp, destp );
}
return dest;
} | {
"domain": "codereview.stackexchange",
"id": 45462,
"lm_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, generics, c11",
"url": null
} |
c, generics, c11
(Here, I made the source argument come before the destination, but perhaps I should have followed the K&R convention of destination before source.)
Let’s test it with the following function that takes the square root of an unsigned int argument: (Technically, I should have declared the arguments as void* for maximum portability.)
#include <math.h>
inline void my_sqrt(const unsigned* const srcp, double* const destp ) {
*destp = sqrt((double)*srcp);
}
And the following test driver:
#include <stdio.h>
#include <stdlib.h>
#define ELEMS 101U
int main(void) {
unsigned xs[ELEMS];
double ys[ELEMS];
for (unsigned i = 0; i < ELEMS; ++i) {
xs[i] = i;
}
map_generic( (map_func)my_sqrt,
ELEMS,
xs,
sizeof(xs[0]),
ys,
sizeof(ys[0]));
for (unsigned i = 1; i < ELEMS; ++i) {
printf("%f\n", ys[i]);
}
return EXIT_SUCCESS;
}
GCC 13.2 with -std=c17 -march=x86-64-v3 -O3 compiles the main loop of map_generic to:
.L8:
mov eax, DWORD PTR [rbp-1296+rbx*4]
vcvtsi2sd xmm0, xmm2, rax
vucomisd xmm1, xmm0
ja .L15
vsqrtsd xmm0, xmm0, xmm0
vmovsd QWORD PTR [rbp-864+rbx*8], xmm0
add rbx, 1
cmp rbx, 101
jne .L8
With -ffast-math, it unrolls this loop into a series of statements like:
vsqrtpd ymm0, YMMWORD PTR .LC0[rip]
vmovapd YMMWORD PTR [rbp-880], ymm0 | {
"domain": "codereview.stackexchange",
"id": 45462,
"lm_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, generics, c11",
"url": null
} |
c, generics, c11
MSVC 19.38 with /std:c17 /arch:AVX2 /O2 /EHc /fp:fast compiles it to:
$LL12@main:
vcvtdq2pd ymm2, XMMWORD PTR xs$[rsp+rbx*4]
vcmppd ymm1, ymm2, ymm5, 1
vandpd ymm0, ymm1, ymm4
vaddpd ymm2, ymm0, ymm2
vsqrtpd ymm3, ymm2
vmovupd YMMWORD PTR ys$[rsp+rbx*8], ymm3
add rbx, 4
cmp rbx, 100 ; 00000064H
jb SHORT $LL12@main
Both Clang 17.0.1 and ICX 2024.0.0 are able to optimize away the initialization of both xs and ys entirely. They set ys to pre-calculated constants, like:
.LCPI0_0:
.quad 0x0000000000000000 # double 0
.quad 0x3ff0000000000000 # double 1
.quad 0x3ff6a09e667f3bcd # double 1.4142135623730951
.quad 0x3ffbb67ae8584caa # double 1.7320508075688772
Test it for yourself on Godbolt. | {
"domain": "codereview.stackexchange",
"id": 45462,
"lm_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, generics, c11",
"url": null
} |
sorting, time-limit-exceeded, binary-tree, binary-search-tree
Title: Sort array of numbers using tree sort - Leetcode 912
Question: Problem statement:
Sort integer array nums in O(N log N) time,
without relying on any library sort routine.
I am trying to use a tree sort method (using the creation of a BST and then performing inorder traversal) in order to sort an array of numbers. I have the following code:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
output = []
def insert(node, val):
if not node:
return TreeNode(val)
if val <= node.val:
node.left = insert(node.left, val)
else:
node.right = insert(node.right, val)
return node
root = TreeNode(nums[0])
for i in range(1, len(nums)):
root = insert(root, nums[i])
def inorder(root):
if not root:
return
inorder(root.left)
output.append(root.val)
inorder(root.right)
inorder(root)
return output
I am getting a TLE (time limit exceeded) error. I am not sure if there is an optimization to do in order to tighten up time from recursive stack calls in both the insert() function. I am not sure if the recursive solution is not optimal (given the amount of recursive calls used). Perhaps I need to approach with an iterative approach in order to build the BST during the insert() calls?
Answer: edge case
I feel the first result displayed here is reasonable:
>>> sorted([])
[]
>>> sorted([6, 4])
[4, 6] | {
"domain": "codereview.stackexchange",
"id": 45463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sorting, time-limit-exceeded, binary-tree, binary-search-tree",
"url": null
} |
sorting, time-limit-exceeded, binary-tree, binary-search-tree
Given zero elements, and asked to spit them back in ascending order,
the proper response is zero elements.
In contrast, your TreeNode(nums[0]) call
catastrophically raises IndexError in the empty case.
base case
Your insert function is lovely.
root = TreeNode(nums[0])
Caller might possibly have preferred to DRY this up with
root = insert(None, nums[0])
so that only insert needs to worry about that detail.
globals
def inorder(root):
See, now this is where "nested defs" gets a bad name.
Your insert was beautiful.
It could have been a separate (testable!) @staticmethod,
but it's simple and it fit in nicely.
In contrast, this function should probably have a signature of
def inorder(output, root):
(Plus, output was perhaps initialized a bit early,
so we have nearly forgotten about it by the time it is used.)
Ok, enough about
coupling.
time complexity
When you approach a cryptography problem,
or an OWASP cyber security problem,
or even a simple sort,
you have to have a mind-set that
the whole world is out to get you.
The computer, the internet, and especially the adversary.
Which in this case would be the LeetCode folks.
Now, imagine a happy world, with unicorns prancing
beneath rainbows. You get N integers to sort.
And guess what?
It's a random permutation of natural numbers up to N.
Life is good, your Binary Tree algorithm can blaze
through them, inserting each number in O(log N) time.
But then the next day storm clouds have come out,
the shy unicorns have run away,
and LeetCode sends you one of these as input:
list(range(n))
list(reversed(range(n))) | {
"domain": "codereview.stackexchange",
"id": 45463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sorting, time-limit-exceeded, binary-tree, binary-search-tree",
"url": null
} |
sorting, time-limit-exceeded, binary-tree, binary-search-tree
list(range(n))
list(reversed(range(n)))
Will insert run in logarithmic time?
Heavy sigh!
It needs O(N) linear time to chase through
those unbalanced nodes.
Total sort time is O(N²) quadratic.
We are ruined!
Fortunately this is an off-line (batch) sort --
you are given the numbers all at once.
It's not like we're trying to maintain an online
pqueue
or anything.
If you want to save the current algorithm,
you could enforce the randomness requirement with
Fisher-Yates
pre-conditioning at linear cost.
Not that I've ever seen anyone do that in real production code.
Plus, it would behave suboptimally if given N 0's
plus a single 1 to sort.
Consider looking into one of the various
Balanced
binary tree datastructures, such as a
heap
or the ever popular
red-black tree. | {
"domain": "codereview.stackexchange",
"id": 45463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "sorting, time-limit-exceeded, binary-tree, binary-search-tree",
"url": null
} |
c, parsing, file
Title: Advent of Code 2023 day 1: Trebuchet in C (part 2)
Question: Problem description from the Advent of Code website:
Part 1:
The task involves analyzing a calibration document containing lines of text. Each line represents a calibration value that needs to be recovered by extracting the first and last digits and combining them into a two-digit number. The goal is to find the sum of all these calibration values.
For example:
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
In this example, the calibration values of these four lines are 12, 38, 15, and 77. Adding these together produces 142.
Part 2:
In problem two, the calibration document may include digits spelled out with letters (e.g., "one," "two," etc.). The task is to identify the actual first and last digits in each line, taking into account both numerical digits and spelled-out numbers. The overall objective remains the same: find the sum of the calibration values obtained from combining the first and last digits of each line.
For example:
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
In this example, the calibration values are 29, 83, 13, 24, 42, 14, and 76. Adding these together produces 281.
Here's the code I wrote in C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getDigits(char* src, int* dest);
int main(int argc, char** argv) {
FILE* input = fopen(argv[1], "r");
if (input == NULL)
return -1;
char* line = NULL;
size_t line_size = 0;
int digits[2], line_len, sum = 0;
while ((line_len = getline(&line, &line_size, input)) != -1) {
getDigits(line, digits);
sum += 10*digits[0] + digits[1];
}
printf("Sum: %d\n", sum);
return 0;
}
void getDigits(char* src, int* dest) {
int len = strlen(src); | {
"domain": "codereview.stackexchange",
"id": 45464,
"lm_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, parsing, file",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.